Decompiled source of Shapez2Performance v0.2.0

plugins/Shapez2Performance.dll

Decompiled 2 hours ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Logging;
using Core.Collections.Disposables;
using Core.Collections.Scoped;
using Core.Events;
using Core.Events.Logging;
using Core.Logging;
using Game.Content.BuildingPath;
using Game.Content.BuildingPath.Simulation;
using Game.Core.Blueprint;
using Game.Core.Blueprint.Exporter;
using Game.Core.Blueprint.Importer;
using Game.Core.Blueprint.Importer.Deserialization;
using Game.Core.Blueprint.Importer.Writing;
using Game.Core.Blueprints;
using Game.Core.BunchEditing;
using Game.Core.Coordinates;
using Game.Core.Logic;
using Game.Core.Map.Simulation;
using Game.Core.Map.Simulation.Clustering;
using Game.Core.Mode;
using Game.Core.Rendering.Islands.Chunks;
using Game.Core.Simulation;
using Game.HUD.BlueprintPlacement;
using Game.Interaction.EntitiesPlacement;
using Game.Interaction.EntitiesPlacement.BlueprintPlacement;
using Game.Interaction.EntitiesPlacement.PlacerBuilders.Processors;
using Game.Placement.Data;
using Game.Placement.Processing;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.UI;

