Decompiled source of NearestStationFirst v1.0.0

plugins/NearestStationFirst.dll

Decompiled 16 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("NearestStationFirst")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e46e69cbef0d16bf7b5f7c60190bc09eeacf8c2a")]
[assembly: AssemblyProduct("NearestStationFirst")]
[assembly: AssemblyTitle("NearestStationFirst")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NearestStationFirst
{
	public static class PairSorter
	{
		private const int IndexBits = 22;

		private const int DistBits = 32;

		private const double Unit = 100.0;

		private const double AU = 40000.0;

		private const long Farthest = 4294967295L;

		[ThreadStatic]
		private static long[] keyBuf;

		[ThreadStatic]
		private static long[] planetKey;

		[ThreadStatic]
		private static int[] planetStamp;

		[ThreadStatic]
		private static int stamp;

		public static double Distance(GalaxyData galaxy, int planetA, int planetB)
		{
			//IL_0034: 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)
			int num = planetA / 100;
			int num2 = planetB / 100;
			if (num != num2)
			{
				StarData val = galaxy.StarById(num);
				StarData val2 = galaxy.StarById(num2);
				if (val == null || val2 == null)
				{
					return 429496729500.0;
				}
				VectorLF3 val3 = val.uPosition - val2.uPosition;
				return ((VectorLF3)(ref val3)).magnitude;
			}
			PlanetData val4 = galaxy.PlanetById(planetA);
			PlanetData val5 = galaxy.PlanetById(planetB);
			if (val4 == null || val5 == null)
			{
				return 0.0;
			}
			return (double)Math.Abs(val4.sunDistance - val5.sunDistance) * 40000.0;
		}

		public static int OwnSlot(ref SupplyDemandPair p, int gid)
		{
			if (p.supplyId != gid)
			{
				return p.demandIndex;
			}
			return p.supplyIndex;
		}

		public static int FirstTier(ERemoteRoutePriority r)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			return ((int)r != 1) ? 1 : 0;
		}

		public static int LastTier(ERemoteRoutePriority r)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			if ((int)r != 1)
			{
				if ((int)r != 2)
				{
					return 4;
				}
				return 5;
			}
			return 0;
		}

		public static int SortStation(StationComponent st, StationComponent[] pool, GalaxyData galaxy)
		{
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			if (st == null || pool == null || galaxy == null)
			{
				return 0;
			}
			SupplyDemandPair[] remotePairs = st.remotePairs;
			int[] remotePairOffsets = st.remotePairOffsets;
			if (remotePairs == null || remotePairOffsets == null || remotePairOffsets.Length < 7)
			{
				return 0;
			}
			int num = remotePairOffsets[6];
			if (num < 2 || num > remotePairs.Length)
			{
				return 0;
			}
			if (keyBuf == null || keyBuf.Length < num)
			{
				keyBuf = new long[Math.Max(num, 256)];
			}
			int num2 = (galaxy.starCount + 2) * 100;
			if (planetKey == null || planetKey.Length < num2)
			{
				planetKey = new long[num2];
				planetStamp = new int[num2];
				stamp = 0;
			}
			if (++stamp == int.MaxValue)
			{
				Array.Clear(planetStamp, 0, planetStamp.Length);
				stamp = 1;
			}
			int gid = st.gid;
			int num3 = FirstTier(st.routePriority);
			int num4 = LastTier(st.routePriority);
			int num5 = 0;
			for (int i = num3; i <= num4; i++)
			{
				int num6 = remotePairOffsets[i];
				int num7 = remotePairOffsets[i + 1];
				int num8 = num7 - num6;
				if (num6 < 0 || num7 > num || num8 < 2 || num8 >= 4194304)
				{
					continue;
				}
				bool flag = true;
				long num9 = -1L;
				for (int j = num6; j < num7; j++)
				{
					bool num10 = remotePairs[j].supplyId == gid;
					int num11 = (num10 ? remotePairs[j].demandId : remotePairs[j].supplyId);
					long num12 = (num10 ? remotePairs[j].supplyIndex : remotePairs[j].demandIndex) & 0xFF;
					long num13 = 4294967295L;
					StationComponent val = ((num11 > 0 && num11 < pool.Length) ? pool[num11] : null);
					if (val != null)
					{
						int planetId = val.planetId;
						if (planetId > 0 && planetId < num2)
						{
							if (planetStamp[planetId] != stamp)
							{
								double num14 = Distance(galaxy, st.planetId, planetId) / 100.0;
								planetKey[planetId] = ((num14 >= 4294967295.0) ? uint.MaxValue : ((long)num14));
								planetStamp[planetId] = stamp;
							}
							num13 = planetKey[planetId];
						}
					}
					long num15 = (num12 << 32) | num13;
					if (num15 < num9)
					{
						flag = false;
					}
					num9 = num15;
					keyBuf[j] = (num15 << 22) | (j - num6);
				}
				if (!flag)
				{
					Array.Sort(keyBuf, remotePairs, num6, num8);
					num5++;
				}
			}
			return num5;
		}

		public static int NextStart(SupplyDemandPair[] pairs, int from, int n, int gid, int cursor)
		{
			if (n <= 1)
			{
				return 0;
			}
			int num = cursor % n;
			if (num < 0)
			{
				num += n;
			}
			int num2 = ((num == 0) ? (n - 1) : (num - 1));
			int num3 = OwnSlot(ref pairs[from + num2], gid);
			int num4 = num2 + 1;
			int num5 = n;
			while (num4 < num5)
			{
				int num6 = num4 + num5 >> 1;
				if (OwnSlot(ref pairs[from + num6], gid) > num3)
				{
					num5 = num6;
				}
				else
				{
					num4 = num6 + 1;
				}
			}
			if (num4 < n)
			{
				return num4;
			}
			return 0;
		}
	}
	[BepInPlugin("com.github.jiesiluo.neareststationfirst", "Nearest Station First", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "com.github.jiesiluo.neareststationfirst";

		public const string Name = "Nearest Station First";

		public const string Version = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> EnabledEntry;

		internal static bool Enabled;

		private void Awake()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			EnabledEntry = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Interstellar stations try the nearest supplier / demander first. 星际物流塔先挑最近的供货 / 收货塔。\nOff = vanilla behaviour again from the next dispatch (lists already sorted stay sorted until the game rebuilds them, which is harmless).");
			Enabled = EnabledEntry.Value;
			EnabledEntry.SettingChanged += delegate
			{
				Enabled = EnabledEntry.Value;
			};
			new Harmony("com.github.jiesiluo.neareststationfirst").PatchAll(typeof(Patches));
		}
	}
	internal static class Patches
	{
		private static bool[] dirty = new bool[4096];

		internal static long sortedStations;

		internal static long sortedTiers;

		internal static void Mark(int gid)
		{
			if (gid <= 0)
			{
				return;
			}
			if (gid >= dirty.Length)
			{
				int num;
				for (num = dirty.Length; num <= gid; num *= 2)
				{
				}
				Array.Resize(ref dirty, num);
			}
			dirty[gid] = true;
		}

		internal static bool IsDirty(int gid)
		{
			if (gid > 0 && gid < dirty.Length)
			{
				return dirty[gid];
			}
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StationComponent), "ClearRemotePairs")]
		private static void Cleared(StationComponent __instance)
		{
			Mark(__instance.gid);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GalacticTransport), "RefreshTraffic")]
		private static void Refreshed(GalacticTransport __instance, int keyStationGId)
		{
			StationComponent[] stationPool = __instance.stationPool;
			if (stationPool == null)
			{
				return;
			}
			if (keyStationGId > 0 && keyStationGId < stationPool.Length)
			{
				StationComponent val = stationPool[keyStationGId];
				if (val != null && val.gid == keyStationGId && val.remotePairs != null && val.remotePairOffsets != null)
				{
					int num = val.remotePairOffsets[6];
					if (num > val.remotePairs.Length)
					{
						num = val.remotePairs.Length;
					}
					for (int i = 0; i < num; i++)
					{
						Mark(val.remotePairs[i].supplyId);
						Mark(val.remotePairs[i].demandId);
					}
				}
			}
			if (!Plugin.Enabled)
			{
				return;
			}
			GalaxyData val2 = ((__instance.gameData != null) ? __instance.gameData.galaxy : null);
			if (val2 == null)
			{
				return;
			}
			int stationCursor = __instance.stationCursor;
			for (int j = 1; j < stationCursor && j < dirty.Length && j < stationPool.Length; j++)
			{
				if (dirty[j])
				{
					StationComponent val3 = stationPool[j];
					if (val3 == null || val3.gid != j)
					{
						dirty[j] = false;
					}
					else
					{
						Sort(val3, stationPool, val2);
					}
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(StationComponent), "DetermineDispatch")]
		private static void BeforeDispatch(StationComponent __instance, int priorityIndex, StationComponent[] gStationPool, GalaxyData galaxy)
		{
			if (!Plugin.Enabled)
			{
				return;
			}
			int gid = __instance.gid;
			if (gid > 0 && gid < dirty.Length && dirty[gid])
			{
				Sort(__instance, gStationPool, galaxy);
			}
			int[] remotePairProcesses = __instance.remotePairProcesses;
			int[] remotePairOffsets = __instance.remotePairOffsets;
			SupplyDemandPair[] remotePairs = __instance.remotePairs;
			if (remotePairProcesses != null && remotePairOffsets != null && remotePairs != null && priorityIndex >= 0 && priorityIndex < remotePairProcesses.Length && priorityIndex + 1 < remotePairOffsets.Length)
			{
				int num = remotePairOffsets[priorityIndex];
				int num2 = remotePairOffsets[priorityIndex + 1] - num;
				if (num2 > 0 && num >= 0 && num + num2 <= remotePairs.Length)
				{
					remotePairProcesses[priorityIndex] = PairSorter.NextStart(remotePairs, num, num2, gid, remotePairProcesses[priorityIndex]);
				}
			}
		}

		private static void Sort(StationComponent st, StationComponent[] pool, GalaxyData galaxy)
		{
			dirty[st.gid] = false;
			try
			{
				int num = PairSorter.SortStation(st, pool, galaxy);
				sortedStations++;
				sortedTiers += num;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"sorting station {st.gid} failed: {arg}");
			}
		}
	}
}