Decompiled source of AutoConnectPower v1.0.1

AutoConnectPower.dll

Decompiled 8 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AutoConnectPower")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+0eb5ec6e1ff14131943cf7f03867bc5bfee4b7b9")]
[assembly: AssemblyProduct("AutoConnectPower")]
[assembly: AssemblyTitle("AutoConnectPower")]
[assembly: AssemblyVersion("1.0.1.0")]
namespace AutoConnectPower;

public enum TowerMode
{
	TeslaOnly,
	Alternate
}
public enum PlacementMode
{
	Direct,
	Ghost
}
[BepInPlugin("Satroki.dsp.AutoConnectPower", "AutoConnectPower", "1.0.1")]
[BepInProcess("DSPGAME.exe")]
public sealed class AutoConnectPowerPlugin : BaseUnityPlugin
{
	public const string PluginGuid = "Satroki.dsp.AutoConnectPower";

	public const string PluginName = "AutoConnectPower";

	public const string PluginVersion = "1.0.1";

	internal static ManualLogSource Log;

	internal static ConfigEntry<TowerMode> TowerModeConfig;

	internal static ConfigEntry<PlacementMode> PlacementModeConfig;

	internal static ConfigEntry<bool> AutoFoundation;

	internal static ConfigEntry<bool> ShowResult;

	internal static ConfigEntry<KeyboardShortcut> Hotkey;

	private void Awake()
	{
		//IL_00ab: 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)
		Log = ((BaseUnityPlugin)this).Logger;
		TowerModeConfig = ((BaseUnityPlugin)this).Config.Bind<TowerMode>("General", "TowerMode", TowerMode.Alternate, "连接塔类型。TeslaOnly = 只使用电力感应塔;Alternate = 长距离连接时交替使用无线输电塔与电力感应塔。");
		PlacementModeConfig = ((BaseUnityPlugin)this).Config.Bind<PlacementMode>("General", "PlacementMode", PlacementMode.Ghost, "落成方式。Ghost = 只生成未建造虚影(默认),由建造无人机或玩家补材料建造;Direct = 直接从背包消耗材料并建成。");
		AutoFoundation = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AutoFoundation", true, "连接塔落点在水面/熔岩等液体表面时自动铺地基(3×3 格,消耗地基物品和沙土;已是地基的格不重复消耗)。默认开启。地面上的塔不铺地基;液体表面塔地基材料/沙土不足时会被跳过。");
		ShowResult = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowResult", true, "在屏幕右下角显示执行结果提示。");
		Hotkey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "Hotkey", new KeyboardShortcut((KeyCode)99, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }), "自动连接电网快捷键(默认 Alt+C,留空/None 关闭)。格式示例:C + LeftAlt;也可以只写一个键,如 F8。");
		((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("{0} v{1} 已加载,快捷键 {2}。", "AutoConnectPower", "1.0.1", Hotkey.Value));
	}

	private void Update()
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		if (Hotkey == null || !IsHotkeyDown(Hotkey.Value) || !Application.isFocused || VFInput.onGUI || VFInput.inputing || GameMain.data == null || GameMain.localPlanet == null || GameMain.mainPlayer == null)
		{
			return;
		}
		try
		{
			PowerGridConnector.Run();
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("自动连接电网失败:" + ex));
			Tip("自动连接电网失败,请查看 BepInEx 日志");
		}
	}

	private static bool IsHotkeyDown(KeyboardShortcut shortcut)
	{
		//IL_0002: 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_002b: Unknown result type (might be due to invalid IL or missing references)
		if ((int)((KeyboardShortcut)(ref shortcut)).MainKey == 0)
		{
			return false;
		}
		if (!Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey))
		{
			return false;
		}
		foreach (KeyCode modifier in ((KeyboardShortcut)(ref shortcut)).Modifiers)
		{
			if (!Input.GetKey(modifier))
			{
				return false;
			}
		}
		return true;
	}

	internal static void Tip(string message)
	{
		if (message != null && (ShowResult == null || ShowResult.Value) && GameMain.data != null && GameMain.mainPlayer != null)
		{
			UIRealtimeTip.Popup(message, true, 0);
		}
	}
}
internal readonly struct ConnNode
{
	public readonly Vector3 Dir;

	public readonly float Connect;

	public readonly float Cover;

	public readonly bool IsGhost;

	public ConnNode(Vector3 dir, float connect, float cover, bool isGhost = false)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		Dir = dir;
		Connect = connect;
		Cover = cover;
		IsGhost = isGhost;
	}
}
internal sealed class PlannedTower
{
	public int ProtoId;

	public Vector3 Dir;

	public float Connect;

	public float Cover;

	public int HashId = -1;

	public bool Skip;
}
internal sealed class PowerComponent
{
	public int NetworkId;

	public readonly List<ConnNode> Nodes = new List<ConnNode>();
}
internal enum FoundationOutcome
{
	Already,
	Paved,
	Failed
}
internal sealed class PowerGridConnector
{
	private sealed class PointHash
	{
		private readonly float _cellSize;

		private readonly Dictionary<(int, int, int), List<int>> _buckets = new Dictionary<(int, int, int), List<int>>();

		private readonly List<Vector3> _points = new List<Vector3>();

		private readonly List<bool> _active = new List<bool>();

		public PointHash(float cellSize)
		{
			_cellSize = cellSize;
		}

		public int Add(Vector3 point)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			(int, int, int) key = Key(point);
			if (!_buckets.TryGetValue(key, out var value))
			{
				value = new List<int>(4);
				_buckets[key] = value;
			}
			int count = _points.Count;
			_points.Add(point);
			_active.Add(item: true);
			value.Add(count);
			return count;
		}

		public void Remove(int id)
		{
			if (id >= 0 && id < _active.Count)
			{
				_active[id] = false;
			}
		}