[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("Shapez2Performance")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0+f8fa657bb7e5f0f02dfacf92daa900c73f43c0d9")]
[assembly: AssemblyProduct("Shapez2Performance")]
[assembly: AssemblyTitle("Shapez2Performance")]
[assembly: AssemblyVersion("0.2.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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]
	[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;
		}
	}
}
namespace Shapez2Performance
{
	internal static class BlueprintAutoCopy
	{
		private sealed class Request
		{
			internal readonly IBlueprintExporter Exporter;

			internal readonly IAnnotatedBlueprint Blueprint;

			internal readonly string PreviousClipboard;

			internal Request(IBlueprintExporter exporter, IAnnotatedBlueprint blueprint, string previousClipboard)
			{
				Exporter = exporter;
				Blueprint = blueprint;
				PreviousClipboard = previousClipboard;
			}
		}

		private const int BackgroundBuildingCount = 10000;

		private static Task<string>? _working;

		private static Request? _current;

		private static Request? _queued;

		private static ManualLogSource? _log;

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(HUDBlueprintHistory), "OnPlacementChange", (Type[])null, (Type[])null) ?? throw new MissingMethodException("HUDBlueprintHistory", "OnPlacementChange");
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(HUDBlueprintHistory), "OnDispose", (Type[])null, (Type[])null) ?? throw new MissingMethodException("HUDBlueprintHistory", "OnDispose");
			_log = log;
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(BlueprintAutoCopy), "DeferExport", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(BlueprintAutoCopy), "Cancel", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static IEnumerable<CodeInstruction> DeferExport(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo export = AccessTools.DeclaredMethod(typeof(IBlueprintExporter), "Export", (Type[])null, (Type[])null);
			MethodInfo methodInfo = AccessTools.PropertySetter(typeof(GUIUtility), "systemCopyBuffer");
			int num = list.FindIndex((CodeInstruction op) => CodeInstructionExtensions.Calls(op, export));
			if (num < 0 || num + 1 >= list.Count || !CodeInstructionExtensions.Calls(list[num + 1], methodInfo))
			{
				throw new InvalidOperationException("找不到选择蓝图后自动复制的调用。");
			}
			list[num].opcode = OpCodes.Call;
			list[num].operand = AccessTools.DeclaredMethod(typeof(BlueprintAutoCopy), "Copy", (Type[])null, (Type[])null);
			list[num + 1].opcode = OpCodes.Nop;
			list[num + 1].operand = null;
			return list;
		}

		private static void Cancel()
		{
			_queued = null;
			_current = null;
		}

		private static void Copy(IBlueprintExporter exporter, IAnnotatedBlueprint blueprint)
		{
			Cancel();
			AnnotatedIslandBlueprint val = (AnnotatedIslandBlueprint)(object)((blueprint is AnnotatedIslandBlueprint) ? blueprint : null);
			int num;
			if (val == null)
			{
				AnnotatedBuildingBlueprint val2 = (AnnotatedBuildingBlueprint)(object)((blueprint is AnnotatedBuildingBlueprint) ? blueprint : null);
				num = ((val2 != null) ? val2.BuildingBlueprint.Entries.Length : 0);
			}
			else
			{
				num = val.IslandBlueprint.BuildingCount;
			}
			if (num < 10000 || ((object)exporter).GetType() != typeof(BlueprintExporter))
			{
				GUIUtility.systemCopyBuffer = exporter.Export(blueprint);
				return;
			}
			_queued = new Request(exporter, blueprint, GUIUtility.systemCopyBuffer);
			StartQueued();
		}

		private static void StartQueued()
		{
			if (_working != null)
			{
				return;
			}
			Request request = _queued;
			if (request != null)
			{
				_queued = null;
				_current = request;
				_working = Task.Run(() => request.Exporter.Export(request.Blueprint));
			}
		}

		internal static void Update()
		{
			Task<string> working = _working;
			if (working == null || !working.IsCompleted)
			{
				return;
			}
			try
			{
				string result = working.GetAwaiter().GetResult();
				Request current = _current;
				if (current != null && GUIUtility.systemCopyBuffer == current.PreviousClipboard)
				{
					GUIUtility.systemCopyBuffer = result;
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = _log;
				if (log != null)
				{
					log.LogWarning((object)("[blueprint preview] 自动复制蓝图失败。" + ex.GetBaseException().Message));
				}
			}
			finally
			{
				_working = null;
				_current = null;
				StartQueued();
			}
		}
	}
	internal sealed class BlueprintBenchmark
	{
		private enum Phase
		{
			Start,
			RemovalChecked,
			WaitingForPreview,
			Preview,
			PreviewDetails,
			PreviewResumed,
			PreviewDone,
			Place,
			Placed,
			Remove,
			Redo,
			Redone,
			Delete,
			Removed
		}

		private sealed class ScriptedCursor : IPlacementTracker
		{
			internal const int PreviewPositions = 3;

			internal static readonly GlobalChunkCoordinate Anchor = new GlobalChunkCoordinate(80, 80, (short)0);

			private const int FramesPerPosition = 4;

			private int _frames;

			private bool _confirmed;

			internal int PreviewMoves { get; private set; }

			internal GlobalChunkCoordinate? ConflictAnchor { get; set; }

			internal bool AtConflictAnchor { get; private set; }

			internal bool ConfirmRequested { get; set; }

			internal ChunkVector DetailOffset { get; set; }

			internal PlatformDetailPreview.PreviewSample? DetailSample { get; set; }

			internal bool ResumeMoving { get; set; }

			public void Track(InputDownstreamContext inputContext, Viewport viewport, PlacementInputHolder placementInput, IReadOnlyMapLayoutModel map, IPlacementData placementData, IPlacementErrors placementErrors, out bool inputUpdated)
			{
				//IL_007b: Unknown result type (might be due to invalid IL or missing references)
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0080: 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_0091: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ca: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0109: Unknown result type (might be due to invalid IL or missing references)
				//IL_0110: Unknown result type (might be due to invalid IL or missing references)
				BlueprintPlacementInput<GlobalChunkCoordinate> val = ((PlacementInputHolder)(ref placementInput)).As<BlueprintPlacementInput<GlobalChunkCoordinate>>();
				int num = _frames++ - (ConflictAnchor.HasValue ? 1 : 0);
				int num2 = (ResumeMoving ? 3 : Math.Min(Math.Max(num, 0) / 4, 2));
				AtConflictAnchor = num < 0;
				GlobalChunkCoordinate val2 = (AtConflictAnchor ? ConflictAnchor.Value : (Anchor + new ChunkVector(num2, 0, (short)0)));
				if (DetailSample != null)
				{
					DetailSample.Cursor = val2 + DetailOffset;
				}
				bool flag = ConfirmRequested && !_confirmed;
				int num3;
				if (val.StartedPlacement)
				{
					GlobalChunkCoordinate val3 = val.StartPosition;
					if (((GlobalChunkCoordinate)(ref val3)).Equals(val2))
					{
						val3 = val.EndPosition;
						num3 = ((!((GlobalChunkCoordinate)(ref val3)).Equals(val2)) ? 1 : 0);
						goto IL_00e8;
					}
				}
				num3 = 1;
				goto IL_00e8;
				IL_00e8:
				inputUpdated = (byte)((uint)num3 | (flag ? 1u : 0u)) != 0;
				if (!AtConflictAnchor)
				{
					PreviewMoves = Math.Max(PreviewMoves, num2 + 1);
				}
				val.StartPosition = val2;
				val.EndPosition = val2;
				val.StartedPlacement = true;
				val.StartedDragging = false;
				val.Confirmed = flag;
				val.Cancelled = false;
				val.UseForce = false;
				_confirmed |= flag;
			}
		}

		private const int SettleFrames = 60;

		private readonly bool _verifyEdits = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-verify-blueprint-edits", StringComparer.Ordinal);

		private readonly bool _asyncPreview = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-async-blueprint-preview", StringComparer.Ordinal);

		private readonly bool _clipboardPreview = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-clipboard-preview", StringComparer.Ordinal);

		private readonly bool _checkPlatformWarning = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-check-platform-warning", StringComparer.Ordinal);

		internal const string PreviewOnlyArgument = "--mlj-perf-preview-only";

		private readonly bool _previewOnly = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-preview-only", StringComparer.Ordinal);

		private readonly bool _checkDetails = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-preview-details", StringComparer.Ordinal);

		private readonly bool _checkConveyorRemoval = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-check-conveyor-delete", StringComparer.Ordinal);

		private readonly bool _checkSignalRemoval = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-check-signal-delete", StringComparer.Ordinal);

		private readonly ManualLogSource _log;

		private readonly string _blueprintPath;

		private readonly ScriptedCursor _cursor = new ScriptedCursor();

		private readonly Stopwatch _timer = new Stopwatch();

		private readonly Stopwatch _pasteTimer = new Stopwatch();

		private Phase _phase;

		private int _frames;

		private int _initialIslands;

		private int _initialBuildings;

		private HashSet<IslandId>? _originalIslands;

		private int _placedIslands;

		private int _placedBuildings;

		private int _previousBatchedPaths;

		private int _previousBatchedBelts;

		private IBlueprintStarter? _starter;

		private MapModel _map;

		private PlayerActionManager _actions;

		private EntityPlacementRunner _runner;

		private bool _checkedConflict;

		private bool _reportedFirstPreview;

		private int _expectedDetails;

		internal bool IsOverdue => _timer.Elapsed.TotalSeconds >= 300.0;

		internal bool PreviewOnlyCompleted { get; private set; }

		internal BlueprintBenchmark(ManualLogSource log, string blueprintPath)
		{
			_log = log;
			_blueprintPath = blueprintPath;
		}

		internal string? Advance(GameSessionOrchestrator session, string uid)
		{
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_085e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0863: Unknown result type (might be due to invalid IL or missing references)
			//IL_086d: Expected O, but got Unknown
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			_frames++;
			switch (_phase)
			{
			case Phase.Start:
				_map = ReadField<MapModel>(session, "MapModel");
				_actions = ReadField<PlayerActionManager>(session, "PlayerActions");
				if (_checkConveyorRemoval || _checkSignalRemoval)
				{
					AccessTools.MethodDelegate<Action<GameSessionOrchestrator>>(AccessTools.DeclaredMethod(typeof(GameSessionOrchestrator), "FinalizeLogicUpdate", (Type[])null, (Type[])null), (object)null, true)(session);
					Simulator simulator = ReadField<Simulator>(session, "Simulator");
					GameMode mode = ReadField<GameMode>(session, "Mode");
					if (_checkConveyorRemoval)
					{
						ConveyorRemovalBenchmark.Check(_map, _actions, ReadField<Player>(_actions, "Player"), simulator, mode, ReadField<ShapeRegistry>(session, "ShapeRegistry").GetItem(ReadField<ShapeIdManager>(session, "ShapeIdManager").Resolve("CuCuCuCu")), _log);
						TimingProbe.ReportTick("传送带拆除校验");
					}
					if (_checkSignalRemoval)
					{
						SignalRemovalBenchmark.Check(_map, simulator, mode, _log);
						TimingProbe.ReportTick("信号线路拆除校验");
					}
					Enter(Phase.RemovalChecked);
					break;
				}
				goto case Phase.RemovalChecked;
			case Phase.RemovalChecked:
				_initialIslands = _map.IslandCount;
				_initialBuildings = _map.BuildingCount;
				if (_verifyEdits)
				{
					_originalIslands = _map.Islands.Select((IslandModel island) => ((IslandModel)(ref island)).Id).ToHashSet();
				}
				TimingProbe.ReportTick("放置前");
				_log.LogInfo((object)("[blueprint benchmark] 开始采样 " + Path.GetFileName(_blueprintPath) + "。"));
				StartPreview(session);
				Enter(StartPreviewPhase());
				break;
			case Phase.WaitingForPreview:
			{
				IEntityPlacer placer = default(IEntityPlacer);
				if (_runner.TryGetCurrentPlacer(ref placer))
				{
					if (_frames < 2)
					{
						throw new InvalidOperationException("大型蓝图没有在后台等待解析。");
					}
					string arg = (_clipboardPreview ? "粘贴" : "点选");
					_log.LogInfo((object)$"[blueprint benchmark] {arg}后经过 {_frames} 次游戏更新启用预览,耗时 {ElapsedMilliseconds()} 毫秒。");
					SetUpCursor(session.Viewport, placer);
					Enter(Phase.Preview);
				}
				break;
			}
			case Phase.Preview:
			{
				IEntityPlacer val = default(IEntityPlacer);
				if (_cursor.AtConflictAnchor && !_checkedConflict)
				{
					IPlacementData val2 = default(IPlacementData);
					if (_runner.TryGetCurrentPlacer(ref val, ref val2))
					{
						IFlatPlacementData val3 = (IFlatPlacementData)(object)((val2 is IFlatPlacementData) ? val2 : null);
						if (val3 != null && val3.Islands.Count != 0)
						{
							IslandPlacement val4 = val3.Islands[0];
							if (!BuildingPlacementFeedbackExtensions.WillBePlaced(((IslandPlacement)(ref val4)).PlacementAllowability))
							{
								_checkedConflict = true;
								TimingProbe.ReportTick("平台冲突预览");
								_log.LogInfo((object)"[blueprint benchmark] 已核对平台冲突标记。");
								break;
							}
						}
					}
					throw new InvalidOperationException("与沙盒原有平台重叠的蓝图平台没有标为冲突。");
				}
				if ((_clipboardPreview || _previewOnly) && !_reportedFirstPreview && _cursor.PreviewMoves == 1)
				{
					if (_clipboardPreview)
					{
						_log.LogInfo((object)$"[blueprint benchmark] 粘贴到首个可用预览耗时 {_pasteTimer.Elapsed.TotalMilliseconds:F2} 毫秒。");
					}
					TimingProbe.ReportTick("首帧预览");
					_reportedFirstPreview = true;
				}
				else if (_cursor.PreviewMoves == 3)
				{
					TimingProbe.ReportTick("移动预览");
					IEntityPlacer val5 = default(IEntityPlacer);
					IPlacementData data = default(IPlacementData);
					if (PlatformFootprintPreview.Enabled && _runner.TryGetCurrentPlacer(ref val5, ref data))
					{
						CheckConfirmation(val5.PlacementInput, data, hasPreview: true);
					}
					IPlacementData val6 = default(IPlacementData);
					if (_runner.TryGetCurrentPlacer(ref val, ref val6))
					{
						IFlatPlacementData val7 = (IFlatPlacementData)(object)((val6 is IFlatPlacementData) ? val6 : null);
						if (val7 != null)
						{
							_log.LogInfo((object)$"[blueprint benchmark] 预览展开了 {val7.Islands.Count} 个平台和 {val7.Buildings.Count} 座建筑。");
						}
					}
					if (_previewOnly)
					{
						if (_checkDetails)
						{
							if (_cursor.DetailSample.DrawnBuildings != 0)
							{
								throw new InvalidOperationException("改变落点时仍在显示建筑细节。");
							}
							Enter(Phase.PreviewDetails);
						}
						else
						{
							Stop();
							PreviewOnlyCompleted = true;
						}
					}
					else
					{
						_cursor.ConfirmRequested = true;
						_log.LogInfo((object)$"[blueprint benchmark] 已移动预览 {_cursor.PreviewMoves} 次,开始确认放置。");
						Enter(Phase.Place);
					}
				}
				else if (_frames >= 60)
				{
					throw new InvalidOperationException("游戏未完成蓝图预览。");
				}
				break;
			}
			case Phase.PreviewDetails:
				if (_timer.ElapsedMilliseconds >= 650)
				{
					int drawnBuildings = _cursor.DetailSample.DrawnBuildings;
					if (drawnBuildings != _expectedDetails)
					{
						throw new InvalidOperationException($"停稳后绘制了 {drawnBuildings} 座建筑,预期 {_expectedDetails} 座。");
					}
					_log.LogInfo((object)$"[blueprint benchmark] 停稳后绘制了 {drawnBuildings} 座建筑。");
					TimingProbe.ReportTick("停稳细节预览");
					_cursor.ResumeMoving = true;
					Enter(Phase.PreviewResumed);
				}
				break;
			case Phase.PreviewResumed:
				if (_cursor.DetailSample.DrawnBuildings != 0)
				{
					throw new InvalidOperationException("重新移动时仍在显示建筑细节。");
				}
				TimingProbe.ReportTick("再次移动预览");
				_log.LogInfo((object)"[blueprint benchmark] 再次移动时只显示平台。");
				Enter(Phase.PreviewDone);
				break;
			case Phase.PreviewDone:
				Stop();
				PreviewOnlyCompleted = true;
				break;
			case Phase.Place:
				if (_map.IslandCount > _initialIslands)
				{
					TimingProbe.ReportTick("确认放置");
					IBlueprintStarter? starter = _starter;
					if (starter != null)
					{
						starter.StopBlueprintPlacement();
					}
					_starter = null;
					_placedIslands = _map.IslandCount;
					_placedBuildings = _map.BuildingCount;
					_log.LogInfo((object)$"[blueprint benchmark] 放置完成,平台 +{_map.IslandCount - _initialIslands},建筑 +{_map.BuildingCount - _initialBuildings},耗时 {ElapsedMilliseconds()} 毫秒。");
					Enter(Phase.Placed);
				}
				else if (_frames >= 60)
				{
					throw new InvalidOperationException("放置后平台数量没有增加。请检查蓝图、坐标和游戏放置限制。");
				}
				break;
			case Phase.Placed:
				if (_frames >= 60)
				{
					TimingProbe.ReportTick("放置后");
					if (!_actions.CanUndo())
					{
						throw new InvalidOperationException("游戏没有记录可撤销的放置动作。");
					}
					_actions.ScheduleUndo();
					_log.LogInfo((object)"[blueprint benchmark] 开始撤销放置。");
					Enter(Phase.Remove);
				}
				break;
			case Phase.Remove:
				if (_map.IslandCount == _initialIslands && _map.BuildingCount == _initialBuildings)
				{
					TimingProbe.ReportTick("撤销放置");
					_log.LogInfo((object)("[blueprint benchmark] 平台和建筑数量已恢复,撤销耗时 " + ElapsedMilliseconds() + " 毫秒。"));
					if (_verifyEdits)
					{
						if (!_actions.CanRedo())
						{
							throw new InvalidOperationException("游戏没有记录可重做的放置动作。");
						}
						_actions.ScheduleRedo();
						Enter(Phase.Redo);
					}
					else
					{
						Enter(Phase.Removed);
					}
				}
				else if (_frames >= 60)
				{
					throw new InvalidOperationException("撤销后平台或建筑数量没有恢复。");
				}
				break;
			case Phase.Redo:
				if (_map.IslandCount == _placedIslands && _map.BuildingCount == _placedBuildings)
				{
					TimingProbe.ReportTick("重做放置");
					_log.LogInfo((object)("[blueprint benchmark] 重做恢复了平台和建筑数量,用时 " + ElapsedMilliseconds() + " 毫秒。"));
					Enter(Phase.Redone);
					break;
				}
				goto IL_0934;
			case Phase.Redone:
				if (_frames >= 60)
				{
					DeletePayload[] array = _map.Islands.Where((IslandModel island) => !_originalIslands.Contains(((IslandModel)(ref island)).Id)).Select((Func<IslandModel, DeletePayload>)((IslandModel island) => new DeletePayload(((IslandModel)(ref island)).Id))).ToArray();
					Player val8 = ReadField<Player>(_actions, "Player");
					if (array.Length != _placedIslands - _initialIslands || !_actions.TryScheduleAction((IPlayerAction)new ActionModifyIsland((IMapModel)(object)_map, val8, new Payload((IReadOnlyList<DeletePayload>)array, false, false))))
					{
						throw new InvalidOperationException("无法提交平台拆除动作。");
					}
					_previousBatchedPaths = ConveyorPathRemoval.BatchedPaths;
					_previousBatchedBelts = ConveyorPathRemoval.BatchedBuildings;
					Enter(Phase.Delete);
				}
				break;
			case Phase.Delete:
				if (_map.IslandCount == _initialIslands && _map.BuildingCount == _initialBuildings)
				{
					TimingProbe.ReportTick("主动拆除");
					_log.LogInfo((object)("[blueprint benchmark] 主动拆除后平台和建筑数量已恢复,用时 " + ElapsedMilliseconds() + " 毫秒。"));
					_log.LogInfo((object)$"[blueprint benchmark] 批量注销了 {ConveyorPathRemoval.BatchedPaths - _previousBatchedPaths} 条传送带路径,共 {ConveyorPathRemoval.BatchedBuildings - _previousBatchedBelts} 格。");
					Enter(Phase.Removed);
					break;
				}
				goto IL_0934;
			case Phase.Removed:
				{
					if (_frames >= 60)
					{
						TimingProbe.ReportTick("撤销后");
						_timer.Restart();
						if (!session.TrySaveCurrentSync())
						{
							throw new InvalidOperationException("游戏未能保存撤销后的存档。");
						}
						string text = ReadField<SavegameManager>(session, "SavegamesManager").FindMostRecentSavegameEntryByUid(uid)?.FullPath ?? throw new InvalidOperationException("未找到撤销后的存档文件。");
						_log.LogInfo((object)("[blueprint benchmark] 撤销后存档写入耗时 " + ElapsedMilliseconds() + " 毫秒。" + text));
						return text;
					}
					break;
				}
				IL_0934:
				if (_frames >= 60)
				{
					throw new InvalidOperationException("重做或主动拆除后,平台与建筑数量不符合预期。");
				}
				break;
			}
			return null;
		}

		internal void Stop()
		{
			if (_cursor.DetailSample != null)
			{
				PlatformDetailPreview.BenchmarkSample = null;
			}
			IBlueprintStarter? starter = _starter;
			if (starter != null)
			{
				starter.StopBlueprintPlacement();
			}
			_starter = null;
		}

		private Phase StartPreviewPhase()
		{
			IEntityPlacer val = default(IEntityPlacer);
			if ((!_clipboardPreview && !_asyncPreview) || _runner.TryGetCurrentPlacer(ref val))
			{
				return Phase.Preview;
			}
			return Phase.WaitingForPreview;
		}

		private void StartPreview(GameSessionOrchestrator session)
		{
			IBlueprintImporter val = ReadField<IBlueprintImporter>(ReadField<BlueprintLibrary>(session, "BlueprintLibrary"), "BlueprintImporter");
			object owner = ReadField<object>(session, "PlayerInteractionOrchestrator");
			_starter = ReadField<IBlueprintStarter>(owner, "_BlueprintStarter");
			_runner = ReadField<EntityPlacementRunner>(owner, "EntityPlacementRunner");
			if (_clipboardPreview)
			{
				string arg = File.ReadAllText(_blueprintPath).Trim();
				HUDBlueprintHistory arg2 = Object.FindFirstObjectByType<HUDBlueprintHistory>() ?? throw new InvalidOperationException("游戏未启动蓝图历史 HUD。");
				Action<HUDBlueprintHistory, string> action = AccessTools.MethodDelegate<Action<HUDBlueprintHistory, string>>(AccessTools.DeclaredMethod(typeof(HUDBlueprintHistory), "HandleBlueprintPaste", new Type[1] { typeof(string) }, (Type[])null), (object)null, true);
				_timer.Restart();
				_pasteTimer.Restart();
				action(arg2, arg);
				_log.LogInfo((object)("[blueprint benchmark] 粘贴调用返回耗时 " + ElapsedMilliseconds() + " 毫秒。"));
				TimingProbe.ReportTick("粘贴调用");
				IEntityPlacer placer = default(IEntityPlacer);
				if (_runner.TryGetCurrentPlacer(ref placer))
				{
					SetUpCursor(session.Viewport, placer);
				}
				return;
			}
			_timer.Restart();
			if (_asyncPreview)
			{
				LibraryBlueprintFile libraryBlueprintFile = new LibraryBlueprintFile(_blueprintPath, val, _log);
				_starter.StartBlueprintPlacement(libraryBlueprintFile.Entry.Blueprint, (GridRotation?)null);
				return;
			}
			IAnnotatedBlueprint val2 = default(IAnnotatedBlueprint);
			int num = default(int);
			BlueprintException ex = default(BlueprintException);
			if (!val.TryImport(File.ReadAllText(_blueprintPath), ref val2, ref num, ref ex))
			{
				throw new InvalidOperationException("蓝图导入失败。" + ((Exception)(object)ex).Message);
			}
			_log.LogInfo((object)("[blueprint benchmark] 导入 " + Path.GetFileName(_blueprintPath) + " 耗时 " + ElapsedMilliseconds() + " 毫秒。"));
			_starter.StartBlueprintPlacement(val2, (GridRotation?)null);
			IEntityPlacer placer2 = default(IEntityPlacer);
			if (!_runner.TryGetCurrentPlacer(ref placer2))
			{
				throw new InvalidOperationException("游戏未启动平台蓝图放置。");
			}
			SetUpCursor(session.Viewport, placer2);
		}

		private void SetUpCursor(Viewport viewport, IEntityPlacer placer)
		{
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0279: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_0296: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c8: Expected O, but got Unknown
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: 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_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: 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_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: 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_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			if (placer is ModularEntityPlacer<FlatPlacementData> val)
			{
				IAnnotatedBlueprint obj = BlueprintPlacementExtensions.CurrentBlueprintOrDefault((IEntityPlacementRunner)(object)_runner);
				AnnotatedIslandBlueprint val2 = (AnnotatedIslandBlueprint)(object)((obj is AnnotatedIslandBlueprint) ? obj : null);
				if (val2 != null)
				{
					if (_checkPlatformWarning)
					{
						CheckPlatformWarning(val2.IslandBlueprint);
					}
					ChunkVector val7;
					IslandModel val11 = default(IslandModel);
					if (_previewOnly)
					{
						IslandBlueprint islandBlueprint = val2.IslandBlueprint;
						bool flag = islandBlueprint.Entries.Length <= 16 && islandBlueprint.BuildingCount <= 2504;
						Entry val3 = islandBlueprint.Entries.First((Entry entry) => entry.BuildingBlueprint != null);
						int num = val3.BuildingBlueprint.BuildingCount;
						if (_checkDetails && !flag)
						{
							Entry[] entries = islandBlueprint.Entries;
							foreach (Entry val4 in entries)
							{
								BuildingBlueprint buildingBlueprint = val4.BuildingBlueprint;
								int num3 = ((buildingBlueprint != null) ? buildingBlueprint.BuildingCount : 0);
								if (num3 > 0 && num3 <= 1000 && (num > 1000 || num3 > num))
								{
									val3 = val4;
									num = num3;
								}
							}
						}
						ChunkVector val5 = val3.Chunk_L;
						if (_checkDetails)
						{
							GlobalChunkTransform val6 = default(GlobalChunkTransform);
							((GlobalChunkTransform)(ref val6))..ctor(ScriptedCursor.Anchor + val5, val3.Rotation);
							val7 = val3.Definition.Layout.GetChunkPositions()[0];
							val5 = ((ChunkVector)(ref val7)).ToGlobal(ref val6) - ScriptedCursor.Anchor;
							_expectedDetails = (flag ? islandBlueprint.BuildingCount : ((num <= 1000) ? num : 0));
							_cursor.DetailOffset = val5;
							_cursor.DetailSample = new PlatformDetailPreview.PreviewSample();
							PlatformDetailPreview.BenchmarkSample = _cursor.DetailSample;
						}
						GlobalChunkCoordinate val8 = ScriptedCursor.Anchor + val5;
						WorldCoordinate val9 = ((GlobalChunkCoordinate)(ref val8)).ToCenter_W();
						SerializedData val10 = viewport.Serialize();
						val10.PositionX = val9.x;
						val10.PositionY = val9.z;
						val10.Zoom = 24f;
						viewport.Deserialize(val10);
						TimingProbe.ReportTick("点选蓝图");
					}
					else if (PlatformFootprintPreview.Enabled && _map.TryGetIsland(GlobalChunkCoordinate.Origin, ref val11))
					{
						Entry val12 = val2.IslandBlueprint.Entries[0];
						GlobalChunkTransform val13 = default(GlobalChunkTransform);
						((GlobalChunkTransform)(ref val13))..ctor(GlobalChunkCoordinate.Origin + val12.Chunk_L, val12.Rotation);
						val7 = val12.Definition.Layout.GetChunkPositions()[0];
						GlobalChunkCoordinate val14 = ((ChunkVector)(ref val7)).ToGlobal(ref val13);
						_cursor.ConflictAnchor = GlobalChunkCoordinate.Origin - (val14 - GlobalChunkCoordinate.Origin);
						FlatPlacementData val15 = new FlatPlacementData(ReadField<ILogger>(_map, "Logger"));
						try
						{
							CheckConfirmation(placer.PlacementInput, (IPlacementData)(object)val15, hasPreview: false);
						}
						finally
						{
							((IDisposable)val15)?.Dispose();
						}
					}
					val.RemoveTracker<MousePlacementTracker<GlobalChunkCoordinate>>();
					val.RemoveTracker<CompletePlacementTracker>();
					val.AddTrackerAtEnd((IPlacementTracker)(object)_cursor);
					return;
				}
			}
			throw new InvalidOperationException("本次采样需要平台蓝图。");
		}

		private void CheckPlatformWarning(IslandBlueprint sample)
		{
			//IL_0072: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: 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_00bb: Expected O, but got Unknown
			//IL_00bb: 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_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017f: Expected O, but got Unknown
			//IL_0183: 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_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cb: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_021b: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: 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_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0244: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0269: Unknown result type (might be due to invalid IL or missing references)
			//IL_026e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			//IL_0288: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0291: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: Expected O, but got Unknown
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			IViewportLayersController val = ReadField<IViewportLayersController>(_starter, "ViewportLayersController");
			IInteractionMode val2 = ReadField<IInteractionMode>(_starter, "InteractionMode");
			Player val3 = ReadField<Player>(_starter, "Player");
			Entry val4 = sample.Entries.First(delegate(Entry entry)
			{
				BuildingBlueprint buildingBlueprint = entry.BuildingBlueprint;
				return buildingBlueprint != null && buildingBlueprint.BuildingCount > 0;
			});
			Entry val5 = val4.BuildingBlueprint.Entries[0];
			TileVector val6 = default(TileVector);
			((TileVector)(ref val6))..ctor(0, 0, (short)(val.MaxBuildingLayer + 1));
			BuildingBlueprint val7 = new BuildingBlueprint((IEnumerable<Entry>)(object)new Entry[1]
			{
				new Entry(val5.Definition, val6, val5.Rotation, val5.AdditionalConfigData)
			});
			GlobalChunkCoordinate origin = GlobalChunkCoordinate.Origin;
			IReadOnlyList<ChunkVector> chunkPositions = val4.Definition.Layout.GetChunkPositions();
			ChunkVector val8 = default(ChunkVector);
			((ChunkVector)(ref val8))..ctor(chunkPositions.Max((ChunkVector tile) => tile.x) - chunkPositions.Min((ChunkVector tile) => tile.x) + 1, 0, (short)0);
			IslandBlueprint val9 = new IslandBlueprint((IEnumerable<Entry>)(object)new Entry[2]
			{
				new Entry(val4.Definition, default(ChunkVector), GridRotation.NoRotate, val4.Configuration, val7),
				new Entry(val4.Definition, val8, GridRotation.NoRotate, val4.Configuration, (BuildingBlueprint)null)
			});
			ChunkVector val10 = default(ChunkVector);
			((ChunkVector)(ref val10))..ctor(val9.Dimensions.x, 0, (short)0);
			BlueprintPlacementInput<GlobalChunkCoordinate> val11 = new BlueprintPlacementInput<GlobalChunkCoordinate>(GridRotation.NoRotate, false)
			{
				StartPosition = origin,
				EndPosition = origin + val10
			};
			PlacementInputHolder val12 = default(PlacementInputHolder);
			((PlacementInputHolder)(ref val12))..ctor((IPlacementInput)(object)val11);
			BlueprintBuildingStaticAllowabilityCacheComputer val13 = new BlueprintBuildingStaticAllowabilityCacheComputer(val, val2, val3);
			FlatPlacementData val14 = new FlatPlacementData(ReadField<ILogger>(_map, "Logger"));
			try
			{
				val14.AdditionalData.AttachData<ICachedBlueprintData>(val13.ComputeData((IBlueprint)(object)val9));
				GlobalChunkCoordinate[] positions = (GlobalChunkCoordinate[])(object)new GlobalChunkCoordinate[5]
				{
					origin,
					origin + val8,
					origin + val10,
					origin + val10 + val8,
					origin + val10 + val10
				};
				GlobalChunkTransform val15 = default(GlobalChunkTransform);
				for (int num = 0; num < positions.Length; num++)
				{
					((GlobalChunkTransform)(ref val15))..ctor(positions[num], GridRotation.NoRotate);
					IslandDescriptor val16 = new IslandDescriptor(val4.Definition, ref val15, (IIslandConfiguration)null, (SimulationStateContainer)null);
					val14.AddIslandPlacement(new IslandPlacement(val16, (PlacementAllowability)3, num));
				}
				PlacementIslandsDrawer val17 = new PlacementIslandsDrawer((IReadOnlyMapLayout)(object)_map.Layout, (IIslandPreviewDrawer)null);
				val17.SetNewPlacementData((IPlacementData)(object)val14, val12);
				Dictionary<GlobalChunkCoordinate, PlacementAllowability> colors = ReadField<List<IslandPreviewRenderData>>(val17, "DrawData").ToDictionary((IslandPreviewRenderData entry) => entry.Transform.Position, (IslandPreviewRenderData entry) => entry.PlacementAllowability);
				if (positions.Where(delegate(GlobalChunkCoordinate _, int i)
				{
					//IL_000d: 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_0018: Invalid comparison between Unknown and I4
					bool flag = (int)colors[positions[i]] == 0;
					bool flag2 = ((i == 0 || i == 2) ? true : false);
					return flag != flag2;
				}).Any() || val14.Islands.Any((IslandPlacement entry) => !BuildingPlacementFeedbackExtensions.WillBePlaced(((IslandPlacement)(ref entry)).PlacementAllowability)))
				{
					throw new InvalidOperationException("超层建筑的提示没有只标红蓝图副本中受影响的平台。");
				}
				_log.LogInfo((object)"[blueprint benchmark] 已核对超层建筑会标红两个副本中的对应平台,不改变平台的实际放置判定。");
			}
			finally
			{
				((IDisposable)val14)?.Dispose();
			}
		}

		private void CheckConfirmation(PlacementInputHolder input, IPlacementData data, bool hasPreview)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_004b: 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_0066: Expected O, but got Unknown
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_0089: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: 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_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: 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)
			IEntityPlacer val = default(IEntityPlacer);
			if (!_runner.TryGetCurrentPlacer(ref val) || !(val is ModularEntityPlacer<FlatPlacementData> val2))
			{
				throw new InvalidOperationException("找不到蓝图预览输入处理器。");
			}
			IPlacementTracker val3 = val2.PlacementTrackers[0];
			CompletePlacementTracker val4 = new CompletePlacementTracker();
			KeySet val5 = default(KeySet);
			((KeySet)(ref val5))..ctor((KeyCode)323, (KeyCode)0, (KeyCode)0, (ControllerBinding)0);
			Keybinding val6 = new Keybinding("building-placement.confirm-placement", val5, (KeySet?)null, true, false, 0.001f, (string)null);
			InputDownstreamContext val7 = new InputDownstreamContext((IReadOnlyDictionary<string, Keybinding>)new Dictionary<string, Keybinding> { ["building-placement.confirm-placement"] = val6 });
			(Keybinding, KeySet)[] array = new(Keybinding, KeySet)[1] { (val6, val5) };
			(Keybinding, KeySet)[] array2 = Array.Empty<(Keybinding, KeySet)>();
			val7.Update((IEnumerable<ValueTuple<Keybinding, KeySet>>)array2, (IEnumerable<ValueTuple<Keybinding, KeySet>>)array, default(float2), default(float2), 0f, (GameObject)null);
			bool flag = default(bool);
			val3.Track(val7, (Viewport)null, input, (IReadOnlyMapLayoutModel)null, data, (IPlacementErrors)null, ref flag);
			val7.Update((IEnumerable<ValueTuple<Keybinding, KeySet>>)array, (IEnumerable<ValueTuple<Keybinding, KeySet>>)array2, default(float2), default(float2), 0f, (GameObject)null);
			val3.Track(val7, (Viewport)null, input, (IReadOnlyMapLayoutModel)null, data, (IPlacementErrors)null, ref flag);
			val4.Track(val7, (Viewport)null, input, (IReadOnlyMapLayoutModel)null, data, (IPlacementErrors)null, ref flag);
			BlueprintPlacementInput<GlobalChunkCoordinate> obj = ((PlacementInputHolder)(ref input)).As<BlueprintPlacementInput<GlobalChunkCoordinate>>();
			if (obj.Confirmed != hasPreview)
			{
				throw new InvalidOperationException("蓝图确认输入没有按预览就绪状态处理。");
			}
			obj.Confirmed = false;
			_log.LogInfo((object)(hasPreview ? "[blueprint benchmark] 预览就绪后的点击已确认。" : "[blueprint benchmark] 预览出现前的点击已拦截。"));
		}

		private void Enter(Phase phase)
		{
			_phase = phase;
			_frames = 0;
			_timer.Restart();
		}

		private string ElapsedMilliseconds()
		{
			return _timer.Elapsed.TotalMilliseconds.ToString("F2", CultureInfo.InvariantCulture);
		}

		private static T ReadField<T>(object owner, string name)
		{
			object obj = AccessTools.Field(owner.GetType(), name)?.GetValue(owner);
			if (obj is T)
			{
				return (T)obj;
			}
			throw new InvalidOperationException("无法读取 " + owner.GetType().Name + "." + name + "。");
		}
	}
	internal static class BlueprintRemoval
	{
		internal const string DisableArgument = "--mlj-perf-original-blueprint-removal";

		private const int MinimumPlatforms = 32;

		private const int MinimumClusterSize = 128;

		private static readonly FieldRef<SimulationCluster, List<SimulationNode>> UpdateOrder = AccessTools.FieldRefAccess<SimulationCluster, List<SimulationNode>>("UpdateOrder");

		private static Func<SimulationCluster, bool> _hasValidOrder = null;

		[ThreadStatic]
		private static Dictionary<SimulationCluster, int>? _firstLiveNodes;

		[ThreadStatic]
		private static MapLayout? _deletingLayout;

		internal static bool IsBulkRemoval => _firstLiveNodes != null;

		internal static void Install(Harmony harmony)
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Expected O, but got Unknown
			//IL_00c1: Expected O, but got Unknown
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			//IL_0100: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Expected O, but got Unknown
			Type? typeFromHandle = typeof(SimulationGraph);
			Type typeFromHandle2 = typeof(BlueprintRemoval);
			_hasValidOrder = AccessTools.MethodDelegate<Func<SimulationCluster, bool>>(Method(typeof(SimulationCluster), "get_HasValidUpdateOrder"), (object)null, true);
			MethodInfo methodInfo = Method(typeFromHandle, "ExecuteRemove");
			MethodInfo methodInfo2 = Method(typeFromHandle2, "UseRemovalCursor");
			MethodInfo methodInfo3 = Method(typeof(ActionModifyIsland), "ExecuteDelete");
			MethodInfo methodInfo4 = Method(typeof(Map), "DeleteIsland");
			MethodInfo methodInfo5 = Method(typeof(MapLayout), "RemoveBuilding");
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null);
			try
			{
				harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(typeFromHandle2, "Begin", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeFromHandle2, "End", (Type[])null), (HarmonyMethod)null);
				if (!Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-original-platform-layout-delete", StringComparer.Ordinal))
				{
					harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeFromHandle2, "BeginIsland", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeFromHandle2, "EndIsland", (Type[])null), (HarmonyMethod)null);
					harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeFromHandle2, "RemoveFromIsland", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch
			{
				harmony.Unpatch((MethodBase)methodInfo, methodInfo2);
				harmony.Unpatch((MethodBase)methodInfo3, Method(typeFromHandle2, "Begin"));
				harmony.Unpatch((MethodBase)methodInfo3, Method(typeFromHandle2, "End"));
				harmony.Unpatch((MethodBase)methodInfo4, Method(typeFromHandle2, "BeginIsland"));
				harmony.Unpatch((MethodBase)methodInfo4, Method(typeFromHandle2, "EndIsland"));
				harmony.Unpatch((MethodBase)methodInfo5, Method(typeFromHandle2, "RemoveFromIsland"));
				throw;
			}
		}

		private static MethodInfo Method(Type type, string name)
		{
			return AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
		}

		private static void Begin(Payload ___Data, out Dictionary<SimulationCluster, int>? __state)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			__state = _firstLiveNodes;
			_firstLiveNodes = ((___Data.Delete.Count >= 32) ? new Dictionary<SimulationCluster, int>() : null);
		}

		private static void End(Dictionary<SimulationCluster, int>? __state)
		{
			_firstLiveNodes = __state;
		}

		private static void BeginIsland(Map __instance, out MapLayout? __state)
		{
			__state = _deletingLayout;
			_deletingLayout = (MapLayout?)((_firstLiveNodes == null) ? null : /*isinst with value type is only supported in some contexts*/);
		}

		private static void EndIsland(MapLayout? __state)
		{
			_deletingLayout = __state;
		}

		private static bool RemoveFromIsland(MapLayout __instance, BuildingInstance __0, Dictionary<GlobalTileCoordinate, BuildingInstance> ___BuildingsByPosition, MultiRegisterEvent<BuildingInstance> ____OnBuildingRemoved, ILogger ___Logger)
		{
			//IL_000a: 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_0028: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: 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_0048: 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_0076: 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_0084: Unknown result type (might be due to invalid IL or missing references)
			if (_deletingLayout != __instance)
			{
				return true;
			}
			TileVector[] tiles = ((IEntityConnectorData<TileVector>)(object)((IEntityDefinition)__0.Definition).CustomData.Get<IBuildingConnectorData>()).Tiles;
			EventExtensions.InvokeSafe<BuildingInstance>(____OnBuildingRemoved, __0, ___Logger);
			GlobalTileTransform transform = __0.Transform;
			TileVector[] array = tiles;
			for (int i = 0; i < array.Length; i++)
			{
				TileVector val = array[i];
				GlobalTileCoordinate val2 = ((TileVector)(ref val)).ToGlobal(ref transform);
				if (!___BuildingsByPosition.Remove(val2, out var value))
				{
					throw new InvalidOperationException($"找不到要拆除的建筑占用格 {val2}。");
				}
				if ((ref __0) != (ref value))
				{
					___BuildingsByPosition.Add(val2, value);
					throw new InvalidOperationException($"要拆除的建筑与占用格 {val2} 的记录不一致。");
				}
			}
			return false;
		}

		private static IEnumerable<CodeInstruction> UseRemovalCursor(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo original = Method(typeof(SimulationGraph), "IsClusterEmpty");
			int num = list.FindIndex((CodeInstruction op) => CodeInstructionExtensions.Calls(op, original));
			if (num < 0 || list.Count((CodeInstruction op) => CodeInstructionExtensions.Calls(op, original)) != 1)
			{
				throw new InvalidOperationException("找不到删除模拟节点后的空簇判断。");
			}
			list[num].operand = Method(typeof(BlueprintRemoval), "IsEmpty");
			return list;
		}

		private static bool IsEmpty(SimulationCluster cluster)
		{
			List<SimulationNode> list = UpdateOrder.Invoke(cluster);
			if (_hasValidOrder(cluster))
			{
				return list.Count == 0;
			}
			Dictionary<SimulationCluster, int> dictionary = ((list.Count >= 128) ? _firstLiveNodes : null);
			int i = 0;
			dictionary?.TryGetValue(cluster, out i);
			for (; i < list.Count && list[i] == null; i++)
			{
			}
			if (i == list.Count)
			{
				dictionary?.Remove(cluster);
				return true;
			}
			if (dictionary != null)
			{
				dictionary[cluster] = i;
			}
			return false;
		}
	}
	internal static class BlueprintSelectionLoad
	{
		private sealed class Request
		{
			internal readonly LibraryBlueprintFile File;

			internal readonly IBlueprintStarter Starter;

			internal readonly GridRotation? Rotation;

			internal readonly ManualLogSource Log;

			internal readonly Stopwatch Timer = Stopwatch.StartNew();

			internal Request(LibraryBlueprintFile file, IBlueprintStarter starter, GridRotation? rotation, ManualLogSource log)
			{
				File = file;
				Starter = starter;
				Rotation = rotation;
				Log = log;
			}
		}

		private static Request? _current;

		private static Request? _queued;

		private static Task<BlueprintCandidate>? _working;

		private static string _metadata = "";

		private static int _version;

		internal static bool IsPending
		{
			get
			{
				if (_current == null)
				{
					return _queued != null;
				}
				return true;
			}
		}

		internal static void RequestPreview(LibraryBlueprintFile file, IBlueprintStarter starter, GridRotation? rotation, ManualLogSource log)
		{
			Cancel();
			_queued = new Request(file, starter, rotation, log);
			StartQueued();
		}

		internal static void Cancel()
		{
			_current = null;
			_queued = null;
		}

		private static void StartQueued()
		{
			if (_working != null)
			{
				return;
			}
			Request queued = _queued;
			if (queued == null)
			{
				return;
			}
			_queued = null;
			try
			{
				_working = queued.File.Prepare(out _metadata, out _version);
				_current = queued;
			}
			catch (Exception ex)
			{
				queued.Log.LogWarning((object)("[blueprint library] 无法加载蓝图。" + ((BlueprintLibraryEntryBase)queued.File.Entry).Title + "。" + ex.GetBaseException().Message));
			}
		}

		internal static void Update()
		{
			Task<BlueprintCandidate> working = _working;
			if (working == null || !working.IsCompleted)
			{
				return;
			}
			Request current = _current;
			_working = null;
			_current = null;
			try
			{
				BlueprintCandidate result = working.GetAwaiter().GetResult();
				if (current != null)
				{
					IAnnotatedBlueprint val = current.File.AcceptPrepared(result, _metadata, _version);
					current.Starter.StartBlueprintPlacement(val, current.Rotation);
					current.Log.LogInfo((object)$"[blueprint library] 点选到启动预览 {current.Timer.Elapsed.TotalMilliseconds:F2} 毫秒。{((BlueprintLibraryEntryBase)current.File.Entry).Title}");
				}
			}
			catch (Exception ex)
			{
				if (current != null)
				{
					current.Log.LogWarning((object)("[blueprint library] 无法加载蓝图。" + ((BlueprintLibraryEntryBase)current.File.Entry).Title + "。" + ex.GetBaseException().Message));
				}
			}
			finally
			{
				StartQueued();
			}
		}
	}
	internal static class ClearTraversalSet
	{
		internal const string DisableArgument = "--mlj-perf-original-graph";

		private const int SparseCount = 32;

		private static readonly Predicate<SimulationNode> RemoveAll = (SimulationNode _) => true;

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			Type typeFromHandle = typeof(SimulationCluster);
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeFromHandle, "RecomputeUpdateOrder", (Type[])null, (Type[])null);
			ParameterInfo[] array = methodInfo?.GetParameters();
			if (array == null || array.Length != 1 || !array[0].IsOut)
			{
				throw new MissingMethodException(typeFromHandle.FullName, "RecomputeUpdateOrder");
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ClearTraversalSet), "ReplaceClear", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			log.LogInfo((object)"[graph traversal] 已启用。模拟簇排序时逐项清除稀疏的遍历集合。");
		}

		private static IEnumerable<CodeInstruction> ReplaceClear(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo clear = AccessTools.DeclaredMethod(typeof(HashSet<SimulationNode>), "Clear", (Type[])null, (Type[])null);
			int num = list.FindIndex((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, clear));
			if (num < 0 || list.Count((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, clear)) != 1)
			{
				throw new InvalidOperationException("无法确认模拟簇排序中的集合清除指令。");
			}
			list[num].opcode = OpCodes.Call;
			list[num].operand = AccessTools.DeclaredMethod(typeof(ClearTraversalSet), "Clear", (Type[])null, (Type[])null);
			return list;
		}

		private static void Clear(HashSet<SimulationNode> visited)
		{
			if (visited.Count <= 32)
			{
				visited.RemoveWhere(RemoveAll);
			}
			else
			{
				visited.Clear();
			}
		}
	}
	internal static class ClipboardBlueprintLoad
	{
		private sealed class Request
		{
			internal readonly HUDBlueprintHistory Owner;

			internal readonly IBlueprintImporter Importer;

			internal readonly string Text;

			internal readonly Stopwatch Timer = Stopwatch.StartNew();

			internal Task? Parse;

			internal bool Cancelled;

			internal string Metadata = "";

			internal int Version;

			internal BlueprintCandidate? Candidate;

			internal BlueprintException? Error;

			internal double ReadMilliseconds;

			internal Request(HUDBlueprintHistory owner, IBlueprintImporter importer, string text)
			{
				Owner = owner;
				Importer = importer;
				Text = text;
			}

			internal void Read()
			{
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				Stopwatch stopwatch = Stopwatch.StartNew();
				try
				{
					string content = default(string);
					if (Importer.Disassembler.TryDisassembleBlueprint(Text, ref content, ref Metadata, ref Version, ref Error))
					{
						Candidate = LibraryBlueprintFile.ReadCandidate(Importer.Deserializer, content);
					}
				}
				catch (Exception ex)
				{
					Error = (BlueprintException?)(((object)((ex is BlueprintException) ? ex : null)) ?? ((object)new UnexpectedBlueprintException(ex)));
				}
				finally
				{
					ReadMilliseconds = stopwatch.Elapsed.TotalMilliseconds;
				}
			}
		}

		internal const string DisableArgument = "--mlj-perf-original-clipboard-paste";

		private const string DisableCacheArgument = "--mlj-perf-no-clipboard-cache";

		private static (HUDBlueprintHistory Owner, IBlueprintImporter Importer, string Text, AnnotatedIslandBlueprint Blueprint, int Version)? _lastPaste;

		private static bool _cacheEnabled;

		private static Request? _pending;

		private static Request? _working;

		private static Request? _replay;

		private static Action<HUDBlueprintHistory, string> _paste;

		private static Func<HUDPart, Player> _player;

		internal static void Install(Harmony harmony)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00b1: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Expected O, but got Unknown
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Expected O, but got Unknown
			_cacheEnabled = !Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-no-clipboard-cache", StringComparer.Ordinal);
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(HUDBlueprintHistory), "HandleBlueprintPaste", new Type[1] { typeof(string) }, (Type[])null) ?? throw new MissingMethodException("HUDBlueprintHistory", "HandleBlueprintPaste(string)");
			_player = AccessTools.MethodDelegate<Func<HUDPart, Player>>(AccessTools.PropertyGetter(typeof(HUDPart), "Player"), (object)null, true);
			Type typeFromHandle = typeof(ClipboardBlueprintLoad);
			Type typeFromHandle2 = typeof(EntityPlacementRunner);
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeFromHandle, "QueuePaste", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeFromHandle, "UsePreparedImport", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			_paste = AccessTools.MethodDelegate<Action<HUDBlueprintHistory, string>>(methodInfo, (object)null, true);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(HUDBlueprintHistory), "OnDispose", (Type[])null, (Type[])null), new HarmonyMethod(typeFromHandle, "Release", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeFromHandle2, "StartPlacement", new Type[3]
			{
				typeof(IEntityPlacer),
				typeof(bool),
				typeof(GridRotation)
			}, (Type[])null), new HarmonyMethod(typeFromHandle, "Cancel", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeFromHandle2, "StopCurrentPlacement", (Type[])null, (Type[])null), new HarmonyMethod(typeFromHandle, "Cancel", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeFromHandle2, "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeFromHandle, "CancelOnEscape", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool QueuePaste(HUDBlueprintHistory __instance, string __0, IBlueprintImporter ___BlueprintImporter, IInteractionMode ___InteractionMode, IBlueprintStarter ___BlueprintStarter)
		{
			if (_replay != null)
			{
				return true;
			}
			Cancel();
			if ((long)__0.Length < 262144L || !__0.StartsWith("SHAPEZ2-", StringComparison.Ordinal) || ((object)___BlueprintImporter).GetType() != typeof(BlueprintImporter) || ((object)___BlueprintImporter.Deserializer).GetType() != typeof(BlueprintDeserializer) || !___InteractionMode.AllowBlueprints(_player((HUDPart)(object)__instance)))
			{
				return true;
			}
			(HUDBlueprintHistory, IBlueprintImporter, string, AnnotatedIslandBlueprint, int)? lastPaste = _lastPaste;
			if (lastPaste.HasValue)
			{
				(HUDBlueprintHistory, IBlueprintImporter, string, AnnotatedIslandBlueprint, int) valueOrDefault = lastPaste.GetValueOrDefault();
				if (valueOrDefault.Item1 == __instance && valueOrDefault.Item2 == ___BlueprintImporter && string.Equals(valueOrDefault.Item3, __0, StringComparison.Ordinal))
				{
					BlueprintSelectionLoad.Cancel();
					return true;
				}
			}
			BlueprintSelectionLoad.Cancel();
			___BlueprintStarter.StopBlueprintPlacement();
			_pending = new Request(__instance, ___BlueprintImporter, __0);
			StartPending();
			return false;
		}

		internal static void Cancel()
		{
			_pending = null;
			Request working = _working;
			if (working != null)
			{
				working.Cancelled = true;
			}
		}

		internal static void Release()
		{
			Cancel();
			_lastPaste = null;
		}

		private static void CancelOnEscape(InputDownstreamContext __0)
		{
			if (_pending == null)
			{
				Request working = _working;
				if (working == null || working.Cancelled)
				{
					return;
				}
			}
			if (__0.IsActivated("global.cancel") || __0.IsActivated("building-placement.cancel-placement"))
			{
				Cancel();
			}
		}

		private static void StartPending()
		{
			if (_working == null)
			{
				Request pending = _pending;
				if (pending != null)
				{
					_pending = null;
					_working = pending;
					pending.Parse = Task.Run((Action)pending.Read);
				}
			}
		}

		internal static void Update()
		{
			Request working = _working;
			if (working == null)
			{
				return;
			}
			Task parse = working.Parse;
			if (parse == null || !parse.IsCompleted)
			{
				return;
			}
			_working = null;
			try
			{
				working.Parse.GetAwaiter().GetResult();
				if (!working.Cancelled && !((Object)(object)working.Owner == (Object)null))
				{
					_replay = working;
					_paste(working.Owner, working.Text);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource? log = TimingProbe.Log;
				if (log != null)
				{
					log.LogWarning((object)("[blueprint clipboard] 粘贴蓝图失败。" + ex.GetBaseException().Message));
				}
			}
			finally
			{
				_replay = null;
				StartPending();
			}
		}

		private static IEnumerable<CodeInstruction> UsePreparedImport(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo import = AccessTools.DeclaredMethod(typeof(IBlueprintImporter), "TryImport", (Type[])null, (Type[])null);
			int num = list.FindIndex((CodeInstruction op) => CodeInstructionExtensions.Calls(op, import));
			if (num < 0 || list.Count((CodeInstruction op) => CodeInstructionExtensions.Calls(op, import)) != 1)
			{
				throw new InvalidOperationException("找不到游戏内粘贴蓝图的导入调用。");
			}
			list[num].opcode = OpCodes.Call;
			list[num].operand = AccessTools.DeclaredMethod(typeof(ClipboardBlueprintLoad), "Import", (Type[])null, (Type[])null);
			return list;
		}

		private static bool Import(IBlueprintImporter importer, string text, out IAnnotatedBlueprint? blueprint, out int version, out BlueprintException? exception)
		{
			(HUDBlueprintHistory, IBlueprintImporter, string, AnnotatedIslandBlueprint, int)? lastPaste = _lastPaste;
			if (lastPaste.HasValue)
			{
				(HUDBlueprintHistory, IBlueprintImporter, string, AnnotatedIslandBlueprint, int) valueOrDefault = lastPaste.GetValueOrDefault();
				if (valueOrDefault.Item2 == importer && string.Equals(valueOrDefault.Item3, text, StringComparison.Ordinal))
				{
					blueprint = (IAnnotatedBlueprint?)(object)valueOrDefault.Item4;
					version = valueOrDefault.Item5;
					exception = null;
					return true;
				}
			}
			Request replay = _replay;
			if (replay == null || importer != replay.Importer || (object)text != replay.Text)
			{
				return importer.TryImport(text, ref blueprint, ref version, ref exception);
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			blueprint = null;
			version = replay.Version;
			exception = replay.Error;
			BlueprintCandidate candidate = replay.Candidate;
			if (candidate == null || !importer.Migrator.TryMigrate(candidate, ref exception) || !importer.Sanitizer.TrySanitize(candidate, ref exception))
			{
				return false;
			}
			IBlueprintMetadata instance = default(IBlueprintMetadata);
			if (!importer.Deserializer.TryDeserializeMetadata(replay.Metadata, ref instance, ref exception))
			{
				instance = (IBlueprintMetadata)(object)EmptyBlueprintMetadata.Instance;
			}
			blueprint = PlatformBlueprintWriter.Write(importer.Writer, candidate, instance);
			if (_cacheEnabled && exception == null)
			{
				IAnnotatedBlueprint? obj = blueprint;
				AnnotatedIslandBlueprint val = (AnnotatedIslandBlueprint)(object)((obj is AnnotatedIslandBlueprint) ? obj : null);
				if (val != null)
				{
					_lastPaste = (replay.Owner, importer, text, val, version);
				}
			}
			ManualLogSource? log = TimingProbe.Log;
			if (log != null)
			{
				log.LogInfo((object)$"[blueprint clipboard] 粘贴到生成蓝图 {replay.Timer.Elapsed.TotalMilliseconds:F2} 毫秒,后台解析 {replay.ReadMilliseconds:F2} 毫秒,主线程生成 {stopwatch.Elapsed.TotalMilliseconds:F2} 毫秒。");
			}
			return true;
		}
	}
	internal static class ConveyorPathRemoval
	{
		private sealed class PlatformRemoval
		{
			internal readonly IReadOnlyMapLayout Layout;

			private readonly IslandInstance _island;

			private Dictionary<ConnectableConveyorSimulation, DeferredPath>? _paths;

			private List<(DeferredPath Path, BuildingInstance Building)>? _deferred;

			private bool _flushing;

			private ConveyorSimulationSystem? _system;

			internal PlatformRemoval(IReadOnlyMapLayout layout, IslandInstance island)
			{
				//IL_000e: 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)
				Layout = layout;
				_island = island;
			}

			internal bool Defer(ConveyorSimulationSystem system, in BuildingInstance building)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_0101: 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_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: 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)
				if (_flushing || !_getPaths(system).TryGetValue(building.Transform.Position, out var value) || ((ConnectablePathSimulation<ConveyorPathSimulation, BuildingItemInput, BuildingItemOutput>)(object)value).Buildings.Count < 4)
				{
					return false;
				}
				if (_paths == null)
				{
					_paths = new Dictionary<ConnectableConveyorSimulation, DeferredPath>();
				}
				if (!_paths.TryGetValue(value, out DeferredPath value2))
				{
					IslandInstance val2 = default(IslandInstance);
					foreach (BuildingInstance building2 in ((ConnectablePathSimulation<ConveyorPathSimulation, BuildingItemInput, BuildingItemOutput>)(object)value).Buildings)
					{
						BuildingInstance current = building2;
						GlobalChunkCoordinate val = ((GlobalTileCoordinate)(ref current.Transform.Position)).ToChunkCoordinate();
						if (!Layout.TryGetIsland(ref val, ref val2) || val2.State != _island.State)
						{
							return false;
						}
					}
					value2 = new DeferredPath(system, value);
					_paths.Add(value, value2);
					_system = system;
				}
				(_deferred ?? (_deferred = new List<(DeferredPath, BuildingInstance)>())).Add((value2, building));
				value2.Count++;
				return true;
			}

			internal void FlushForLookup(in GlobalTileCoordinate position)
			{
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				if (_flushing)
				{
					return;
				}
				ConveyorSimulationSystem system = _system;
				if (system != null)
				{
					Dictionary<ConnectableConveyorSimulation, DeferredPath> paths = _paths;
					if (paths != null && paths.Count > 0 && _getPaths(system).TryGetValue(position, out var value) && _paths.ContainsKey(value))
					{
						Flush();
					}
				}
			}

			internal void Flush(bool recovering = false)
			{
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f2: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
				if (_flushing || _deferred == null || _deferred.Count == 0)
				{
					return;
				}
				_flushing = true;
				try
				{
					BuildingInstance val2 = default(BuildingInstance);
					foreach (var item in _deferred)
					{
						var (deferredPath, val) = item;
						if (!deferredPath.Removed)
						{
							if (!recovering && deferredPath.Count == ((ConnectablePathSimulation<ConveyorPathSimulation, BuildingItemInput, BuildingItemOutput>)(object)deferredPath.Path).Buildings.Count && !deferredPath.Replaying)
							{
								_deletePath(deferredPath.System, deferredPath.Path);
								BatchedPaths++;
								BatchedBuildings += deferredPath.Count;
								deferredPath.Removed = true;
							}
							else if (!recovering || !Layout.TryGetBuilding(ref val.Transform.Position, ref val2) || val2.State != val.State)
							{
								deferredPath.Replaying = true;
								_removeTile(deferredPath.System, val);
							}
						}
					}
				}
				finally
				{
					_deferred.Clear();
					_paths.Clear();
					_system = null;
					_flushing = false;
				}
			}
		}

		private sealed class DeferredPath
		{
			internal readonly ConveyorSimulationSystem System;

			internal readonly ConnectableConveyorSimulation Path;

			internal int Count;

			internal bool Removed;

			internal bool Replaying;

			internal DeferredPath(ConveyorSimulationSystem system, ConnectableConveyorSimulation path)
			{
				System = system;
				Path = path;
			}
		}

		internal const string DisableArgument = "--mlj-perf-original-conveyor-removal";

		private const int MinimumPathLength = 4;

		[ThreadStatic]
		private static PlatformRemoval? _platform;

		private static Action<ConveyorSimulationSystem, ConnectableConveyorSimulation> _deletePath;

		private static Action<ConveyorSimulationSystem, BuildingInstance> _removeTile;

		private static Func<ConveyorSimulationSystem, Dictionary<GlobalTileCoordinate, ConnectableConveyorSimulation>> _getPaths;

		internal static int BatchedPaths { get; private set; }

		internal static int BatchedBuildings { get; private set; }

		internal static void Install(Harmony harmony)
		{
			//IL_013b: 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_0170: Unknown result type (might be due to invalid IL or missing references)
			Type? typeFromHandle = typeof(BuildingPathSimulationSystem<ConnectableConveyorSimulation, BuildingItemInput, BuildingItemOutput>);
			_deletePath = AccessTools.MethodDelegate<Action<ConveyorSimulationSystem, ConnectableConveyorSimulation>>(Method(typeFromHandle, "DeletePath"), (object)null, true);
			_removeTile = AccessTools.MethodDelegate<Action<ConveyorSimulationSystem, BuildingInstance>>(Method(typeFromHandle, "RemoveBuildingFromPath"), (object)null, true);
			FieldRef<ConveyorSimulationSystem, Dictionary<GlobalTileCoordinate, ConnectableConveyorSimulation>> paths = AccessTools.FieldRefAccess<ConveyorSimulationSystem, Dictionary<GlobalTileCoordinate, ConnectableConveyorSimulation>>("PathByPosition");
			_getPaths = (ConveyorSimulationSystem system) => paths.Invoke(system);
			Type typeFromHandle2 = typeof(ConveyorPathRemoval);
			(MethodInfo, string, string, string)[] array = new(MethodInfo, string, string, string)[4]
			{
				(Method(typeof(Simulator), "TerminateBuildingOffer"), null, "UsePathRemoval", null),
				(Method(typeof(Map), "DeleteIsland"), "Begin", "FinishBeforeIslandEvent", "End"),
				(Method(typeof(Simulator), "TryFindTileSimulation"), "FlushBeforeLookup", null, null),
				(Method(typeof(MapLayout), "AddBuilding"), "FlushBeforeAdd", null, null)
			};
			try
			{
				(MethodInfo, string, string, string)[] array2 = array;
				for (int num = 0; num < array2.Length; num++)
				{
					(MethodInfo, string, string, string) tuple = array2[num];
					harmony.Patch((MethodBase)tuple.Item1, (tuple.Item2 == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeFromHandle2, tuple.Item2, (Type[])null), (HarmonyMethod)null, (tuple.Item3 == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeFromHandle2, tuple.Item3, (Type[])null), (tuple.Item4 == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeFromHandle2, tuple.Item4, (Type[])null), (HarmonyMethod)null);
				}
			}
			catch
			{
				(MethodInfo, string, string, string)[] array2 = array;
				for (int num = 0; num < array2.Length; num++)
				{
					(MethodInfo, string, string, string) tuple2 = array2[num];
					string[] array3 = new string[3] { tuple2.Item2, tuple2.Item3, tuple2.Item4 };
					foreach (string text in array3)
					{
						if (text != null)
						{
							harmony.Unpatch((MethodBase)tuple2.Item1, Method(typeFromHandle2, text));
						}
					}
				}
				throw;
			}
		}

		private static MethodInfo Method(Type type, string name)
		{
			return AccessTools.DeclaredMethod(type, name, (Type[])null, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
		}

		private static void Begin(Map __instance, in IslandId __0, out PlatformRemoval? __state)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			__state = _platform;
			_platform?.Flush();
			IslandInstance island = default(IslandInstance);
			_platform = ((BlueprintRemoval.IsBulkRemoval && __instance.TryGetIsland(ref __0, ref island)) ? new PlatformRemoval((IReadOnlyMapLayout)(object)__instance.Layout, island) : null);
		}

		private static void End(PlatformRemoval? __state, Exception? __exception)
		{
			try
			{
				_platform?.Flush(__exception != null);
			}
			finally
			{
				_platform = __state;
			}
		}

		private static void FlushBeforeLookup(in GlobalTileCoordinate __0, IReadOnlyMapLayout ___Layout)
		{
			PlatformRemoval platform = _platform;
			if (platform != null && ___Layout == platform.Layout)
			{
				platform.FlushForLookup(in __0);
			}
		}

		private static void FlushBeforeAdd(MapLayout __instance)
		{
			PlatformRemoval platform = _platform;
			if (platform != null && (object)__instance == platform.Layout)
			{
				platform.Flush();
			}
		}

		private static IEnumerable<CodeInstruction> UsePathRemoval(IEnumerable<CodeInstruction> instructions)
		{
			List<CodeInstruction> list = instructions.ToList();
			MethodInfo original = Method(typeof(IBuildingTenantSimulationSystem), "BuildingOfferIsTerminated");
			CodeInstruction[] array = list.Where((CodeInstruction op) => CodeInstructionExtensions.Calls(op, original)).ToArray();
			if (array.Length != 2)
			{
				throw new InvalidOperationException("找不到建筑模拟系统的注销调用。");
			}
			array[1].opcode = OpCodes.Call;
			array[1].operand = Method(typeof(ConveyorPathRemoval), "TerminateOffer");
			return list;
		}

		private static IEnumerable<CodeInstruction> FinishBeforeIslandEvent(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			List<CodeInstruction> list = instructions.ToList();
			FieldInfo removalEvent = AccessTools.DeclaredField(typeof(Map), "_OnBeforeIslandRemoved");
			int num = list.FindIndex((CodeInstruction op) => CodeInstructionExtensions.LoadsField(op, removalEvent, false));
			if (num < 0 || list.Count((CodeInstruction op) => CodeInstructionExtensions.LoadsField(op, removalEvent, false)) != 1)
			{
				throw new InvalidOperationException("找不到平台移除通知的位置。");
			}
			CodeInstruction val = new CodeInstruction(OpCodes.Call, (object)Method(typeof(ConveyorPathRemoval), "FinishPlatform"));
			val.labels.AddRange(list[num].labels);
			list[num].labels.Clear();
			list.Insert(num, val);
			return list;
		}

		private static void FinishPlatform()
		{
			_platform?.Flush();
		}

		private static bool TerminateOffer(IBuildingTenantSimulationSystem system, in BuildingInstance building, IReadOnlyMapLayout layout, in SimulationSystemPropagationHandle propagation)
		{
			PlatformRemoval platform = _platform;
			if (platform != null && layout == platform.Layout)
			{
				ConveyorSimulationSystem val = (ConveyorSimulationSystem)(object)((system is ConveyorSimulationSystem) ? system : null);
				if (val != null && platform.Defer(val, in building))
				{
					return true;
				}
			}
			return system.BuildingOfferIsTerminated(ref building, layout, ref propagation);
		}
	}
	internal static class ConveyorRemovalBenchmark
	{
		internal unsafe static void Check(MapModel map, PlayerActionManager actions, Player player, Simulator simulator, GameMode mode, ShapeItem item, ManualLogSource log)
		{
			//IL_004f: 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_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_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_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: 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_00b7: 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_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: 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_0136: 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_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_014e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: 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_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: 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_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Expected O, but got Unknown
			//IL_02be: 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)
			//IL_02ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0307: Expected O, but got Unknown
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_034a: Unknown result type (might be due to invalid IL or missing references)
			int islandCount = map.IslandCount;
			int buildingCount = map.BuildingCount;
			GlobalChunkCoordinate origin = new GlobalChunkCoordinate(256, 256, (short)0);
			GlobalChunkTransform transform = new GlobalChunkTransform(origin, GridRotation.NoRotate);
			IIslandDefinition platform = mode.Islands.AllDefinitions.First(delegate(IIslandDefinition definition)
			{
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: 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_0052: Unknown result type (might be due to invalid IL or missing references)
				if (((IEntityDefinition)definition).CustomData.Has<CanHoldBuildingsIslandTag>() && definition.Layout.GetChunkPositions().Count == 1)
				{
					ChunkVector val8 = definition.Layout.GetChunkPositions()[0];
					if (((ChunkVector)(ref val8)).Equals(ChunkVector.Zero))
					{
						return HasPlayableRow(new IslandLayoutQuery(definition, transform, (int)mode.MaxBuildingLayer));
					}
				}
				return false;
			});
			IslandModel val = CreatePlatform(origin);
			IslandModel val2 = CreatePlatform(origin + new ChunkVector(2, 0, (short)0));
			IslandModel val3 = CreatePlatform(origin + new ChunkVector(3, 0, (short)0));
			List<DeletePayload> list = DeleteGroup(((IslandModel)(ref val)).Id);
			IBuildingDefinition belt = mode.Buildings.ForwardBelt;
			BuildingItemOutput outlet = ((IEntityDefinition)belt).CustomData.Get<IBuildingConnectorData>().BuildingConnectorsOfType<BuildingItemOutput>()[0];
			GridRotation rotation = GridRotation.RotationsInClockwiseOrder.First(delegate(GridRotation orientation)
			{
				//IL_0002: 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_0015: 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)
				//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_002a: Unknown result type (might be due to invalid IL or missing references)
				GlobalTileTransform val8 = default(GlobalTileTransform);
				((GlobalTileTransform)(ref val8))..ctor(GlobalTileCoordinate.Origin, orientation);
				TileVector val9 = TileVector.op_Implicit(((BuildingBaseIO)outlet).Pivot(ref val8).Direction);
				return ((TileVector)(ref val9)).Equals(new TileVector(1, 0, (short)0));
			});
			GlobalTileCoordinate val4 = ((GlobalChunkCoordinate)(ref origin)).ToOrigin_G() + new TileVector(3, 6, (short)0);
			GlobalChunkCoordinate position = ((IslandModel)(ref val2)).Position;
			GlobalTileCoordinate val5 = ((GlobalChunkCoordinate)(ref position)).ToOrigin_G() + new TileVector(17, 3, (short)0);
			GlobalTileCoordinate position2 = val5 + new TileVector(4, 0, (short)0);
			BunchEditScope val6 = map.StartBunchEdit();
			try
			{
				for (int num = 0; num < 8; num++)
				{
					PlaceBelt(val4 + new TileVector(num, 0, (short)0));
				}
				for (int num2 = 0; num2 < 6; num2++)
				{
					PlaceBelt(val5 + new TileVector(num2, 0, (short)0));
				}
			}
			finally
			{
				((IDisposable)(*(BunchEditScope*)(&val6))/*cast due to .constrained prefix*/).Dispose();
			}
			RequirePath(val4, 8);
			RequirePath(position2, 6);
			Cargo(val4).Item = (IBeltItem)(object)item;
			Cargo(val5).Item = (IBeltItem)(object)item;
			Cargo(position2).Item = (IBeltItem)(object)item;
			ActionModifyIsland current = new ActionModifyIsland((IMapModel)(object)map, player, new Payload((IReadOnlyList<DeletePayload>)list, false, false));
			int batchedPaths = ConveyorPathRemoval.BatchedPaths;
			Execute((IPlayerAction)(object)current, out var reverse);
			int num3 = ConveyorPathRemoval.BatchedPaths - batchedPaths;
			bool flag = Environment.GetCommandLineArgs().Contains<string>("--mlj-perf-original-conveyor-removal", StringComparer.Ordinal);
			ILocalizedTileSimulation val7 = default(ILocalizedTileSimulation);
			if (num3 != ((!flag) ? 1 : 0) || simulator.TryFindTileSimulation(ref val4, ref val7))
			{
				throw new InvalidOperationException($"整拆传送带的路径注销记录不符。批量注销 {num3} 条路径。");
			}
			Execute(reverse, out var reverse2);
			RequirePath(val4, 8);
			RequireCargo(val4);
			Execute(reverse2, out var reverse3);
			batchedPaths = ConveyorPathRemoval.BatchedPaths;
			Execute((IPlayerAction)new ActionModifyIsland((IMapModel)(object)map, player, new Payload((IReadOnlyList<DeletePayload>)DeleteGroup(((IslandModel)(ref val2)).Id), false, false)), out reverse3);
			if (ConveyorPathRemoval.BatchedPaths != batchedPaths || simulator.TryFindTileSimulation(ref val5, ref val7))
			{
				throw new InvalidOperationException("跨平台传送带的被拆除端未走正常的部分拆除。");
			}
			RequirePath(position2, 3);
			RequireCargo(position2);
			MapModel obj = map;
			IslandId id = ((IslandModel)(ref val3)).Id;
			obj.DeleteIsland(ref id);
			if (map.IslandCount != islandCount || map.BuildingCount != buildingCount)
			{
				throw new InvalidOperationException("传送带拆除样本没有恢复地图的原有数量。");
			}
			log.LogInfo((object)$"[blueprint benchmark] 整条路径批量注销 {num3} 条,跨平台保留端及其货物、整条拆除撤销后的路径及货物均通过核对。");
			BeltSlotState Cargo(GlobalTileCoordinate val8)
			{
				//IL_0006: 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)
				BuildingModel val9 = default(BuildingModel);
				if (!map.TryGetBuilding(val8, ref val9))
				{
					throw new InvalidOperationException($"找不到传送带 {val8}。");
				}
				return ((BuildingModel)(ref val9)).State.Cast<ConveyorSimulationState>().Slot0;
			}
			IslandModel CreatePlatform(GlobalChunkCoordinate val8)
			{
				//IL_000c: 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_0012: 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)
				return map.CreateIsland(platform, new GlobalChunkTransform(val8, GridRotation.NoRotate), (IIslandConfiguration)null);
			}
			List<DeletePayload> DeleteGroup(IslandId island)
			{
				//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_0019: 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)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: 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_0038: Unknown result type (might be due to invalid IL or missing references)
				List<DeletePayload> list2 = new List<DeletePayload>
				{
					new DeletePayload(island)
				};
				for (int i = 0; i < 31; i++)
				{
					IslandModel val8 = CreatePlatform(origin + new ChunkVector(i, 2, (short)0));
					list2.Add(new DeletePayload(((IslandModel)(ref val8)).Id));
				}
				return list2;
			}
			void Execute(IPlayerAction val8, out IPlayerAction reference)
			{
				if (!actions.ExecuteActionImmediately_INTERNAL(val8, ref reference))
				{
					throw new InvalidOperationException("传送带拆除样本的操作失败。");
				}
			}
			static bool HasPlayableRow(IslandLayoutQuery layout)
			{
				IslandTileCoordinate val8 = default(IslandTileCoordinate);
				for (short num4 = 3; num4 < 11; num4++)
				{
					((IslandTileCoordinate)(ref val8))..ctor(num4, (short)6, (short)0);
					if (!((IslandLayoutQuery)(ref layout)).IsValidAndBuildableTile_I(ref val8) || ((IslandLayoutQuery)(ref layout)).GetNotchFlag_I(ref val8).HasValue)
					{
						return false;
					}
				}
				return true;
			}
			void PlaceBelt(GlobalTileCoordinate val9)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0004: 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)
				GlobalTileTransform val8 = default(GlobalTileTransform);
				((GlobalTileTransform)(ref val8))..ctor(val9, rotation);
				map.CreateBuilding(belt, ref val8, (IBuildingConfiguration)null);
			}
			void RequireCargo(GlobalTileCoordinate val8)
			{
				//IL_0007: 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)
				if (!((object)item).Equals((object?)Cargo(val8).Item))
				{
					throw new InvalidOperationException($"传送带 {val8} 的货物不一致。");
				}
			}
			void RequirePath(GlobalTileCoordinate val8, int count)
			{
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				ILocalizedTileSimulation val9 = default(ILocalizedTileSimulation);
				if (simulator.TryFindTileSimulation(ref val8, ref val9))
				{
					ConnectableConveyorSimulation val10 = (ConnectableConveyorSimulation)(object)((val9 is ConnectableConveyorSimulation) ? val9 : null);
					if (val10 != null && ((ConnectablePathSimulation<ConveyorPathSimulation, BuildingItemInput, BuildingItemOutput>)(object)val10).Buildings.Count == count)
					{
						return;
					}
				}
				throw new InvalidOperationException($"传送带位置 {val8} 应属于一条 {count} 格长的路径。");
			}
		}
	}
	internal static class LargeBlueprintPreview
	{
		internal const string Argument = "--mlj-perf-light-preview";

		private const int LargeBlueprintBuildingCount = 10000;

		private static IEntityPlacer? _largePlacer;

		internal static void Install(Harmony harmony, ManualLogSource log)
		{
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Expected O, but got Unknown
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			Type type = typeof(GameSessionOrchestrator).Assembly.GetType("BlueprintStarter") ?? throw new TypeLoadException("BlueprintStarter");
			MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "StartBlueprintPlacement", new Type[2]
			{
				typeof(IAnnotatedBlueprint),
				typeof(GridRotation?)
			}, (Type[])null) ?? throw new MissingMethodException(type.FullName, "StartBlueprintPlacement");
			MethodInfo methodInfo2 = AccessTools.DeclaredMethod(typeof(EntityPlacementRunner), "ModifyLayoutWithPlacementData", new Type[1] { typeof(IPlacementData) }, (Type[])null) ?? throw new MissingMethodException("EntityPlacementRunner", "ModifyLayoutWithPlacementData");
			MethodInfo methodInfo3 = AccessTools.DeclaredMethod(typeof(EntityPlacementRunner), "StopPlacement", new Type[1] { typeof(IEntityPlacer) }, (Type[])null) ?? throw new MissingMethodException("EntityPlacementRunner", "StopPlacement");
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(LargeBlueprintPreview), "StagePrediction", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(LargeBlueprintPreview), "ClearPlacer", (Typ