Decompiled source of Advanced Backpacks v1.1.1

AdvancedBackpacks.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HypnoCode;
using Microsoft.CodeAnalysis;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.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 HypnoCode
{
	internal static class Admin
	{
		private static readonly FieldInfo AdminListField = AccessTools.Field(typeof(ZNet), "m_adminList");

		private static string Bare(string value)
		{
			return value.Substring(value.LastIndexOf('_') + 1).Trim();
		}

		private static bool Listed(IEnumerable<string> admins, string id)
		{
			if (admins == null || string.IsNullOrEmpty(id))
			{
				return false;
			}
			string text = Bare(id);
			if (text.Length == 0)
			{
				return false;
			}
			foreach (string admin in admins)
			{
				if (admin != null && (string.Equals(admin.Trim(), id, StringComparison.OrdinalIgnoreCase) || string.Equals(Bare(admin), text, StringComparison.OrdinalIgnoreCase)))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool IsPeer(long uid)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (uid == ZNet.GetUID())
			{
				return true;
			}
			ZNetPeer peer = instance.GetPeer(uid);
			if (peer == null || peer.m_socket == null)
			{
				return false;
			}
			string hostName = peer.m_socket.GetHostName();
			if (string.IsNullOrEmpty(hostName))
			{
				return false;
			}
			if (instance.IsAdmin(hostName))
			{
				return true;
			}
			SyncedList val = (SyncedList)((AdminListField != null) ? /*isinst with value type is only supported in some contexts*/: null);
			return Listed((val != null) ? val.GetList() : instance.GetAdminList(), hostName);
		}

		internal static bool IsLocal(bool serverSays = false)
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			if (instance.LocalPlayerIsAdminOrHost() || serverSays)
			{
				return true;
			}
			string id;
			try
			{
				id = ((object)Unsafe.As<PlatformUserID, PlatformUserID>(ref UserInfo.GetLocalUser().UserId)/*cast due to .constrained prefix*/).ToString();
			}
			catch
			{
				return false;
			}
			return Listed(instance.GetAdminList(), id);
		}
	}
	internal static class Compat
	{
		internal enum Kind
		{
			CompatMode,
			Info,
			Option,
			Resolved
		}

		internal sealed class Known
		{
			public string Guid;

			public string TypeName;

			public string Name;

			public Kind Kind;

			public Dictionary<string, string> Does;

			public Dictionary<string, string> Toggle;
		}

		private const string Backpack = "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)";

		private const string BackpackSlots = "the backpack's rows go right after the player's own rows, before Extra Slots' special slots";

		private const string BackpackArchery = "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is";

		internal static readonly Known[] Table = new Known[7]
		{
			new Known
			{
				Guid = "seneaL.valheim.ui",
				Name = "SeneaL UI",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)" },
					{ "AdvancedBackpacks", "the backpack's rows and its portal/ship dock follow SeneaL's layout, and the inventory is saved around SeneaL's own saving (no items lost at a save)" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "SeneaLUI" },
					{ "AdvancedBackpacks", "SeneaLUI" }
				}
			},
			new Known
			{
				Guid = "seneaL.valheim.api",
				Name = "SeneaL API",
				Kind = Kind.Info,
				Does = new Dictionary<string, string> { { "ImmersiveTrader", "the Quest Log gets a tab in SeneaL's character window" } },
				Toggle = new Dictionary<string, string> { { "ImmersiveTrader", "SeneaLQuestLogTab" } }
			},
			new Known
			{
				Guid = "shudnal.ExtraSlots",
				Name = "Extra Slots",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's rows go right after the player's own rows, before Extra Slots' special slots" },
					{ "AdvancedBackpacks", "the backpack's rows go right after the player's own rows, before Extra Slots' special slots" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "ExtraSlots" },
					{ "AdvancedBackpacks", "ExtraSlots" }
				}
			},
			new Known
			{
				Guid = "ishid4.mods.betterarchery",
				Name = "Better Archery",
				Kind = Kind.CompatMode,
				Does = new Dictionary<string, string>
				{
					{ "COAH", "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is" },
					{ "AdvancedBackpacks", "the backpack's row goes above Better Archery's quiver rows, and the portal/ship dock leaves the quiver where it is" }
				},
				Toggle = new Dictionary<string, string>
				{
					{ "COAH", "BetterArchery" },
					{ "AdvancedBackpacks", "BetterArchery" }
				}
			},
			new Known
			{
				TypeName = "ValheimProfessions.ProfessionManager",
				Name = "ValheimProfessions",
				Kind = Kind.Option,
				Does = new Dictionary<string, string> { { "ImmersiveTrader", "traders, boards and caravans turn away a player with a profession when [Compatibility] BlockPlayersWithProfession is on" } },
				Toggle = new Dictionary<string, string> { { "ImmersiveTrader", "BlockPlayersWithProfession" } }
			},
			new Known
			{
				Guid = "goldenrevolver.quick_stack_store",
				Name = "Quick Stack Store",
				Kind = Kind.Info,
				Does = new Dictionary<string, string> { { "SortByQoL", "works with it: when it refreshes the crafting list, the sorting and the filters are applied again" } }
			},
			new Known
			{
				Guid = "p0kahontazz.coah",
				Name = "Children of the Ancient Heart",
				Kind = Kind.Resolved,
				Does = new Dictionary<string, string>
				{
					{ "AdvancedBackpacks", "Advanced Backpacks is switched off (COAH has the same backpacks); the Advanced Backpacks a player carries become COAH backpacks with what they hold" },
					{ "AdvancedPortal", "the Advanced Portal is no longer in the hammer (COAH's Heart Portal is the same); the ones standing keep working" }
				}
			}
		};

		private static readonly Dictionary<string, string> OurGuids = new Dictionary<string, string>
		{
			{ "ImmersiveTrader", "p0kahontazz.immersivetrader" },
			{ "COAH", "p0kahontazz.coah" },
			{ "AdvancedBackpacks", "p0kahontazz.advancedbackpacks" },
			{ "AdvancedPortal", "p0kahontazz.advancedportal" },
			{ "SortByQoL", "p0kahontazz.sortbyqol" }
		};

		internal static Type FindType(string fullName)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				try
				{
					Type type = assembly.GetType(fullName, throwOnError: false);
					if (type != null)
					{
						return type;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		internal static bool Installed(Known known, out string version)
		{
			version = "";
			try
			{
				if (known.Guid != null)
				{
					if (!Chainloader.PluginInfos.TryGetValue(known.Guid, out var value) || value == null)
					{
						return false;
					}
					version = ((value.Metadata != null && value.Metadata.Version != null) ? value.Metadata.Version.ToString() : "");
					return true;
				}
				return known.TypeName != null && FindType(known.TypeName) != null;
			}
			catch
			{
				return false;
			}
		}

		private static string Off(Known known, string ours)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			try
			{
				if (known.Toggle == null || !known.Toggle.TryGetValue(ours, out var value) || !OurGuids.TryGetValue(ours, out var value2))
				{
					return "";
				}
				if (!Chainloader.PluginInfos.TryGetValue(value2, out var value3) || value3 == null || (Object)(object)value3.Instance == (Object)null)
				{
					return "";
				}
				ConfigFile config = value3.Instance.Config;
				ConfigDefinition val = new ConfigDefinition("Compatibility", value);
				if (config == null || !config.ContainsKey(val) || !(config[val].BoxedValue is bool))
				{
					return "";
				}
				return ((bool)config[val].BoxedValue) ? "" : (" (off: [Compatibility] " + value + " = false)");
			}
			catch
			{
				return "";
			}
		}

		internal static void Report(ManualLogSource log, string ours)
		{
			if (log == null)
			{
				return;
			}
			Known[] table = Table;
			foreach (Known known in table)
			{
				if (known.Does != null && known.Does.TryGetValue(ours, out var value) && Installed(known, out var version))
				{
					log.LogInfo((object)("Detected " + known.Name + ((version.Length > 0) ? (" " + version) : "") + ": " + value + Off(known, ours) + "."));
				}
			}
		}

		internal static List<string> Lines()
		{
			List<string> list = new List<string>();
			Known[] table = Table;
			foreach (Known known in table)
			{
				if (Installed(known, out var version))
				{
					list.Add(known.Name + ((version.Length > 0) ? (" " + version) : "") + " (" + (known.Guid ?? known.TypeName) + ", " + known.Kind.ToString() + "): " + string.Join("; ", known.Does.Select((KeyValuePair<string, string> p) => p.Key + " - " + p.Value + Off(known, p.Key)).ToArray()));
				}
			}
			return list;
		}
	}
	internal static class LogLimit
	{
		private sealed class Seen
		{
			public float Next = float.MinValue;

			public int Skipped;
		}

		private const float Every = 10f;

		private static readonly Dictionary<string, Seen> State = new Dictionary<string, Seen>();

		internal static void Warn(ManualLogSource log, string key, string message)
		{
			if (log != null)
			{
				float unscaledTime = Time.unscaledTime;
				if (!State.TryGetValue(key, out var value))
				{
					value = (State[key] = new Seen());
				}
				if (unscaledTime < value.Next)
				{
					value.Skipped++;
					return;
				}
				log.LogWarning((object)((value.Skipped > 0) ? (message + " (and " + value.Skipped + " more times in the last " + 10f.ToString("0") + " s)") : message));
				value.Next = unscaledTime + 10f;
				value.Skipped = 0;
			}
		}
	}
	internal static class ModReport
	{
		private sealed class Listener : ILogListener, IDisposable
		{
			public void LogEvent(object sender, LogEventArgs e)
			{
				//IL_0004: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//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)
				if (e == null || (e.Level & 7) == 0)
				{
					return;
				}
				string text = Convert.ToString(e.Data) ?? "";
				if ((e.Level & 3) != 0)
				{
					KeepError(text);
				}
				if (text.Length > 800)
				{
					text = text.Substring(0, 800) + " ...";
				}
				string item = DateTime.Now.ToString("HH:mm:ss") + " [" + ((object)e.Level/*cast due to .constrained prefix*/).ToString() + ": " + ((e.Source != null) ? e.Source.SourceName : "?") + "] " + text.Replace("\r", "").Replace("\n", " | ");
				lock (recent)
				{
					recent.Enqueue(item);
					while (recent.Count > 200)
					{
						recent.Dequeue();
					}
				}
			}

			public void Dispose()
			{
			}
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static Func<PluginInfo, bool> <>9__8_0;

			public static Func<PluginInfo, string> <>9__8_1;

			public static Func<PluginInfo, bool> <>9__8_2;

			public static Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, string> <>9__9_0;

			public static Func<KeyValuePair<ConfigDefinition, ConfigEntryBase>, string> <>9__9_1;

			public static ConsoleEvent <>9__12_0;

			public static Func<PluginInfo, bool> <>9__15_0;

			public static Func<PluginInfo, string> <>9__15_1;

			public static Func<Patch, bool> <>9__21_0;

			public static Func<MethodBase, bool> <>9__22_0;

			public static Func<string, KeyValuePair<string, int>> <>9__32_0;

			public static Func<Type, bool> <>9__32_1;

			internal bool <Plugins>b__8_0(PluginInfo p)
			{
				if (p != null)
				{
					return p.Metadata != null;
				}
				return false;
			}

			internal string <Plugins>b__8_1(PluginInfo p)
			{
				return p.Metadata.GUID;
			}

			internal bool <Plugins>b__8_2(PluginInfo p)
			{
				return IsHypnogoogic(p.Metadata.GUID);
			}

			internal string <ChangedSettings>b__9_0(KeyValuePair<ConfigDefinition, ConfigEntryBase> p)
			{
				return p.Key.Section;
			}

			internal string <ChangedSettings>b__9_1(KeyValuePair<ConfigDefinition, ConfigEntryBase> p)
			{
				return p.Key.Key;
			}

			internal void <RegisterCommand>b__12_0(ConsoleEventArgs args)
			{
				if (args.Length < 2 || !string.Equals(args[1], "report", StringComparison.OrdinalIgnoreCase))
				{
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("Usage: hypno report");
					}
					return;
				}
				try
				{
					string text = WriteCommon();
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("Report written: " + text + " - send this file with your bug report (it holds no account name or secrets).");
					}
				}
				catch (Exception ex)
				{
					if ((Object)(object)args.Context != (Object)null)
					{
						args.Context.AddString("The report could not be written: " + ex.Message);
					}
				}
			}

			internal bool <WriteCommon>b__15_0(PluginInfo p)
			{
				if (p != null && p.Metadata != null && (Object)(object)p.Instance != (Object)null)
				{
					return IsHypnogoogic(p.Metadata.GUID);
				}
				return false;
			}

			internal string <WriteCommon>b__15_1(PluginInfo p)
			{
				return p.Metadata.Name;
			}

			internal bool <AllPatches>b__21_0(Patch p)
			{
				if (p.PatchMethod != null)
				{
					return p.PatchMethod.DeclaringType != null;
				}
				return false;
			}

			internal bool <Patchers>b__22_0(MethodBase m)
			{
				return m != null;
			}

			internal KeyValuePair<string, int> <ErrorsByClass>b__32_0(string t)
			{
				return new KeyValuePair<string, int>(t, errorCounts[t]);
			}

			internal bool <ErrorsByClass>b__32_1(Type t)
			{
				return t != null;
			}
		}

		private const int Keep = 200;

		private static readonly Queue<string> recent = new Queue<string>();

		private static Listener listener;

		internal const string CommonFile = "Hypnogoogic-report.txt";

		internal static readonly List<Action<StringBuilder>> Top = new List<Action<StringBuilder>>();

		internal static readonly List<Action<StringBuilder>> Extra = new List<Action<StringBuilder>>();

		private const int ErrorsKept = 50;

		private const int ErrorLength = 8000;

		private static readonly List<string> errors = new List<string>();

		private static readonly Dictionary<string, int> errorCounts = new Dictionary<string, int>(StringComparer.Ordinal);

		private static readonly Regex Dmd = new Regex("DMD<(?:[^<>]*<)?([^<>:]+)::([^<>]+?)>");

		private static readonly Regex Patched = new Regex("([\\w\\.\\+/]+)::?([\\w]+)_Patch\\d+");

		private static readonly Regex Frame = new Regex("^\\s*(?:at\\s+)?(?:\\(wrapper [^)]*\\)\\s*)?([\\w\\.\\+/`<>\\[\\]|]+?)[\\.:](\\.?c?ctor|[\\w<>|`]+)\\s*(?:\\[[^\\]]*\\]\\s*)?\\(");

		internal static void StartLog()
		{
			if (listener == null)
			{
				listener = new Listener();
				Logger.Listeners.Add((ILogListener)(object)listener);
			}
		}

		internal static bool IsHypnogoogic(string guid)
		{
			if (guid != null)
			{
				if (!guid.StartsWith("p0kahontazz.", StringComparison.OrdinalIgnoreCase))
				{
					return guid == "pl.rootsandremedies.foods";
				}
				return true;
			}
			return false;
		}

		internal static string GameType()
		{
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null)
			{
				return "main menu (no world)";
			}
			if (!instance.IsServer())
			{
				return "client on a server";
			}
			if (instance.IsDedicated())
			{
				return "dedicated server";
			}
			bool flag = true;
			try
			{
				FieldInfo field = typeof(ZNet).GetField("m_openServer", BindingFlags.Static | BindingFlags.NonPublic);
				if (field != null)
				{
					flag = (bool)field.GetValue(null);
				}
			}
			catch
			{
			}
			if (!flag)
			{
				return "single player";
			}
			return "host (others can join)";
		}

		internal static void Head(StringBuilder sb, string title)
		{
			sb.AppendLine("=== " + title + " ===");
			sb.AppendLine("Written: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " UTC");
			try
			{
				sb.AppendLine("Valheim: " + Version.GetVersionString(false));
			}
			catch
			{
				sb.AppendLine("Valheim: ?");
			}
			sb.AppendLine("Game: " + GameType());
			try
			{
				if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.GetWorldName() != null)
				{
					sb.AppendLine("World: " + ZNet.instance.GetWorldName());
				}
			}
			catch
			{
			}
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null)
			{
				sb.AppendLine("Character: " + localPlayer.GetPlayerName() + " (player id " + localPlayer.GetPlayerID() + ")");
			}
			sb.AppendLine();
		}

		internal static void Plugins(StringBuilder sb)
		{
			List<PluginInfo> list = Chainloader.PluginInfos.Values.Where((PluginInfo p) => p != null && p.Metadata != null).OrderBy<PluginInfo, string>((PluginInfo p) => p.Metadata.GUID, StringComparer.OrdinalIgnoreCase).ToList();
			sb.AppendLine("--- Hypnogoogic mods ---");
			foreach (PluginInfo item in list.Where((PluginInfo p) => IsHypnogoogic(p.Metadata.GUID)))
			{
				sb.AppendLine(item.Metadata.Name + " " + item.Metadata.Version?.ToString() + "  (" + item.Metadata.GUID + ")");
			}
			sb.AppendLine();
			sb.AppendLine("--- Known mods (how ours work with them, see Compat) ---");
			List<string> list2 = Compat.Lines();
			if (list2.Count == 0)
			{
				sb.AppendLine("(none installed)");
			}
			foreach (string item2 in list2)
			{
				sb.AppendLine(item2);
			}
			sb.AppendLine();
			sb.AppendLine("--- All plugins (" + list.Count + ") ---");
			foreach (PluginInfo item3 in list)
			{
				sb.AppendLine(item3.Metadata.GUID + "  " + item3.Metadata.Version?.ToString() + "  " + item3.Metadata.Name);
			}
			sb.AppendLine();
		}

		internal static void ChangedSettings(StringBuilder sb, ConfigFile config, string title)
		{
			sb.AppendLine("--- " + title + ": settings changed from the default ---");
			int num = 0;
			if (config != null)
			{
				foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in from p in (IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)config
					orderby p.Key.Section, p.Key.Key
					select p)
				{
					ConfigEntryBase value = item.Value;
					if (value != null && !object.Equals(value.BoxedValue, value.DefaultValue))
					{
						string text = item.Key.Section + "." + item.Key.Key;
						string text2 = item.Key.Key.ToLowerInvariant();
						bool flag = value.SettingType == typeof(string) && (text2.Contains("key") || text2.Contains("token") || text2.Contains("password") || text2.Contains("secret") || text2.Contains("webhook"));
						sb.AppendLine(text + " = " + (flag ? "(hidden)" : value.GetSerializedValue()) + "   (default " + (flag ? "(hidden)" : ((value.DefaultValue != null) ? Convert.ToString(value.DefaultValue) : "none")) + ")");
						num++;
					}
				}
			}
			if (num == 0)
			{
				sb.AppendLine("(none)");
			}
			sb.AppendLine();
		}

		internal static void RecentLog(StringBuilder sb)
		{
			string[] array;
			lock (recent)
			{
				array = recent.ToArray();
			}
			sb.AppendLine("--- Last " + array.Length + " warnings and errors of the log (all mods) ---");
			if (listener == null)
			{
				sb.AppendLine("(not kept: the log was not watched)");
			}
			string[] array2 = array;
			foreach (string value in array2)
			{
				sb.AppendLine(value);
			}
			sb.AppendLine();
		}

		internal static void RegisterCommand()
		{
			//IL_0038: 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_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			StartLog();
			object obj = <>c.<>9__12_0;
			if (obj == null)
			{
				ConsoleEvent val = delegate(ConsoleEventArgs args)
				{
					if (args.Length < 2 || !string.Equals(args[1], "report", StringComparison.OrdinalIgnoreCase))
					{
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("Usage: hypno report");
						}
						return;
					}
					try
					{
						string text = WriteCommon();
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("Report written: " + text + " - send this file with your bug report (it holds no account name or secrets).");
						}
					}
					catch (Exception ex)
					{
						if ((Object)(object)args.Context != (Object)null)
						{
							args.Context.AddString("The report could not be written: " + ex.Message);
						}
					}
				};
				<>c.<>9__12_0 = val;
				obj = (object)val;
			}
			new ConsoleCommand("hypno", "hypno report - writes BepInEx/Hypnogoogic-report.txt (game, mods, settings, last warnings) to send with a bug report", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false);
		}

		internal static string WriteCommon()
		{
			StringBuilder stringBuilder = new StringBuilder();
			Head(stringBuilder, "Hypnogoogic mods report");
			Sections(stringBuilder, Top);
			Plugins(stringBuilder);
			foreach (PluginInfo item in Chainloader.PluginInfos.Values.Where((PluginInfo p) => p != null && p.Metadata != null && (Object)(object)p.Instance != (Object)null && IsHypnogoogic(p.Metadata.GUID)).OrderBy<PluginInfo, string>((PluginInfo p) => p.Metadata.Name, StringComparer.OrdinalIgnoreCase))
			{
				ChangedSettings(stringBuilder, item.Instance.Config, item.Metadata.Name + " " + item.Metadata.Version);
			}
			Sections(stringBuilder, new List<Action<StringBuilder>> { Collisions, ErrorsByClass });
			Sections(stringBuilder, Extra);
			RecentLog(stringBuilder);
			return Write("Hypnogoogic-report.txt", stringBuilder.ToString());
		}

		private static void Sections(StringBuilder sb, List<Action<StringBuilder>> sections)
		{
			Action<StringBuilder>[] array = sections.ToArray();
			foreach (Action<StringBuilder> action in array)
			{
				try
				{
					action(sb);
				}
				catch (Exception ex)
				{
					sb.AppendLine("(a report section failed: " + ex.Message + ")");
				}
			}
		}

		private static Dictionary<Assembly, BepInPlugin> ByAssembly()
		{
			Dictionary<Assembly, BepInPlugin> dictionary = new Dictionary<Assembly, BepInPlugin>();
			foreach (PluginInfo value in Chainloader.PluginInfos.Values)
			{
				if (value != null && value.Metadata != null && value.Instance != null)
				{
					dictionary[((object)value.Instance).GetType().Assembly] = value.Metadata;
				}
			}
			return dictionary;
		}

		private static string ModName(Assembly assembly, Dictionary<Assembly, BepInPlugin> map)
		{
			if (!map.TryGetValue(assembly, out var value))
			{
				return assembly.GetName().Name + " (not a plugin)";
			}
			return value.Name + " " + value.Version?.ToString() + " (" + value.GUID + ")";
		}

		private static string Method(MethodBase m)
		{
			return ((m.DeclaringType != null) ? m.DeclaringType.FullName : "?") + "." + m.Name;
		}

		private static bool Ours(Patch p, Dictionary<Assembly, BepInPlugin> map)
		{
			if (map.TryGetValue(p.PatchMethod.DeclaringType.Assembly, out var value))
			{
				return IsHypnogoogic(value.GUID);
			}
			return false;
		}

		private static List<Patch> AllPatches(Patches info)
		{
			return (from p in info.Prefixes.Concat(info.Postfixes).Concat(info.Transpilers).Concat(info.Finalizers)
				where p.PatchMethod != null && p.PatchMethod.DeclaringType != null
				select p).ToList();
		}

		internal static void Patchers(StringBuilder sb, IEnumerable<MethodBase> methods)
		{
			Dictionary<Assembly, BepInPlugin> map = ByAssembly();
			foreach (MethodBase item in methods.Where((MethodBase m) => m != null))
			{
				Patches patchInfo = Harmony.GetPatchInfo(item);
				List<Patch> list = ((patchInfo == null) ? new List<Patch>() : (from p in AllPatches(patchInfo)
					where !Ours(p, map)
					select p).ToList());
				sb.AppendLine(Method(item) + ((list.Count == 0) ? ": no other mod patches it" : ":"));
				foreach (Patch item2 in list)
				{
					sb.AppendLine("    " + ModName(item2.PatchMethod.DeclaringType.Assembly, map) + "  " + Method(item2.PatchMethod));
				}
			}
		}

		private static void Collisions(StringBuilder sb)
		{
			sb.AppendLine("--- Collisions with other mods (the method of the game <- their mod, class and method) ---");
			Dictionary<Assembly, BepInPlugin> map = ByAssembly();
			int num = 0;
			foreach (MethodBase item in Harmony.GetAllPatchedMethods().ToList())
			{
				Patches patchInfo = Harmony.GetPatchInfo(item);
				if (patchInfo == null)
				{
					continue;
				}
				List<Patch> list = patchInfo.Prefixes.Where((Patch p) => Real(p) && Ours(p, map)).ToList();
				List<Patch> list2 = patchInfo.Transpilers.Where((Patch p) => Real(p) && Ours(p, map)).ToList();
				List<(Patch, string, Patch)> list3 = new List<(Patch, string, Patch)>();
				if (list.Count > 0)
				{
					foreach (Patch item2 in patchInfo.Prefixes.Where((Patch p) => Theirs(p) && p.PatchMethod.ReturnType == typeof(bool)))
					{
						list3.Add((item2, "its prefix can skip ours", list[0]));
					}
				}
				if (list2.Count > 0)
				{
					foreach (Patch item3 in patchInfo.Transpilers.Where(Theirs))
					{
						list3.Add((item3, "both rewrite the code", list2[0]));
					}
				}
				foreach (var item4 in list3)
				{
					num++;
					sb.AppendLine(Method(item) + "  <-  " + ModName(item4.Item1.PatchMethod.DeclaringType.Assembly, map) + "  " + Method(item4.Item1.PatchMethod) + "  [" + item4.Item2 + "]  ours: " + ModName(item4.Item3.PatchMethod.DeclaringType.Assembly, map) + "  " + Method(item4.Item3.PatchMethod));
				}
			}
			if (num == 0)
			{
				sb.AppendLine("(none seen)");
			}
			sb.AppendLine();
			static bool Real(Patch p)
			{
				if (p.PatchMethod != null)
				{
					return p.PatchMethod.DeclaringType != null;
				}
				return false;
			}
			bool Theirs(Patch p)
			{
				if (Real(p) && !Ours(p, map))
				{
					return !(p.owner ?? "").StartsWith("com.jotunn", StringComparison.OrdinalIgnoreCase);
				}
				return false;
			}
		}

		private static void KeepError(string text)
		{
			if (text.Length > 8000)
			{
				text = text.Substring(0, 8000);
			}
			lock (errors)
			{
				if (errorCounts.TryGetValue(text, out var value))
				{
					errorCounts[text] = value + 1;
				}
				else if (errors.Count < 50)
				{
					errors.Add(text);
					errorCounts[text] = 1;
				}
			}
		}

		private static void ErrorsByClass(StringBuilder sb)
		{
			sb.AppendLine("--- Errors by mod, class and method ---");
			List<KeyValuePair<string, int>> list;
			lock (errors)
			{
				list = errors.Select((string t) => new KeyValuePair<string, int>(t, errorCounts[t])).ToList();
			}
			if (list.Count == 0)
			{
				sb.AppendLine("(no errors)");
				sb.AppendLine();
				return;
			}
			Dictionary<Assembly, BepInPlugin> dictionary = ByAssembly();
			Dictionary<string, Assembly> dictionary2 = new Dictionary<string, Assembly>(StringComparer.Ordinal);
			foreach (Assembly key2 in dictionary.Keys)
			{
				Type[] array;
				try
				{
					array = key2.GetTypes();
				}
				catch (ReflectionTypeLoadException ex)
				{
					array = ex.Types.Where((Type t) => t != null).ToArray();
				}
				catch (Exception)
				{
					continue;
				}
				Type[] array2 = array;
				foreach (Type type in array2)
				{
					if (type.FullName != null)
					{
						dictionary2[type.FullName.Replace('+', '.')] = key2;
					}
				}
			}
			Dictionary<string, List<MethodBase>> dictionary3 = new Dictionary<string, List<MethodBase>>(StringComparer.Ordinal);
			foreach (MethodBase allPatchedMethod in Harmony.GetAllPatchedMethods())
			{
				if (!(allPatchedMethod.DeclaringType == null))
				{
					string key = allPatchedMethod.DeclaringType.Name + "." + allPatchedMethod.Name;
					if (!dictionary3.TryGetValue(key, out var value))
					{
						value = (dictionary3[key] = new List<MethodBase>());
					}
					value.Add(allPatchedMethod);
				}
			}
			foreach (KeyValuePair<string, int> item2 in list)
			{
				string[] array3 = item2.Key.Replace("\r", "").Split('\n');
				sb.AppendLine(((item2.Value > 1) ? ("[" + item2.Value + " times] ") : "") + array3[0]);
				HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
				List<string> list3 = new List<string>();
				List<string> list4 = new List<string>();
				string[] array4 = array3;
				foreach (string input in array4)
				{
					Match match = Dmd.Match(input);
					if (!match.Success)
					{
						match = Patched.Match(input);
					}
					if (match.Success)
					{
						string text = match.Groups[1].Value.Replace('+', '.').Replace('/', '.');
						string text2 = text.Substring(text.LastIndexOf('.') + 1) + "." + match.Groups[2].Value;
						if (!hashSet.Add("game " + text2) || !dictionary3.TryGetValue(text2, out var value2))
						{
							continue;
						}
						foreach (MethodBase item3 in value2)
						{
							Patches patchInfo = Harmony.GetPatchInfo(item3);
							if (patchInfo == null)
							{
								continue;
							}
							list4.Add("  in " + Method(item3) + " - patched by:");
							foreach (Patch item4 in AllPatches(patchInfo))
							{
								list4.Add("      " + ModName(item4.PatchMethod.DeclaringType.Assembly, dictionary) + "  " + Method(item4.PatchMethod));
							}
						}
						continue;
					}
					Match match2 = Frame.Match(input);
					if (!match2.Success)
					{
						continue;
					}
					string text3 = match2.Groups[1].Value.Replace('+', '.').Replace('/', '.');
					if (dictionary2.TryGetValue(text3, out var value3))
					{
						string item = "  mod: " + ModName(value3, dictionary) + "  class " + text3 + "  method " + match2.Groups[2].Value;
						if (hashSet.Add(item) && list3.Count < 8)
						{
							list3.Add(item);
						}
					}
				}
				foreach (string item5 in list3)
				{
					sb.AppendLine(item5);
				}
				foreach (string item6 in list4.Take(30))
				{
					sb.AppendLine(item6);
				}
				if (list3.Count == 0 && list4.Count == 0)
				{
					sb.AppendLine("  (no class of a mod in the trace)");
				}
			}
			sb.AppendLine();
		}

		internal static string Write(string fileName, string text)
		{
			string text2 = Path.Combine(Paths.BepInExRootPath, fileName);
			File.WriteAllText(text2, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
			return text2;
		}
	}
	internal static class Prefabs
	{
		private static Dictionary<int, GameObject> Named(ZNetScene scene)
		{
			return (Dictionary<int, GameObject>)AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs").GetValue(scene);
		}

		internal static void RegisterScene(ZNetScene scene, GameObject prefab)
		{
			Dictionary<int, GameObject> dictionary = Named(scene);
			int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)prefab).name);
			if (dictionary.ContainsKey(stableHashCode))
			{
				throw new InvalidOperationException("Prefab name collision: " + ((Object)prefab).name);
			}
			dictionary.Add(stableHashCode, prefab);
			scene.m_prefabs.Add(prefab);
		}

		internal static void Replace(ZNetScene scene, GameObject prefab)
		{
			Named(scene)[StringExtensionMethods.GetStableHashCode(((Object)prefab).name)] = prefab;
			if (!scene.m_prefabs.Contains(prefab))
			{
				scene.m_prefabs.Add(prefab);
			}
		}

		internal static PieceTable Hammer(ZNetScene scene)
		{
			GameObject val = (((Object)(object)scene != (Object)null) ? scene.GetPrefab("Hammer") : null);
			ItemDrop val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<ItemDrop>() : null);
			if (!((Object)(object)val2 != (Object)null))
			{
				return null;
			}
			return val2.m_itemData.m_shared.m_buildPieces;
		}

		internal static void AddToHammer(PieceTable table, GameObject prefab)
		{
			if (!((Object)(object)table == (Object)null) && !((Object)(object)prefab == (Object)null))
			{
				table.m_pieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null || ((Object)p).name == ((Object)prefab).name);
				table.m_pieces.Add(prefab);
			}
		}
	}
	internal static class StateFile
	{
		internal static class WorldCopy
		{
			internal static Func<bool> Applies = () => false;

			internal static Func<bool> Ready = () => false;

			internal static Func<string, string[]> Read = (string name) => (string[])null;

			internal static Func<string, DateTime> Stamp = (string name) => DateTime.MinValue;

			internal static Func<string, string[], bool> Write = (string name, string[] lines) => false;

			internal static Func<List<string>> Names = () => new List<string>();
		}

		internal sealed class Source
		{
			internal string Label;

			internal string[] Lines;

			internal DateTime Stamp;

			internal bool IsWorld;
		}

		internal static Action<string> Info = delegate
		{
		};

		internal static Action<string> Warn = delegate
		{
		};

		private const int KeepBackups = 7;

		private const string MirrorFolder = "HypnoCode-state";

		private const string LatestName = "latest";

		private const double LatestEverySeconds = 60.0;

		private static readonly Dictionary<string, DateTime> latestAt = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);

		private static readonly object Gate = new object();

		private static readonly Dictionary<string, string> backedUpOn = new Dictionary<string, string>();

		private static readonly HashSet<string> reconciled = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> warned = new HashSet<string>();

		internal static Func<string> SaveRoot = DefaultSaveRoot;

		internal static Func<string> GameRoot = DefaultGameRoot;

		internal const double WorldNewerBySeconds = 120.0;

		internal static string Folder(string mod)
		{
			string text = Path.Combine(Paths.BepInExRootPath, "data", mod);
			Directory.CreateDirectory(text);
			return text;
		}

		private static void WarnOnce(string key, string text)
		{
			if (warned.Add(key))
			{
				Warn(text);
			}
		}

		private static string DefaultSaveRoot()
		{
			try
			{
				string saveDataPath = Utils.GetSaveDataPath((FileSource)2);
				if (!string.IsNullOrEmpty(saveDataPath))
				{
					return saveDataPath;
				}
			}
			catch (Exception ex)
			{
				WarnOnce("saveroot", "State file copy beside the saves: the game's save path is not available (" + ex.Message + "); trying the default data path.");
			}
			try
			{
				string persistantDataPath = Utils.persistantDataPath;
				if (!string.IsNullOrEmpty(persistantDataPath))
				{
					return persistantDataPath;
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		private static string DefaultGameRoot()
		{
			try
			{
				string bepInExRootPath = Paths.BepInExRootPath;
				if (string.IsNullOrEmpty(bepInExRootPath))
				{
					return null;
				}
				string directoryName = Path.GetDirectoryName(bepInExRootPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
				return string.IsNullOrEmpty(directoryName) ? null : directoryName;
			}
			catch (Exception ex)
			{
				WarnOnce("gameroot", "State file copy in the game folder: the folder is not known (" + ex.Message + ").");
				return null;
			}
		}

		private static List<string> MirrorRoots()
		{
			List<string> list = new List<string>();
			Func<string>[] array = new Func<string>[2] { SaveRoot, GameRoot };
			foreach (Func<string> func in array)
			{
				string text = null;
				try
				{
					text = func();
				}
				catch (Exception ex)
				{
					WarnOnce("root:" + ex.Message, "State file copy: a folder could not be resolved (" + ex.Message + ").");
				}
				if (!string.IsNullOrEmpty(text))
				{
					string root = Path.Combine(text, "HypnoCode-state");
					if (!list.Any((string r) => string.Equals(r, root, StringComparison.OrdinalIgnoreCase)))
					{
						list.Add(root);
					}
				}
			}
			if (list.Count == 0)
			{
				WarnOnce("noroots", "State files have NO copy outside BepInEx/data (neither the save folder nor the game folder could be resolved): the state is only as safe as BepInEx/data on this server.");
			}
			return list;
		}

		private static List<string> MirrorPaths(string path)
		{
			string mod = Path.GetFileName(Path.GetDirectoryName(path));
			string file = Path.GetFileName(path);
			return (from r in MirrorRoots()
				select Path.Combine(r, mod, file)).ToList();
		}

		internal static string PathOf(string mod, string file)
		{
			string text = Path.Combine(Folder(mod), file);
			MoveOld(Path.Combine(Paths.ConfigPath, file), text);
			MoveOld(Path.Combine(Paths.ConfigPath, file + ".bak"), text + ".bak");
			return text;
		}

		private static void MoveOld(string old, string path)
		{
			try
			{
				if (!File.Exists(path) && File.Exists(old))
				{
					File.Copy(old, path);
					string text = old + ".moved";
					if (File.Exists(text))
					{
						File.Delete(text);
					}
					File.Move(old, text);
					Info("State file moved out of BepInEx/config: " + Path.GetFileName(old) + " -> " + path + " (the old one is kept as " + Path.GetFileName(text) + ").");
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + Path.GetFileName(old) + " could not be moved (" + ex.Message + "); it is read where it is next time.");
			}
		}

		private static string[] TryRead(string file)
		{
			try
			{
				if (File.Exists(file))
				{
					return File.ReadAllLines(file);
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + file + " could not be read (" + ex.Message + ").");
			}
			return null;
		}

		internal static string[] ReadLines(string path)
		{
			lock (Gate)
			{
				DailyBackup(path);
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string> { path };
				list.AddRange(MirrorPaths(path));
				Dictionary<string, string[]> found = new Dictionary<string, string[]>();
				foreach (string item in list)
				{
					found[item] = TryRead(item);
				}
				List<string> list2 = list.Where((string p) => found[p] != null && found[p].Length != 0).ToList();
				string[] array = null;
				DateTime dateTime = DateTime.MinValue;
				bool flag = false;
				bool flag2 = false;
				try
				{
					flag = WorldCopy.Applies();
					flag2 = flag && WorldCopy.Ready();
					if (flag2)
					{
						array = WorldCopy.Read(fileName);
						if (array != null)
						{
							dateTime = WorldCopy.Stamp(fileName);
						}
					}
				}
				catch (Exception ex)
				{
					flag2 = false;
					WarnOnce("worldread:" + fileName, "State file " + fileName + ": the world's copy could not be read (" + ex.Message + ").");
				}
				if (flag && !flag2)
				{
					WarnOnce("worldnotready:" + fileName, "State file " + fileName + " was read before the world was loaded: the world's copy is merged at the next read.");
				}
				DateTime dateTime2 = DateTime.MinValue;
				foreach (string item2 in list)
				{
					try
					{
						if (found[item2] != null)
						{
							DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(item2);
							if (lastWriteTimeUtc > dateTime2)
							{
								dateTime2 = lastWriteTimeUtc;
							}
						}
					}
					catch (Exception)
					{
					}
				}
				bool flag3 = array != null && array.Length != 0 && (list.All((string p) => found[p] == null) || ((list2.Count == 0) ? (dateTime > dateTime2) : (dateTime > dateTime2.AddSeconds(120.0))));
				if (flag3)
				{
					if (list2.Count == 0)
					{
						Warn("State file " + fileName + " is gone from BepInEx/data and from its copies (wiped on this server?): " + array.Length + " lines taken from the world save.");
					}
					else
					{
						Info("State file " + fileName + ": the world's copy (" + array.Length + " lines, " + dateTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC) is newer than every file (" + dateTime2.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC): the files were behind, merged.");
					}
				}
				else if (array != null && array.Length != 0 && list2.Count > 0)
				{
					Info("State file " + fileName + ": the world's copy is not newer than the files, the files are used.");
				}
				List<string[]> list3 = list2.Select((string p) => found[p]).ToList();
				if (flag3)
				{
					list3.Add(array);
				}
				List<string> merged;
				if (list3.Count > 0)
				{
					merged = Merge(list3);
				}
				else if (list.All((string p) => found[p] == null))
				{
					merged = FromBackups(path);
				}
				else
				{
					merged = new List<string>();
					string text = path + ".bak";
					if (list.Count == 1)
					{
						string[] array2 = TryRead(text);
						if (array2 != null && array2.Length != 0)
						{
							Warn("State file " + fileName + " is empty: read from " + Path.GetFileName(text) + ".");
							merged = array2.ToList();
						}
					}
				}
				if (merged.Count > 0)
				{
					foreach (string place in list)
					{
						string[] array3 = found[place];
						if (array3 != null && array3.SequenceEqual(merged))
						{
							continue;
						}
						bool flag4 = place == path;
						try
						{
							RewriteFile(place, merged);
							if (array3 == null || array3.Length == 0)
							{
								if (flag4 && list2.Count > 0)
								{
									Warn("State file " + fileName + " was missing or empty in BepInEx/data (wiped on this server?): " + merged.Count + " lines put back from " + string.Join(", ", list2.Where((string p) => p != place)) + ".");
								}
								else
								{
									Info("State file " + fileName + ": copy made in " + place + " (" + merged.Count + " lines).");
								}
							}
							else
							{
								Warn("State file " + fileName + ": the copy in " + place + " was behind (" + array3.Length + " lines, the merge of all copies has " + merged.Count + "): updated, nothing was lost.");
							}
						}
						catch (Exception ex3)
						{
							WarnOnce("repair:" + place, "State file " + fileName + ": the copy in " + place + " could not be updated (" + ex3.Message + ").");
						}
					}
				}
				if (flag2 && ((array == null) ? (merged.Count > 0) : (!array.SequenceEqual(merged))))
				{
					try
					{
						if (WorldCopy.Write(fileName, merged.ToArray()))
						{
							Info("State file " + fileName + ": the world's copy " + ((array == null) ? "made" : "updated") + " (" + merged.Count + " lines).");
						}
					}
					catch (Exception ex4)
					{
						WarnOnce("worldwrite:" + fileName, "State file " + fileName + ": the world's copy could not be written (" + ex4.Message + ").");
					}
				}
				if (!flag || flag2)
				{
					reconciled.Add(path);
				}
				if (merged.Count > 0)
				{
					KeepLatest(path, found.Values.Any((string[] l) => l == null || l.Length != merged.Count));
				}
				return merged.ToArray();
			}
		}

		internal static List<Source> ReadSources(string path, out bool worldPending)
		{
			lock (Gate)
			{
				DailyBackup(path);
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string>();
				list.Add(path);
				list.AddRange(MirrorPaths(path));
				List<Source> list2 = new List<Source>();
				foreach (string item in list)
				{
					DateTime stamp = DateTime.MinValue;
					string[] array = TryRead(item);
					if (array != null)
					{
						try
						{
							stamp = File.GetLastWriteTimeUtc(item);
						}
						catch (Exception)
						{
						}
					}
					list2.Add(new Source
					{
						Label = item,
						Lines = array,
						Stamp = stamp
					});
				}
				worldPending = false;
				try
				{
					if (WorldCopy.Applies())
					{
						if (WorldCopy.Ready())
						{
							string[] array2 = WorldCopy.Read(fileName);
							list2.Add(new Source
							{
								Label = "the world save",
								Lines = array2,
								Stamp = ((array2 == null) ? DateTime.MinValue : WorldCopy.Stamp(fileName)),
								IsWorld = true
							});
						}
						else
						{
							worldPending = true;
						}
					}
				}
				catch (Exception ex2)
				{
					worldPending = false;
					WarnOnce("worldread:" + fileName, "State file " + fileName + ": the world's copy could not be read (" + ex2.Message + ").");
				}
				return list2;
			}
		}

		internal static List<string> LinesFromBackups(string path)
		{
			lock (Gate)
			{
				return FromBackups(path);
			}
		}

		internal static bool WorldReady()
		{
			try
			{
				return WorldCopy.Applies() && WorldCopy.Ready();
			}
			catch (Exception)
			{
				return false;
			}
		}

		internal static bool WorldNotLoadedYet()
		{
			try
			{
				return WorldCopy.Applies() && !WorldCopy.Ready();
			}
			catch (Exception)
			{
				return false;
			}
		}

		internal static void MarkReconciled(string path)
		{
			lock (Gate)
			{
				reconciled.Add(path);
			}
		}

		private static List<string> Merge(List<string[]> sources)
		{
			int num = 0;
			for (int i = 1; i < sources.Count; i++)
			{
				if (sources[i].Length > sources[num].Length)
				{
					num = i;
				}
			}
			List<string> list = new List<string>(sources[num]);
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (string item in list)
			{
				dictionary.TryGetValue(item, out var value);
				dictionary[item] = value + 1;
			}
			for (int j = 0; j < sources.Count; j++)
			{
				if (j == num)
				{
					continue;
				}
				Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
				string[] array = sources[j];
				foreach (string text in array)
				{
					dictionary2.TryGetValue(text, out var value2);
					value2 = (dictionary2[text] = value2 + 1);
					dictionary.TryGetValue(text, out var value3);
					if (value2 > value3)
					{
						list.Add(text);
						dictionary[text] = value3 + 1;
					}
				}
			}
			return list;
		}

		private static List<string> FromBackups(string path)
		{
			string fileName = Path.GetFileName(path);
			string text = path + ".bak";
			string[] array = TryRead(text);
			if (array != null && array.Length != 0)
			{
				Warn("State file " + fileName + " is gone: read from " + Path.GetFileName(text) + ".");
				return array.ToList();
			}
			try
			{
				string directoryName = Path.GetDirectoryName(path);
				List<KeyValuePair<string, string>> source = Backups(directoryName);
				foreach (KeyValuePair<string, string> item in source.Where((KeyValuePair<string, string> b) => b.Key == "latest").Concat(source.Where((KeyValuePair<string, string> b) => b.Key != "latest")).ToList())
				{
					string[] array2 = null;
					foreach (string item2 in BackupLocations(directoryName, item.Key))
					{
						string[] array3 = TryRead(Path.Combine(item2, fileName));
						if (array3 != null && array3.Length != 0 && (array2 == null || array3.Length > array2.Length))
						{
							array2 = array3;
						}
					}
					if (array2 != null)
					{
						Warn("State file " + fileName + " is gone from every place: restored from the backup copy '" + item.Key + "' (" + array2.Length + " lines). Anything newer than that copy is lost.");
						return array2.ToList();
					}
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + fileName + ": the backup copies could not be searched (" + ex.Message + ").");
			}
			return new List<string>();
		}

		internal static void Append(string path, string line)
		{
			lock (Gate)
			{
				if (!reconciled.Contains(path))
				{
					ReadLines(path);
				}
				string fileName = Path.GetFileName(path);
				string contents = line + Environment.NewLine;
				bool flag = false;
				try
				{
					Directory.CreateDirectory(Path.GetDirectoryName(path));
					File.AppendAllText(path, contents);
					flag = true;
				}
				catch (Exception ex)
				{
					WarnOnce("append:" + path, "State file " + fileName + " could not be written in BepInEx/data (" + ex.Message + "); the other copies are written.");
				}
				foreach (string item in MirrorPaths(path))
				{
					try
					{
						Directory.CreateDirectory(Path.GetDirectoryName(item));
						if (File.Exists(item))
						{
							File.AppendAllText(item, contents);
						}
						else if (File.Exists(path))
						{
							File.Copy(path, item);
						}
						else
						{
							File.AppendAllText(item, contents);
						}
						flag = true;
					}
					catch (Exception ex2)
					{
						WarnOnce("append:" + item, "State file " + fileName + ": the copy in " + item + " could not be written (" + ex2.Message + ").");
					}
				}
				try
				{
					if (WorldCopy.Applies() && WorldCopy.Ready())
					{
						string[] array = WorldCopy.Read(fileName) ?? new string[0];
						string[] array2 = new string[array.Length + 1];
						Array.Copy(array, array2, array.Length);
						array2[array.Length] = line;
						if (WorldCopy.Write(fileName, array2))
						{
							flag = true;
						}
					}
				}
				catch (Exception ex3)
				{
					WarnOnce("worldappend:" + fileName, "State file " + fileName + ": the world's copy could not be written (" + ex3.Message + ").");
				}
				if (!flag)
				{
					throw new IOException("State file " + fileName + " could not be written in any place.");
				}
				DailyBackup(path);
				KeepLatest(path, force: false);
			}
		}

		internal static void Rewrite(string path, IEnumerable<string> lines)
		{
			lock (Gate)
			{
				List<string> list = lines.ToList();
				string fileName = Path.GetFileName(path);
				bool flag = false;
				Exception ex = null;
				try
				{
					RewriteFile(path, list);
					flag = true;
				}
				catch (Exception ex2)
				{
					ex = ex2;
					WarnOnce("rewrite:" + path, "State file " + fileName + " could not be rewritten in BepInEx/data (" + ex2.Message + "); the other copies are.");
				}
				foreach (string item in MirrorPaths(path))
				{
					try
					{
						RewriteFile(item, list);
						flag = true;
					}
					catch (Exception ex3)
					{
						WarnOnce("rewrite:" + item, "State file " + fileName + ": the copy in " + item + " could not be rewritten (" + ex3.Message + ").");
					}
				}
				try
				{
					if (WorldCopy.Applies() && WorldCopy.Ready() && WorldCopy.Write(fileName, list.ToArray()))
					{
						flag = true;
					}
				}
				catch (Exception ex4)
				{
					WarnOnce("worldrewrite:" + fileName, "State file " + fileName + ": the world's copy could not be rewritten (" + ex4.Message + ").");
				}
				reconciled.Add(path);
				if (!flag)
				{
					throw ex ?? new IOException("State file " + fileName + " could not be rewritten in any place.");
				}
				KeepLatest(path, force: true);
			}
		}

		private static void RewriteFile(string path, IEnumerable<string> lines)
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			string text = path + ".tmp";
			string text2 = path + ".bak";
			File.WriteAllLines(text, lines);
			try
			{
				if (File.Exists(path))
				{
					File.Replace(text, path, text2);
				}
				else
				{
					File.Move(text, path);
				}
			}
			catch (Exception ex)
			{
				Warn("State file " + Path.GetFileName(path) + ": atomic replace failed (" + ex.Message + "), copying instead.");
				if (File.Exists(path))
				{
					File.Copy(path, text2, overwrite: true);
				}
				File.Copy(text, path, overwrite: true);
				File.Delete(text);
			}
		}

		private static void KeepLatest(string path, bool force)
		{
			try
			{
				DateTime utcNow = DateTime.UtcNow;
				if (!force && latestAt.TryGetValue(path, out var value) && (utcNow - value).TotalSeconds < 60.0)
				{
					return;
				}
				latestAt[path] = utcNow;
				string fileName = Path.GetFileName(path);
				List<string> list = new List<string>();
				list.Add(path);
				list.AddRange(MirrorPaths(path));
				foreach (string item in list)
				{
					if (File.Exists(item))
					{
						string text = Path.Combine(Path.GetDirectoryName(item), "backups", "latest");
						Directory.CreateDirectory(text);
						File.Copy(item, Path.Combine(text, fileName), overwrite: true);
					}
				}
			}
			catch (Exception ex)
			{
				WarnOnce("latest", "State files: the rolling backup copy could not be written (" + ex.Message + ").");
			}
		}

		private static List<string> BackupRoots(string dir)
		{
			string mod = Path.GetFileName(dir);
			List<string> list = new List<string>();
			list.Add(Path.Combine(dir, "backups"));
			list.AddRange(from r in MirrorRoots()
				select Path.Combine(r, mod, "backups"));
			return list;
		}

		private static List<string> BackupLocations(string dir, string name)
		{
			return (from r in BackupRoots(dir)
				select Path.Combine(r, name)).Where(Directory.Exists).ToList();
		}

		private static long SizeOf(string folder)
		{
			try
			{
				return Directory.GetFiles(folder).Sum((string f) => new FileInfo(f).Length);
			}
			catch (Exception)
			{
				return 0L;
			}
		}

		internal static void DailyBackup(string path)
		{
			lock (Gate)
			{
				try
				{
					string directoryName = Path.GetDirectoryName(path);
					if (string.IsNullOrEmpty(directoryName))
					{
						return;
					}
					string text = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
					if (backedUpOn.TryGetValue(directoryName, out var value) && value == text)
					{
						return;
					}
					string fileName = Path.GetFileName(directoryName);
					bool flag = BackupInto(directoryName, text);
					foreach (string item in MirrorRoots())
					{
						BackupInto(Path.Combine(item, fileName), text);
					}
					if (flag)
					{
						backedUpOn[directoryName] = text;
					}
				}
				catch (Exception ex)
				{
					Warn("Daily backup of the state files failed (" + ex.Message + ").");
				}
			}
		}

		private static bool BackupInto(string folder, string name)
		{
			if (!Directory.Exists(folder))
			{
				return false;
			}
			string text = Path.Combine(folder, "backups");
			string text2 = Path.Combine(text, name);
			if (Directory.Exists(text2))
			{
				return true;
			}
			string[] array = (from f in Directory.GetFiles(folder)
				where !f.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)
				select f).ToArray();
			if (array.Length == 0)
			{
				return false;
			}
			Directory.CreateDirectory(text2);
			string[] array2 = array;
			foreach (string text3 in array2)
			{
				File.Copy(text3, Path.Combine(text2, Path.GetFileName(text3)), overwrite: true);
			}
			array2 = (from d in Directory.GetDirectories(text)
				where IsDaily(Path.GetFileName(d))
				select d).OrderByDescending<string, string>((string d) => Path.GetFileName(d), StringComparer.Ordinal).Skip(7).ToArray();
			for (int num = 0; num < array2.Length; num++)
			{
				Directory.Delete(array2[num], recursive: true);
			}
			Info("State files backed up to " + text2 + " (" + array.Length + " files, the " + 7 + " newest days are kept).");
			return true;
		}

		private static bool IsDaily(string name)
		{
			DateTime result;
			if (name.Length == 10)
			{
				return DateTime.TryParseExact(name, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
			}
			return false;
		}

		private static bool IsStateFile(string path)
		{
			string fileName = Path.GetFileName(path);
			if (!fileName.EndsWith(".bak", StringComparison.OrdinalIgnoreCase) && !fileName.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase))
			{
				return !fileName.EndsWith(".moved", StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		internal static string Snapshot(string dir, string label, out int count)
		{
			lock (Gate)
			{
				count = 0;
				string text = label + "-" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);
				string mod = Path.GetFileName(dir);
				List<string> list = new List<string>();
				list.Add(dir);
				list.AddRange(from r in MirrorRoots()
					select Path.Combine(r, mod));
				foreach (string item in list)
				{
					if (!Directory.Exists(item))
					{
						continue;
					}
					string[] array = (from f in Directory.GetFiles(item)
						where !f.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase)
						select f).ToArray();
					if (array.Length != 0)
					{
						string text2 = Path.Combine(item, "backups", text);
						Directory.CreateDirectory(text2);
						string[] array2 = array;
						foreach (string text3 in array2)
						{
							File.Copy(text3, Path.Combine(text2, Path.GetFileName(text3)), overwrite: true);
						}
						count = Math.Max(count, array.Length);
						Info("State files copied to " + text2 + " (" + array.Length + " files).");
					}
				}
				return text;
			}
		}

		internal static List<KeyValuePair<string, string>> Backups(string dir)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			Dictionary<string, DateTime> dictionary = new Dictionary<string, DateTime>();
			foreach (string item in BackupRoots(dir))
			{
				if (!Directory.Exists(item))
				{
					continue;
				}
				string[] directories = Directory.GetDirectories(item);
				foreach (string path in directories)
				{
					string fileName = Path.GetFileName(path);
					DateTime lastWriteTime = Directory.GetLastWriteTime(path);
					if (!dictionary.TryGetValue(fileName, out var value) || lastWriteTime > value)
					{
						dictionary[fileName] = lastWriteTime;
					}
				}
			}
			foreach (KeyValuePair<string, DateTime> item2 in dictionary.OrderByDescending((KeyValuePair<string, DateTime> p) => p.Value))
			{
				int num = (from l in BackupLocations(dir, item2.Key)
					select Directory.GetFiles(l).Count(IsStateFile)).DefaultIfEmpty(0).Max();
				list.Add(new KeyValuePair<string, string>(item2.Key, item2.Value.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + ", " + num + " state files"));
			}
			return list;
		}

		internal static int RestoreFrom(string dir, string backupName)
		{
			if (string.IsNullOrEmpty(backupName) || backupName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || backupName.Contains(".."))
			{
				return -1;
			}
			List<string> list = BackupLocations(dir, backupName);
			if (list.Count == 0)
			{
				return -1;
			}
			string text = list.OrderByDescending(SizeOf).First();
			int num = 0;
			foreach (string item in Directory.GetFiles(text).Where(IsStateFile))
			{
				Rewrite(Path.Combine(dir, Path.GetFileName(item)), File.ReadAllLines(item));
				num++;
			}
			Info("State files restored from " + text + " (" + num + " files).");
			return num;
		}

		private static string Brief(string file)
		{
			try
			{
				if (!File.Exists(file))
				{
					return "MISSING";
				}
				FileInfo fileInfo = new FileInfo(file);
				return File.ReadAllLines(file).Length + " lines, " + fileInfo.Length + " B, " + fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
			}
			catch (Exception ex)
			{
				return "unreadable (" + ex.Message + ")";
			}
		}

		internal static List<string> Describe(string mod)
		{
			lock (Gate)
			{
				List<string> list = new List<string>();
				string text = Folder(mod);
				List<string> list2 = MirrorRoots();
				list.Add("Copies of the state files (reading merges all of them, every write goes to all):");
				list.Add("  data:   " + text);
				foreach (string item in list2)
				{
					list.Add("  copy:   " + Path.Combine(item, mod));
				}
				if (list2.Count == 0)
				{
					list.Add("  WARNING: no copy outside BepInEx/data (the save folder and the game folder could not be resolved).");
				}
				bool flag = false;
				bool flag2 = false;
				try
				{
					flag = WorldCopy.Applies();
					flag2 = flag && WorldCopy.Ready();
				}
				catch (Exception)
				{
				}
				list.Add("  world:  " + ((!flag) ? "not on this side (only a server or host keeps it)" : (flag2 ? "inside the world save (a persistent object far outside the map; saved with the world)" : "the world is not loaded yet")));
				List<string> list3 = new List<string>();
				list3.Add(text);
				list3.AddRange(list2.Select((string r) => Path.Combine(r, mod)));
				SortedSet<string> sortedSet = new SortedSet<string>(StringComparer.Ordinal);
				foreach (string item2 in list3)
				{
					if (!Directory.Exists(item2))
					{
						continue;
					}
					foreach (string item3 in Directory.GetFiles(item2).Where(IsStateFile))
					{
						sortedSet.Add(Path.GetFileName(item3));
					}
				}
				if (flag2)
				{
					try
					{
						foreach (string item4 in WorldCopy.Names())
						{
							sortedSet.Add(item4);
						}
					}
					catch (Exception ex2)
					{
						list.Add("  world copy: names could not be read (" + ex2.Message + ")");
					}
				}
				foreach (string item5 in sortedSet)
				{
					List<string> list4 = new List<string> { "data " + Brief(Path.Combine(text, item5)) };
					for (int num = 0; num < list2.Count; num++)
					{
						list4.Add("copy" + (num + 1) + " " + Brief(Path.Combine(list2[num], mod, item5)));
					}
					if (flag2)
					{
						try
						{
							string[] array = WorldCopy.Read(item5);
							list4.Add((array == null) ? "world MISSING" : ("world " + array.Length + " lines, " + WorldCopy.Stamp(item5).ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC"));
						}
						catch (Exception ex3)
						{
							list4.Add("world unreadable (" + ex3.Message + ")");
						}
					}
					list.Add("  " + item5 + ": " + string.Join(" | ", list4));
				}
				List<KeyValuePair<string, string>> list5 = Backups(text);
				list.Add("  backups: " + list5.Count + ((list5.Count > 0) ? (" (newest " + list5[0].Key + ")") : "") + " - 'it backup list'");
				return list;
			}
		}

		internal static void ForgetReconciled()
		{
			lock (Gate)
			{
				reconciled.Clear();
			}
		}

		internal static void ForgetForTests()
		{
			lock (Gate)
			{
				backedUpOn.Clear();
				reconciled.Clear();
				warned.Clear();
				latestAt.Clear();
			}
		}
	}
	internal static class UiKit
	{
		internal static Action<string> Warn = delegate
		{
		};

		internal static readonly Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

		internal static Sprite panelSprite;

		internal static Type panelType;

		internal static Color panelColor = new Color(0.25f, 0.17f, 0.1f, 0.97f);

		internal static float panelPpu = 1f;

		internal static Material panelMaterial;

		internal static Button buttonTemplate;

		internal static TMP_FontAsset font;

		internal static TMP_FontAsset titleFont;

		internal static Color titleColor = new Color(1f, 0.63f, 0.235f);

		internal static Color bodyColor = new Color(0.98f, 0.95f, 0.9f);

		internal static bool skin;

		internal static Sprite flat;

		internal static TMP_FontAsset BodyFont()
		{
			if ((Object)(object)font == (Object)null)
			{
				Discover();
			}
			return font;
		}

		internal static RectTransform Rect(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: 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)
			RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) })
			{
				layer = LayerMask.NameToLayer("UI")
			}.GetComponent<RectTransform>();
			((Transform)component).SetParent(parent, false);
			component.anchorMin = aMin;
			component.anchorMax = aMax;
			component.offsetMin = oMin;
			component.offsetMax = oMax;
			return component;
		}

		internal static Image Box(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			Image obj = ((Component)Rect(name, parent, aMin, aMax, oMin, oMax)).gameObject.AddComponent<Image>();
			((Graphic)obj).color = color;
			return obj;
		}

		internal static Sprite FindSprite(string name)
		{
			if (sprites.TryGetValue(name, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			value = null;
			Sprite[] array = Resources.FindObjectsOfTypeAll<Sprite>();
			foreach (Sprite val in array)
			{
				if ((Object)(object)val != (Object)null && ((Object)val).name == name)
				{
					value = val;
					break;
				}
			}
			sprites[name] = value;
			return value;
		}

		internal static bool Draws(TMP_FontAsset f)
		{
			if ((Object)(object)f == (Object)null)
			{
				return false;
			}
			try
			{
				return f.HasCharacter('A', true, true) && f.HasCharacter('g', true, true) && f.HasCharacter('7', true, true);
			}
			catch
			{
				return false;
			}
		}

		internal static void Discover()
		{
			//IL_005d: 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_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_027e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			skin = false;
			panelSprite = null;
			buttonTemplate = null;
			InventoryGui instance = InventoryGui.instance;
			TMP_FontAsset val = null;
			try
			{
				val = (((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeDecription != (Object)null) ? instance.m_recipeDecription.font : null);
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeDecription != (Object)null)
				{
					bodyColor = ((Graphic)instance.m_recipeDecription).color;
				}
			}
			catch
			{
			}
			try
			{
				titleFont = (((Object)(object)instance != (Object)null && (Object)(object)instance.m_recipeName != (Object)null && Draws(instance.m_recipeName.font)) ? instance.m_recipeName.font : null);
			}
			catch
			{
				titleFont = null;
			}
			TMP_FontAsset val2 = (Draws(val) ? val : null);
			if ((Object)(object)val2 == (Object)null)
			{
				TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
				foreach (TMP_FontAsset val3 in array)
				{
					if ((Object)(object)val3 != (Object)null && ((Object)val3).name.IndexOf("Averia", StringComparison.OrdinalIgnoreCase) >= 0 && Draws(val3))
					{
						val2 = val3;
						break;
					}
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				try
				{
					TMP_FontAsset defaultFontAsset = TMP_Settings.defaultFontAsset;
					if (Draws(defaultFontAsset))
					{
						val2 = defaultFontAsset;
					}
				}
				catch
				{
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
				foreach (TMP_FontAsset val4 in array)
				{
					if (Draws(val4))
					{
						val2 = val4;
						break;
					}
				}
			}
			font = val2 ?? val;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.m_crafting == (Object)null)
			{
				return;
			}
			try
			{
				List<Image> list = ((Component)instance.m_crafting).GetComponentsInChildren<Image>(true).ToList();
				Transform parent = ((Transform)instance.m_crafting).parent;
				int num = 0;
				while (num < 3 && (Object)(object)parent != (Object)null)
				{
					Image component = ((Component)parent).GetComponent<Image>();
					if ((Object)(object)component != (Object)null)
					{
						list.Add(component);
					}
					num++;
					parent = parent.parent;
				}
				Func<Image, bool> bad = delegate(Image val6)
				{
					string text = (((Object)val6).name + " " + ((Object)val6.sprite).name).ToLowerInvariant();
					string[] array2 = new string[12]
					{
						"darken", "blob", "shadow", "glow", "select", "icon", "scroll", "handle", "bar", "highlight",
						"button", "tab"
					};
					foreach (string value in array2)
					{
						if (text.Contains(value))
						{
							return true;
						}
					}
					return false;
				};
				Image val5 = list.Where((Image val6) => (Object)(object)val6.sprite != (Object)null && !bad(val6) && ((Graphic)val6).color.a > 0.5f).OrderByDescending(delegate(Image val6)
				{
					//IL_0006: Unknown result type (might be due to invalid IL or missing references)
					//IL_000b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0019: Unknown result type (might be due to invalid IL or missing references)
					//IL_001e: Unknown result type (might be due to invalid IL or missing references)
					Rect rect = ((Graphic)val6).rectTransform.rect;
					float width = ((Rect)(ref rect)).width;
					rect = ((Graphic)val6).rectTransform.rect;
					return width * ((Rect)(ref rect)).height;
				}).FirstOrDefault();
				if ((Object)(object)val5 != (Object)null)
				{
					panelSprite = val5.sprite;
					panelType = val5.type;
					panelColor = ((Graphic)val5).color;
					panelPpu = val5.pixelsPerUnitMultiplier;
					panelMaterial = ((Graphic)val5).material;
				}
				buttonTemplate = instance.m_craftButton;
				skin = (Object)(object)val5 != (Object)null;
			}
			catch (Exception ex)
			{
				Warn("HypnoCode: the game's skin was not found (" + ex.Message + "), plain colours are used.");
			}
		}

		internal static TMP_Text Label(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, string text, float size, Color color, TextAlignmentOptions align, bool ellipsis = false)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0051: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)Rect(name, parent, aMin, aMax, oMin, oMax)).gameObject;
			gameObject.SetActive(false);
			TextMeshProUGUI val = gameObject.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)font != (Object)null)
			{
				((TMP_Text)val).font = font;
			}
			((TMP_Text)val).text = text;
			((TMP_Text)val).fontSize = size;
			((Graphic)val).color = color;
			((TMP_Text)val).alignment = align;
			((Graphic)val).raycastTarget = false;
			((TMP_Text)val).enableWordWrapping = false;
			((TMP_Text)val).overflowMode = (TextOverflowModes)(ellipsis ? 1 : 0);
			gameObject.SetActive(true);
			return (TMP_Text)(object)val;
		}

		internal static bool Keep(Component c)
		{
			if (!(c is Graphic) && !(c is Selectable) && !(c is Mask) && !(c is RectMask2D) && !(c is LayoutGroup) && !(c is ContentSizeFitter) && !(c is LayoutElement))
			{
				return c is BaseMeshEffect;
			}
			return true;
		}

		internal static Button MakeButton(string name, Transform parent, Vector2 aMin, Vector2 aMax, Vector2 oMin, Vector2 oMax, string text, Color colour, Action click, out TMP_Text labelOut, float size = 30f, bool edge = false)
		{
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Expected O, but got Unknown
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: 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)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//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_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0368: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: 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_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0314: Unknown result type (might be due to invalid IL or missing references)
			//IL_0320: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0285: 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_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: 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_0122: 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_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			Image val2;
			Button val3;
			if (skin && (Object)(object)buttonTemplate != (Object)null)
			{
				GameObject val = Object.Instantiate<GameObject>(((Component)buttonTemplate).gameObject, parent, false);
				((Object)val).name = name;
				val.SetActive(true);
				ColorBlock colors = ((Selectable)buttonTemplate).colors;
				Transition transition = ((Selectable)buttonTemplate).transition;
				SpriteState spriteState = ((Selectable)buttonTemplate).spriteState;
				foreach (MonoBehaviour item in val.GetComponentsInChildren<MonoBehaviour>(true).ToList())
				{
					if ((Object)(object)item != (Object)null && !Keep((Component)(object)item))
					{
						Object.DestroyImmediate((Object)(object)item);
					}
				}
				foreach (Selectable item2 in val.GetComponentsInChildren<Selectable>(true).ToList())
				{
					if ((Object)(object)item2 != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)item2);
					}
				}
				val2 = val.GetComponent<Image>();
				val3 = val.AddComponent<Button>();
				((Selectable)val3).targetGraphic = (Graphic)(object)val2;
				((Selectable)val3).transition = transition;
				((Selectable)val3).colors = colors;
				((Selectable)val3).spriteState = spriteState;
				TMP_Text[] componentsInChildren = val.GetComponentsInChildren<TMP_Text>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					((Component)componentsInChildren[i]).gameObject.SetActive(false);
				}
				RectTransform val4 = (RectTransform)val.transform;
				val4.anchorMin = aMin;
				val4.anchorMax = aMax;
				val4.offsetMin = oMin;
				val4.offsetMax = oMax;
			}
			else
			{
				val2 = Box(name, parent, aMin, aMax, oMin, oMax, new Color(0.1f, 0.07f, 0.04f, 0.9f));
				val3 = ((Component)val2).gameObject.AddComponent<Button>();
				((Selectable)val3).targetGraphic = (Graphic)(object)val2;
			}
			((UnityEvent)val3.onClick).AddListener((UnityAction)delegate
			{
				ClickSound();
				click();
			});
			TMP_Text val5 = Label("text", ((Component)val2).transform, Vector2.zero, Vector2.one, Vector2.zero, Vector2.zero, text, size, colour, (TextAlignmentOptions)514);
			GameObject edge2 = null;
			RectTransform val6;
			if (edge)
			{
				val6 = Rect("edge", ((Component)val3).transform, Vector2.zero, Vector2.one, new Vector2(-1f, -1f), new Vector2(1f, 1f));
				Image val7 = ((Component)val6).gameObject.AddComponent<Image>();
				((Graphic)val7).raycastTarget = false;
				Sprite val8 = FindSprite("selection_frame");
				if ((Object)(object)val8 != (Object)null)
				{
					Vector4 border = val8.border;
					if (((Vector4)(ref border)).sqrMagnitude > 0f)
					{
						val7.sprite = val8;
						val7.type = (Type)1;
						((Graphic)val7).color = new Color(colour.r, colour.g, colour.b, 0.95f);
						goto IL_033e;
					}
				}
				((Graphic)val7).color = new Color(colour.r, colour.g, colour.b, 0f);
				Outline obj = ((Component)val6).gameObject.AddComponent<Outline>();
				((Shadow)obj).effectColor = new Color(colour.r, colour.g, colour.b, 0.9f);
				((Shadow)obj).effectDistance = new Vector2(2f, -2f);
				goto IL_033e;
			}
			goto IL_034e;
			IL_033e:
			((Transform)val6).SetAsFirstSibling();
			edge2 = ((Component)val6).gameObject;
			goto IL_034e;
			IL_034e:
			UiButtonTint uiButtonTint = ((Component)val3).gameObject.AddComponent<UiButtonTint>();
			uiButtonTint.Target = val3;
			uiButtonTint.Label = val5;
			uiButtonTint.Colour = colour;
			uiButtonTint.Edge = edge2;
			labelOut = val5;
			return val3;
		}

		internal static void ClickSound()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("sfx_gui_button") : null);
			if ((Object)(object)val != (Object)null && (Object)(object)Utils.GetMainCamera() != (Object)null)
			{
				Object.Instantiate<GameObject>(val, ((Component)Utils.GetMainCamera()).transform.position, Quaternion.identity);
			}
		}

		internal static Sprite FlatSprite()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			//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_007e: 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)
			if ((Object)(object)flat != (Object)null)
			{
				return flat;
			}
			Texture2D val = new Texture2D(4, 4, (TextureFormat)4, false)
			{
				hideFlags = (HideFlags)61
			};
			Color32[] array = (Color32[])(object)new Color32[16];
			for (int i = 0; i < 16; i++)
			{
				array[i] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
			}
			val.SetPixels32(array);
			val.Apply(false, true);
			flat = Sprite.Create(val, new Rect(0f, 0f, 4f, 4f), new Vector2(0.5f, 0.5f), 100f);
			((Object)flat).hideFlags = (HideFlags)61;
			return flat;
		}
	}
	public sealed class UiButtonTint : MonoBehaviour
	{
		public Button Target;

		public TMP_Text Label;

		public Color Colour;

		public GameObject Edge;

		private void Update()
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)Target == (Object)null))
			{
				bool interactable = ((Selectable)Target).interactable;
				if ((Object)(object)Label != (Object)null)
				{
					((Graphic)Label).color = (Color)(interactable ? Colour : new Color(0.5f, 0.48f, 0.45f, 1f));
				}
				if ((Object)(object)Edge != (Object)null && Edge.activeSelf != interactable)
				{
					Edge.SetActive(interactable);
				}
			}
		}
	}
	internal static class HubConsole
	{
		private sealed class Line : List<KeyValuePair<string, ConsoleColor>>
		{
			internal string Text => string.Concat(this.Select((KeyValuePair<string, ConsoleColor> p) => p.Key));

			internal Line Add(string text, ConsoleColor colour)
			{
				Add(new KeyValuePair<string, ConsoleColor>(text, colour));
				return this;
			}
		}

		internal const string Discord = "https://discord.gg/QygN9rEKEw";

		internal const string Website = "https://hypnomods.pages.dev/";

		internal const int Good = 0;

		internal const int Warn = 1;

		internal const int Neutral = 2;

		private const string Key = "HypnoCode.Hub.Console.v1";

		private const int Width = 49;

		private const int Column = 35;

		private const ConsoleColor Violet = (ConsoleColor)(-1);

		private const float Patience = 60f;

		private static ManualLogSource source;

		private static Dictionary<string, object> State
		{
			get
			{
				if (AppDomain.CurrentDomain.GetData("HypnoCode.Hub.Console.v1") is Dictionary<string, object> result)
				{
					return result;
				}
				Dictionary<string, object> dictionary = new Dictionary<string, object>
				{
					["mods"] = new List<object[]>(),
					["reports"] = new Dictionary<string, object[]>(),
					["started"] = false,
					["since"] = -1f,
					["printed"] = ""
				};
				AppDomain.CurrentDomain.SetData("HypnoCode.Hub.Console.v1", dictionary);
				return dictionary;
			}
		}

		private static List<object[]> Mods => (List<object[]>)State["mods"];

		private static Dictionary<string, object[]> Reports => (Dictionary<string, object[]>)State["reports"];

		internal static void Register(string id, string name, string version)
		{
			if (Mods.All((object[] m) => (string)m[0] != id))
			{
				Mods.Add(new object[3] { id, name, version });
			}
		}

		internal static void PrintStart()
		{
			if ((bool)State["started"] || Mods.Count == 0)
			{
				return;
			}
			State["started"] = true;
			List<Line> list = Head();
			foreach (object[] mod in Mods)
			{
				list.Add(Row((string)mod[1], ConsoleColor.Gray, (string)mod[2], ConsoleColor.Gray));
				list.Add(Row("WORKING", ConsoleColor.DarkGreen, "loading assets ...", ConsoleColor.DarkYellow));
			}
			list.Add(Waves());
			list.Add(new Line());
			Write(list);
		}

		internal static void Report(string id, List<object[]> rows, bool missing)
		{
			Reports[id] = new object[2] { rows, missing };
			State["printed"] = "";
			if ((float)State["since"] < 0f)
			{
				State["since"] = Time.realtimeSinceStartup;
			}
			Tick();
		}

		internal static void Tick()
		{
			float num = (float)State["since"];
			if (!(num < 0f) && (Mods.All((object[] m) => Reports.ContainsKey((string)m[0])) || !(Time.realtimeSinceStartup - num < 60f)))
			{
				State["since"] = -1f;
				PrintLoaded();
			}
		}

		private static void PrintLoaded()
		{
			List<Line> list = Head();
			bool flag = false;
			bool flag2 = true;
			foreach (object[] mod in Mods)
			{
				if (!flag2)
				{
					list.Add(new Line());
				}
				flag2 = false;
				if (!Reports.TryGetValue((string)mod[0], out var value))
				{
					flag = true;
					list.Add(Row((string)mod[1] + " " + (string)mod[2], ConsoleColor.DarkRed, "no answer", ConsoleColor.DarkRed));
					continue;
				}
				list.Add(Row((string)mod[1], ConsoleColor.Gray, "LOADED", ConsoleColor.DarkGreen));
				foreach (object[] item in (List<object[]>)value[0])
				{
					int num = (int)item[2];
					list.Add(Row((string)item[0], ConsoleColor.Gray, ((string)item[1]).TrimStart(), num switch
					{
						1 => ConsoleColor.DarkYellow, 
						0 => ConsoleColor.DarkGreen, 
						_ => ConsoleColor.DarkGray, 
					}));
				}
				flag |= (bool)value[1];
			}
			list.Add(Waves());
			if (flag)
			{
				list.Add(new Line().Add("Something is missing. Send BepInEx\\Hypnogoogic-report.txt and BepInEx\\LogOutput.log on our Discord: https://discord.gg/QygN9rEKEw", ConsoleColor.DarkRed));
			}
			list.Add(new Line());
			string text = string.Join("\n", list.Select((Line l) => l.Text));
			if (!((string)State["printed"] == text))
			{
				State["printed"] = text;
				Write(list);
			}
		}

		private static Line Waves()
		{
			return new Line().Add(string.Concat(from i in Enumerable.Range(0, 49)
				select (i % 2 != 0) ? "~" : "≈"), ConsoleColor.DarkCyan);
		}

		private static Line Row(string label, ConsoleColor colour, string value, ConsoleColor valueColour)
		{
			return new Line().Add("  » ", ConsoleColor.DarkGray).Add(label, colour).Add(" " + new string('·', Math.Max(2, 34 - label.Length)) + " ", ConsoleColor.DarkGray)
				.Add(value, valueColour);
		}

		private static List<Line> Head()
		{
			return new List<Line>
			{
				new Line(),
				Waves(),
				new Line().Add("  ▄▀▄▀   ", ConsoleColor.DarkCyan).Add("H Y P N O G O O G I C   M O D S", (ConsoleColor)(-1)).Add("   ▀▄▀▄", ConsoleColor.DarkCyan),
				Waves()
			};
		}

		private static void Write(List<Line> lines)
		{
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Expected O, but got Unknown
			if (source == null)
			{
				source = Logger.CreateLogSource("Hypnogoogic");
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Line line in lines)
			{
				stringBuilder.Append('\n').Append(line.Text.TrimEnd());
			}
			TextWriter textWriter = null;
			MethodInfo methodInfo = null;
			try
			{
				Type type = typeof(Paths).Assembly.GetType("BepInEx.ConsoleManager");
				methodInfo = type?.GetMethod("SetConsoleColor", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				object obj = type?.GetProperty("ConsoleActive", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null, null);
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				if (((uint)num & (flag ? 1u : 0u)) != 0)
				{
					textWriter = type.GetProperty("ConsoleStream", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null, null) as TextWriter;
				}
			}
			catch (Exception)
			{
				textWriter = null;
			}
			if (textWriter == null || methodInfo == null)
			{
				source.LogInfo((object)stringBuilder.ToString());
				return;
			}
			LogEventArgs e = new LogEventArgs((object)stringBuilder.ToString(), (LogLevel)16, (ILogSource)(object)source);
			ILogListener[] array = Logger.Listeners.ToArray();
			foreach (ILogListener val in array)
			{
				if (!(val is ConsoleLogListener))
				{
					try
					{
						val.LogEvent((object)source, e);
					}
					catch (Exception)
					{
					}
				}
			}
			try
			{
				bool flag2 = TrueColour();
				foreach (Line line2 in lines)
				{
					foreach (KeyValuePair<string, ConsoleColor> item in line2)
					{
						if (item.Value == (ConsoleColor)(-1) && flag2)
						{
							textWriter.Write("\u001b[38;2;169;139;176m" + item.Key + "\u001b[0m");
							textWriter.Flush();
							continue;
						}
						textWriter.Flush();
						methodInfo.Invoke(null, new object[1] { (item.Value == (ConsoleColor)(-1)) ? ConsoleColor.DarkMagenta : item.Value });
						textWriter.Write(item.Key);
					}
					textWriter.Write(Environment.NewLine);
				}
				textWriter.Flush();
			}
			catch (Exception)
			{
			}
			finally
			{
				try
				{
					methodInfo.Invoke(null, new object[1] { ConsoleColor.Gray });
				}
				catch (Exception)
				{
				}
			}
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
		private static extern IntPtr CreateFileW(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);

		[DllImport("kernel32.dll")]
		private static extern bool GetConsoleMode(IntPtr console, out uint mode);

		[DllImport("kernel32.dll")]
		private static extern bool SetConsoleMode(IntPtr console, uint mode);

		[DllImport("kernel32.dll")]
		private static extern bool CloseHandle(IntPtr handle);

		private static bool TrueColour()
		{
			try
			{
				IntPtr intPtr = CreateFileW("CONOUT$", 3221225472u, 3u, IntPtr.Zero, 3u, 0u, IntPtr.Zero);
				if (intPtr == (IntPtr)(-1))
				{
					return false;
				}
				uint mode;
				bool result = GetConsoleMode(intPtr, out mode) && ((mode & 4) != 0 || SetConsoleMode(intPtr, mode | 4));
				CloseHandle(intPtr);
				return result;
			}
			catch (Exception)
			{
				return false;
			}
		}
	}
	internal static class HubMod
	{
		internal sealed class Table
		{
			internal readonly List<object[]> Rows = new List<object[]>();

			internal readonly List<string> Missing = new List<string>();

			internal void Count(string label, int good, int total)
			{
				Rows.Add(new object[3]
				{
					label,
					good.ToString().PadLeft(3) + "/" + total,
					(good < total) ? 1 : 0
				});
				if (good < total)
				{
					Missing.Add(label + " " + good + "/" + total);
				}
			}

			internal void Note(string label, string value)
			{
				Rows.Add(new object[3] { label, value, 2 });
			}
		}

		private sealed class Driver : MonoBehaviour
		{
			private ZNetScene scene;

			private float due = -1f;

			private string last = "";

			private void Start()
			{
				HubConsole.PrintStart();
			}

			private void Update()
			{
				HubConsole.Tick();
				ZNetScene instance = ZNetScene.instance;
				if ((Object)(object)instance != (Object)(object)scene)
				{
					scene = instance;
					due = (((Object)(object)instance != (Object)null) ? (Time.realtimeSinceStartup + 25f) : (-1f));
				}
				if (!(due < 0f) && !((Object)(object)instance == (Object)null) && !(Time.realtimeSinceStartup < due) && (!TraderAwaited() || !(Time.realtimeSinceStartup < due + 600f)))
				{
					due = -1f;
					Count();
				}
			}

			private void Count()
			{
				Table table = new Table();
				try
				{
					fill(table);
				}
				catch (Exception ex)
				{
					table.Rows.Add(new object[3] { "Count", "check failed", 1 });
					table.Missing.Add("the count itself failed");
					log.LogWarning((object)(((Object)this).name + ": counting what is loaded failed: " + ex));
				}
				string text = string.Join("\n", table.Rows.Select((object[] r) => (string)r[0] + "|" + (string)r[1]));
				if (!(text == last))
				{
					last = text;
					bool flag = table.Missing.Count > 0;
					if (flag)
					{
						log.LogWarning((object)(((Object)this).name + ": missing or not loaded: " + string.Join(", ", table.Missing)));
						WriteReport();
					}
					HubConsole.Report(id, table.Rows, flag);
				}
			}

			private static void WriteReport()
			{
				try
				{
					string path = Path.Combine(Paths.BepInExRootPath, "Hypnogoogic-report.txt");
					if (!File.Exists(path) || !((DateTime.UtcNow - File.GetLastWriteTimeUtc(path)).TotalMinutes < 2.0))
					{
						ModReport.WriteCommon();
					}
				}
				catch (Exception ex)
				{
					log.LogWarning((object)("Hypnogoogic-report.txt could not be written: " + ex.Message));
				}
			}

			private static bool TraderAwaited()
			{
				if (!(AppDomain.CurrentDomain.GetData("HypnoCode.Hub.Console.v1") is Dictionary<string, object> dictionary))
				{
					return false;
				}
				List<object[]> source = (List<object[]>)dictionary["mods"];
				Dictionary<string, object[]> dictionary2 = (Dictionary<string, object[]>)dictionary["reports"];
				if (source.Any((object[] m) => (string)m[0] == "p0kahontazz.immersivetrader"))
				{
					return !dictionary2.ContainsKey("p0kahontazz.immersivetrader");
				}
				return false;
			}
		}

		private const string ConsoleState = "HypnoCode.Hub.Console.v1";

		private const string Trader = "p0kahontazz.immersivetrader";

		private const float After = 25f;

		private const float ForTrader = 600f;

		private static string id;

		private static string name;

		private static ManualLogSource log;

		private static Action<Table> fill;

		internal static void Register(BaseUnityPlugin plugin, string modName, ManualLogSource source, Action<Table> count)
		{
			id = plugin.Info.Metadata.GUID;
			name = modName;
			log = source;
			fill = count;
			HubConsole.Register(id, name, plugin.Info.Metadata.Version.ToString());
			((Component)plugin).gameObject.AddComponent<Driver>();
		}
	}
}
namespace AdvancedBackpacks
{
	internal static class Assets
	{
		internal static GameObject Storage;

		internal static readonly List<GameObject> ItemPrefabs = new List<GameObject>();

		internal static readonly List<Object> Owned = new List<Object>();

		internal static void CreateStorage(ZNetScene scene)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			Release();
			Storage = new GameObject("Advanced Backpacks storage");
			Storage.SetActive(false);
			Storage.transform.SetParent(((Component)scene).transform, false);
		}

		internal static void Release()
		{
			if (ItemPrefabs.Count > 0 && (Object)(object)ObjectDB.instance != (Object)null && ObjectDB.instance.m_items != null)
			{
				ObjectDB.instance.m_items.RemoveAll((GameObject i) => (Object)(object)i == (Object)null || ItemPrefabs.Contains(i));
			}
			ItemPrefabs.Clear();
			foreach (Object item in Owned)
			{
				if (item != (Object)null)
				{
					Object.Destroy(item);
				}
			}
			Owned.Clear();
			if ((Object)(object)Storage != (Object)null)
			{
				Object.Destroy((Object)(object)Storage);
			}
			Storage = null;
		}

		internal static void RegisterScene(ZNetScene scene, GameObject prefab)
		{
			Prefabs.RegisterScene(scene, prefab);
		}

		internal static GameObject Need(ZNetScene scene, string name)
		{
			return scene.GetPrefab(name) ?? throw new InvalidOperationException("Prefab missing: " + name);
		}

		internal static void RegisterItems(ObjectDB db)
		{
			if ((Object)(object)db == (Object)null || db.m_items == null || ItemPrefabs.Count == 0)
			{
				return;
			}
			bool flag = false;
			foreach (GameObject itemPrefab in ItemPrefabs)
			{
				if ((Object)(object)itemPrefab != (Object)null && !db.m_items.Contains(itemPrefab))
				{
					db.m_items.Add(itemPrefab);
					flag = true;
				}
			}
			if (!flag)
			{
				return;
			}
			try
			{
				AccessTools.Method(typeof(ObjectDB), "UpdateRegisters", (Type[])null, (Type[])null).Invoke(db, null);
			}
			catch (Exception ex)
			{
				AdvancedBackpacksPlugin.Log.LogError((object)("ObjectDB.UpdateRegisters failed: " + ex));
			}
		}

		internal static Stream Resource(string name)
		{
			return Assembly.GetExecutingAssembly().GetManifestResourceStream("advancedbackpacks." + name) ?? throw new FileNotFoundException("Embedded resource missing: " + name);
		}

		private static byte[] Bytes(string resource)
		{
			using Stream stream = Resource(resource);
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			return memoryStream.ToArray();
		}

		internal static Texture2D LoadTexture(string resource)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
			if (!ImageConversion.LoadImage(val, Bytes(resource)))
			{
				throw new InvalidDataException(resource);
			}
			((Object)val).name = "AB " + resource;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			Owned.Add((Object)(object)val);
			return val;
		}

		internal static Sprite LoadIcon(string resource)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			//IL_0054: 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)
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if (!ImageConversion.LoadImage(val, Bytes(resource)))
			{
				throw new InvalidDataException(resource);
			}
			((Object)val).name = "AB " + resource;
			Owned.Add((Object)(object)val);
			Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
			Owned.Add((Object)(object)val2);
			return val2;
		}

		internal static void ReadMeshes(string resource, out Mesh visual, out Mesh collision)
		{
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_0148: 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_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			BinaryReader reader = new BinaryReader(Resource(resource));
			try
			{
				if (Encoding.ASCII.GetString(reader.ReadBytes(8)) != "COAHS100")
				{
					throw new InvalidDataException(resource + ": bad header");
				}
				int num = reader.ReadInt32();
				int arg = reader.ReadInt32();
				int arg2 = reader.ReadInt32();
				int arg3 = reader.ReadInt32();
				Func<int, Vector3[]> func = delegate(int count)
				{
					//IL_002e: Unknown result type (might be due to invalid IL or missing references)
					//IL_0033: Unknown result type (might be due to invalid IL or missing references)
					Vector3[] array2 = (Vector3[])(object)new Vector3[count];
					for (int i = 0; i < count; i++)
					{
						array2[i] = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
					}
					return array2;
				};
				Func<int, int[]> func2 = delegate(int count)
				{
					int[] array2 = new int[count];
					for (int i = 0; i < count; i++)
					{
						array2[i] = reader.ReadInt32();
					}
					return array2;
				};
				Vector3[] vertices = func(num);
				Vector3[] normals = func(num);
				Vector2[] array = (Vector2[])(object)new Vector2[num];
				for (int num2 = 0; num2 < num; num2++)
				{
					array[num2] = new Vector2(reader.ReadSingle(), reader.ReadSingle());
				}
				visual = new Mesh
				{
					name = "AB " + resource
				};
				if (num > 65000)
				{
					visual.indexFormat = (IndexFormat)1;
				}
				visual.vertices = vertices;
				visual.normals = normals;
				visual.uv = array;
				visual.triangles = func2(arg);
				visual.RecalculateBounds();
				visual.RecalculateTangents();
				collision = new Mesh
				{
					name = "AB " + resource + " collider",
					vertices = func(arg2),
					triangles = func2(arg3)
				};
				collision.RecalculateBounds();
				collision.RecalculateNormals();
				Owned.Add((Object)(object)visual);
				Owned.Add((Object)(object)collision);
			}
			finally
			{
				if (reader != null)
				{
					((IDisposable)reader).Dispose();
				}
			}
		}

		private static void SetTexture(Material m, string name, Texture t)
		{
			if (m.HasProperty(name))
			{
				m.SetTexture(name, t);
			}
		}