		public bool AnyWithin(Vector3 point, float radius)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			float num = radius * radius;
			(int, int, int) tuple = Key(point);
			int item = tuple.Item1;
			int item2 = tuple.Item2;
			int item3 = tuple.Item3;
			for (int i = -1; i <= 1; i++)
			{
				for (int j = -1; j <= 1; j++)
				{
					for (int k = -1; k <= 1; k++)
					{
						if (!_buckets.TryGetValue((item + i, item2 + j, item3 + k), out var value))
						{
							continue;
						}
						for (int l = 0; l < value.Count; l++)
						{
							int index = value[l];
							if (_active[index])
							{
								Vector3 val = _points[index] - point;
								if (((Vector3)(ref val)).sqrMagnitude < num)
								{
									return true;
								}
							}
						}
					}
				}
			}
			return false;
		}

		private (int, int, int) Key(Vector3 point)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			return (Mathf.FloorToInt(point.x / _cellSize), Mathf.FloorToInt(point.y / _cellSize), Mathf.FloorToInt(point.z / _cellSize));
		}
	}

	public const int TeslaId = 2201;

	public const int WirelessId = 2202;

	private const float MinTowerSpacing = 3.6f;

	private const float ChainSafety = 1.2f;

	private const float MinStep = 1f;

	private const int FoundationSize = 3;

	private const int FoundationCells = 9;

	private const int FoundationBrushType = 1;

	private const float FoundationBrushRadius = 2.972838f;

	private static readonly float[] StepFactors = new float[4] { 1f, 0.85f, 0.7f, 0.55f };

	private static readonly float[] ChainLateralAngles = new float[14]
	{
		0f, 20f, -20f, 40f, -40f, 60f, -60f, 90f, -90f, 120f,
		-120f, 150f, -150f, 180f
	};

	private static readonly float[] CoverageLateralAngles = new float[8] { 0f, 45f, -45f, 90f, -90f, 135f, -135f, 180f };

	private readonly PlanetData _planet;

	private readonly PlanetFactory _factory;

	private readonly PowerSystem _power;

	private readonly Player _player;

	private readonly float _radius;

	private readonly bool _hasWater;

	private readonly float _waterLevel;

	private readonly int _primaryId;

	private readonly int _secondaryId;

	private readonly bool _alternate;

	private readonly float _primaryCover;

	private readonly bool _autoFoundation;

	private static readonly Collider[] TmpColliders = (Collider[])(object)new Collider[512];

	private const int BuildCollisionMask = 395264;

	private readonly List<ConnNode> _connected = new List<ConnNode>();

	private readonly List<PlannedTower> _plan = new List<PlannedTower>();

	private readonly List<PowerComponent> _remaining = new List<PowerComponent>();

	private readonly List<Vector3> _uncoveredDirs = new List<Vector3>();

	private readonly PointHash _powerPoints = new PointHash(8f);

	private readonly Vector3[] _foundationPoints = (Vector3[])(object)new Vector3[9];

	private readonly int[] _foundationIndices = new int[9];

	private int _networkCount;

	private int _ghostComponentCount;

	private int _generatorCount;

	private bool _hasGrid;

	private int _failedLinks;

	private int _failedCoverage;

	private int _foundationPaved;

	private int _foundationSkipped;

	private int _foundationItemsUsed;

	private int _foundationSandUsed;

	private PowerGridConnector(PlanetData planet, TowerMode mode)
	{
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Invalid comparison between Unknown and I4
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Invalid comparison between Unknown and I4
		_planet = planet;
		_factory = planet.factory;
		_power = _factory.powerSystem;
		_player = GameMain.mainPlayer;
		_radius = planet.realRadius + 0.2f;
		_hasWater = (int)planet.type == 2 || (int)planet.type == 1 || planet.waterItemId != 0 || Mathf.Abs(planet.waterHeight) > 0.01f;
		_waterLevel = planet.realRadius + planet.waterHeight;
		_autoFoundation = AutoConnectPowerPlugin.AutoFoundation?.Value ?? true;
		ItemProto item = ((ProtoSet<ItemProto>)(object)LDB.items)?.Select(2201);
		ItemProto item2 = ((ProtoSet<ItemProto>)(object)LDB.items)?.Select(2202);
		bool flag = IsPowerTower(item) && IsItemUnlocked(2201);
		if ((mode == TowerMode.Alternate && flag) & (IsPowerTower(item2) && IsItemUnlocked(2202)))
		{
			_primaryId = 2201;
			_secondaryId = 2202;
			_alternate = true;
		}
		else
		{
			_primaryId = (flag ? 2201 : 2202);
			_secondaryId = _primaryId;
			_alternate = false;
		}
		_primaryCover = TowerCover(_primaryId);
	}

	public static void Run()
	{
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Invalid comparison between Unknown and I4
		PlanetData localPlanet = GameMain.localPlanet;
		if (localPlanet == null || localPlanet.factory == null || !localPlanet.factoryLoaded || localPlanet.factory.powerSystem == null)
		{
			AutoConnectPowerPlugin.Tip("当前星球的电网尚未加载");
		}
		else if ((int)localPlanet.type == 5)
		{
			AutoConnectPowerPlugin.Tip("气体行星不需要连接电网");
		}
		else if (GameMain.mainPlayer == null || localPlanet.aux == null || localPlanet.data == null)
		{
			AutoConnectPowerPlugin.Tip("当前星球的建造数据尚未加载");
		}
		else if (!IsUsableTower(2201) && !IsUsableTower(2202))
		{
			AutoConnectPowerPlugin.Tip("尚未解锁电力感应塔或无线输电塔");
		}
		else
		{
			new PowerGridConnector(localPlanet, AutoConnectPowerPlugin.TowerModeConfig?.Value ?? TowerMode.Alternate).Execute(AutoConnectPowerPlugin.PlacementModeConfig?.Value ?? PlacementMode.Ghost);
		}
	}

	private static bool IsUsableTower(int itemId)
	{
		if (IsPowerTower(((ProtoSet<ItemProto>)(object)LDB.items)?.Select(itemId)))
		{
			return IsItemUnlocked(itemId);
		}
		return false;
	}

	private static bool IsItemUnlocked(int itemId)
	{
		if (GameMain.sandboxToolsEnabled)
		{
			return true;
		}
		GameHistoryData history = GameMain.history;
		if (history != null)
		{
			return history.ItemUnlocked(itemId);
		}
		return true;
	}

	private static bool IsPowerTower(ItemProto item)
	{
		if (item != null && item.prefabDesc != null)
		{
			return item.prefabDesc.isPowerNode;
		}
		return false;
	}

	private float TowerConnect(int protoId)
	{
		ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(protoId);
		if (val == null || val.prefabDesc == null)
		{
			return 0f;
		}
		return val.prefabDesc.powerConnectDistance;
	}

	private float TowerCover(int protoId)
	{
		ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(protoId);
		if (val == null || val.prefabDesc == null)
		{
			return 0f;
		}
		return val.prefabDesc.powerCoverRadius;
	}

	private void Execute(PlacementMode placement)
	{
		Stopwatch stopwatch = Stopwatch.StartNew();
		Scan();
		if (!_hasGrid)
		{
			AutoConnectPowerPlugin.Tip((_uncoveredDirs.Count > 0) ? "本星球没有可用的电网,无法自动连接" : "本星球没有需要连接的电力设备");
			return;
		}
		if (_networkCount <= 1 && _remaining.Count == 0 && _uncoveredDirs.Count == 0)
		{
			AutoConnectPowerPlugin.Tip((_generatorCount == 0) ? "电网已连通,但本星球没有发电机,无法供电" : "电网已全部连通,无需处理");
			return;
		}
		if (_generatorCount == 0)
		{
			ManualLogSource log = AutoConnectPowerPlugin.Log;
			if (log != null)
			{
				log.LogWarning((object)"本星球没有发电机,只能合并现有电网,无法为无供电设备提供电力。");
			}
		}
		if (_remaining.Count > 0)
		{
			ConnectNetworks();
		}
		PlanCoverage();
		if (_plan.Count == 0)
		{
			string message = "没有找到可放置连接塔的位置(可能被地形、水面/熔岩或建筑阻挡)";
			if (_failedLinks > 0 || _failedCoverage > 0)
			{
				message = $"未能连接:{_failedLinks} 条线路、{_failedCoverage} 个设备被地形或建筑阻挡";
			}
			AutoConnectPowerPlugin.Tip(message);
			return;
		}
		Build(placement, out var built, out var ghosts);
		int count = _plan.Count;
		int num = CountPlannedCoverage();
		int num2 = CountNetworks();
		int num3 = CountUncoveredConsumers();
		stopwatch.Stop();
		string text;
		if (placement == PlacementMode.Direct && built > 0)
		{
			text = $"自动连接电网:建成 {built} 座,虚影 {ghosts} 座;电网 {_networkCount}→{num2},无供电设备 {_uncoveredDirs.Count}→{num3}";
		}
		else
		{
			text = $"自动连接电网:生成 {ghosts} 个虚影(共 {count} 座),建成后合并 {_networkCount} 个电网";
			if (num > 0)
			{
				text += $",覆盖 {num} 个设备";
			}
		}
		if (_ghostComponentCount > 0)
		{
			text += $",虚影电网 {_ghostComponentCount} 个";
		}
		if (_autoFoundation)
		{
			if (_foundationPaved > 0)
			{
				text += $",铺地基 {_foundationPaved} 处(地基 {_foundationItemsUsed},沙土 {_foundationSandUsed})";
			}
			if (_foundationSkipped > 0)
			{
				text += $",{_foundationSkipped} 座水面/熔岩塔因地基不足跳过";
			}
			if (_foundationPaved == 0 && _foundationSkipped > 0)
			{
				ManualLogSource log2 = AutoConnectPowerPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)"自动铺地基未成功:检查地基物品(1131)和沙土。");
				}
			}
		}
		if (_failedLinks > 0 || _failedCoverage > 0)
		{
			text += $";{_failedLinks} 条线路、{_failedCoverage} 个设备未能连接";
		}
		AutoConnectPowerPlugin.Tip(text);
		ManualLogSource log3 = AutoConnectPowerPlugin.Log;
		if (log3 != null)
		{
			log3.LogInfo((object)$"自动连接电网:建成 {built},虚影 {ghosts},电网 {_networkCount}→{num2},地基 {_foundationPaved}/{_foundationSkipped},耗时 {stopwatch.ElapsedMilliseconds}ms");
		}
	}

	private void Scan()
	{
		//IL_007d: 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_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_012b: 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_0470: Unknown result type (might be due to invalid IL or missing references)
		//IL_0475: Unknown result type (might be due to invalid IL or missing references)
		//IL_0478: Unknown result type (might be due to invalid IL or missing references)
		//IL_0483: Unknown result type (might be due to invalid IL or missing references)
		//IL_0422: Unknown result type (might be due to invalid IL or missing references)
		//IL_0427: Unknown result type (might be due to invalid IL or missing references)
		//IL_0493: Unknown result type (might be due to invalid IL or missing references)
		//IL_0438: Unknown result type (might be due to invalid IL or missing references)
		//IL_0448: Unknown result type (might be due to invalid IL or missing references)
		Dictionary<int, PowerComponent> dictionary = new Dictionary<int, PowerComponent>();
		List<ConnNode> list = new List<ConnNode>();
		List<ConnNode> list2 = new List<ConnNode>();
		List<Vector3> list3 = new List<Vector3>();
		PowerNodeComponent[] nodePool = _power.nodePool;
		EntityData[] entityPool = _factory.entityPool;
		if (nodePool != null)
		{
			for (int i = 1; i < _power.nodeCursor; i++)
			{
				if (nodePool[i].id != i)
				{
					continue;
				}
				int entityId = nodePool[i].entityId;
				if (entityId <= 0 || entityId >= entityPool.Length)
				{
					continue;
				}
				EntityData val = entityPool[entityId];
				if (val.id == 0)
				{
					continue;
				}
				Vector3 normalized = ((Vector3)(ref val.pos)).normalized;
				if (((Vector3)(ref normalized)).sqrMagnitude < 0.5f)
				{
					continue;
				}
				int networkId = nodePool[i].networkId;
				if (networkId > 0)
				{
					if (!dictionary.TryGetValue(networkId, out var value))
					{
						value = (dictionary[networkId] = new PowerComponent
						{
							NetworkId = networkId
						});
					}
					ConnNode item = new ConnNode(normalized, nodePool[i].connectDistance, nodePool[i].coverRadius);
					value.Nodes.Add(item);
					list.Add(item);
					_powerPoints.Add(normalized * _radius);
				}
			}
		}
		_networkCount = dictionary.Count;
		PowerGeneratorComponent[] genPool = _power.genPool;
		if (genPool != null)
		{
			for (int j = 1; j < _power.genCursor; j++)
			{
				if (genPool[j].id == j)
				{
					_generatorCount++;
				}
			}
		}
		ScanPrebuilds(list2, list3);
		List<PowerComponent> list4 = BuildGhostComponents(list2);
		_ghostComponentCount = list4.Count;
		List<PowerComponent> list5 = new List<PowerComponent>(dictionary.Values);
		list5.Sort((PowerComponent a, PowerComponent b) => b.Nodes.Count.CompareTo(a.Nodes.Count));
		if (list5.Count > 0 && list4.Count > 0)
		{
			for (int num = list4.Count - 1; num >= 0; num--)
			{
				PowerComponent powerComponent2 = FindGhostHost(list5, list4[num]);
				if (powerComponent2 != null)
				{
					powerComponent2.Nodes.AddRange(list4[num].Nodes);
					list4.RemoveAt(num);
				}
			}
		}
		if (list5.Count > 0)
		{
			foreach (ConnNode node in list5[0].Nodes)
			{
				_connected.Add(node);
			}
			for (int num2 = 1; num2 < list5.Count; num2++)
			{
				_remaining.Add(list5[num2]);
			}
			foreach (PowerComponent item2 in list4)
			{
				_remaining.Add(item2);
			}
		}
		else if (list4.Count > 0)
		{
			list4.Sort((PowerComponent a, PowerComponent b) => b.Nodes.Count.CompareTo(a.Nodes.Count));
			foreach (ConnNode node2 in list4[0].Nodes)
			{
				_connected.Add(node2);
			}
			for (int num3 = 1; num3 < list4.Count; num3++)
			{
				_remaining.Add(list4[num3]);
			}
		}
		_hasGrid = list5.Count > 0 || list4.Count > 0;
		PowerConsumerComponent[] consumerPool = _power.consumerPool;
		if (consumerPool != null)
		{
			for (int num4 = 1; num4 < _power.consumerCursor; num4++)
			{
				if (consumerPool[num4].id == num4 && consumerPool[num4].networkId == 0)
				{
					Vector3 normalized2 = ((Vector3)(ref consumerPool[num4].plugPos)).normalized;
					if (!(((Vector3)(ref normalized2)).sqrMagnitude < 0.5f) && !IsCoveredByNodes(normalized2, list2))
					{
						_uncoveredDirs.Add(normalized2);
					}
				}
			}
		}
		foreach (Vector3 item3 in list3)
		{
			if (!IsCoveredByNodes(item3, list) && !IsCoveredByNodes(item3, list2))
			{
				_uncoveredDirs.Add(item3);
			}
		}
	}

	private void ScanPrebuilds(List<ConnNode> ghostNodes, List<Vector3> ghostConsumers)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: 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_0042: 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_006b: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
		PrebuildData[] prebuildPool = _factory.prebuildPool;
		if (prebuildPool == null)
		{
			return;
		}
		for (int i = 1; i < _factory.prebuildCursor; i++)
		{
			PrebuildData val = prebuildPool[i];
			if (val.id != i || val.isDestroyed)
			{
				continue;
			}
			ItemProto val2 = ((ProtoSet<ItemProto>)(object)LDB.items)?.Select((int)val.protoId);
			if (val2 == null || val2.prefabDesc == null)
			{
				continue;
			}
			Vector3 normalized = ((Vector3)(ref val.pos)).normalized;
			if (((Vector3)(ref normalized)).sqrMagnitude < 0.5f)
			{
				continue;
			}
			if (val2.prefabDesc.isPowerNode)
			{
				ghostNodes.Add(new ConnNode(normalized, val2.prefabDesc.powerConnectDistance, val2.prefabDesc.powerCoverRadius, isGhost: true));
				_powerPoints.Add(normalized * _radius);
				if (val2.prefabDesc.isPowerGen)
				{
					_generatorCount++;
				}
			}
			else if (val2.prefabDesc.isPowerConsumer)
			{
				ghostConsumers.Add(normalized);
			}
		}
	}

	private List<PowerComponent> BuildGhostComponents(List<ConnNode> ghostNodes)
	{
		List<PowerComponent> list = new List<PowerComponent>();
		foreach (ConnNode ghostNode in ghostNodes)
		{
			List<PowerComponent> list2 = new List<PowerComponent>();
			foreach (PowerComponent item in list)
			{
				if (ComponentNear(item, ghostNode))
				{
					list2.Add(item);
				}
			}
			PowerComponent powerComponent;
			if (list2.Count == 0)
			{
				powerComponent = new PowerComponent
				{
					NetworkId = -1 - list.Count
				};
				list.Add(powerComponent);
			}
			else
			{
				powerComponent = list2[0];
				for (int i = 1; i < list2.Count; i++)
				{
					powerComponent.Nodes.AddRange(list2[i].Nodes);
					list.Remove(list2[i]);
				}
			}
			powerComponent.Nodes.Add(ghostNode);
		}
		return list;
	}

	private bool ComponentNear(PowerComponent component, ConnNode node)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < component.Nodes.Count; i++)
		{
			ConnNode connNode = component.Nodes[i];
			if (Chord(connNode.Dir, node.Dir) <= Mathf.Max(connNode.Connect, node.Connect) - 0.1f)
			{
				return true;
			}
		}
		return false;
	}

	private PowerComponent FindGhostHost(List<PowerComponent> components, PowerComponent ghost)
	{
		for (int i = 0; i < components.Count; i++)
		{
			if (IsReachable(ghost.Nodes, components[i].Nodes))
			{
				return components[i];
			}
		}
		return null;
	}

	private bool IsCoveredByNodes(Vector3 dir, List<ConnNode> nodes)
	{
		//IL_000d: 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)
		for (int i = 0; i < nodes.Count; i++)
		{
			ConnNode connNode = nodes[i];
			if (SqrChord(dir, connNode.Dir) <= connNode.Cover * connNode.Cover)
			{
				return true;
			}
		}
		return false;
	}

	private void ConnectNetworks()
	{
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		while (_remaining.Count > 0)
		{
			int num = -1;
			int index = -1;
			int index2 = -1;
			float num2 = float.MaxValue;
			for (int i = 0; i < _remaining.Count; i++)
			{
				PowerComponent powerComponent = _remaining[i];
				for (int j = 0; j < powerComponent.Nodes.Count; j++)
				{
					ConnNode connNode = powerComponent.Nodes[j];
					for (int k = 0; k < _connected.Count; k++)
					{
						float num3 = Chord(connNode.Dir, _connected[k].Dir);
						if (num3 < num2)
						{
							num2 = num3;
							num = i;
							index = j;
							index2 = k;
						}
					}
				}
			}
			if (num < 0)
			{
				break;
			}
			PowerComponent powerComponent2 = _remaining[num];
			ConnNode start = _connected[index2];
			ConnNode target = powerComponent2.Nodes[index];
			if (!TryPlanChain(start, target, out var chain))
			{
				_failedLinks++;
				ManualLogSource log = AutoConnectPowerPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)$"无法连接电网 {powerComponent2.NetworkId}({num2:F0}m)");
				}
				_remaining.RemoveAt(num);
				continue;
			}
			List<ConnNode> list = new List<ConnNode>();
			foreach (PlannedTower item2 in chain)
			{
				AddPlanTower(item2);
				ConnNode item = new ConnNode(item2.Dir, item2.Connect, item2.Cover);
				_connected.Add(item);
				list.Add(item);
			}
			foreach (ConnNode node in powerComponent2.Nodes)
			{
				_connected.Add(node);
				list.Add(node);
			}
			_remaining.RemoveAt(num);
			MergeRemainingByPlan(list);
		}
	}

	private void MergeRemainingByPlan(List<ConnNode> added)
	{
		if (added.Count == 0 || _remaining.Count == 0)
		{
			return;
		}
		List<ConnNode> list = new List<ConnNode>(added);
		bool flag = true;
		while (flag)
		{
			flag = false;
			for (int num = _remaining.Count - 1; num >= 0; num--)
			{
				PowerComponent powerComponent = _remaining[num];
				if (IsReachable(powerComponent.Nodes, list))
				{
					foreach (ConnNode node in powerComponent.Nodes)
					{
						_connected.Add(node);
						list.Add(node);
					}
					_remaining.RemoveAt(num);
					flag = true;
				}
			}
		}
	}

	private bool IsReachable(List<ConnNode> nodes, List<ConnNode> frontier)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < nodes.Count; i++)
		{
			ConnNode connNode = nodes[i];
			for (int j = 0; j < frontier.Count; j++)
			{
				ConnNode connNode2 = frontier[j];
				float num = Chord(connNode.Dir, connNode2.Dir);
				float num2 = Mathf.Max(connNode.Connect, connNode2.Connect);
				if (num <= num2 - 0.1f)
				{
					return true;
				}
			}
		}
		return false;
	}

	private void PlanCoverage()
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: 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_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ff: 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_011c: 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_012a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0234: 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_01c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_032a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
		if (_uncoveredDirs.Count == 0 || _connected.Count == 0)
		{
			return;
		}
		bool[] array = new bool[_uncoveredDirs.Count];
		foreach (PlannedTower item in _plan)
		{
			MarkCoveredBy(item, array);
		}
		foreach (ConnNode item2 in _connected)
		{
			if (item2.IsGhost)
			{
				MarkCoveredBy(item2.Dir, item2.Cover, array);
			}
		}
		for (int i = 0; i < _uncoveredDirs.Count; i++)
		{
			if (array[i])
			{
				continue;
			}
			Vector3 val = _uncoveredDirs[i];
			float distance;
			int num = FindNearestConnected(val, out distance);
			if (num < 0)
			{
				continue;
			}
			PlannedTower plannedTower = null;
			float num2 = float.MinValue;
			foreach (Vector3 item3 in CoverageCandidates(val, _connected[num].Dir))
			{
				if (!TryPlaceTower(item3, _primaryId, hasFrom: false, default(Vector3), 0f, 5f, CoverageLateralAngles, null, out var tower) || Chord(tower.Dir, val) > tower.Cover - 0.05f)
				{
					continue;
				}
				int num3 = CountUncoveredCovered(tower.Dir, tower.Cover, array);
				if (num3 > 0)
				{
					int num4 = EstimateLinkTowers(tower, _connected[num]);
					float num5 = (float)num3 * 100000f - (float)num4 * 500f - Chord(tower.Dir, _connected[num].Dir);
					if (num5 > num2)
					{
						num2 = num5;
						plannedTower = tower;
					}
				}
			}
			if (plannedTower == null)
			{
				_failedCoverage++;
				continue;
			}
			AddPlanTower(plannedTower);
			bool[] array2 = (bool[])array.Clone();
			MarkCoveredBy(plannedTower, array);
			float distance2;
			int num6 = FindNearestConnected(plannedTower.Dir, out distance2);
			if (num6 < 0)
			{
				continue;
			}
			ConnNode target = _connected[num6];
			float num7 = Mathf.Max(plannedTower.Connect, target.Connect);
			if (distance2 > num7 - 0.05f)
			{
				if (!TryPlanChain(new ConnNode(plannedTower.Dir, plannedTower.Connect, plannedTower.Cover), target, out var chain))
				{
					RemovePlanTower(plannedTower);
					array = array2;
					_failedCoverage++;
					continue;
				}
				foreach (PlannedTower item4 in chain)
				{
					AddPlanTower(item4);
					_connected.Add(new ConnNode(item4.Dir, item4.Connect, item4.Cover));
					MarkCoveredBy(item4, array);
				}
			}
			_connected.Add(new ConnNode(plannedTower.Dir, plannedTower.Connect, plannedTower.Cover));
		}
	}

	private IEnumerable<Vector3> CoverageCandidates(Vector3 consumerDir, Vector3 gridDir)
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: 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)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		Vector3 tangent = gridDir - consumerDir * Vector3.Dot(gridDir, consumerDir);
		if (((Vector3)(ref tangent)).sqrMagnitude < 1E-06f)
		{
			tangent = Vector3.Cross(consumerDir, Vector3.up);
			if (((Vector3)(ref tangent)).sqrMagnitude < 1E-06f)
			{
				tangent = Vector3.Cross(consumerDir, Vector3.right);
			}
		}
		((Vector3)(ref tangent)).Normalize();
		Vector3 val = Vector3.Cross(consumerDir, tangent);
		Vector3 bitangent = ((Vector3)(ref val)).normalized;
		float cover = Mathf.Max(1f, _primaryCover);
		float[] distances = new float[3] { 0.98f, 0.8f, 0.6f };
		float[] angles = new float[12]
		{
			0f, 30f, -30f, 60f, -60f, 90f, -90f, 120f, -120f, 150f,
			-150f, 180f
		};
		for (int di = 0; di < distances.Length; di++)
		{
			for (int ai = 0; ai < angles.Length; ai++)
			{
				float num = angles[ai] * (MathF.PI / 180f);
				Vector3 val2 = (tangent * Mathf.Cos(num) + bitangent * Mathf.Sin(num)) * (distances[di] * cover / _radius);
				val = consumerDir + val2;
				yield return ((Vector3)(ref val)).normalized;
			}
		}
	}

	private int CountUncoveredCovered(Vector3 dir, float cover, bool[] covered)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		int num = 0;
		float num2 = cover * cover;
		for (int i = 0; i < _uncoveredDirs.Count; i++)
		{
			if (!covered[i] && SqrChord(dir, _uncoveredDirs[i]) <= num2)
			{
				num++;
			}
		}
		return num;
	}

	private void MarkCoveredBy(PlannedTower tower, bool[] covered)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		MarkCoveredBy(tower.Dir, tower.Cover, covered);
	}

	private void MarkCoveredBy(Vector3 dir, float cover, bool[] covered)
	{
		//IL_000e: 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)
		float num = cover * cover;
		for (int i = 0; i < _uncoveredDirs.Count; i++)
		{
			if (!covered[i] && SqrChord(dir, _uncoveredDirs[i]) <= num)
			{
				covered[i] = true;
			}
		}
	}

	private int CountPlannedCoverage()
	{
		bool[] array = new bool[_uncoveredDirs.Count];
		foreach (PlannedTower item in _plan)
		{
			MarkCoveredBy(item, array);
		}
		int num = 0;
		for (int i = 0; i < array.Length; i++)
		{
			if (array[i])
			{
				num++;
			}
		}
		return num;
	}

	private int EstimateLinkTowers(PlannedTower tower, ConnNode grid)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		float num = Chord(tower.Dir, grid.Dir);
		float num2 = Mathf.Max(tower.Connect, grid.Connect);
		if (num <= num2)
		{
			return 0;
		}
		float num3 = Mathf.Max(1f, num2 - 1.2f);
		return Mathf.Max(0, Mathf.CeilToInt(num / num3) - 1);
	}

	private int FindNearestConnected(Vector3 dir, out float distance)
	{
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		int result = -1;
		float num = float.MaxValue;
		for (int i = 0; i < _connected.Count; i++)
		{
			float num2 = Chord(dir, _connected[i].Dir);
			if (num2 < num)
			{
				num = num2;
				result = i;
			}
		}
		distance = num;
		return result;
	}

	private bool TryPlanChain(ConnNode start, ConnNode target, out List<PlannedTower> chain)
	{
		//IL_0005: 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)
		chain = null;
		if (Chord(start.Dir, target.Dir) <= Mathf.Max(start.Connect, target.Connect) - 0.05f)
		{
			chain = new List<PlannedTower>();
			return true;
		}
		List<PlannedTower> list = null;
		foreach (int item in StartTypes())
		{
			if (TryPlanChainFrom(item, start, target, out var chain2) && (list == null || chain2.Count < list.Count))
			{
				list = chain2;
			}
		}
		if (list == null)
		{
			return false;
		}
		chain = list;
		return true;
	}

	private IEnumerable<int> StartTypes()
	{
		yield return _primaryId;
		if (_alternate && _secondaryId != _primaryId)
		{
			yield return _secondaryId;
		}
	}

	private int NextTowerType(int startType, int index)
	{
		if (!_alternate)
		{
			return _primaryId;
		}
		if ((index & 1) == 0)
		{
			return startType;
		}
		if (startType != 2201)
		{
			return 2201;
		}
		return 2202;
	}

	private bool TryPlanChainFrom(int startType, ConnNode start, ConnNode target, out List<PlannedTower> chain)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: 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_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		chain = null;
		List<PlannedTower> list = new List<PlannedTower>();
		Vector3 dir = start.Dir;
		float connect = start.Connect;
		for (int i = 0; i < 512; i++)
		{
			if (Chord(dir, target.Dir) <= Mathf.Max(connect, target.Connect) - 0.05f)
			{
				chain = list;
				return true;
			}
			int protoId = NextTowerType(startType, list.Count);
			float num = Mathf.Max(connect, TowerConnect(protoId));
			float num2 = num - 1.2f;
			if (num2 < 1f)
			{
				break;
			}
			bool flag = false;
			for (int j = 0; j < StepFactors.Length; j++)
			{
				Vector3 desiredDir = StepTowards(dir, target.Dir, num2 * StepFactors[j]);
				if (TryPlaceTower(desiredDir, protoId, hasFrom: true, dir, num - 0.15f, 2f, ChainLateralAngles, list, out var tower))
				{
					list.Add(tower);
					dir = tower.Dir;
					connect = tower.Connect;
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				break;
			}
		}
		chain = null;
		return false;
	}

	private bool TryPlaceTower(Vector3 desiredDir, int protoId, bool hasFrom, Vector3 fromDir, float maxFromDistance, float lateral, float[] lateralAngles, List<PlannedTower> local, out PlannedTower tower)
	{
		//IL_001d: 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_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: 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)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: 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)
		tower = null;
		for (int i = 0; i < lateralAngles.Length; i++)
		{
			Vector3 desiredDir2 = ((i == 0) ? desiredDir : RotateOnTangent(desiredDir, lateralAngles[i], lateral));
			if (!TryPlaceAt(desiredDir2, protoId, out var dir) || (hasFrom && Chord(fromDir, dir) > maxFromDistance))
			{
				continue;
			}
			if (local != null)
			{
				bool flag = false;
				for (int j = 0; j < local.Count; j++)
				{
					if (Chord(local[j].Dir, dir) < 3.6f)
					{
						flag = true;
						break;
					}
				}
				if (flag)
				{
					continue;
				}
			}
			tower = new PlannedTower
			{
				ProtoId = protoId,
				Dir = dir,
				Connect = TowerConnect(protoId),
				Cover = TowerCover(protoId)
			};
			return true;
		}
		return false;
	}

	private bool TryPlaceAt(Vector3 desiredDir, int protoId, out Vector3 dir)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: 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)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: 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_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: 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_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: 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_0094: Unknown result type (might be due to invalid IL or missing references)
		dir = desiredDir;
		Vector3 val = _planet.aux.Snap(desiredDir * _radius, false);
		if (((Vector3)(ref val)).sqrMagnitude < 0.5f)
		{
			return false;
		}
		dir = ((Vector3)(ref val)).normalized;
		Vector3 val2 = dir * _radius;
		if (IsUnderwater(val2))
		{
			if (!_autoFoundation)
			{
				return false;
			}
			if (!CanAffordFoundation())
			{
				return false;
			}
		}
		if (_powerPoints.AnyWithin(val2, 3.6f))
		{
			return false;
		}
		Quaternion rotation = Maths.SphericalRotation(val2, 0f);
		if (CollidesWithBuilding(val2, rotation, protoId))
		{
			return false;
		}
		return true;
	}

	private bool CollidesWithBuilding(Vector3 position, Quaternion rotation, int protoId)
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: 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)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: 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_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_005a: 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_008c: 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_00f3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: 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)
		if (_planet.physics == null)
		{
			return false;
		}
		ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(protoId);
		if (val == null || val.prefabDesc == null)
		{
			return false;
		}
		ColliderData buildCollider = val.prefabDesc.buildCollider;
		Vector3 val2 = position + rotation * buildCollider.pos;
		Quaternion val3 = rotation * buildCollider.q;
		Vector3 ext = buildCollider.ext;
		if (ext.x < 0.1f)
		{
			ext.x = 1f;
		}
		if (ext.y < 0.1f)
		{
			ext.y = 1.2f;
		}
		if (ext.z < 0.1f)
		{
			ext.z = 1f;
		}
		ext.x += 0.12f;
		ext.z += 0.12f;
		NearColliderLogic nearColliderLogic = _planet.physics.nearColliderLogic;
		if (nearColliderLogic != null)
		{
			nearColliderLogic.ActiveCollidersInArea(position, 5f);
			Physics.SyncTransforms();
		}
		int num = Physics.OverlapBoxNonAlloc(val2, ext, TmpColliders, val3, 395264, (QueryTriggerInteraction)2);
		ColliderData val5 = default(ColliderData);
		for (int i = 0; i < num; i++)
		{
			Collider val4 = TmpColliders[i];
			if ((Object)(object)val4 == (Object)null)
			{
				continue;
			}
			if (((Component)val4).gameObject.layer == 17)
			{
				return true;
			}
			if (((Component)val4).gameObject.layer != 11)
			{
				bool colliderData = _planet.physics.GetColliderData(val4, ref val5);
				if (colliderData && (int)((ColliderData)(ref val5)).objType != 0)
				{
					return true;
				}
				if ((((Component)val4).gameObject.layer != 18 || !((Object)(object)((Component)val4).GetComponent<BuildPreviewModel>() != (Object)null)) && colliderData && ((ColliderData)(ref val5)).isForBuild)
				{
					return true;
				}
			}
		}
		return false;
	}

	private void AddPlanTower(PlannedTower tower)
	{
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		_plan.Add(tower);
		tower.HashId = _powerPoints.Add(tower.Dir * _radius);
	}

	private void RemovePlanTower(PlannedTower tower)
	{
		_plan.Remove(tower);
		if (tower.HashId >= 0)
		{
			_powerPoints.Remove(tower.HashId);
			tower.HashId = -1;
		}
	}

	private bool IsUnderwater(Vector3 position)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		if (!_hasWater)
		{
			return false;
		}
		return _planet.data.QueryHeight(position) < _waterLevel + 0.25f;
	}

	private bool CanAffordFoundation()
	{
		if (_player == null)
		{
			return false;
		}
		if (_player.package.GetItemCount(1131) + _player.inhandItemCount >= 9)
		{
			if (_player.sandCount <= 0)
			{
				return HasInfiniteSand();
			}
			return true;
		}
		return false;
	}

	private static bool HasInfiniteSand()
	{
		if (GameMain.sandboxToolsEnabled && GameMain.data?.history != null)
		{
			return GameMain.data.history.HasFeatureKey(1100001);
		}
		return false;
	}

	private void PaveFoundations()
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: 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_0039: Unknown result type (might be due to invalid IL or missing references)
		int num = 0;
		for (int i = 0; i < _plan.Count; i++)
		{
			PlannedTower plannedTower = _plan[i];
			Vector3 position = plannedTower.Dir * _radius;
			if (!IsUnderwater(position))
			{
				continue;
			}
			num++;
			FoundationOutcome foundationOutcome;
			try
			{
				foundationOutcome = TryPaveFoundation(position, out var itemsUsed, out var sandUsed);
				if (foundationOutcome == FoundationOutcome.Paved)
				{
					_foundationPaved++;
					_foundationItemsUsed += itemsUsed;
					_foundationSandUsed += sandUsed;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = AutoConnectPowerPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("铺地基失败:" + ex));
				}
				foundationOutcome = FoundationOutcome.Failed;
			}
			if (foundationOutcome == FoundationOutcome.Failed)
			{
				plannedTower.Skip = true;
				_foundationSkipped++;
			}
		}
		if (_foundationSkipped > 0)
		{
			for (int num2 = _plan.Count - 1; num2 >= 0; num2--)
			{
				if (_plan[num2].Skip)
				{
					_plan.RemoveAt(num2);
				}
			}
		}
		if (_foundationPaved > 0 || _foundationSkipped > 0)
		{
			ManualLogSource log2 = AutoConnectPowerPlugin.Log;
			if (log2 != null)
			{
				log2.LogInfo((object)$"自动地基:水面/熔岩塔 {num},成功 {_foundationPaved},跳过 {_foundationSkipped}");
			}
		}
		_factory.BeginFlattenTerrain();
	}

	private FoundationOutcome TryPaveFoundation(Vector3 position, out int itemsUsed, out int sandUsed)
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: 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_012b: Unknown result type (might be due to invalid IL or missing references)
		itemsUsed = 0;
		sandUsed = 0;
		PlatformSystem platformSystem = _factory.platformSystem;
		if (platformSystem == null)
		{
			return FoundationOutcome.Failed;
		}
		platformSystem.EnsureReformData();
		Vector3 val = default(Vector3);
		int num = _planet.aux.ReformSnap(position, 0, 3, 1, 0, _foundationPoints, _foundationIndices, platformSystem, ref val);
		if (num <= 0)
		{
			int reformIndexForPosition = platformSystem.GetReformIndexForPosition(position);
			if (reformIndexForPosition >= 0 && platformSystem.IsTerrainReformed(platformSystem.GetReformType(reformIndexForPosition)))
			{
				return FoundationOutcome.Already;
			}
			return FoundationOutcome.Failed;
		}
		bool flag = true;
		for (int i = 0; i < num; i++)
		{
			int num2 = _foundationIndices[i];
			if (num2 < 0 || platformSystem.GetReformType(num2) != 1)
			{
				flag = false;
				break;
			}
		}
		if (flag)
		{
			return FoundationOutcome.Already;
		}
		if (_player.package.GetItemCount(1131) + _player.inhandItemCount < num)
		{
			return FoundationOutcome.Failed;
		}
		int num3 = 0;
		int num4 = 0;
		_factory.ComputeFlattenTerrainReform(_foundationPoints, val, 2.972838f, num, ref num3, ref num4, 3f, 1f);
		int num5 = ((!HasInfiniteSand()) ? (num3 - num4) : 0);
		long num6 = _player.sandCount - num5;
		if (num6 < 0)
		{
			_factory.BeginFlattenTerrain();
			return FoundationOutcome.Failed;
		}
		_factory.FlattenTerrainReform(val, 2.972838f, 3, false, 3f);
		if (num5 > 0)
		{
			_player.SetSandCount(num6, (ESandSource)0);
		}
		for (int j = 0; j < num; j++)
		{
			int num7 = _foundationIndices[j];
			if (num7 >= 0)
			{
				if (platformSystem.GetReformType(num7) != 1)
				{
					platformSystem.SetReformType(num7, 1);
				}
				if (platformSystem.GetReformColor(num7) != 0)
				{
					platformSystem.SetReformColor(num7, 0);
				}
			}
		}
		if (platformSystem.reformDataBuffer != null)
		{
			try
			{
				platformSystem.reformDataBuffer.SetData((Array)platformSystem.reformData);
			}
			catch (Exception)
			{
			}
		}
		int num8 = num;
		int num10 = default(int);
		if (_player.inhandItemId == 1131 && _player.inhandItemCount > 0)
		{
			int num9 = Mathf.Min(num8, _player.inhandItemCount);
			_player.UseHandItems(num9, ref num10);
			num8 -= num9;
		}
		if (num8 > 0)
		{
			int num11 = 1131;
			int num12 = num8;
			_player.package.TakeTailItems(ref num11, ref num12, ref num10, false);
		}
		itemsUsed = num;
		sandUsed = Mathf.Max(0, num5);
		if (GameMain.history != null)
		{
			GameMain.history.MarkItemBuilt(1131, num);
		}
		return FoundationOutcome.Paved;
	}

	private void Build(PlacementMode placement, out int built, out int ghosts)
	{
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		built = 0;
		ghosts = 0;
		if (_autoFoundation)
		{
			PaveFoundations();
		}
		bool flag = placement == PlacementMode.Direct;
		if (flag)
		{
			_factory.BeginFlattenTerrain();
			PlanetFactory.batchBuild = true;
		}
		try
		{
			foreach (PlannedTower item in _plan)
			{
				bool flag2 = false;
				if (flag)
				{
					flag2 = TakeTowerItem(item.ProtoId);
				}
				int itemRequired = ((!(flag && flag2)) ? 1 : 0);
				PrebuildData val = MakePrebuild(item, itemRequired);
				int num = _factory.AddPrebuildDataWithComponents(val);
				if (num > 0)
				{
					if (flag && flag2)
					{
						_factory.BuildFinally(_player, num, false, true);
						built++;
					}
					else
					{
						ghosts++;
					}
				}
			}
		}
		finally
		{
			if (flag)
			{
				PlanetFactory.batchBuild = false;
				_factory.EndFlattenTerrain();
				PlanetPhysics physics = _planet.physics;
				if (physics != null)
				{
					physics.SetPlanetPhysicsColliderDirty();
				}
				PlanetPhysics physics2 = _planet.physics;
				if (physics2 != null)
				{
					RaycastLogic raycastLogic = physics2.raycastLogic;
					if (raycastLogic != null)
					{
						raycastLogic.NotifyBatchObjectRemove();
					}
				}
				PlanetAudio audio = _planet.audio;
				if (audio != null)
				{
					audio.SetPlanetAudioDirty();
				}
			}
		}
	}

	private bool TakeTowerItem(int protoId)
	{
		int num = default(int);
		if (_player.inhandItemId == protoId && _player.inhandItemCount > 0)
		{
			_player.UseHandItems(1, ref num);
			return true;
		}
		int num2 = protoId;
		int num3 = 1;
		_player.package.TakeTailItems(ref num2, ref num3, ref num, false);
		if (num3 == 1)
		{
			return num2 == protoId;
		}
		return false;
	}

	private PrebuildData MakePrebuild(PlannedTower tower, int itemRequired)
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: 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_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: 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_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: 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_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: 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_00b9: Unknown result type (might be due to invalid IL or missing references)
		ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(tower.ProtoId);
		Vector3 val2 = tower.Dir * _radius;
		Quaternion val3 = Maths.SphericalRotation(val2, 0f);
		int num = ((val != null && val.prefabDesc != null && val.prefabDesc.modelIndex > 0) ? val.prefabDesc.modelIndex : (val?.ModelIndex ?? 0));
		return new PrebuildData
		{
			protoId = (short)tower.ProtoId,
			modelIndex = (short)num,
			pos = val2,
			pos2 = val2,
			rot = val3,
			rot2 = val3,
			isDestroyed = false,
			itemRequired = itemRequired,
			paramCount = 0
		};
	}

	private int CountNetworks()
	{
		HashSet<int> hashSet = new HashSet<int>();
		PowerNodeComponent[] nodePool = _power.nodePool;
		if (nodePool != null)
		{
			for (int i = 1; i < _power.nodeCursor; i++)
			{
				if (nodePool[i].id == i && nodePool[i].networkId > 0)
				{
					hashSet.Add(nodePool[i].networkId);
				}
			}
		}
		return hashSet.Count;
	}

	private int CountUncoveredConsumers()
	{
		int num = 0;
		PowerConsumerComponent[] consumerPool = _power.consumerPool;
		if (consumerPool != null)
		{
			for (int i = 1; i < _power.consumerCursor; i++)
			{
				if (consumerPool[i].id == i && consumerPool[i].networkId == 0)
				{
					num++;
				}
			}
		}
		return num;
	}

	private Vector3 RotateOnTangent(Vector3 dir, float angleDegrees, float distance)
	{
		//IL_000a: 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_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: 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)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: 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_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//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_0061: 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_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: 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_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: 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_0086: 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_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		float num = angleDegrees * (MathF.PI / 180f);
		Vector3 normalized = ((Vector3)(ref dir)).normalized;
		Vector3 val = Vector3.Cross(normalized, Vector3.up);
		if (((Vector3)(ref val)).sqrMagnitude < 0.0001f)
		{
			val = Vector3.Cross(normalized, Vector3.right);
		}
		((Vector3)(ref val)).Normalize();
		Vector3 val2 = Vector3.Cross(normalized, val);
		Vector3 normalized2 = ((Vector3)(ref val2)).normalized;
		Vector3 val3 = (val * Mathf.Cos(num) + normalized2 * Mathf.Sin(num)) * (distance / _radius);
		val2 = normalized + val3;
		return ((Vector3)(ref val2)).normalized;
	}

	private Vector3 StepTowards(Vector3 fromDir, Vector3 toDir, float chordDistance)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: 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_0059: 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)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: 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)
		float num = Mathf.Acos(Mathf.Clamp(Vector3.Dot(fromDir, toDir), -1f, 1f));
		if (num < 1E-05f)
		{
			return toDir;
		}
		float num2 = Mathf.Clamp(chordDistance / (2f * _radius), 0f, 1f);
		float num3 = Mathf.Clamp01(2f * Mathf.Asin(num2) / num);
		Vector3 val = Vector3.Slerp(fromDir, toDir, num3);
		return ((Vector3)(ref val)).normalized;
	}

	private float Chord(Vector3 a, Vector3 b)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		return Mathf.Sqrt(SqrChord(a, b));
	}

	private float SqrChord(Vector3 a, Vector3 b)
	{
		//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)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: 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_0021: Unknown result type (might be due to invalid IL or missing references)
		float num = a.x - b.x;
		float num2 = a.y - b.y;
		float num3 = a.z - b.z;
		return (num * num + num2 * num2 + num3 * num3) * _radius * _radius;
	}
}