Decompiled source of SpawnLab v1.0.2

Mods/SpawnLab.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text.Json;
using System.Threading.Tasks;
using BoneLib;
using BoneLib.BoneMenu;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSLZ.Marrow.Data;
using Il2CppSLZ.Marrow.Pool;
using Il2CppSLZ.Marrow.Warehouse;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using MelonLoader;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using SpawnLab;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(SpawnLabMod), "SpawnLab", "1.0.2", "ChappieStudios", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ChappieStudios")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("SpawnLab")]
[assembly: AssemblyTitle("SpawnLab")]
[assembly: AssemblyVersion("1.0.2.0")]
[module: RefSafetyRules(11)]
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;
		}
	}
	[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 SpawnLab
{
	internal enum SpawnCategory
	{
		Guns,
		Melee,
		NPCs,
		Vehicles,
		Gadgets,
		Money,
		Props,
		Misc
	}
	internal sealed class SpawnEntry
	{
		public string Title { get; }

		public string Barcode { get; }

		public string SourceName { get; }

		public bool IsDownloaded { get; }

		public SpawnCategory Category { get; }

		internal SpawnEntry(string title, string barcode, string sourceName, bool isDownloaded, SpawnCategory category)
		{
			Title = title;
			Barcode = barcode;
			SourceName = sourceName;
			IsDownloaded = isDownloaded;
			Category = category;
		}
	}
	internal static class SpawnCatalog
	{
		internal static List<SpawnEntry> Load(IEnumerable<string> downloadedRoots, IEnumerable<string> baseRoots, Action<string> warn)
		{
			Dictionary<string, SpawnEntry> dictionary = new Dictionary<string, SpawnEntry>(StringComparer.OrdinalIgnoreCase);
			HashSet<string> visited = new HashSet<string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
			ReadRoots(downloadedRoots, isDownloaded: true, dictionary, visited, warn);
			ReadRoots(baseRoots, isDownloaded: false, dictionary, visited, warn);
			return dictionary.Values.OrderBy((SpawnEntry entry) => (!entry.IsDownloaded) ? 1 : 0).ThenBy<SpawnEntry, string>((SpawnEntry entry) => entry.SourceName, StringComparer.OrdinalIgnoreCase).ThenBy((SpawnEntry entry) => entry.Category)
				.ThenBy<SpawnEntry, string>((SpawnEntry entry) => entry.Title, StringComparer.OrdinalIgnoreCase)
				.ToList();
		}

		internal static List<SpawnEntry> Filter(IEnumerable<SpawnEntry> entries, string query)
		{
			string[] tokens = (query ?? string.Empty).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
			if (tokens.Length == 0)
			{
				return entries.ToList();
			}
			return entries.Where((SpawnEntry entry) => tokens.All((string token) => Contains(entry.Title, token) || Contains(entry.SourceName, token) || Contains(entry.Barcode, token) || Contains(entry.Category.ToString(), token))).ToList();
		}

		private static bool Contains(string value, string token)
		{
			if (value != null)
			{
				return value.IndexOf(token, StringComparison.OrdinalIgnoreCase) >= 0;
			}
			return false;
		}

		private static void ReadRoots(IEnumerable<string> roots, bool isDownloaded, Dictionary<string, SpawnEntry> entries, HashSet<string> visited, Action<string> warn)
		{
			if (roots == null)
			{
				return;
			}
			foreach (string root in roots)
			{
				if (string.IsNullOrWhiteSpace(root))
				{
					continue;
				}
				string fullPath;
				try
				{
					fullPath = Path.GetFullPath(root);
				}
				catch (Exception ex) when (IsFileError(ex))
				{
					warn?.Invoke("Could not inspect pallet directory " + root + ": " + ex.Message);
					continue;
				}
				Stack<string> stack = new Stack<string>();
				stack.Push(fullPath);
				while (stack.Count != 0)
				{
					string text = stack.Pop();
					if (!visited.Add(text))
					{
						continue;
					}
					try
					{
						FileAttributes attributes = File.GetAttributes(text);
						if ((attributes & FileAttributes.ReparsePoint) != FileAttributes.None || (attributes & FileAttributes.Directory) == 0)
						{
							continue;
						}
						goto IL_010c;
					}
					catch (Exception ex2) when (IsFileError(ex2))
					{
						if (!(ex2 is FileNotFoundException) && !(ex2 is DirectoryNotFoundException))
						{
							warn?.Invoke("Could not inspect pallet directory " + text + ": " + ex2.Message);
						}
					}
					continue;
					IL_010c:
					string[] array = Array.Empty<string>();
					try
					{
						array = Directory.GetFiles(text);
						Array.Sort(array, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
					}
					catch (Exception ex3) when (IsFileError(ex3))
					{
						warn?.Invoke("Could not list pallets in " + text + ": " + ex3.Message);
					}
					string[] array2 = array;
					foreach (string text2 in array2)
					{
						if (text2.EndsWith(".pallet.json", StringComparison.OrdinalIgnoreCase))
						{
							try
							{
								ReadPalletFile(text2, isDownloaded, entries);
							}
							catch (Exception ex4) when (IsFileError(ex4) || ex4 is JsonException || ex4 is InvalidOperationException)
							{
								warn?.Invoke("Could not read pallet " + text2 + ": " + ex4.Message);
							}
						}
					}
					try
					{
						string[] directories = Directory.GetDirectories(text);
						Array.Sort(directories, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
						for (int num = directories.Length - 1; num >= 0; num--)
						{
							stack.Push(directories[num]);
						}
					}
					catch (Exception ex5) when (IsFileError(ex5))
					{
						warn?.Invoke("Could not list pallet subdirectories in " + text + ": " + ex5.Message);
					}
				}
			}
		}

		private static bool IsFileError(Exception ex)
		{
			if (!(ex is IOException) && !(ex is UnauthorizedAccessException) && !(ex is SecurityException) && !(ex is ArgumentException))
			{
				return ex is NotSupportedException;
			}
			return true;
		}

		private static void ReadPalletFile(string path, bool isDownloaded, Dictionary<string, SpawnEntry> entries)
		{
			using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(path));
			JsonElement rootElement = jsonDocument.RootElement;
			if (rootElement.ValueKind != JsonValueKind.Object || !rootElement.TryGetProperty("objects", out var value) || value.ValueKind != JsonValueKind.Object)
			{
				return;
			}
			string palletTitle = GetPalletTitle(rootElement, value, path);
			foreach (JsonProperty item in value.EnumerateObject())
			{
				JsonElement value2 = item.Value;
				if (!IsSpawnableCrate(value2))
				{
					continue;
				}
				string text = GetString(value2, "barcode");
				if (!string.IsNullOrWhiteSpace(text) && !entries.ContainsKey(text))
				{
					string text2 = GetString(value2, "title");
					if (string.IsNullOrWhiteSpace(text2))
					{
						text2 = text;
					}
					entries.Add(text, new SpawnEntry(text2, text, palletTitle, isDownloaded, Categorize(text2, text, GetTags(value2))));
				}
			}
		}

		private static string GetPalletTitle(JsonElement root, JsonElement objects, string path)
		{
			if (root.TryGetProperty("root", out var value) && value.ValueKind == JsonValueKind.Object)
			{
				string text = GetString(value, "ref");
				if (!string.IsNullOrWhiteSpace(text) && objects.TryGetProperty(text, out var value2))
				{
					string text2 = GetString(value2, "title");
					if (!string.IsNullOrWhiteSpace(text2))
					{
						return text2;
					}
				}
			}
			string fileName = Path.GetFileName(path);
			if (!fileName.EndsWith(".pallet.json", StringComparison.OrdinalIgnoreCase))
			{
				return fileName;
			}
			return fileName.Substring(0, fileName.Length - ".pallet.json".Length);
		}

		private static bool IsSpawnableCrate(JsonElement crate)
		{
			if (crate.ValueKind == JsonValueKind.Object && crate.TryGetProperty("isa", out var value))
			{
				return string.Equals(GetString(value, "type"), "crate-spawnable#0", StringComparison.Ordinal);
			}
			return false;
		}

		private static string GetString(JsonElement element, string name)
		{
			if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty(name, out var value) || value.ValueKind != JsonValueKind.String)
			{
				return null;
			}
			return value.GetString();
		}

		private static List<string> GetTags(JsonElement crate)
		{
			List<string> list = new List<string>();
			if (crate.TryGetProperty("tags", out var value) && value.ValueKind == JsonValueKind.Array)
			{
				foreach (JsonElement item in value.EnumerateArray())
				{
					if (item.ValueKind == JsonValueKind.String)
					{
						list.Add(item.GetString());
					}
				}
			}
			return list;
		}

		internal static SpawnCategory Categorize(string title, string barcode, List<string> tags)
		{
			string text = $"{title} {barcode} {string.Join(" ", tags)}".ToLowerInvariant();
			if (ContainsAny(text, "money", "dollar", "bill", "coin", "penny", "nickel", "dime", "quarter", "wallet", "credit card"))
			{
				return SpawnCategory.Money;
			}
			if (ContainsAny(text, "npc", "enemy", "ford", "nullbody", "crablet", "skeleton", "zombie", "omni", "security", "agent", "peasant", "cultist"))
			{
				return SpawnCategory.NPCs;
			}
			if (ContainsAny(text, "rifle", "pistol", "gun", "shotgun", "smg", "revolver", "launcher", "magazine", "ammo", "cartridge"))
			{
				return SpawnCategory.Guns;
			}
			if (ContainsAny(text, "sword", "knife", "blade", "axe", "bat", "crowbar", "dagger", "spear", "hammer", "wrench", "mace", "katana"))
			{
				return SpawnCategory.Melee;
			}
			if (ContainsAny(text, "vehicle", "car", "kart", "truck", "taxi", "hover", "board", "bike", "plane"))
			{
				return SpawnCategory.Vehicles;
			}
			if (ContainsAny(text, "tool", "gadget", "utility", "nimbus", "spawn gun", "constrainer", "dev", "capsule", "button"))
			{
				return SpawnCategory.Gadgets;
			}
			if (ContainsAny(text, "prop", "crate", "box", "barrel", "table", "chair", "door", "ball", "target"))
			{
				return SpawnCategory.Props;
			}
			return SpawnCategory.Misc;
		}

		private static bool ContainsAny(string text, params string[] values)
		{
			foreach (string value in values)
			{
				if (text.Contains(value))
				{
					return true;
				}
			}
			return false;
		}
	}
	public sealed class SpawnLabMod : MelonMod
	{
		private sealed record ScanResult(List<SpawnEntry> Entries, List<string> Warnings);

		private sealed record MenuRow(string Name, Color Color, Action<Page> Invoke, string Tooltip = null);

		internal const int RowsPerPage = 6;

		private const float SpawnDistance = 1.25f;

		private Page _rootPage;

		private StringElement _searchInput;

		private FunctionElement _status;

		private List<SpawnEntry> _entries = new List<SpawnEntry>();

		private Task<ScanResult> _scan;

		private IEnumerator<SpawnEntry> _warehouseScan;

		private Dictionary<string, SpawnEntry> _pendingEntries;

		private Action _pendingAction;

		private bool _initialized;

		private bool _initializationFailed;

		private bool _warehouseLoaded;

		private float _nextWarehouseAttempt;

		private float _nextSpawn;

		public override void OnInitializeMelon()
		{
			((MelonBase)this).LoggerInstance.Msg("SpawnLab 1.0.2: bounded lists and keyboard search enabled.");
		}

		public override void OnUpdate()
		{
			try
			{
				if (!_initialized && !_initializationFailed && Page.Root != null)
				{
					InitializeMenu();
				}
				if (_initialized)
				{
					Action pendingAction = _pendingAction;
					_pendingAction = null;
					pendingAction?.Invoke();
					CompleteFileScan();
					ReadWarehouseSlice();
					if (!_warehouseLoaded && _scan == null && _warehouseScan == null && Time.realtimeSinceStartup >= _nextWarehouseAttempt)
					{
						_nextWarehouseAttempt = Time.realtimeSinceStartup + 5f;
						BeginWarehouseScan();
					}
				}
			}
			catch (Exception ex)
			{
				if (!_initialized)
				{
					_initializationFailed = true;
				}
				((MelonBase)this).LoggerInstance.Error("SpawnLab menu action failed: " + ex.Message);
			}
		}

		private void InitializeMenu()
		{
			//IL_000b: 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_0076: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			_rootPage = Page.Root.CreatePage("SpawnLab", Color.cyan, 0, true);
			_searchInput = _rootPage.CreateString("Search", Color.cyan, "", (Action<string>)delegate
			{
			});
			((Element)_searchInput).SetTooltip("Enter an item or mod name with the keyboard, then select Search Items. Multiple words narrow the results.");
			_rootPage.CreateFunction("Search Items", Color.cyan, (Action)delegate
			{
				Queue(OpenSearch);
			});
			_rootPage.CreateFunction("Clear Search", Color.white, (Action)delegate
			{
				Queue(delegate
				{
					_searchInput.Value = "";
				});
			});
			_rootPage.CreateFunction("Refresh List", Color.yellow, (Action)delegate
			{
				Queue(StartRefresh);
			});
			_status = _rootPage.CreateFunction("Loading spawnables...", Color.gray, (Action)delegate
			{
			});
			_rootPage.CreateFunction("All Categories", Color.cyan, (Action)delegate
			{
				Queue(delegate
				{
					OpenCategories(_rootPage, "All Categories", _entries);
				});
			});
			_rootPage.CreateFunction("Downloaded Mods", Color.green, (Action)delegate
			{
				Queue(delegate
				{
					OpenSources(downloaded: true);
				});
			});
			_rootPage.CreateFunction("Base Game", Color.blue, (Action)delegate
			{
				Queue(delegate
				{
					OpenSources(downloaded: false);
				});
			});
			_initialized = true;
			StartRefresh();
		}

		private void Queue(Action action)
		{
			_pendingAction = action;
		}

		private void StartRefresh()
		{
			if (_scan == null && _warehouseScan == null)
			{
				((Element)_status).ElementName = "Loading spawnables...";
				_warehouseLoaded = false;
				string[] downloadedRoots = new string[1] { Path.Combine(Application.persistentDataPath, "Mods") };
				string[] baseRoots = new string[2]
				{
					Path.Combine(MelonEnvironment.UnityGameDataDirectory, "StreamingAssets", "aa"),
					Path.Combine(Application.streamingAssetsPath, "aa")
				};
				_scan = Task.Run(delegate
				{
					List<string> list = new List<string>();
					return new ScanResult(SpawnCatalog.Load(downloadedRoots, baseRoots, list.Add), list);
				});
			}
		}

		private void CompleteFileScan()
		{
			if (_scan == null || !_scan.IsCompleted)
			{
				return;
			}
			Task<ScanResult> scan = _scan;
			_scan = null;
			try
			{
				ScanResult result = scan.GetAwaiter().GetResult();
				_entries = result.Entries;
				foreach (string item in result.Warnings.Take(10))
				{
					((MelonBase)this).LoggerInstance.Warning(item);
				}
				if (result.Warnings.Count > 10)
				{
					((MelonBase)this).LoggerInstance.Warning($"Skipped {result.Warnings.Count - 10} additional unreadable files/folders.");
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Refresh could not read all pallet files: " + ex.Message);
			}
			BeginWarehouseScan();
			UpdateCount();
		}

		private void BeginWarehouseScan()
		{
			if (WarehouseCatalog.IsReady)
			{
				_pendingEntries = _entries.ToDictionary<SpawnEntry, string>((SpawnEntry entry) => entry.Barcode, StringComparer.OrdinalIgnoreCase);
				_warehouseScan = WarehouseCatalog.Read().GetEnumerator();
			}
		}

		private void ReadWarehouseSlice()
		{
			if (_warehouseScan == null)
			{
				return;
			}
			try
			{
				for (int i = 0; i < 32; i++)
				{
					if (!_warehouseScan.MoveNext())
					{
						FinishWarehouseScan(complete: true);
						break;
					}
					SpawnEntry current = _warehouseScan.Current;
					if (current != null && !_pendingEntries.ContainsKey(current.Barcode))
					{
						_pendingEntries.Add(current.Barcode, current);
					}
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Loaded-crate scan stopped: " + ex.Message);
				FinishWarehouseScan(complete: false);
			}
		}

		private void FinishWarehouseScan(bool complete)
		{
			_warehouseScan?.Dispose();
			_warehouseScan = null;
			_entries = _pendingEntries.Values.OrderBy<SpawnEntry, string>((SpawnEntry entry) => entry.Title, StringComparer.OrdinalIgnoreCase).ToList();
			_pendingEntries = null;
			_warehouseLoaded = complete;
			_nextWarehouseAttempt = Time.realtimeSinceStartup + 15f;
			UpdateCount();
		}

		private void UpdateCount()
		{
			((Element)_status).ElementName = $"{_entries.Count} spawnable items";
		}

		private void OpenSearch()
		{
			string text = (_searchInput.Value ?? "").Trim();
			List<SpawnEntry> entries = SpawnCatalog.Filter(_entries, text);
			OpenEntries(_rootPage, string.IsNullOrEmpty(text) ? "All Items" : ("Search: " + text), entries);
		}

		private void OpenSources(bool downloaded)
		{
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			IOrderedEnumerable<IGrouping<string, SpawnEntry>> orderedEnumerable = _entries.Where((SpawnEntry entry) => entry.IsDownloaded == downloaded).GroupBy<SpawnEntry, string>((SpawnEntry entry) => entry.SourceName, StringComparer.OrdinalIgnoreCase).OrderBy<IGrouping<string, SpawnEntry>, string>((IGrouping<string, SpawnEntry> group) => group.Key, StringComparer.OrdinalIgnoreCase);
			List<MenuRow> list = new List<MenuRow>();
			foreach (IGrouping<string, SpawnEntry> item in orderedEnumerable)
			{
				string name = item.Key;
				List<SpawnEntry> entries = item.ToList();
				list.Add(new MenuRow($"{name} ({entries.Count})", Color.white, delegate(Page page)
				{
					OpenCategories(page, name, entries);
				}));
			}
			OpenWindow(_rootPage, downloaded ? "Downloaded Mods" : "Base Game", list, 0);
		}

		private void OpenCategories(Page parent, string title, IEnumerable<SpawnEntry> entries)
		{
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			List<SpawnEntry> source = entries.ToList();
			List<MenuRow> list = new List<MenuRow>();
			foreach (SpawnCategory category in Enum.GetValues(typeof(SpawnCategory)))
			{
				List<SpawnEntry> matches = source.Where((SpawnEntry entry) => entry.Category == category).ToList();
				if (matches.Count != 0)
				{
					string categoryName = category.ToString();
					list.Add(new MenuRow($"{categoryName} ({matches.Count})", CategoryColor(category), delegate(Page page)
					{
						OpenEntries(page, categoryName, matches);
					}));
				}
			}
			OpenWindow(parent, title, list, 0);
		}

		private void OpenEntries(Page parent, string title, IEnumerable<SpawnEntry> entries)
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			List<SpawnEntry> list = entries.OrderBy<SpawnEntry, string>((SpawnEntry entry) => entry.Title, StringComparer.OrdinalIgnoreCase).ThenBy<SpawnEntry, string>((SpawnEntry entry) => entry.SourceName, StringComparer.OrdinalIgnoreCase).ToList();
			List<MenuRow> list2 = new List<MenuRow>(list.Count);
			foreach (SpawnEntry item in list)
			{
				SpawnEntry captured = item;
				list2.Add(new MenuRow(captured.Title, Color.white, delegate
				{
					Spawn(captured);
				}, captured.SourceName + "\n" + captured.Barcode));
			}
			OpenWindow(parent, $"{title} ({list.Count})", list2, 0);
		}

		private void OpenWindow(Page parent, string title, List<MenuRow> rows, int offset)
		{
			//IL_00a9: 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_00b9: Expected O, but got Unknown
			//IL_00d1: 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_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			int num = Math.Max(1, (rows.Count + 6 - 1) / 6);
			offset = Math.Clamp(offset, 0, (num - 1) * 6);
			Page page = new Page(parent, Trim(title) + $" [{offset / 6 + 1}/{num}]", Color.cyan, 0);
			if (rows.Count == 0)
			{
				page.CreateFunction("No matching items", Color.gray, (Action)delegate
				{
				});
			}
			foreach (MenuRow row in rows.Skip(offset).Take(6))
			{
				FunctionElement val = page.CreateFunction(Trim(row.Name), row.Color, (Action)delegate
				{
					Queue(delegate
					{
						row.Invoke(page);
					});
				});
				if (!string.IsNullOrEmpty(row.Tooltip))
				{
					((Element)val).SetTooltip(row.Tooltip);
				}
			}
			int currentOffset = offset;
			if (offset > 0)
			{
				page.CreateFunction("< Previous Page", Color.yellow, (Action)delegate
				{
					Queue(delegate
					{
						OpenWindow(parent, title, rows, currentOffset - 6);
					});
				});
			}
			if (offset + 6 < rows.Count)
			{
				page.CreateFunction("Next Page >", Color.yellow, (Action)delegate
				{
					Queue(delegate
					{
						OpenWindow(parent, title, rows, currentOffset + 6);
					});
				});
			}
			Menu.OpenPage(page);
		}

		private void Spawn(SpawnEntry entry)
		{
			//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_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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: 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_00a2: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			if (Time.realtimeSinceStartup < _nextSpawn)
			{
				return;
			}
			_nextSpawn = Time.realtimeSinceStartup + 0.2f;
			try
			{
				Transform head = Player.Head;
				if ((Object)(object)head == (Object)null)
				{
					((MelonBase)this).LoggerInstance.Warning("Load into a level before spawning an item.");
					return;
				}
				Vector3 forward = head.forward;
				forward.y = 0f;
				if (((Vector3)(ref forward)).sqrMagnitude < 0.001f)
				{
					forward = Vector3.forward;
				}
				((Vector3)(ref forward)).Normalize();
				Vector3 position = head.position + forward * 1.25f + Vector3.down * 0.12f;
				SpawnService.Spawn(entry.Barcode, position, Quaternion.LookRotation(forward, Vector3.up));
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Error("Could not spawn " + entry.Title + ": " + ex.Message);
			}
		}

		private static Color CategoryColor(SpawnCategory category)
		{
			//IL_0024: 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_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_0043: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			return (Color)(category switch
			{
				SpawnCategory.Guns => Color.red, 
				SpawnCategory.Melee => new Color(1f, 0.45f, 0f), 
				SpawnCategory.NPCs => Color.magenta, 
				SpawnCategory.Vehicles => Color.cyan, 
				SpawnCategory.Gadgets => Color.yellow, 
				SpawnCategory.Money => Color.green, 
				SpawnCategory.Props => Color.white, 
				_ => Color.gray, 
			});
		}

		private static string Trim(string value)
		{
			value = (value ?? "Unnamed").Replace("\r", " ").Replace("\n", " ").Trim();
			if (value.Length <= 48)
			{
				return value;
			}
			return value.Substring(0, 45) + "...";
		}
	}
	internal static class SpawnService
	{
		internal static void Spawn(string barcode, Vector3 position, Quaternion rotation)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			//IL_0058: 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_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(barcode))
			{
				throw new ArgumentException("A spawnable barcode is required.", "barcode");
			}
			Assembly assembly = FindFusionAssembly();
			if (assembly != null && IsFusionLevelNetworked(assembly))
			{
				SpawnNetworked(assembly, barcode, position, rotation);
				return;
			}
			try
			{
				Spawnable val = new Spawnable
				{
					crateRef = new SpawnableCrateReference(barcode),
					policyData = null
				};
				AssetSpawner.Register(val);
				Nullable<Vector3> val2 = new Nullable<Vector3>(Vector3.zero)
				{
					hasValue = false
				};
				Nullable<int> val3 = new Nullable<int>(0)
				{
					hasValue = false
				};
				AssetSpawner.Spawn(val, position, rotation, val2, (Transform)null, false, val3, (Action<GameObject>)null, (Action<GameObject>)null);
			}
			catch (Exception innerException)
			{
				throw new InvalidOperationException("SpawnLab could not spawn crate '" + barcode + "' locally.", innerException);
			}
		}

		private static Assembly FindFusionAssembly()
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (string.Equals(assembly.GetName().Name, "LabFusion", StringComparison.OrdinalIgnoreCase))
				{
					return assembly;
				}
			}
			return null;
		}

		private static bool IsFusionLevelNetworked(Assembly fusion)
		{
			try
			{
				Type type = RequireType(fusion, "LabFusion.Scene.NetworkSceneManager");
				PropertyInfo property = type.GetProperty("IsLevelNetworked", BindingFlags.Static | BindingFlags.Public);
				if (property == null || property.PropertyType != typeof(bool) || property.GetGetMethod() == null)
				{
					throw new MissingMemberException(type.FullName, "IsLevelNetworked");
				}
				return (bool)property.GetValue(null);
			}
			catch (Exception exception)
			{
				throw new InvalidOperationException("SpawnLab could not read Fusion's network state. No local spawn was attempted.", Unwrap(exception));
			}
		}

		private static void SpawnNetworked(Assembly fusion, string barcode, Vector3 position, Quaternion rotation)
		{
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Type type = RequireType(fusion, "LabFusion.Marrow.Pool.LocalAssetSpawner");
				MethodInfo? method = type.GetMethod("CreateSpawnable", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(string) }, null);
				if (method == null)
				{
					throw new MissingMethodException(type.FullName, "CreateSpawnable(string)");
				}
				object obj = method.Invoke(null, new object[1] { barcode });
				if (obj == null)
				{
					throw new InvalidOperationException("Fusion returned no spawnable for '" + barcode + "'.");
				}
				Type type2 = RequireType(fusion, "LabFusion.RPC.NetworkAssetSpawner");
				Type nestedType = type2.GetNestedType("SpawnRequestInfo", BindingFlags.Public);
				if (nestedType == null)
				{
					throw new MissingMemberException(type2.FullName, "SpawnRequestInfo");
				}
				MethodInfo? method2 = type2.GetMethod("Spawn", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { nestedType }, null);
				if (method2 == null)
				{
					throw new MissingMethodException(type2.FullName, "Spawn(SpawnRequestInfo)");
				}
				object obj2 = Activator.CreateInstance(nestedType);
				SetRequiredField(obj2, "Spawnable", obj);
				SetRequiredField(obj2, "Position", position);
				SetRequiredField(obj2, "Rotation", rotation);
				SetRequiredField(obj2, "SpawnEffect", true);
				FieldInfo fieldInfo = RequireField(nestedType, "SpawnSource");
				if (!fieldInfo.FieldType.IsEnum || !Enum.IsDefined(fieldInfo.FieldType, "Player"))
				{
					throw new InvalidOperationException("Fusion's SpawnSource enum does not provide the Player source.");
				}
				fieldInfo.SetValue(obj2, Enum.Parse(fieldInfo.FieldType, "Player"));
				method2.Invoke(null, new object[1] { obj2 });
			}
			catch (Exception exception)
			{
				throw new InvalidOperationException("SpawnLab could not request a Fusion-synced spawn for '" + barcode + "'. No local fallback was attempted.", Unwrap(exception));
			}
		}

		private static Type RequireType(Assembly assembly, string name)
		{
			return assembly.GetType(name, throwOnError: false) ?? throw new TypeLoadException("Fusion type is unavailable: " + name);
		}

		private static FieldInfo RequireField(Type type, string name)
		{
			return type.GetField(name, BindingFlags.Instance | BindingFlags.Public) ?? throw new MissingFieldException(type.FullName, name);
		}

		private static void SetRequiredField(object instance, string name, object value)
		{
			RequireField(instance.GetType(), name).SetValue(instance, value);
		}

		private static Exception Unwrap(Exception exception)
		{
			if (!(exception is TargetInvocationException { InnerException: not null } ex))
			{
				return exception;
			}
			return ex.InnerException;
		}
	}
	internal static class WarehouseCatalog
	{
		internal static bool IsReady
		{
			get
			{
				if (AssetWarehouse.ready)
				{
					return AssetWarehouse.Instance != null;
				}
				return false;
			}
		}

		internal static IEnumerable<SpawnEntry> Read()
		{
			if (!IsReady)
			{
				yield break;
			}
			AssetWarehouse instance = AssetWarehouse.Instance;
			List<Crate> crates = instance.GetCrates();
			if (crates == null)
			{
				yield break;
			}
			HashSet<Barcode> gamePallets = instance.gamePallets;
			for (int index = 0; index < crates.Count; index++)
			{
				Crate val = crates[index];
				SpawnableCrate val2 = (((Object)(object)val == (Object)null) ? null : ((Il2CppObjectBase)val).TryCast<SpawnableCrate>());
				if ((Object)(object)val2 == (Object)null)
				{
					yield return null;
					continue;
				}
				Barcode barcode = ((Scannable)val2).Barcode;
				string text = ((barcode != null) ? barcode.ID : null);
				if (string.IsNullOrWhiteSpace(text))
				{
					yield return null;
					continue;
				}
				Pallet pallet = ((Crate)val2).Pallet;
				bool flag = (Object)(object)pallet != (Object)null && (pallet.Internal || (gamePallets != null && ((Scannable)pallet).Barcode != (Barcode)null && gamePallets.Contains(((Scannable)pallet).Barcode)));
				string text2 = (((Object)(object)pallet == (Object)null) ? null : ((Scannable)pallet).Title);
				if (string.IsNullOrWhiteSpace(text2))
				{
					text2 = (flag ? "Base Game" : "Downloaded Mods");
				}
				string text3 = ((Scannable)val2).Title;
				if (string.IsNullOrWhiteSpace(text3))
				{
					text3 = text;
				}
				List<string> list = new List<string>();
				List<string> tags = ((Crate)val2).Tags;
				if (tags != null)
				{
					for (int i = 0; i < tags.Count; i++)
					{
						string text4 = tags[i];
						if (!string.IsNullOrWhiteSpace(text4))
						{
							list.Add(text4);
						}
					}
				}
				yield return new SpawnEntry(text3, text, text2, !flag, SpawnCatalog.Categorize(text3, text, list));
			}
		}
	}
}