Decompiled source of StationSlotDustbin v1.1.1

plugins/StationSlotDustbin.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using crecheng.DSPModSave;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("StationSlotDustbin.InGameTests")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("StationSlotDustbin")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("StationSlotDustbin")]
[assembly: AssemblyTitle("StationSlotDustbin")]
[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 StationSlotDustbin
{
	internal static class BlueprintPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(BuildingParameters), "CopyFromFactoryObject")]
		private static void AfterCopy(ref BuildingParameters __instance, int objectId, PlanetFactory factory, bool __result)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			if (!__result || objectId <= 0 || factory?.transport == null || (int)__instance.type != 9)
			{
				return;
			}
			int[] parameters = __instance.parameters;
			if (parameters != null && parameters.Length >= 2048)
			{
				StationComponent st = Game.StationIn(factory.transport, factory.entityPool[objectId].stationId);
				if (Game.Allowed(st))
				{
					BlueprintMark.Write(parameters, TrashItems(factory.planetId, st));
				}
			}
		}

		internal static int[] TrashItems(int planetId, StationComponent st)
		{
			int[] array = new int[5];
			for (int i = 0; i < array.Length && i < st.storage.Length; i++)
			{
				int itemId = st.storage[i].itemId;
				if (itemId > 0 && Plugin.Store.IsOn(planetId, st.id, itemId))
				{
					array[i] = itemId;
				}
			}
			return array;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BuildingParameters), "ApplyPrebuildParametersToEntity")]
		private static void AfterApply(int entityId, int[] parameters, PlanetFactory factory)
		{
			if (factory?.transport == null || entityId <= 0 || !BlueprintMark.Has(parameters))
			{
				return;
			}
			StationComponent st = Game.StationIn(factory.transport, factory.entityPool[entityId].stationId);
			if (!Game.Allowed(st))
			{
				return;
			}
			foreach (var item2 in BlueprintMark.ToSwitchOn(parameters, st.storage.Length, (int k) => st.storage[k].itemId))
			{
				int item = item2.item;
				Plugin.Store.Set(factory.planetId, st.id, item, on: true);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BuildingParameters), "PasteToFactoryObject")]
		private static void AfterPaste(ref BuildingParameters __instance, int objectId, PlanetFactory factory, bool __result)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			if (!__result || objectId <= 0 || factory?.transport == null || (int)__instance.type != 9)
			{
				return;
			}
			int[] parameters = __instance.parameters;
			if (parameters == null || parameters.Length < 2048)
			{
				return;
			}
			StationComponent val = Game.StationIn(factory.transport, factory.entityPool[objectId].stationId);
			if (!Game.Allowed(val))
			{
				return;
			}
			int[] array = BlueprintMark.Read(parameters) ?? new int[5];
			bool flag = false;
			for (int i = 0; i < val.storage.Length && i < 5; i++)
			{
				int itemId = val.storage[i].itemId;
				if (itemId > 0 && parameters[i * 6] == itemId)
				{
					flag |= Plugin.Store.Set(factory.planetId, val.id, itemId, array[i] == itemId);
				}
			}
			if (flag)
			{
				for (int j = 0; j < val.storage.Length; j++)
				{
					Game.NotifySlotSetting(factory, val, j);
				}
			}
		}
	}
	[BepInPlugin("com.github.jiesiluo.stationslotdustbin", "Station Slot Dustbin", "1.1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin, IModCanSave
	{
		public const string Guid = "com.github.jiesiluo.stationslotdustbin";

		public const string Name = "Station Slot Dustbin";

		public const string Version = "1.1.1";

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> ButtonOffsetX;

		internal static ConfigEntry<float> ButtonOffsetY;

		public static readonly TrashStore Store = new TrashStore();

		private void Awake()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: 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)
			Log = ((BaseUnityPlugin)this).Logger;
			ButtonOffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "ButtonOffsetX", 0f, "Move the trash button of the station window right (positive) or left, in pixels.");
			ButtonOffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "ButtonOffsetY", 0f, "Move the trash button up (positive) or down, in pixels.");
			Store.Changed += NeedsIndex.Rebuild;
			FreezeProbe.Resolve();
			Harmony val = new Harmony("com.github.jiesiluo.stationslotdustbin");
			val.PatchAll(typeof(TransportPatches));
			val.PatchAll(typeof(BlueprintPatches));
			val.PatchAll(typeof(UiPatches));
		}

		public void Export(BinaryWriter w)
		{
			int num = Store.Export(w, Game.SlotOf);
			Log.LogInfo((object)$"saved {num} trash slot(s)");
		}

		public void Import(BinaryReader r)
		{
			var (num, num2) = Store.Import(r, Game.SlotHolds);
			Log.LogInfo((object)($"loaded {num} trash slot(s)" + ((num2 > 0) ? $", dropped {num2} whose slot no longer holds the saved item" : "")));
		}

		public void IntoOtherSave()
		{
			Store.Clear();
		}
	}
	internal static class UiPatches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(UIStationWindow), "_OnOpen")]
		private static void StationWindowOpen(UIStationWindow __instance)
		{
			TrashPanel.Attach(__instance);
		}
	}
	public static class TrashSlots
	{
		public static int Version => Plugin.Store.Version;

		public static bool IsTrash(int planetId, int stationId, int itemId)
		{
			return Plugin.Store.IsOn(planetId, stationId, itemId);
		}

		public static bool Set(PlanetFactory factory, StationComponent station, int itemId, bool on)
		{
			if (factory == null || !Game.Allowed(station) || Game.SlotOfItem(station, itemId) < 0)
			{
				return false;
			}
			if (!Plugin.Store.Set(factory.planetId, station.id, itemId, on))
			{
				return false;
			}
			Game.NotifySlotSetting(factory, station, Game.SlotOfItem(station, itemId));
			return true;
		}
	}
	internal static class Game
	{
		internal static bool NotifyEnabled = true;

		public static bool Allowed(StationComponent st)
		{
			if (st != null && st.id > 0 && !st.isCollector && !st.isVeinCollector)
			{
				return st.storage != null;
			}
			return false;
		}

		public static int SlotOfItem(StationComponent st, int itemId)
		{
			if (st?.storage == null || itemId <= 0)
			{
				return -1;
			}
			for (int i = 0; i < st.storage.Length; i++)
			{
				if (st.storage[i].itemId == itemId)
				{
					return i;
				}
			}
			return -1;
		}

		public static StationComponent StationIn(PlanetTransport t, int stationId)
		{
			if (t?.stationPool == null || stationId <= 0 || stationId >= t.stationCursor || stationId >= t.stationPool.Length)
			{
				return null;
			}
			StationComponent val = t.stationPool[stationId];
			if (val == null || val.id != stationId)
			{
				return null;
			}
			return val;
		}

		public static StationComponent Station(int planetId, int stationId)
		{
			GalaxyData galaxy = GameMain.galaxy;
			PlanetTransport val = ((galaxy == null) ? null : galaxy.PlanetById(planetId)?.factory)?.transport;
			if (val?.stationPool == null || stationId <= 0 || stationId >= val.stationCursor || stationId >= val.stationPool.Length)
			{
				return null;
			}
			StationComponent val2 = val.stationPool[stationId];
			if (val2 == null || val2.id != stationId)
			{
				return null;
			}
			return val2;
		}

		public static int SlotOf(int planetId, int stationId, int itemId)
		{
			StationComponent st = Station(planetId, stationId);
			if (!Allowed(st))
			{
				return -1;
			}
			return SlotOfItem(st, itemId);
		}

		public static bool SlotHolds(int planetId, int stationId, int slot, int itemId)
		{
			StationComponent val = Station(planetId, stationId);
			if (Allowed(val) && slot >= 0 && slot < val.storage.Length)
			{
				return val.storage[slot].itemId == itemId;
			}
			return false;
		}

		public static void NotifySlotSetting(PlanetFactory factory, StationComponent st, int slot)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			if (!NotifyEnabled || factory?.transport == null || !Allowed(st) || slot < 0 || slot >= st.storage.Length)
			{
				return;
			}
			StationStore val = st.storage[slot];
			if (val.itemId <= 0)
			{
				return;
			}
			ModelProto val2 = ((ProtoSet<ModelProto>)(object)LDB.models).Select((int)factory.entityPool[st.entityId].modelIndex);
			if (val2 != null)
			{
				int num = (st.isStellar ? GameMain.history.remoteStationExtraStorage : GameMain.history.localStationExtraStorage);
				if (val.max <= val2.prefabDesc.stationMaxItemCount + num)
				{
					factory.transport.SetStationStorage(st.id, slot, val.itemId, val.max, val.localLogic, val.remoteLogic, (Player)null);
				}
			}
		}
	}
	internal static class NeedsIndex
	{
		private sealed class RefEq : IEqualityComparer<StationComponent>
		{
			public bool Equals(StationComponent a, StationComponent b)
			{
				return a == b;
			}

			public int GetHashCode(StationComponent o)
			{
				return RuntimeHelpers.GetHashCode(o);
			}
		}

		private static readonly RefEq Cmp = new RefEq();

		private static volatile Dictionary<StationComponent, int[]> map = new Dictionary<StationComponent, int[]>(Cmp);

		public static int Count => map.Count;

		public static int[] Get(StationComponent st)
		{
			Dictionary<StationComponent, int[]> dictionary = map;
			if (dictionary.Count == 0 || !dictionary.TryGetValue(st, out var value))
			{
				return null;
			}
			return value;
		}

		public static void Rebuild()
		{
			Dictionary<StationComponent, List<int>> dictionary = new Dictionary<StationComponent, List<int>>(Cmp);
			foreach (TrashEntry item in Plugin.Store.All())
			{
				StationComponent val = Game.Station(item.PlanetId, item.StationId);
				if (Game.Allowed(val))
				{
					if (!dictionary.TryGetValue(val, out var value))
					{
						value = (dictionary[val] = new List<int>());
					}
					value.Add(item.ItemId);
				}
			}
			Dictionary<StationComponent, int[]> dictionary2 = new Dictionary<StationComponent, int[]>(Cmp);
			foreach (KeyValuePair<StationComponent, List<int>> item2 in dictionary)
			{
				dictionary2[item2.Key] = item2.Value.ToArray();
			}
			map = dictionary2;
		}

		internal static void SetForTest(StationComponent st, int[] items)
		{
			Dictionary<StationComponent, int[]> dictionary = new Dictionary<StationComponent, int[]>(map, Cmp);
			if (items == null)
			{
				dictionary.Remove(st);
			}
			else
			{
				dictionary[st] = items;
			}
			map = dictionary;
		}
	}
	internal static class FreezeProbe
	{
		private static MethodInfo tryGet;

		private static FieldInfo modeField;

		private static object frozenValue;

		public static bool Available => tryGet != null;

		public static void Resolve()
		{
			try
			{
				Type type = AccessTools.TypeByName("SampleAndHoldSim.MainManager");
				Type type2 = AccessTools.TypeByName("SampleAndHoldSim.FactoryManager");
				Type type3 = AccessTools.TypeByName("SampleAndHoldSim.FactoryMode");
				if (type == null || type2 == null || type3 == null)
				{
					return;
				}
				tryGet = AccessTools.Method(type, "TryGet", (Type[])null, (Type[])null);
				modeField = AccessTools.Field(type2, "Mode");
				frozenValue = Enum.Parse(type3, "Frozen");
				if (tryGet == null || modeField == null)
				{
					tryGet = null;
					return;
				}
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"PlanetFreeze fork found: trash slots on frozen planets are kept up to {256} below max");
				}
			}
			catch (Exception ex)
			{
				tryGet = null;
				ManualLogSource log2 = Plugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("PlanetFreeze probe off: " + ex.Message));
				}
			}
		}

		public static bool IsFrozen(PlanetFactory f)
		{
			if (tryGet == null || f == null)
			{
				return false;
			}
			try
			{
				object[] array = new object[2] { f.index, null };
				if (!(bool)tryGet.Invoke(null, array) || array[1] == null)
				{
					return false;
				}
				return object.Equals(modeField.GetValue(array[1]), frozenValue);
			}
			catch
			{
				return false;
			}
		}
	}
	internal static class TransportPatches
	{
		[ThreadStatic]
		private static int[] slotBuf;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(StationComponent), "UpdateNeeds")]
		private static void AfterUpdateNeeds(StationComponent __instance)
		{
			int[] array = NeedsIndex.Get(__instance);
			if (array != null)
			{
				StationStore[] storage = __instance.storage;
				int[] array2 = slotBuf ?? (slotBuf = new int[5]);
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = ((i < storage.Length) ? storage[i].itemId : 0);
				}
				TrashMath.OpenNeeds(__instance.needs, array2, array);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlanetTransport), "GameTick")]
		private static void BeforeTransportTick(PlanetTransport __instance)
		{
			CutPlanet(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlanetTransport), "GameTick")]
		private static void AfterTransportTick(PlanetTransport __instance)
		{
			CutPlanet(__instance);
		}

		internal static void CutPlanet(PlanetTransport t)
		{
			PlanetFactory factory = t.factory;
			if (factory == null)
			{
				return;
			}
			TrashEntry[] array = Plugin.Store.ForPlanet(factory.planetId);
			if (array == null)
			{
				return;
			}
			bool frozen = FreezeProbe.IsFrozen(factory);
			StationComponent[] stationPool = t.stationPool;
			int stationCursor = t.stationCursor;
			foreach (TrashEntry trashEntry in array)
			{
				int stationId = trashEntry.StationId;
				if (stationId > 0 && stationId < stationCursor && stationId < stationPool.Length)
				{
					StationComponent val = stationPool[stationId];
					if (Game.Allowed(val) && val.id == stationId)
					{
						Cut(val, trashEntry, frozen);
					}
				}
			}
		}

		internal static int Cut(StationComponent st, TrashEntry entry, bool frozen)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Invalid comparison between Unknown and I4
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Invalid comparison between Unknown and I4
			int num = 0;
			StationStore[] storage = st.storage;
			lock (storage)
			{
				for (int i = 0; i < storage.Length; i++)
				{
					if (storage[i].itemId == entry.ItemId)
					{
						int max = storage[i].max;
						bool flag = (int)storage[i].localLogic == 2 || (int)storage[i].remoteLogic == 2;
						int level = ((frozen && !flag) ? TrashMath.FrozenLevel(max) : TrashMath.Level(max));
						if (TrashMath.Trim(storage[i].count, storage[i].inc, level, out var newCount, out var newInc))
						{
							num = storage[i].count - newCount;
							storage[i].count = newCount;
							storage[i].inc = newInc;
						}
						break;
					}
				}
			}
			if (num > 0)
			{
				entry.AddDestroyed(num);
			}
			return num;
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlanetTransport), "SetStationStorage")]
		private static void BeforeSetStorage(PlanetTransport __instance, int stationId, int storageIdx, out int __state)
		{
			__state = 0;
			StationComponent val = Game.StationIn(__instance, stationId);
			if (val?.storage != null && storageIdx >= 0 && storageIdx < val.storage.Length)
			{
				__state = val.storage[storageIdx].itemId;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlanetTransport), "SetStationStorage")]
		private static void AfterSetStorage(PlanetTransport __instance, int stationId, int storageIdx, int __state)
		{
			if (__state > 0 && __instance.factory != null)
			{
				StationComponent val = Game.StationIn(__instance, stationId);
				int num = ((val?.storage != null && storageIdx >= 0 && storageIdx < val.storage.Length) ? val.storage[storageIdx].itemId : 0);
				if (num != __state)
				{
					Plugin.Store.SlotItemChanged(__instance.factory.planetId, stationId, __state, num);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlanetTransport), "RemoveStationComponent")]
		private static void BeforeRemoveStation(PlanetTransport __instance, int id)
		{
			if (__instance.factory != null && id > 0)
			{
				Plugin.Store.StationRemoved(__instance.factory.planetId, id);
			}
		}
	}
	public static class TrashMath
	{
		public const int FrozenRoom = 256;

		public static int Level(int max)
		{
			if (max > 0)
			{
				return max;
			}
			return 0;
		}

		public static int FrozenLevel(int max)
		{
			if (max > 0)
			{
				return max - Math.Min(256, max / 4);
			}
			return 0;
		}

		public static bool Trim(int count, int inc, int level, out int newCount, out int newInc)
		{
			newCount = count;
			newInc = inc;
			if (level < 0)
			{
				level = 0;
			}
			if (count <= level)
			{
				return false;
			}
			newCount = level;
			if (inc > 0)
			{
				newInc = (int)((long)inc * (long)level / count);
			}
			return true;
		}

		public static int OpenNeeds(int[] needs, int[] slotItems, int[] trashItems)
		{
			if (needs == null || slotItems == null || trashItems == null)
			{
				return 0;
			}
			int num = 0;
			for (int i = 0; i < slotItems.Length && i < needs.Length && i < 5; i++)
			{
				int num2 = slotItems[i];
				if (num2 > 0 && needs[i] == 0 && Array.IndexOf(trashItems, num2) >= 0)
				{
					needs[i] = num2;
					num++;
				}
			}
			return num;
		}
	}
	public sealed class TrashEntry
	{
		public readonly int PlanetId;

		public readonly int StationId;

		public readonly int ItemId;

		public long Destroyed;

		public TrashEntry(int planetId, int stationId, int itemId)
		{
			PlanetId = planetId;
			StationId = stationId;
			ItemId = itemId;
		}

		public void AddDestroyed(int n)
		{
			Interlocked.Add(ref Destroyed, n);
		}
	}
	public sealed class TrashStore
	{
		private struct Key : IEquatable<Key>
		{
			public readonly int P;

			public readonly int S;

			public readonly int I;

			public Key(int p, int s, int i)
			{
				P = p;
				S = s;
				I = i;
			}

			public bool Equals(Key o)
			{
				if (P == o.P && S == o.S)
				{
					return I == o.I;
				}
				return false;
			}

			public override bool Equals(object obj)
			{
				if (obj is Key o)
				{
					return Equals(o);
				}
				return false;
			}

			public override int GetHashCode()
			{
				return (((P * 397) ^ S) * 397) ^ I;
			}
		}

		public const ushort SaveVersion = 1;

		private readonly object gate = new object();

		private readonly Dictionary<Key, TrashEntry> map = new Dictionary<Key, TrashEntry>();

		private volatile Dictionary<int, TrashEntry[]> snapshot = new Dictionary<int, TrashEntry[]>();

		private int version;

		public int Version => version;

		public int Count
		{
			get
			{
				lock (gate)
				{
					return map.Count;
				}
			}
		}

		public event Action Changed;

		public bool IsOn(int planetId, int stationId, int itemId)
		{
			if (itemId <= 0)
			{
				return false;
			}
			lock (gate)
			{
				return map.ContainsKey(new Key(planetId, stationId, itemId));
			}
		}

		public TrashEntry Find(int planetId, int stationId, int itemId)
		{
			lock (gate)
			{
				TrashEntry value;
				return map.TryGetValue(new Key(planetId, stationId, itemId), out value) ? value : null;
			}
		}

		public bool Set(int planetId, int stationId, int itemId, bool on)
		{
			if (itemId <= 0 || stationId <= 0)
			{
				return false;
			}
			lock (gate)
			{
				Key key = new Key(planetId, stationId, itemId);
				if (map.ContainsKey(key) == on)
				{
					return false;
				}
				if (on)
				{
					map[key] = new TrashEntry(planetId, stationId, itemId);
				}
				else
				{
					map.Remove(key);
				}
				Rebuild();
				return true;
			}
		}

		public bool Toggle(int planetId, int stationId, int itemId)
		{
			lock (gate)
			{
				bool flag = !IsOn(planetId, stationId, itemId);
				Set(planetId, stationId, itemId, flag);
				return IsOn(planetId, stationId, itemId);
			}
		}

		public bool SlotItemChanged(int planetId, int stationId, int oldItem, int newItem)
		{
			if (oldItem <= 0 || oldItem == newItem)
			{
				return false;
			}
			return Set(planetId, stationId, oldItem, on: false);
		}

		public int StationRemoved(int planetId, int stationId)
		{
			lock (gate)
			{
				List<Key> list = new List<Key>();
				foreach (Key key in map.Keys)
				{
					if (key.P == planetId && key.S == stationId)
					{
						list.Add(key);
					}
				}
				foreach (Key item in list)
				{
					map.Remove(item);
				}
				if (list.Count > 0)
				{
					Rebuild();
				}
				return list.Count;
			}
		}

		public void Clear()
		{
			lock (gate)
			{
				map.Clear();
				Rebuild();
			}
		}

		public TrashEntry[] ForPlanet(int planetId)
		{
			if (!snapshot.TryGetValue(planetId, out var value))
			{
				return null;
			}
			return value;
		}

		public List<TrashEntry> All()
		{
			lock (gate)
			{
				return new List<TrashEntry>(map.Values);
			}
		}

		private void Rebuild()
		{
			Dictionary<int, List<TrashEntry>> dictionary = new Dictionary<int, List<TrashEntry>>();
			foreach (TrashEntry value2 in map.Values)
			{
				if (!dictionary.TryGetValue(value2.PlanetId, out var value))
				{
					value = (dictionary[value2.PlanetId] = new List<TrashEntry>());
				}
				value.Add(value2);
			}
			Dictionary<int, TrashEntry[]> dictionary2 = new Dictionary<int, TrashEntry[]>(dictionary.Count);
			foreach (KeyValuePair<int, List<TrashEntry>> item in dictionary)
			{
				item.Value.Sort(delegate(TrashEntry a, TrashEntry b)
				{
					int itemId;
					if (a.StationId == b.StationId)
					{
						itemId = a.ItemId;
						return itemId.CompareTo(b.ItemId);
					}
					itemId = a.StationId;
					return itemId.CompareTo(b.StationId);
				});
				dictionary2[item.Key] = item.Value.ToArray();
			}
			snapshot = dictionary2;
			Interlocked.Increment(ref version);
			this.Changed?.Invoke();
		}

		public int Export(BinaryWriter w, Func<int, int, int, int> slotOf)
		{
			List<int[]> list = new List<int[]>();
			lock (gate)
			{
				foreach (TrashEntry value in map.Values)
				{
					int num = slotOf?.Invoke(value.PlanetId, value.StationId, value.ItemId) ?? 0;
					if (num >= 0)
					{
						list.Add(new int[4] { value.PlanetId, value.StationId, num, value.ItemId });
					}
				}
			}
			list.Sort((int[] a, int[] b) => (a[0] == b[0]) ? ((a[1] == b[1]) ? a[2].CompareTo(b[2]) : a[1].CompareTo(b[1])) : a[0].CompareTo(b[0]));
			w.Write((ushort)1);
			w.Write(list.Count);
			foreach (int[] item in list)
			{
				w.Write(item[0]);
				w.Write(item[1]);
				w.Write(item[2]);
				w.Write(item[3]);
			}
			return list.Count;
		}

		public (int kept, int dropped) Import(BinaryReader r, Func<int, int, int, int, bool> valid)
		{
			lock (gate)
			{
				map.Clear();
				int num = 0;
				int num2 = 0;
				ushort num3 = r.ReadUInt16();
				if (num3 >= 1 && num3 <= 1)
				{
					int num4 = r.ReadInt32();
					for (int i = 0; i < num4; i++)
					{
						int num5 = r.ReadInt32();
						int num6 = r.ReadInt32();
						int num7 = r.ReadInt32();
						int num8 = r.ReadInt32();
						Key key = new Key(num5, num6, num8);
						if (num8 > 0 && num6 > 0 && num7 >= 0 && !map.ContainsKey(key) && (valid == null || valid(num5, num6, num7, num8)))
						{
							map[key] = new TrashEntry(num5, num6, num8);
							num++;
						}
						else
						{
							num2++;
						}
					}
				}
				Rebuild();
				return (kept: num, dropped: num2);
			}
		}
	}
	public static class TrashText
	{
		public static string ButtonTitle(bool zh)
		{
			if (!zh)
			{
				return "Trash slots";
			}
			return "垃圾格";
		}

		public static string ButtonBody(bool zh, int onCount)
		{
			if (!zh)
			{
				if (onCount <= 0)
				{
					return "Click to choose which slots of this station destroy their surplus.";
				}
				return $"{onCount} slot(s) of this station destroy their surplus. Click to set.";
			}
			if (onCount <= 0)
			{
				return "点一下设置这座塔哪一格把多出来的销毁。";
			}
			return $"这座塔有 {onCount} 格在销毁多出来的物品。点一下设置。";
		}

		public static string PanelTitle(bool zh)
		{
			if (!zh)
			{
				return "Trash slots (destroy surplus)";
			}
			return "垃圾格(多的销毁)";
		}

		public static string PanelRule(bool zh)
		{
			if (!zh)
			{
				return "Checked slots: once full, whatever comes in is destroyed (drones and ships work as usual, nothing extra is fetched).";
			}
			return "勾上的格子到上限以后,送进来的直接销毁(运输机、运输船照常,不会多拉)。";
		}

		public static string PanelDestroyed(bool zh, long destroyed)
		{
			if (!zh)
			{
				return $"Destroyed by this station since loading: {destroyed}";
			}
			return $"读档以来这座塔已销毁 {destroyed}";
		}

		public static string Row(string itemName, int count, int max)
		{
			return $"{itemName}  {count} / {max}";
		}

		public static string EmptyRow(bool zh)
		{
			if (!zh)
			{
				return "(empty)";
			}
			return "(空格)";
		}
	}
	public static class BlueprintMark
	{
		public const int Offset = 2040;

		public const int Magic = 1397965890;

		public const int FormatVersion = 1;

		public const int MaxSlots = 5;

		public const int Length = 8;

		public const int ParamsLength = 2048;

		public static bool Write(int[] p, int[] trashItems)
		{
			if (p == null || p.Length < 2048)
			{
				return false;
			}
			Clear(p);
			int num = 0;
			for (int i = 0; i < 5; i++)
			{
				if (trashItems == null)
				{
					break;
				}
				if (i >= trashItems.Length)
				{
					break;
				}
				if (trashItems[i] > 0)
				{
					num |= 1 << i;
					p[2043 + i] = trashItems[i];
				}
			}
			if (num == 0)
			{
				return false;
			}
			p[2040] = 1397965890;
			p[2041] = 1;
			p[2042] = num;
			return true;
		}

		public static void Clear(int[] p)
		{
			if (p != null && p.Length >= 2048)
			{
				Array.Clear(p, 2040, 8);
			}
		}

		public static bool Has(int[] p)
		{
			if (p != null && p.Length >= 2048 && p[2040] == 1397965890)
			{
				return p[2041] == 1;
			}
			return false;
		}

		public static int[] Read(int[] p)
		{
			if (!Has(p))
			{
				return null;
			}
			int num = p[2042];
			int[] array = new int[5];
			for (int i = 0; i < 5; i++)
			{
				if ((num & (1 << i)) != 0 && p[2043 + i] > 0)
				{
					array[i] = p[2043 + i];
				}
			}
			return array;
		}

		public static List<(int slot, int item)> ToSwitchOn(int[] p, int slotCount, Func<int, int> itemAt)
		{
			List<(int, int)> list = new List<(int, int)>();
			int[] array = Read(p);
			if (array == null)
			{
				return list;
			}
			for (int i = 0; i < 5 && i < slotCount; i++)
			{
				if (array[i] > 0 && itemAt(i) == array[i])
				{
					list.Add((i, array[i]));
				}
			}
			return list;
		}
	}
	public class ClickRelay : MonoBehaviour, IPointerClickHandler, IEventSystemHandler
	{
		public Action OnClick;

		public void OnPointerClick(PointerEventData e)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			if ((int)e.button == 0)
			{
				OnClick?.Invoke();
			}
		}
	}
	public class TrashPanel : MonoBehaviour
	{
		private class Row
		{
			public GameObject Go;

			public Image Icon;

			public Text Label;

			public Image Box;

			public Image Check;

			public int Slot;
		}

		public const string Prefix = "StationSlotDustbin-";

		public const int SignalIcon = 410;

		public const float ButtonSize = 22f;

		private const float RuleHeight = 34f;

		private const float RowsTop = -89f;

		private static readonly Color OffColor = new Color(1f, 1f, 1f, 0.243f);

		private static readonly Color OnColor = new Color(1f, 0.62f, 0.36f, 0.243f);

		private static readonly Color OffPlain = new Color(0.72f, 0.75f, 0.8f, 0.9f);

		private static readonly Color OnPlain = new Color(1f, 0.62f, 0.36f, 1f);

		private static readonly Color MarkColor = new Color(1f, 0.62f, 0.36f, 1f);

		private static readonly Color PanelColor = new Color(0.05f, 0.075f, 0.11f, 1f);

		private static readonly Color LineColor = new Color(0.656f, 0.915f, 1f, 0.35f);

		private static readonly Color BoxColor = new Color(0.25f, 0.3f, 0.36f, 1f);

		private static readonly Color TextColor = new Color(0.94f, 0.96f, 0.99f, 1f);

		private static readonly Color DimText = new Color(0.74f, 0.79f, 0.84f, 1f);

		private UIStationWindow window;

		private RectTransform root;

		private Font font;

		private Sprite trashSprite;

		private bool plainButton;

		private GameObject buttonGo;

		private Image buttonIcon;

		private UIButton buttonTip;

		private GameObject blocker;

		private GameObject panel;

		private Text ruleText;

		private Text destroyedText;

		private readonly List<Row> rows = new List<Row>();

		private readonly Dictionary<UIStationStorage, Image> marks = new Dictionary<UIStationStorage, Image>();

		private int shownStation = -1;

		private int frame;

		private static FieldInfo storageField;

		public GameObject Button => buttonGo;

		public bool PanelOpen
		{
			get
			{
				if ((Object)(object)panel != (Object)null)
				{
					return panel.activeSelf;
				}
				return false;
			}
		}

		public int RowCount => rows.Count;

		public bool ButtonLit
		{
			get
			{
				//IL_0014: 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_0021: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)buttonIcon != (Object)null)
				{
					return ((Graphic)buttonIcon).color == (plainButton ? OnPlain : OnColor);
				}
				return false;
			}
		}

		public void ClickButton()
		{
			TogglePanel();
		}

		public void ClickRow(int slot)
		{
			foreach (Row row in rows)
			{
				if (row.Slot == slot)
				{
					RowClicked(row);
				}
			}
		}

		public void ClickOutside()
		{
			ClosePanel();
		}

		public bool MarkShown(UIStationStorage ui)
		{
			if (marks.TryGetValue(ui, out var value) && (Object)(object)value != (Object)null)
			{
				return ((Component)value).gameObject.activeSelf;
			}
			return false;
		}

		public static TrashPanel Attach(UIStationWindow w)
		{
			if ((Object)(object)w == (Object)null || (Object)(object)w.windowTrans == (Object)null)
			{
				return null;
			}
			TrashPanel trashPanel = ((Component)w).gameObject.GetComponent<TrashPanel>();
			if ((Object)(object)trashPanel == (Object)null)
			{
				trashPanel = ((Component)w).gameObject.AddComponent<TrashPanel>();
			}
			trashPanel.window = w;
			trashPanel.Build();
			trashPanel.ClosePanel();
			trashPanel.Refresh(full: true);
			return trashPanel;
		}

		private void Build()
		{
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: 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_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0422: Unknown result type (might be due to invalid IL or missing references)
			//IL_0476: Unknown result type (might be due to invalid IL or missing references)
			//IL_047b: Unknown result type (might be due to invalid IL or missing references)
			//IL_047c: Unknown result type (might be due to invalid IL or missing references)
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0495: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_0498: Unknown result type (might be due to invalid IL or missing references)
			//IL_049f: Unknown result type (might be due to invalid IL or missing references)
			//IL_04b1: 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_028a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: 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_02a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_0304: Unknown result type (might be due to invalid IL or missing references)
			//IL_04eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f2: Expected O, but got Unknown
			//IL_05f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0607: Unknown result type (might be due to invalid IL or missing references)
			//IL_0630: Unknown result type (might be due to invalid IL or missing references)
			//IL_063f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0682: Unknown result type (might be due to invalid IL or missing references)
			//IL_0691: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_06c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0705: Unknown result type (might be due to invalid IL or missing references)
			//IL_0722: Unknown result type (might be due to invalid IL or missing references)
			//IL_0727: Unknown result type (might be due to invalid IL or missing references)
			//IL_072b: 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_0569: Unknown result type (might be due to invalid IL or missing references)
			//IL_050e: Unknown result type (might be due to invalid IL or missing references)
			//IL_058b: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_052f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0545: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_05bd: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)buttonGo != (Object)null)
			{
				return;
			}
			root = window.windowTrans;
			font = (((Object)(object)window.titleText != (Object)null) ? window.titleText.font : null);
			trashSprite = null;
			Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
			foreach (Sprite val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name == "trash-2")
				{
					trashSprite = val;
					break;
				}
			}
			if ((Object)(object)trashSprite == (Object)null)
			{
				trashSprite = LDB.signals.IconSprite(410);
			}
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(-70f + Plugin.ButtonOffsetX.Value, -60f + Plugin.ButtonOffsetY.Value);
			UIButton val3 = null;
			try
			{
				val3 = UIRoot.instance.uiGame.researchQueue.pauseButton;
			}
			catch (Exception)
			{
			}
			Vector2 val5 = default(Vector2);
			Vector2 anchorMin;
			if ((Object)(object)val3 != (Object)null)
			{
				buttonGo = Object.Instantiate<GameObject>(((Component)val3).gameObject, (Transform)(object)root);
				((Object)buttonGo).name = "StationSlotDustbin-button";
				RectTransform val4 = (RectTransform)buttonGo.transform;
				((Vector2)(ref val5))..ctor(1f, 1f);
				val4.pivot = val5;
				anchorMin = (val4.anchorMax = val5);
				val4.anchorMin = anchorMin;
				float num = 11f / 30f;
				((Transform)val4).localScale = new Vector3(num, num, num);
				val4.anchoredPosition = val2;
				Transform val7 = buttonGo.transform.Find("icon");
				buttonIcon = (((Object)(object)val7 != (Object)null) ? ((Component)val7).GetComponent<Image>() : null);
				buttonTip = buttonGo.GetComponent<UIButton>();
				if ((Object)(object)buttonIcon == (Object)null || (Object)(object)buttonTip == (Object)null)
				{
					Object.Destroy((Object)(object)buttonGo);
					buttonGo = null;
				}
				else
				{
					if ((Object)(object)trashSprite != (Object)null)
					{
						buttonIcon.sprite = trashSprite;
					}
					buttonIcon.preserveAspect = true;
					((Graphic)buttonIcon).color = OffColor;
					buttonTip.onClick += delegate
					{
						TogglePanel();
					};
				}
			}
			if ((Object)(object)buttonGo == (Object)null)
			{
				plainButton = true;
				buttonGo = NewUI("button", (Transform)(object)root);
				RectTransform val8 = (RectTransform)buttonGo.transform;
				((Vector2)(ref val5))..ctor(1f, 1f);
				val8.pivot = val5;
				anchorMin = (val8.anchorMax = val5);
				val8.anchorMin = anchorMin;
				val8.sizeDelta = new Vector2(22f, 22f);
				val8.anchoredPosition = val2;
				buttonIcon = buttonGo.AddComponent<Image>();
				buttonIcon.sprite = trashSprite;
				buttonIcon.preserveAspect = true;
				((Graphic)buttonIcon).color = OffPlain;
				buttonGo.AddComponent<ClickRelay>().OnClick = TogglePanel;
				buttonTip = buttonGo.AddComponent<UIButton>();
				buttonTip.transitions = (Transition[])(object)new Transition[0];
			}
			buttonTip.tips.tipTitle = "";
			buttonTip.tips.tipText = "";
			buttonTip.tips.corner = 3;
			buttonTip.tips.delay = 0.4f;
			buttonTip.tips.width = 240;
			blocker = NewUI("blocker", (Transform)(object)root);
			RectTransform val10 = (RectTransform)blocker.transform;
			val10.anchorMin = Vector2.zero;
			val10.anchorMax = Vector2.one;
			anchorMin = (val10.offsetMax = Vector2.zero);
			val10.offsetMin = anchorMin;
			((Graphic)blocker.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0f);
			blocker.AddComponent<ClickRelay>().OnClick = ClosePanel;
			blocker.SetActive(false);
			panel = NewUI("panel", (Transform)(object)root);
			RectTransform val11 = (RectTransform)panel.transform;
			((Vector2)(ref val5))..ctor(1f, 1f);
			val11.pivot = val5;
			anchorMin = (val11.anchorMax = val5);
			val11.anchorMin = anchorMin;
			((Graphic)panel.AddComponent<Image>()).color = PanelColor;
			for (int num2 = 0; num2 < 4; num2++)
			{
				GameObject obj = NewUI("line" + num2, panel.transform);
				RectTransform val13 = (RectTransform)obj.transform;
				if (num2 < 2)
				{
					val13.anchorMin = new Vector2(0f, (num2 == 0) ? 1f : 0f);
					val13.anchorMax = new Vector2(1f, (num2 == 0) ? 1f : 0f);
					val13.sizeDelta = new Vector2(0f, 1f);
				}
				else
				{
					val13.anchorMin = new Vector2((num2 == 2) ? 0f : 1f, 0f);
					val13.anchorMax = new Vector2((num2 == 2) ? 0f : 1f, 1f);
					val13.sizeDelta = new Vector2(1f, 0f);
				}
				val13.anchoredPosition = Vector2.zero;
				Image obj2 = obj.AddComponent<Image>();
				((Graphic)obj2).color = LineColor;
				((Graphic)obj2).raycastTarget = false;
			}
			NewText(panel.transform, "title", TrashText.PanelTitle(Localization.isZHCN), 15, TextColor, new Vector2(12f, -8f), 280f);
			ruleText = NewText(panel.transform, "rule", "", 12, DimText, new Vector2(12f, -31f), 296f);
			ruleText.horizontalOverflow = (HorizontalWrapMode)0;
			ruleText.verticalOverflow = (VerticalWrapMode)1;
			ruleText.alignment = (TextAnchor)0;
			((RectTransform)((Component)ruleText).transform).sizeDelta = new Vector2(296f, 34f);
			destroyedText = NewText(panel.transform, "destroyed", "", 12, DimText, new Vector2(12f, -67f), 296f);
			panel.SetActive(false);
			buttonGo.transform.SetAsLastSibling();
			ManualLogSource log = Plugin.Log;
			object[] obj3 = new object[5]
			{
				val2,
				((Object)root).name,
				null,
				null,
				null
			};
			Rect rect = root.rect;
			obj3[2] = ((Rect)(ref rect)).size;
			obj3[3] = (plainButton ? "plain icon" : "round button");
			obj3[4] = (((Object)(object)trashSprite != (Object)null) ? ((Object)trashSprite).name : "none");
			log.LogDebug((object)string.Format("station window: trash button at {0} in {1} ({2}), {3}, icon {4}", obj3));
		}

		private GameObject NewUI(string name, Transform parent)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			GameObject val = new GameObject("StationSlotDustbin-" + name, new Type[1] { typeof(RectTransform) })
			{
				layer = ((Component)parent).gameObject.layer
			};
			val.transform.SetParent(parent, false);
			return val;
		}

		private Text NewText(Transform parent, string name, string s, int size, Color c, Vector2 pos, float width)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: 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_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = NewUI(name, parent);
			RectTransform val = (RectTransform)obj.transform;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0f, 1f);
			val.pivot = val2;
			Vector2 anchorMin = (val.anchorMax = val2);
			val.anchorMin = anchorMin;
			val.anchoredPosition = pos;
			val.sizeDelta = new Vector2(width, (float)(size + 6));
			Text obj2 = obj.AddComponent<Text>();
			obj2.font = font;
			obj2.fontSize = size;
			((Graphic)obj2).color = c;
			obj2.text = s;
			obj2.alignment = (TextAnchor)3;
			obj2.horizontalOverflow = (HorizontalWrapMode)1;
			obj2.verticalOverflow = (VerticalWrapMode)1;
			((Graphic)obj2).raycastTarget = false;
			return obj2;
		}

		private Row NewRow(int slot, float y)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: 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_015f: 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_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: 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_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_023a: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: 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_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: 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_02c6: 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_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e7: 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_0348: Unknown result type (might be due to invalid IL or missing references)
			Row r = new Row
			{
				Slot = slot
			};
			r.Go = NewUI("row" + slot, panel.transform);
			RectTransform val = (RectTransform)r.Go.transform;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0f, 1f);
			val.pivot = val2;
			Vector2 anchorMin = (val.anchorMax = val2);
			val.anchorMin = anchorMin;
			val.anchoredPosition = new Vector2(8f, y);
			val.sizeDelta = new Vector2(304f, 28f);
			((Graphic)r.Go.AddComponent<Image>()).color = new Color(1f, 1f, 1f, 0.05f);
			r.Go.AddComponent<ClickRelay>().OnClick = delegate
			{
				RowClicked(r);
			};
			GameObject val4 = NewUI("icon", r.Go.transform);
			RectTransform val5 = (RectTransform)val4.transform;
			((Vector2)(ref val2))..ctor(0f, 0.5f);
			val5.pivot = val2;
			anchorMin = (val5.anchorMax = val2);
			val5.anchorMin = anchorMin;
			val5.anchoredPosition = new Vector2(4f, 0f);
			val5.sizeDelta = new Vector2(24f, 24f);
			r.Icon = val4.AddComponent<Image>();
			((Graphic)r.Icon).raycastTarget = false;
			r.Icon.preserveAspect = true;
			r.Label = NewText(r.Go.transform, "label", "", 13, TextColor, new Vector2(34f, -4f), 220f);
			GameObject val7 = NewUI("box", r.Go.transform);
			RectTransform val8 = (RectTransform)val7.transform;
			((Vector2)(ref val2))..ctor(1f, 0.5f);
			val8.pivot = val2;
			anchorMin = (val8.anchorMax = val2);
			val8.anchorMin = anchorMin;
			val8.anchoredPosition = new Vector2(-6f, 0f);
			val8.sizeDelta = new Vector2(18f, 18f);
			r.Box = val7.AddComponent<Image>();
			((Graphic)r.Box).color = BoxColor;
			((Graphic)r.Box).raycastTarget = false;
			GameObject val10 = NewUI("check", val7.transform);
			RectTransform val11 = (RectTransform)val10.transform;
			val11.anchorMin = Vector2.zero;
			val11.anchorMax = Vector2.one;
			val11.offsetMin = new Vector2(2f, 2f);
			val11.offsetMax = new Vector2(-2f, -2f);
			r.Check = val10.AddComponent<Image>();
			r.Check.sprite = trashSprite;
			r.Check.preserveAspect = true;
			((Graphic)r.Check).color = MarkColor;
			((Graphic)r.Check).raycastTarget = false;
			return r;
		}

		private Image MarkFor(UIStationStorage ui)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			if (marks.TryGetValue(ui, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if ((Object)(object)ui.itemButton == (Object)null)
			{
				return null;
			}
			GameObject obj = NewUI("mark", ((Component)ui.itemButton).transform);
			RectTransform val = (RectTransform)obj.transform;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(1f, 1f);
			val.pivot = val2;
			Vector2 anchorMin = (val.anchorMax = val2);
			val.anchorMin = anchorMin;
			val.anchoredPosition = new Vector2(2f, 2f);
			val.sizeDelta = new Vector2(14f, 14f);
			value = obj.AddComponent<Image>();
			value.sprite = trashSprite;
			value.preserveAspect = true;
			((Graphic)value).color = MarkColor;
			((Graphic)value).raycastTarget = false;
			obj.SetActive(false);
			marks[ui] = value;
			return value;
		}

		private bool Current(out PlanetFactory factory, out StationComponent st)
		{
			factory = (((Object)(object)window != (Object)null) ? window.factory : null);
			st = null;
			if ((Object)(object)window == (Object)null || !((ManualBehaviour)window).active || factory?.transport == null)
			{
				return false;
			}
			st = Game.StationIn(factory.transport, window.stationId);
			return Game.Allowed(st);
		}

		private void TogglePanel()
		{
			if (PanelOpen)
			{
				ClosePanel();
			}
			else
			{
				OpenPanel();
			}
		}

		private void OpenPanel()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if (Current(out var _, out var _))
			{
				if ((Object)(object)buttonTip != (Object)null)
				{
					buttonTip.CloseTip();
				}
				blocker.SetActive(true);
				blocker.transform.SetAsLastSibling();
				panel.SetActive(true);
				panel.transform.SetAsLastSibling();
				buttonGo.transform.SetAsLastSibling();
				shownStation = -1;
				Refresh(full: true);
				VFAudio.Create("ui-click-0", (Transform)null, Vector3.zero, true, 0, -1, -1L);
			}
		}

		public void ClosePanel()
		{
			if ((Object)(object)panel != (Object)null)
			{
				panel.SetActive(false);
			}
			if ((Object)(object)blocker != (Object)null)
			{
				blocker.SetActive(false);
			}
		}

		private void RowClicked(Row r)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			if (Current(out var factory, out var st) && r.Slot < st.storage.Length)
			{
				int itemId = st.storage[r.Slot].itemId;
				if (itemId > 0)
				{
					TrashSlots.Set(factory, st, itemId, !Plugin.Store.IsOn(factory.planetId, st.id, itemId));
					VFAudio.Create("ui-click-0", (Transform)null, Vector3.zero, true, 0, -1, -1L);
					Refresh(full: true);
				}
			}
		}

		private void LateUpdate()
		{
			if (++frame % 10 == 0)
			{
				Refresh(full: true);
			}
			else
			{
				Refresh(full: false);
			}
		}

		private void OnDisable()
		{
			ClosePanel();
		}

		public void Refresh(bool full)
		{
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: 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_013c: 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_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_038e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0418: Unknown result type (might be due to invalid IL or missing references)
			//IL_041f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0481: Unknown result type (might be due to invalid IL or missing references)
			//IL_047a: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)buttonGo == (Object)null)
			{
				return;
			}
			PlanetFactory factory;
			StationComponent st;
			bool flag = Current(out factory, out st);
			if (buttonGo.activeSelf != flag)
			{
				buttonGo.SetActive(flag);
			}
			if (!flag)
			{
				ClosePanel();
				foreach (Image value2 in marks.Values)
				{
					if ((Object)(object)value2 != (Object)null && ((Component)value2).gameObject.activeSelf)
					{
						((Component)value2).gameObject.SetActive(false);
					}
				}
				shownStation = -1;
				return;
			}
			bool isZHCN = Localization.isZHCN;
			int num = 0;
			for (int i = 0; i < st.storage.Length; i++)
			{
				if (st.storage[i].itemId > 0 && Plugin.Store.IsOn(factory.planetId, st.id, st.storage[i].itemId))
				{
					num++;
				}
			}
			Color val = ((num <= 0) ? (plainButton ? OffPlain : OffColor) : (plainButton ? OnPlain : OnColor));
			if (((Graphic)buttonIcon).color != val)
			{
				((Graphic)buttonIcon).color = val;
			}
			if (full)
			{
				buttonTip.tips.tipTitle = TrashText.ButtonTitle(isZHCN);
				buttonTip.tips.tipText = TrashText.ButtonBody(isZHCN, num);
			}
			UIStationStorage[] array = Traverse(window);
			if (array != null)
			{
				UIStationStorage[] array2 = array;
				foreach (UIStationStorage val2 in array2)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						bool flag2 = ((Component)val2).gameObject.activeInHierarchy && val2.station == st && val2.index < st.storage.Length && st.storage[val2.index].itemId > 0 && Plugin.Store.IsOn(factory.planetId, st.id, st.storage[val2.index].itemId);
						Image value;
						Image val3 = (flag2 ? MarkFor(val2) : (marks.TryGetValue(val2, out value) ? value : null));
						if ((Object)(object)val3 != (Object)null && ((Component)val3).gameObject.activeSelf != flag2)
						{
							((Component)val3).gameObject.SetActive(flag2);
						}
						if (flag2)
						{
							((Component)val3).transform.SetAsLastSibling();
						}
					}
				}
			}
			if (!PanelOpen)
			{
				return;
			}
			if (shownStation != st.id || rows.Count != st.storage.Length)
			{
				LayoutRows(st);
				full = true;
			}
			if (!full)
			{
				return;
			}
			ruleText.text = TrashText.PanelRule(isZHCN);
			long num2 = 0L;
			foreach (TrashEntry item in Plugin.Store.All())
			{
				if (item.PlanetId == factory.planetId && item.StationId == st.id)
				{
					num2 += item.Destroyed;
				}
			}
			destroyedText.text = TrashText.PanelDestroyed(isZHCN, num2);
			foreach (Row row in rows)
			{
				StationStore val4 = st.storage[row.Slot];
				ItemProto val5 = ((val4.itemId > 0) ? ((ProtoSet<ItemProto>)(object)LDB.items).Select(val4.itemId) : null);
				bool enabled = val5 != null && Plugin.Store.IsOn(factory.planetId, st.id, val4.itemId);
				((Behaviour)row.Icon).enabled = val5 != null;
				if (val5 != null)
				{
					row.Icon.sprite = val5.iconSprite;
				}
				row.Label.text = ((val5 != null) ? TrashText.Row(((Proto)val5).name, val4.count, val4.max) : TrashText.EmptyRow(isZHCN));
				((Graphic)row.Label).color = ((val5 != null) ? TextColor : DimText);
				((Graphic)row.Box).color = (Color)((val5 != null) ? BoxColor : new Color(BoxColor.r, BoxColor.g, BoxColor.b, 0.35f));
				((Behaviour)row.Check).enabled = enabled;
			}
		}

		private void LayoutRows(StationComponent st)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: 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)
			foreach (Row row in rows)
			{
				if ((Object)(object)row.Go != (Object)null)
				{
					Object.Destroy((Object)(object)row.Go);
				}
			}
			rows.Clear();
			float num = -89f;
			int num2 = 0;
			while (num2 < st.storage.Length)
			{
				rows.Add(NewRow(num2, num));
				num2++;
				num -= 30f;
			}
			RectTransform val = (RectTransform)panel.transform;
			val.sizeDelta = new Vector2(320f, 0f - num + 6f);
			RectTransform val2 = (RectTransform)buttonGo.transform;
			val.anchoredPosition = val2.anchoredPosition + new Vector2(0f, -26f);
			shownStation = st.id;
		}

		private static UIStationStorage[] Traverse(UIStationWindow w)
		{
			if (storageField == null)
			{
				storageField = typeof(UIStationWindow).GetField("storageUIs", BindingFlags.Instance | BindingFlags.NonPublic);
			}
			return storageField?.GetValue(w) as UIStationStorage[];
		}
	}
}