Decompiled source of AchievementTracker v1.1.0

plugins/AchievementTracker/AchievementTracker.dll

Decompiled 13 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("AchievementTracker")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+37e337d4ba8dd582848592f9d906c8b5d55aec38")]
[assembly: AssemblyProduct("AchievementTracker")]
[assembly: AssemblyTitle("AchievementTracker")]
[assembly: InternalsVisibleTo("AchievementTracker.Tests")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	internal static class IsExternalInit
	{
	}
}
namespace AchievementTracker
{
	[BepInPlugin("speenah.achievementtracker", "Achievement Tracker", "1.1.0")]
	public class HostPlugin : BaseUnityPlugin
	{
		private sealed class Loaded
		{
			public Action Tick;

			public Func<string, string, string> Handle;

			public Action Dispose;

			public string Name;
		}

		public const string Guid = "speenah.achievementtracker";

		private ConfigEntry<int> _port;

		private ConfigEntry<float> _tick;

		private volatile Loaded _module;

		private volatile string _lastError = "";

		private string _lastTickError;

		private float _nextTick;

		private readonly List<TcpListener> _listeners = new List<TcpListener>();

		private volatile bool _stopping;

		private int _activeClients;

		private const int MaxClients = 32;

		private string _pluginDir;

		private string WebRoot => Path.Combine(_pluginDir, "web");

		private void Awake()
		{
			_pluginDir = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location) ?? Path.Combine(Paths.PluginPath, "AchievementTracker");
			_port = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "Port", 8787, "Port for the tracker page: http://localhost:<port>/");
			_tick = ((BaseUnityPlugin)this).Config.Bind<float>("Server", "RefreshSeconds", 1f, "How often the game data snapshot is rebuilt.");
			TrackerModule trackerModule = new TrackerModule(((BaseUnityPlugin)this).Logger, _pluginDir);
			_module = new Loaded
			{
				Tick = trackerModule.Tick,
				Handle = trackerModule.Handle,
				Dispose = trackerModule.Dispose,
				Name = "built-in"
			};
			StartServer();
		}

		private void Update()
		{
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < _nextTick)
			{
				return;
			}
			_nextTick = unscaledTime + Mathf.Max(0.2f, _tick.Value);
			Loaded module = _module;
			if (module == null)
			{
				return;
			}
			try
			{
				module.Tick();
				_lastTickError = null;
			}
			catch (Exception ex)
			{
				string text = (ex.InnerException ?? ex).ToString();
				if (text != _lastTickError)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Module tick failed: " + text));
				}
				_lastTickError = text;
				_lastError = text;
			}
		}

		private void StartServer()
		{
			int value = _port.Value;
			IPAddress[] array = new IPAddress[2]
			{
				IPAddress.Loopback,
				IPAddress.IPv6Loopback
			};
			foreach (IPAddress iPAddress in array)
			{
				try
				{
					TcpListener l = new TcpListener(iPAddress, value);
					if (iPAddress.AddressFamily == AddressFamily.InterNetworkV6)
					{
						l.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, optionValue: true);
					}
					l.Start();
					_listeners.Add(l);
					Thread thread = new Thread((ThreadStart)delegate
					{
						Accept(l);
					});
					thread.IsBackground = true;
					thread.Name = "AchievementTracker HTTP " + iPAddress;
					thread.Start();
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)$"Could not listen on {iPAddress}:{value}: {ex.Message}");
				}
			}
			if (_listeners.Count > 0)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Achievement tracker page: http://localhost:{value}/");
			}
			else
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not start web server on port " + value));
			}
		}

		private void Accept(TcpListener l)
		{
			bool flag = false;
			while (!_stopping)
			{
				TcpClient c;
				try
				{
					c = l.AcceptTcpClient();
				}
				catch (Exception ex)
				{
					if (_stopping)
					{
						break;
					}
					if (!flag)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("HTTP accept: " + ex.Message));
					}
					flag = true;
					Thread.Sleep(500);
					continue;
				}
				if (Interlocked.Increment(ref _activeClients) > 32)
				{
					Interlocked.Decrement(ref _activeClients);
					c.Close();
					continue;
				}
				ThreadPool.QueueUserWorkItem(delegate
				{
					try
					{
						ServeClient(c);
					}
					finally
					{
						Interlocked.Decrement(ref _activeClients);
					}
				});
			}
		}

		private void ServeClient(TcpClient client)
		{
			using (client)
			{
				try
				{
					client.ReceiveTimeout = 5000;
					client.SendTimeout = 5000;
					NetworkStream stream = client.GetStream();
					string text = ReadHead(stream);
					if (text == null)
					{
						return;
					}
					if (!Http.Target(text, out var path, out var query))
					{
						Write(stream, 400, "text/plain", Encoding.UTF8.GetBytes("Bad request"));
						return;
					}
					if (!Http.IsAllowedRequest(text))
					{
						Write(stream, 403, "text/plain", Encoding.UTF8.GetBytes("Forbidden"));
						return;
					}
					int code;
					string type;
					byte[] body;
					try
					{
						Respond(path, query, out code, out type, out body);
					}
					catch (Exception ex)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("HTTP " + path + ": " + ex.Message));
						code = 500;
						type = "text/plain";
						body = Encoding.UTF8.GetBytes("Internal error");
					}
					Write(stream, code, type, body);
				}
				catch (IOException)
				{
				}
				catch (SocketException)
				{
				}
				catch (ObjectDisposedException)
				{
				}
				catch (Exception ex5)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("HTTP client: " + ex5.Message));
				}
			}
		}

		private static string ReadHead(NetworkStream s)
		{
			byte[] array = new byte[8192];
			int num = 0;
			DateTime dateTime = DateTime.UtcNow.AddSeconds(10.0);
			while (num < array.Length)
			{
				int num2 = s.Read(array, num, array.Length - num);
				if (num2 <= 0 || DateTime.UtcNow > dateTime)
				{
					return null;
				}
				num += num2;
				for (int i = Math.Max(0, num - num2 - 3); i + 3 < num; i++)
				{
					if (array[i] == 13 && array[i + 1] == 10 && array[i + 2] == 13 && array[i + 3] == 10)
					{
						return Encoding.ASCII.GetString(array, 0, i + 2);
					}
				}
			}
			return null;
		}

		private static void Write(NetworkStream s, int code, string type, byte[] body)
		{
			string text = code switch
			{
				200 => "OK", 
				400 => "Bad Request", 
				403 => "Forbidden", 
				404 => "Not Found", 
				503 => "Service Unavailable", 
				_ => "Error", 
			};
			if (!type.Contains("charset") && (type.StartsWith("text") || type == "application/json"))
			{
				type += "; charset=utf-8";
			}
			byte[] bytes = Encoding.ASCII.GetBytes($"HTTP/1.1 {code} {text}\r\nContent-Type: {type}\r\nContent-Length: {body.Length}\r\n" + "Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\r\n");
			s.Write(bytes, 0, bytes.Length);
			s.Write(body, 0, body.Length);
			s.Flush();
		}

		private void Respond(string path, string query, out int code, out string type, out byte[] body)
		{
			code = 200;
			type = "application/json";
			body = null;
			string text = null;
			if (path == "/api/host")
			{
				Loaded module = _module;
				text = "{\"module\":" + ((module != null) ? "true" : "false") + ",\"name\":" + Http.JsonString(module?.Name ?? "") + ",\"error\":" + Http.JsonString(_lastError) + "}";
			}
			else if (path.StartsWith("/api/"))
			{
				Loaded module2 = _module;
				text = module2?.Handle(path, query);
				if (text == null)
				{
					code = ((module2 == null) ? 503 : 404);
					text = "{\"error\":" + Http.JsonString((module2 == null) ? ("module not loaded: " + _lastError) : "unknown endpoint") + "}";
				}
			}
			else
			{
				string text2 = Http.StaticFile(WebRoot, path);
				if (text2 == null || !File.Exists(text2))
				{
					code = 404;
					type = "text/plain";
					text = "Not found";
				}
				else
				{
					type = Http.ContentType(text2);
					body = File.ReadAllBytes(text2);
				}
			}
			if (body == null)
			{
				body = Encoding.UTF8.GetBytes(text);
			}
		}

		private void OnDestroy()
		{
			_stopping = true;
			foreach (TcpListener listener in _listeners)
			{
				try
				{
					listener.Stop();
				}
				catch (Exception ex)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Stop listener: " + ex.Message));
				}
			}
			_listeners.Clear();
			try
			{
				_module?.Dispose();
			}
			catch (Exception ex2)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Module dispose: " + ex2.Message));
			}
		}
	}
	internal static class Http
	{
		public static bool Target(string head, out string path, out string query)
		{
			path = (query = null);
			int num = head.IndexOf('\r');
			string[] array = ((num < 0) ? head : head.Substring(0, num)).Split(new char[1] { ' ' });
			if (array.Length < 2)
			{
				return false;
			}
			string text = array[1];
			if (text.StartsWith("http://", StringComparison.Ordinal) || text.StartsWith("https://", StringComparison.Ordinal))
			{
				int num2 = text.IndexOf('/', text.IndexOf("//", StringComparison.Ordinal) + 2);
				text = ((num2 < 0) ? "/" : text.Substring(num2));
			}
			int num3 = text.IndexOf('?');
			path = ((num3 < 0) ? text : text.Substring(0, num3));
			query = ((num3 < 0) ? "" : text.Substring(num3));
			return true;
		}

		public static bool IsAllowedRequest(string head)
		{
			if (IsAllowedHost(Header(head, "Host")))
			{
				string text = Header(head, "Sec-Fetch-Site");
				if (text == "cross-site" || text == "same-site")
				{
					return IsPageNavigation(head);
				}
				return true;
			}
			return false;
		}

		private static bool IsPageNavigation(string head)
		{
			if (head.StartsWith("GET ", StringComparison.Ordinal) && Header(head, "Sec-Fetch-Mode") == "navigate" && Header(head, "Sec-Fetch-Dest") == "document" && Target(head, out var path, out var _))
			{
				return !path.StartsWith("/api/", StringComparison.Ordinal);
			}
			return false;
		}

		public static string StaticFile(string root, string urlPath)
		{
			string text = ((urlPath == "/") ? "index.html" : Uri.UnescapeDataString(urlPath.TrimStart(new char[1] { '/' })));
			if (text.Length == 0 || text.IndexOf(':') >= 0 || text.IndexOf('\0') >= 0)
			{
				return null;
			}
			try
			{
				string text2 = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
				char directorySeparatorChar = Path.DirectorySeparatorChar;
				string text3 = text2 + directorySeparatorChar;
				string fullPath = Path.GetFullPath(Path.Combine(text3, text));
				return fullPath.StartsWith(text3, StringComparison.OrdinalIgnoreCase) ? fullPath : null;
			}
			catch (ArgumentException)
			{
				return null;
			}
			catch (NotSupportedException)
			{
				return null;
			}
			catch (PathTooLongException)
			{
				return null;
			}
		}

		public static string Header(string head, string name)
		{
			string[] array = head.Split(new string[1] { "\r\n" }, StringSplitOptions.None);
			foreach (string text in array)
			{
				int num = text.IndexOf(':');
				if (num == name.Length && string.Compare(text, 0, name, 0, num, StringComparison.OrdinalIgnoreCase) == 0)
				{
					return text.Substring(num + 1).Trim();
				}
			}
			return null;
		}

		public static bool IsAllowedHost(string host)
		{
			if (string.IsNullOrEmpty(host))
			{
				return true;
			}
			string text;
			if (host[0] == '[')
			{
				int num = host.IndexOf(']');
				if (num < 0)
				{
					return false;
				}
				text = host.Substring(1, num - 1);
			}
			else
			{
				int num2 = host.LastIndexOf(':');
				text = ((num2 < 0) ? host : host.Substring(0, num2));
			}
			text = text.TrimEnd(new char[1] { '.' });
			if (IPAddress.TryParse(text, out IPAddress _))
			{
				return true;
			}
			if (!text.Equals("localhost", StringComparison.OrdinalIgnoreCase))
			{
				return text.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		public static string ContentType(string file)
		{
			return Path.GetExtension(file).ToLowerInvariant() switch
			{
				".html" => "text/html; charset=utf-8", 
				".js" => "text/javascript; charset=utf-8", 
				".css" => "text/css; charset=utf-8", 
				".json" => "application/json", 
				".png" => "image/png", 
				".svg" => "image/svg+xml", 
				_ => "application/octet-stream", 
			};
		}

		public static string JsonString(string s)
		{
			if (s == null)
			{
				return "null";
			}
			StringBuilder stringBuilder = new StringBuilder("\"");
			foreach (char c in s)
			{
				if (c == '"' || c == '\\')
				{
					stringBuilder.Append('\\').Append(c);
				}
				else if (c < ' ')
				{
					StringBuilder stringBuilder2 = stringBuilder.Append("\\u");
					int num = c;
					stringBuilder2.Append(num.ToString("x4"));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.Append('"').ToString();
		}
	}
	public class TrackerModule
	{
		private sealed class ModScan : IWalkVisitor
		{
			public readonly Dictionary<int, string> Strong = new Dictionary<int, string>();

			public readonly Dictionary<int, string> Weak = new Dictionary<int, string>();

			public readonly List<KeyValuePair<AssetBundle, string>> Bundles = new List<KeyValuePair<AssetBundle, string>>();

			public readonly HashSet<Assembly> PluginAsms = new HashSet<Assembly>();

			public readonly ObjectWalk Walk;

			public ModScan()
			{
				Walk = new ObjectWalk(this, PluginAsms);
			}

			public bool Enter(object v, string plugin, string source)
			{
				Object val = (Object)((v is Object) ? v : null);
				if (val == null)
				{
					return true;
				}
				if (!Object.op_Implicit(val))
				{
					return false;
				}
				GameObject val2 = (GameObject)((v is GameObject) ? v : null);
				if (val2 != null)
				{
					Claim(val2, plugin, source);
					return false;
				}
				AssetBundle val3 = (AssetBundle)((v is AssetBundle) ? v : null);
				if (val3 != null)
				{
					if (Walk.FirstVisit(v))
					{
						Bundles.Add(new KeyValuePair<AssetBundle, string>(val3, source ?? plugin));
					}
					return false;
				}
				Component val4 = (Component)((v is Component) ? v : null);
				if (val4 != null)
				{
					Claim(val4.gameObject, plugin, source);
				}
				return Walk.IsModType(v.GetType());
			}

			private void Claim(GameObject go, string plugin, string source)
			{
				int instanceID = ((Object)go).GetInstanceID();
				if (source != null)
				{
					if (!Strong.ContainsKey(instanceID))
					{
						Strong[instanceID] = source;
					}
				}
				else if (!Weak.ContainsKey(instanceID))
				{
					Weak[instanceID] = plugin;
				}
			}

			public string SourceOf(object o)
			{
				try
				{
					object? obj = o.GetType().GetProperty("SourceMod", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(o, null);
					object? obj2 = ((obj is BepInPlugin) ? obj : null);
					return (obj2 != null) ? ((BepInPlugin)obj2).Name : null;
				}
				catch
				{
					return null;
				}
			}
		}

		private sealed class Req
		{
			public string Kind;

			public string Key;

			public float Need;

			public RequirementOperator Op;

			public int Mod;

			public Achievement Other;

			public PlayerStatType Stat;
		}

		private sealed class AchRef
		{
			public Achievement A;

			public readonly List<Req> Reqs = new List<Req>();
		}

		private const float AvailEvery = 2f;

		private float _nextAvail;

		private AvailabilityInfo _avail;

		private double _availMs;

		private const int VerifyPerCycle = 4;

		private int _verifyCursor;

		private int _verified;

		private int _mismatches;

		private string _lastMismatch;

		private Dictionary<string, List<Container>> _chestsByTok = new Dictionary<string, List<Container>>();

		private static readonly MethodInfo HaveRequirementItems = typeof(Player).GetMethod("HaveRequirementItems", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[4]
		{
			typeof(Recipe),
			typeof(bool),
			typeof(int),
			typeof(int)
		}, null);

		private static FieldInfo _vpChestsField;

		private static bool _vpLooked;

		private KnownRecipes _known;

		private static readonly FieldInfo KnownStationsField = typeof(Player).GetField("m_knownStations", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		private Dictionary<string, Piece> _pieceByTok;

		private List<KeyValuePair<FieldInfo, string>> _staticFields;

		private readonly ManualLogSource _log;

		private volatile string _catalogJson = "{\"v\":0}";

		private volatile string _stateJson = "{\"ok\":false,\"reason\":\"Starting up\"}";

		private volatile bool _rebuild;

		private int _catalogVersion = (Environment.TickCount & 0x3FFFFFF) * 16;

		private Player _catalogPlayer;

		private int _catalogShape = -1;

		private readonly Stopwatch _sw = new Stopwatch();

		private double _lastTickMs;

		private double _maxTickMs;

		private double _catalogMs;

		private int _ticks;

		private long _lastRequestTicks = DateTime.UtcNow.Ticks;

		private static readonly long IdleAfter = TimeSpan.FromSeconds(5.0).Ticks;

		private readonly List<AchRef> _achs = new List<AchRef>();

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

		private readonly Dictionary<string, ItemDrop> _itemByToken = new Dictionary<string, ItemDrop>();

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

		private static readonly Dictionary<PlayerStatType, PlayerStatType> RunningStat = new Dictionary<PlayerStatType, PlayerStatType> { [(PlayerStatType)129] = (PlayerStatType)128 };

		private List<Component> _stationCache = new List<Component>();

		private float _nextStationScan;

		private HashSet<int> _stationPrefabs;

		private static readonly FieldInfo InstancesField = typeof(ZNetScene).GetField("m_instances", BindingFlags.Instance | BindingFlags.NonPublic);

		private string _ownerLookupError;

		private static IList VpChests()
		{
			if (!_vpLooked)
			{
				_vpLooked = true;
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				for (int i = 0; i < assemblies.Length; i++)
				{
					Type type = assemblies[i].GetType("ValheimPlus.GameClasses.Inventory_NearbyChests_Cache", throwOnError: false);
					if (type != null)
					{
						_vpChestsField = type.GetField("chests", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						break;
					}
				}
			}
			return _vpChestsField?.GetValue(null) as IList;
		}

		private static void PrimeVpChests(Player player, CraftingStation station)
		{
			VpChests();
			if (HaveRequirementItems == null || _vpChestsField == null)
			{
				return;
			}
			bool flag = (Object)(object)station != (Object)null && station.m_upgrader;
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				Requirement[] array = recipe?.m_resources;
				Requirement val = ((array != null && array.Length > 0) ? recipe.m_resources[0] : null);
				if (!((Object)(object)val?.m_resItem == (Object)null) && val.m_upgraderResource == flag)
				{
					try
					{
						HaveRequirementItems.Invoke(player, new object[4] { recipe, false, 1, 1 });
						break;
					}
					catch (TargetInvocationException)
					{
						break;
					}
				}
			}
		}

		private void UpdateAvailability(Player player, PlayerProfile prof)
		{
			//IL_0677: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected I4, but got Unknown
			if (Time.unscaledTime < _nextAvail)
			{
				return;
			}
			_nextAvail = Time.unscaledTime + 2f;
			CraftingStation currentCraftingStation = player.GetCurrentCraftingStation();
			ItemData val = null;
			foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems())
			{
				if (allItem != null && allItem.m_equipped && (Object)(object)allItem.m_shared?.m_buildPieces != (Object)null)
				{
					val = allItem;
					break;
				}
			}
			bool flag = val != null;
			Stopwatch stopwatch = Stopwatch.StartNew();
			HashSet<string> hashSet = new HashSet<string>();
			HashSet<string> hashSet2 = new HashSet<string>();
			foreach (AchRef ach in _achs)
			{
				if (ach.A.m_unlocked)
				{
					continue;
				}
				int num = (int)ach.A.m_difficultyRequirement;
				PlayerStats ps = ((num >= 0 && num < prof.m_playerStats.Length) ? prof.m_playerStats[num] : prof.m_playerStats[1]);
				foreach (Req req in ach.Reqs)
				{
					if ((req.Kind != "craft" && req.Kind != "food" && req.Kind != "piece") || Value(ps, req) >= req.Need)
					{
						continue;
					}
					if (req.Kind == "piece")
					{
						hashSet2.Add(req.Key);
						continue;
					}
					string text = ItemTokenFor(req);
					if (text != null)
					{
						hashSet.Add(text);
					}
				}
			}
			UpdateKnown(player, hashSet, hashSet2);
			if ((Object)(object)currentCraftingStation == (Object)null && !flag)
			{
				return;
			}
			MaterialCounts counts = new MaterialCounts(Game.m_worldLevel);
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			Dictionary<string, List<Container>> dictionary2 = new Dictionary<string, List<Container>>();
			foreach (ItemData allItem2 in ((Humanoid)player).GetInventory().GetAllItems())
			{
				if (allItem2 != null && allItem2.m_shared?.m_name != null)
				{
					Count(allItem2);
				}
			}
			PrimeVpChests(player, currentCraftingStation);
			IList list = VpChests();
			if (list != null)
			{
				foreach (object item in list)
				{
					Container val2 = (Container)((item is Container) ? item : null);
					if ((Object)(object)val2 == (Object)null || !Object.op_Implicit((Object)(object)val2))
					{
						continue;
					}
					Inventory inventory = val2.GetInventory();
					if (inventory == null)
					{
						continue;
					}
					foreach (ItemData allItem3 in inventory.GetAllItems())
					{
						string text2 = allItem3?.m_shared?.m_name;
						if (text2 != null)
						{
							dictionary.TryGetValue(text2, out var value);
							dictionary[text2] = value + allItem3.m_stack;
							Count(allItem3);
							if (!dictionary2.TryGetValue(text2, out var value2))
							{
								value2 = (dictionary2[text2] = new List<Container>());
							}
							if (value2.Count == 0 || (Object)(object)value2[value2.Count - 1] != (Object)(object)val2)
							{
								value2.Add(val2);
							}
						}
					}
				}
			}
			_chestsByTok = dictionary2;
			List<KeyValuePair<Recipe, bool>> list3 = new List<KeyValuePair<Recipe, bool>>();
			Dictionary<string, object[]> dictionary3 = new Dictionary<string, object[]>();
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				string text3 = recipe?.m_item?.m_itemData?.m_shared?.m_name;
				if (text3 != null && recipe.m_enabled && !recipe.m_noCraftOnlyUpgrade && hashSet.Contains(text3))
				{
					bool flag2 = MatsOk(recipe, recipe.m_craftingStation);
					bool flag3 = Materials.StationOk(((Object)(object)recipe.m_craftingStation != (Object)null) ? recipe.m_craftingStation.m_name : null, recipe.m_minStationLevel, ((Object)(object)currentCraftingStation != (Object)null) ? currentCraftingStation.m_name : null, ((Object)(object)currentCraftingStation != (Object)null) ? currentCraftingStation.GetLevel(true) : 0);
					bool flag4 = player.IsRecipeKnown(text3);
					dictionary3[text3] = Rows.AvailItem(flag4 && flag2 && flag3, flag2, flag4, UndiscoveredMaterials(player, recipe, flag4), KnownStationLevel(player, recipe));
					list3.Add(new KeyValuePair<Recipe, bool>(recipe, flag2));
				}
			}
			if (HaveRequirementItems != null && list3.Count > 0)
			{
				for (int i = 0; i < 4; i++)
				{
					KeyValuePair<Recipe, bool> keyValuePair = list3[_verifyCursor++ % list3.Count];
					bool flag5;
					try
					{
						flag5 = (bool)HaveRequirementItems.Invoke(player, new object[4] { keyValuePair.Key, false, 1, 1 });
					}
					catch
					{
						continue;
					}
					_verified++;
					bool flag6 = MatsOk(keyValuePair.Key, currentCraftingStation);
					if (flag5 != flag6)
					{
						_mismatches++;
						_lastMismatch = Loc(keyValuePair.Key.m_item.m_itemData.m_shared.m_name) + " (game says " + (flag5 ? "yes" : "no") + ")";
					}
				}
			}
			Dictionary<string, object[]> dictionary4 = new Dictionary<string, object[]>();
			foreach (string item2 in hashSet2)
			{
				Piece val3 = FindPiece(item2);
				if (!((Object)(object)val3 == (Object)null))
				{
					bool flag7 = (Object)(object)val3.m_craftingStation == (Object)null || Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(val3.m_craftingStation.m_name, ((Component)player).transform.position));
					bool flag8 = counts.CanBuild(MatsOf(val3.m_resources));
					bool flag9 = player.IsRecipeKnown(val3.m_name);
					dictionary4[item2] = Rows.AvailPiece(flag9 && flag8 && flag7, flag7, flag8, flag9, UndiscoveredMaterials(player, val3, flag9));
				}
			}
			_avail = new AvailabilityInfo(DateTime.Now.ToString("HH:mm:ss", CultureInfo.InvariantCulture), ((Object)(object)currentCraftingStation != (Object)null) ? Loc(currentCraftingStation.m_name) : null, ((Object)(object)currentCraftingStation != (Object)null) ? currentCraftingStation.m_name : null, ((Object)(object)currentCraftingStation != (Object)null) ? currentCraftingStation.GetLevel(true) : 0, flag ? Loc(val.m_shared.m_name) : null, dictionary3, dictionary4, list?.Count ?? (-1), dictionary, new VerifyInfo(_verified, _mismatches, _lastMismatch), (float)stopwatch.Elapsed.TotalMilliseconds);
			_availMs = stopwatch.Elapsed.TotalMilliseconds;
			void Count(ItemData it)
			{
				counts.Add(it.m_shared.m_name, it.m_quality, it.m_stack, it.m_worldLevel);
			}
			bool MatsOk(Recipe r, CraftingStation st)
			{
				return counts.CanCraft(MatsOf(r.m_resources), r.m_requireOnlyOneIngredient, Upgrader(st));
			}
		}

		private static List<Mat> MatsOf(Requirement[] res)
		{
			List<Mat> list = new List<Mat>();
			if (res != null)
			{
				foreach (Requirement val in res)
				{
					if (!((Object)(object)val?.m_resItem == (Object)null))
					{
						SharedData shared = val.m_resItem.m_itemData.m_shared;
						list.Add(new Mat(shared.m_name, val.m_amount, val.m_upgraderResource, shared.m_maxQuality));
					}
				}
			}
			return list;
		}

		private static bool? Upgrader(CraftingStation st)
		{
			if (!((Object)(object)st != (Object)null))
			{
				return null;
			}
			return st.m_upgrader;
		}

		private void UpdateKnown(Player player, HashSet<string> itemToks, HashSet<string> pieceToks)
		{
			Dictionary<string, object[]> dictionary = new Dictionary<string, object[]>();
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				string text = recipe?.m_item?.m_itemData?.m_shared?.m_name;
				if (text != null && recipe.m_enabled && !recipe.m_noCraftOnlyUpgrade && itemToks.Contains(text) && !dictionary.ContainsKey(text))
				{
					bool known = player.IsRecipeKnown(text);
					dictionary[text] = Rows.KnownItem(known, UndiscoveredMaterials(player, recipe, known), KnownStationLevel(player, recipe));
				}
			}
			Dictionary<string, object[]> dictionary2 = new Dictionary<string, object[]>();
			foreach (string pieceTok in pieceToks)
			{
				Piece val = FindPiece(pieceTok);
				if (!((Object)(object)val == (Object)null))
				{
					bool known2 = player.IsRecipeKnown(val.m_name);
					dictionary2[pieceTok] = Rows.KnownPiece(known2, UndiscoveredMaterials(player, val, known2));
				}
			}
			_known = new KnownRecipes(dictionary, dictionary2);
		}

		private static List<string> UndiscoveredMaterials(Player player, Recipe r, bool known)
		{
			List<string> list = new List<string>();
			if (!known)
			{
				foreach (Mat item in MatsOf(r.m_resources))
				{
					if (Materials.Needed(item, Upgrader(r.m_craftingStation)) && !player.IsKnownMaterial(item.Token))
					{
						list.Add(item.Token);
					}
				}
			}
			return list;
		}

		private static List<string> UndiscoveredMaterials(Player player, Piece p, bool known)
		{
			List<string> list = new List<string>();
			if (!known)
			{
				foreach (Mat item in MatsOf(p.m_resources))
				{
					if (item.Amount > 0 && !player.IsKnownMaterial(item.Token))
					{
						list.Add(item.Token);
					}
				}
			}
			return list;
		}

		private static int KnownStationLevel(Player player, Recipe r)
		{
			if (!((Object)(object)r.m_craftingStation != (Object)null))
			{
				return 99;
			}
			return KnownStationLevel(player, r.m_craftingStation.m_name);
		}

		private static int KnownStationLevel(Player player, string station)
		{
			if (!(KnownStationsField?.GetValue(player) is IDictionary<string, int> dictionary) || !dictionary.TryGetValue(station, out var value))
			{
				return 0;
			}
			return value;
		}

		private Piece FindPiece(string tok)
		{
			if (_pieceByTok == null)
			{
				_pieceByTok = new Dictionary<string, Piece>();
				foreach (ItemDrop value2 in _itemByToken.Values)
				{
					PieceTable buildPieces = value2.m_itemData.m_shared.m_buildPieces;
					if ((Object)(object)buildPieces == (Object)null)
					{
						continue;
					}
					foreach (GameObject piece in buildPieces.m_pieces)
					{
						Piece val = (Object.op_Implicit((Object)(object)piece) ? piece.GetComponent<Piece>() : null);
						if ((Object)(object)val != (Object)null && !string.IsNullOrEmpty(val.m_name) && !_pieceByTok.ContainsKey(val.m_name))
						{
							_pieceByTok[val.m_name] = val;
						}
					}
				}
			}
			if (!_pieceByTok.TryGetValue(tok, out var value))
			{
				return null;
			}
			return value;
		}

		private ModScan ScanMods()
		{
			ModScan modScan = new ModScan();
			List<KeyValuePair<Assembly, string>> list = new List<KeyValuePair<Assembly, string>>();
			Assembly assembly = typeof(TrackerModule).Assembly;
			foreach (PluginInfo value2 in Chainloader.PluginInfos.Values)
			{
				Assembly assembly2 = (Object.op_Implicit((Object)(object)((value2 != null) ? value2.Instance : null)) ? ((object)value2.Instance).GetType().Assembly : null);
				if (!(assembly2 == null) && modScan.PluginAsms.Add(assembly2) && !(value2.Metadata.GUID == "speenah.achievementtracker") && !(assembly2 == assembly))
				{
					list.Add(new KeyValuePair<Assembly, string>(assembly2, value2.Metadata.Name));
				}
			}
			if (_staticFields == null)
			{
				_staticFields = new List<KeyValuePair<FieldInfo, string>>();
				foreach (KeyValuePair<Assembly, string> item in list)
				{
					Type[] types;
					try
					{
						types = item.Key.GetTypes();
					}
					catch (ReflectionTypeLoadException ex)
					{
						types = ex.Types;
					}
					catch
					{
						continue;
					}
					Type[] array = types;
					foreach (Type type in array)
					{
						if (type == null || type.IsGenericTypeDefinition)
						{
							continue;
						}
						FieldInfo[] fields;
						try
						{
							fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
						}
						catch
						{
							continue;
						}
						FieldInfo[] array2 = fields;
						foreach (FieldInfo fieldInfo in array2)
						{
							if (!fieldInfo.IsLiteral && ObjectWalk.Worth(fieldInfo.FieldType))
							{
								_staticFields.Add(new KeyValuePair<FieldInfo, string>(fieldInfo, item.Value));
							}
						}
					}
				}
			}
			foreach (KeyValuePair<FieldInfo, string> staticField in _staticFields)
			{
				object value;
				try
				{
					value = staticField.Key.GetValue(null);
				}
				catch
				{
					continue;
				}
				modScan.Walk.Walk(value, staticField.Value, null);
			}
			return modScan;
		}

		private static string ModOf(ModScan s, GameObject go, Component c)
		{
			if (!Object.op_Implicit((Object)(object)go))
			{
				return null;
			}
			int instanceID = ((Object)go).GetInstanceID();
			bool runtime = instanceID < 0 || ((Object)(object)c != (Object)null && ((Object)c).GetInstanceID() < 0);
			string bundleOwner = null;
			foreach (KeyValuePair<AssetBundle, string> bundle in s.Bundles)
			{
				bool flag;
				try
				{
					flag = Object.op_Implicit((Object)(object)bundle.Key) && bundle.Key.Contains(((Object)go).name);
				}
				catch
				{
					flag = false;
				}
				if (flag)
				{
					bundleOwner = bundle.Value;
					break;
				}
			}
			s.Strong.TryGetValue(instanceID, out var value);
			s.Weak.TryGetValue(instanceID, out var value2);
			return ModNames.Pick(runtime, value, bundleOwner, value2);
		}

		private Dictionary<string, string> ModdedRequirements()
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			Stopwatch stopwatch = Stopwatch.StartNew();
			bool flag = _staticFields == null;
			ModScan modScan;
			try
			{
				modScan = ScanMods();
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Mod scan: " + ex.Message));
				return dictionary;
			}
			Dictionary<string, List<Piece>> dictionary2 = new Dictionary<string, List<Piece>>();
			foreach (ItemDrop value6 in _itemByToken.Values)
			{
				PieceTable buildPieces = value6.m_itemData.m_shared.m_buildPieces;
				if ((Object)(object)buildPieces == (Object)null)
				{
					continue;
				}
				foreach (GameObject piece in buildPieces.m_pieces)
				{
					Piece val = (Object.op_Implicit((Object)(object)piece) ? piece.GetComponent<Piece>() : null);
					if (!((Object)(object)val == (Object)null) && !string.IsNullOrEmpty(val.m_name))
					{
						if (!dictionary2.TryGetValue(val.m_name, out var value))
						{
							value = (dictionary2[val.m_name] = new List<Piece>());
						}
						value.Add(val);
					}
				}
			}
			foreach (AchRef ach in _achs)
			{
				foreach (Req req in ach.Reqs)
				{
					if (string.IsNullOrEmpty(req.Key) || dictionary.ContainsKey(req.Key))
					{
						continue;
					}
					string text = null;
					try
					{
						switch (req.Kind)
						{
						case "piece":
						{
							if (!dictionary2.TryGetValue(req.Key, out var value2))
							{
								break;
							}
							foreach (Piece item in value2)
							{
								if ((text = ModOf(modScan, ((Component)item).gameObject, (Component)(object)item)) != null)
								{
									break;
								}
							}
							break;
						}
						case "craft":
						case "food":
						case "pickup":
						{
							if (_itemByToken.TryGetValue(ItemTokenFor(req) ?? req.Key, out var value4))
							{
								text = ModOf(modScan, ((Component)value4).gameObject, (Component)(object)value4);
							}
							break;
						}
						case "kill":
						{
							if (_creaturePrefab.TryGetValue(req.Key, out var value3))
							{
								GameObject prefab2 = ZNetScene.instance.GetPrefab(value3);
								if (Object.op_Implicit((Object)(object)prefab2))
								{
									text = ModOf(modScan, prefab2, (Component)(object)prefab2.GetComponent<Character>());
								}
							}
							break;
						}
						case "pickable":
						{
							GameObject prefab = ZNetScene.instance.GetPrefab(req.Key);
							if (Object.op_Implicit((Object)(object)prefab))
							{
								text = ModOf(modScan, prefab, (Component)(object)prefab.GetComponent<Pickable>());
							}
							break;
						}
						}
					}
					catch
					{
						text = null;
					}
					if (text != null)
					{
						dictionary[req.Key] = text;
					}
				}
			}
			Dictionary<string, int> dictionary3 = new Dictionary<string, int>();
			foreach (string value7 in dictionary.Values)
			{
				dictionary3[value7] = (dictionary3.TryGetValue(value7, out var value5) ? value5 : 0) + 1;
			}
			List<string> list2 = new List<string>();
			foreach (KeyValuePair<string, int> item2 in dictionary3)
			{
				list2.Add(item2.Key + " " + item2.Value);
			}
			_log.LogInfo((object)(string.Format("Mod-added requirements: {0} ({1}); scanned {2} objects, ", dictionary.Count, string.Join(", ", list2), modScan.Walk.Visits) + $"{modScan.Bundles.Count} bundles in {stopwatch.ElapsedMilliseconds} ms" + (flag ? " (first scan)" : "")));
			return dictionary;
		}

		public TrackerModule(ManualLogSource log, string pluginDir)
		{
			_log = log;
		}

		public void Dispose()
		{
		}

		public string Handle(string path, string query)
		{
			switch (path)
			{
			case "/api/catalog":
				return _catalogJson;
			case "/api/state":
				Interlocked.Exchange(ref _lastRequestTicks, DateTime.UtcNow.Ticks);
				return _stateJson;
			case "/api/rebuild":
				_rebuild = true;
				return "{\"ok\":true}";
			default:
				return null;
			}
		}

		public void Tick()
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)Game.instance == (Object)null || (Object)(object)Achievements.m_instance == (Object)null || (Object)(object)ObjectDB.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
			{
				_stateJson = Json.Write(new NotReady(Ok: false, "Not in a world yet", _catalogVersion));
				return;
			}
			if (DateTime.UtcNow.Ticks - Interlocked.Read(in _lastRequestTicks) > IdleAfter)
			{
				_stateJson = Json.Write(new NotReady(Ok: false, "Waking up…", _catalogVersion));
				return;
			}
			_sw.Restart();
			int num = Shape();
			if (_rebuild || (Object)(object)localPlayer != (Object)(object)_catalogPlayer || num != _catalogShape)
			{
				_rebuild = false;
				BuildCatalog();
				_catalogPlayer = localPlayer;
				_catalogShape = num;
				_catalogMs = _sw.Elapsed.TotalMilliseconds;
				_sw.Restart();
			}
			UpdateAvailability(localPlayer, Game.instance.GetPlayerProfile());
			BuildState(localPlayer);
			_lastTickMs = _sw.Elapsed.TotalMilliseconds;
			if (++_ticks > 3)
			{
				_maxTickMs = Math.Max(_maxTickMs, _lastTickMs);
			}
		}

		private static int Shape()
		{
			int num = 0;
			foreach (AchievementList achievementList in Achievements.m_instance.m_achievementLists)
			{
				foreach (Achievement achievement in achievementList.m_achievements)
				{
					num = num * 31 + achievement.m_itemCraftTriggers.Count + achievement.m_piecePlacedTriggers.Count * 7 + achievement.m_enemyStatsTriggers.Count * 13 + achievement.m_itemPickupTriggers.Count * 17 + achievement.m_foodEatenTriggers.Count * 19 + 1;
				}
			}
			return num;
		}

		private unsafe void BuildCatalog()
		{
			//IL_10f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_1100: Expected I4, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e5: Expected I4, but got Unknown
			//IL_070a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0711: Unknown result type (might be due to invalid IL or missing references)
			//IL_0718: Unknown result type (might be due to invalid IL or missing references)
			//IL_0423: Unknown result type (might be due to invalid IL or missing references)
			//IL_043b: Expected I4, but got Unknown
			//IL_0810: Expected I4, but got Unknown
			//IL_0810: Expected I4, but got Unknown
			//IL_0810: Expected I4, but got Unknown
			//IL_0e6f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e80: Expected I4, but got Unknown
			//IL_0d9e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0dbb: Expected I4, but got Unknown
			_achs.Clear();
			_names.Clear();
			_itemByToken.Clear();
			_pieceByTok = null;
			_stationPrefabs = null;
			_creaturePrefab.Clear();
			foreach (GameObject prefab2 in ZNetScene.instance.m_prefabs)
			{
				Character val = (Object.op_Implicit((Object)(object)prefab2) ? prefab2.GetComponent<Character>() : null);
				if ((Object)(object)val != (Object)null && !string.IsNullOrEmpty(val.m_name) && !_creaturePrefab.ContainsKey(val.m_name))
				{
					_creaturePrefab[val.m_name] = ((Object)prefab2).name;
				}
			}
			foreach (GameObject item in ObjectDB.instance.m_items)
			{
				ItemDrop val2 = (Object.op_Implicit((Object)(object)item) ? item.GetComponent<ItemDrop>() : null);
				string text = val2?.m_itemData?.m_shared?.m_name;
				if (!string.IsNullOrEmpty(text) && !_itemByToken.ContainsKey(text))
				{
					_itemByToken[text] = val2;
				}
			}
			List<AchievementInfo> list = new List<AchievementInfo>();
			int num = 0;
			foreach (AchievementList achievementList in Achievements.m_instance.m_achievementLists)
			{
				foreach (Achievement achievement in achievementList.m_achievements)
				{
					if ((Object)(object)achievement == (Object)null)
					{
						continue;
					}
					AchRef achRef = new AchRef
					{
						A = achievement
					};
					foreach (PlayerStatRequirement item2 in achievement.m_statTrigger)
					{
						List<Req> reqs = achRef.Reqs;
						Req obj = new Req
						{
							Kind = "stat"
						};
						PlayerStatType stat = item2.m_stat;
						obj.Key = ((object)(*(PlayerStatType*)(&stat))/*cast due to .constrained prefix*/).ToString();
						obj.Stat = item2.m_stat;
						obj.Need = item2.m_amountAboveEquals;
						obj.Op = (RequirementOperator)0;
						reqs.Add(obj);
					}
					AddDict(achRef, "world", achievement.m_knownWorldTriggers);
					AddDict(achRef, "worldkey", achievement.m_knownWorldKeysTriggers);
					AddDict(achRef, "command", achievement.m_knownCommandsTriggers);
					foreach (EnemyStatRequirement enemyStatsTrigger in achievement.m_enemyStatsTriggers)
					{
						achRef.Reqs.Add(new Req
						{
							Kind = "kill",
							Key = enemyStatsTrigger.m_stat,
							Need = enemyStatsTrigger.m_amount,
							Op = enemyStatsTrigger.m_operator,
							Mod = (int)enemyStatsTrigger.m_modifier
						});
					}
					AddDict(achRef, "pickup", achievement.m_itemPickupTriggers);
					AddDict(achRef, "craft", achievement.m_itemCraftTriggers);
					AddDict(achRef, "pickable", achievement.m_pickableTriggers);
					AddDict(achRef, "food", achievement.m_foodEatenTriggers);
					AddDict(achRef, "piece", achievement.m_piecePlacedTriggers);
					foreach (Achievement otherAchievementTrigger in achievement.m_otherAchievementTriggers)
					{
						if ((Object)(object)otherAchievementTrigger != (Object)null)
						{
							achRef.Reqs.Add(new Req
							{
								Kind = "other",
								Key = otherAchievementTrigger.m_id,
								Other = otherAchievementTrigger,
								Need = 1f
							});
						}
					}
					_achs.Add(achRef);
					List<object[]> list2 = new List<object[]>();
					foreach (Req req in achRef.Reqs)
					{
						list2.Add(Rows.Requirement(req.Kind, req.Key, req.Need, (int)req.Op, req.Mod, ItemTokenFor(req)));
						Name((req.Kind == "other") ? null : req.Key);
						if (req.Kind == "other")
						{
							_names["ach:" + req.Key] = Loc(req.Other.m_name);
						}
					}
					list.Add(new AchievementInfo(achievement.m_id, Loc(achievement.m_name), Loc(achievement.m_description), achievement.m_isSecret, achievement.m_isDynamicallyPopulated, achievement.m_lenientBuildAchievement, ((object)Unsafe.As<DifficultyRequirement, DifficultyRequirement>(ref achievement.m_difficultyRequirement)/*cast due to .constrained prefix*/).ToString(), num, list2));
				}
				num++;
			}
			Dictionary<string, List<Recipe>> dictionary = new Dictionary<string, List<Recipe>>();
			foreach (Recipe recipe in ObjectDB.instance.m_recipes)
			{
				string text2 = recipe?.m_item?.m_itemData?.m_shared?.m_name;
				if (!string.IsNullOrEmpty(text2))
				{
					if (!dictionary.TryGetValue(text2, out var value))
					{
						value = (dictionary[text2] = new List<Recipe>());
					}
					value.Add(recipe);
				}
			}
			Dictionary<string, List<RecipeInfo>> dictionary2 = new Dictionary<string, List<RecipeInfo>>();
			foreach (KeyValuePair<string, List<Recipe>> item3 in dictionary)
			{
				Name(item3.Key);
				dictionary2[item3.Key] = item3.Value.ConvertAll((Recipe r) => new RecipeInfo(StationTok(r.m_craftingStation), r.m_minStationLevel, (Object)(object)r.m_craftingStation != (Object)null && r.m_craftingStation.m_upgrader, r.m_amount, r.m_enabled, r.m_noCraftOnlyUpgrade, r.m_requireOnlyOneIngredient, Mats(r.m_resources)));
			}
			Dictionary<string, ItemStats> dictionary3 = new Dictionary<string, ItemStats>();
			foreach (string key2 in dictionary.Keys)
			{
				if (_itemByToken.TryGetValue(key2, out var value2))
				{
					ItemData itemData = value2.m_itemData;
					SharedData shared = itemData.m_shared;
					SharedData val3 = ((!((Object)(object)shared.m_appendToolTip != (Object)null)) ? null : shared.m_appendToolTip.m_itemData?.m_shared);
					Recipe val4 = dictionary[key2].Find((Recipe x) => x.m_enabled) ?? dictionary[key2][0];
					dictionary3[key2] = new ItemStats((int)shared.m_itemType, (int)shared.m_attachOverride, (int)shared.m_skillType, shared.m_ammoType ?? "", shared.m_attack?.m_attackAnimation ?? "", ((DamageTypes)(ref shared.m_damages)).GetTotalDamage(), new float[3] { shared.m_food, shared.m_foodStamina, shared.m_foodEitr }, (Object)(object)shared.m_consumeStatusEffect != (Object)null, Safe((Func<float>)itemData.GetArmor, 0f), Safe((Func<float>)itemData.GetMaxDurability, 0f), Safe((Func<float>)itemData.GetBaseBlockPower, 0f), shared.m_timedBlockBonus, shared.m_maxAdrenaline, val4.m_listSortWeight, (val3 == null) ? null : new float[3] { val3.m_food, val3.m_foodStamina, val3.m_foodEitr });
				}
			}
			List<string[]> list4 = new List<string[]>();
			List<string[]> list5 = new List<string[]>();
			List<string[]> list6 = new List<string[]>();
			Dictionary<string, HashSet<string>> dictionary4 = new Dictionary<string, HashSet<string>>();
			Dictionary<string, HashSet<string>> dictionary5 = new Dictionary<string, HashSet<string>>();
			foreach (GameObject prefab3 in ZNetScene.instance.m_prefabs)
			{
				if (!Object.op_Implicit((Object)(object)prefab3))
				{
					continue;
				}
				string text3 = PieceTok(prefab3);
				CookingStation component = prefab3.GetComponent<CookingStation>();
				if ((Object)(object)component != (Object)null)
				{
					foreach (ItemConversion item4 in component.m_conversion)
					{
						if (Object.op_Implicit((Object)(object)item4?.m_from) && Object.op_Implicit((Object)(object)item4.m_to))
						{
							list4.Add(Rows.Cook(Tok(item4.m_to), text3 ?? component.m_name, Tok(item4.m_from), F(item4.m_cookTime), component.m_useFuel, ((Object)prefab3).name));
						}
					}
				}
				Fermenter component2 = prefab3.GetComponent<Fermenter>();
				if ((Object)(object)component2 != (Object)null)
				{
					foreach (ItemConversion item5 in component2.m_conversion)
					{
						if (Object.op_Implicit((Object)(object)item5?.m_from) && Object.op_Implicit((Object)(object)item5.m_to))
						{
							list5.Add(Rows.Ferment(Tok(item5.m_to), text3 ?? component2.m_name, Tok(item5.m_from), item5.m_producedItems.ToString(), ((Object)prefab3).name));
						}
					}
				}
				Smelter component3 = prefab3.GetComponent<Smelter>();
				if ((Object)(object)component3 != (Object)null)
				{
					foreach (ItemConversion item6 in component3.m_conversion)
					{
						if (Object.op_Implicit((Object)(object)item6?.m_from) && Object.op_Implicit((Object)(object)item6.m_to))
						{
							list6.Add(Rows.Smelt(Tok(item6.m_to), text3 ?? component3.m_name, Tok(item6.m_from), ((Object)prefab3).name));
						}
					}
				}
				CharacterDrop component4 = prefab3.GetComponent<CharacterDrop>();
				Character component5 = prefab3.GetComponent<Character>();
				if ((Object)(object)component4 != (Object)null && (Object)(object)component5 != (Object)null)
				{
					foreach (Drop drop in component4.m_drops)
					{
						ItemDrop val5 = (Object.op_Implicit((Object)(object)drop?.m_prefab) ? drop.m_prefab.GetComponent<ItemDrop>() : null);
						if (!((Object)(object)val5 == (Object)null))
						{
							string key = Tok(val5);
							if (!dictionary4.TryGetValue(key, out var value3))
							{
								value3 = (dictionary4[key] = new HashSet<string>());
							}
							value3.Add(component5.m_name);
							Name(component5.m_name);
						}
					}
				}
				Pickable component6 = prefab3.GetComponent<Pickable>();
				if ((Object)(object)component6 != (Object)null && Object.op_Implicit((Object)(object)component6.m_itemPrefab))
				{
					string name = ((Object)component6.m_itemPrefab).name;
					if (!dictionary5.TryGetValue(name, out var value4))
					{
						value4 = (dictionary5[name] = new HashSet<string>());
					}
					value4.Add(((Object)prefab3).name);
				}
			}
			foreach (string[] item7 in list4)
			{
				NameRow(item7);
			}
			foreach (string[] item8 in list5)
			{
				NameRow(item8);
			}
			foreach (string[] item9 in list6)
			{
				NameRow(item9);
			}
			foreach (HashSet<string> value9 in dictionary5.Values)
			{
				foreach (string item10 in value9)
				{
					Name(item10);
				}
			}
			List<Spawner> list7 = new List<Spawner>();
			List<RaidSpawn> list8 = new List<RaidSpawn>();
			try
			{
				SpawnSystem val6 = (Object.op_Implicit((Object)(object)ZoneSystem.instance?.m_zoneCtrlPrefab) ? ZoneSystem.instance.m_zoneCtrlPrefab.GetComponent<SpawnSystem>() : null);
				if ((Object)(object)val6 != (Object)null)
				{
					foreach (SpawnSystemList spawnList in val6.m_spawnLists)
					{
						if (!((Object)(object)spawnList != (Object)null))
						{
							continue;
						}
						foreach (SpawnData spawner in spawnList.m_spawners)
						{
							if (Object.op_Implicit((Object)(object)spawner?.m_prefab) && spawner.m_enabled && !spawner.m_devDisabled)
							{
								list7.Add(new Spawner(((Object)spawner.m_prefab).name, (int)spawner.m_biome, SpawnBiomes.IsGated(spawner.m_requiredPersistentEvent, spawner.m_requiredGlobalKey)));
							}
						}
					}
				}
				if ((Object)(object)RandEventSystem.instance != (Object)null)
				{
					foreach (RandomEvent @event in RandEventSystem.instance.m_events)
					{
						if (@event == null || !@event.m_enabled)
						{
							continue;
						}
						foreach (SpawnData item11 in @event.m_spawn)
						{
							if (Object.op_Implicit((Object)(object)item11?.m_prefab))
							{
								list8.Add(new RaidSpawn(((Object)item11.m_prefab).name, (int)@event.m_biome, @event.m_name));
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Creature biome scan: " + ex.Message));
			}
			Dictionary<string, int> dictionary6 = SpawnBiomes.Natural(list7);
			Dictionary<string, HashSet<string>> dictionary7 = new Dictionary<string, HashSet<string>>();
			Dictionary<string, int> dictionary8 = SpawnBiomes.Raids(list8, dictionary7);
			Dictionary<string, object[]> dictionary9 = new Dictionary<string, object[]>();
			foreach (GameObject prefab4 in ZNetScene.instance.m_prefabs)
			{
				Character val7 = (Object.op_Implicit((Object)(object)prefab4) ? prefab4.GetComponent<Character>() : null);
				if (!((Object)(object)val7 == (Object)null) && !string.IsNullOrEmpty(val7.m_name) && !(val7 is Player) && !dictionary9.ContainsKey(((Object)prefab4).name))
				{
					dictionary6.TryGetValue(((Object)prefab4).name, out var value5);
					dictionary8.TryGetValue(((Object)prefab4).name, out var value6);
					dictionary9[((Object)prefab4).name] = Rows.Creature(val7.m_name, ((Object)prefab4).name, value5, value6, val7.IsBoss(), dictionary7.TryGetValue(((Object)prefab4).name, out var value7) ? value7 : new HashSet<string>());
				}
			}
			Dictionary<string, int> dictionary10 = new Dictionary<string, int>();
			Dictionary<string, int> dictionary11 = new Dictionary<string, int>();
			try
			{
				foreach (KeyValuePair<string, int> item12 in dictionary6)
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(item12.Key);
					Fish val8 = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<Fish>() : null);
					if ((Object)(object)val8 != (Object)null && !string.IsNullOrEmpty(val8.m_name))
					{
						Or(dictionary10, val8.m_name, item12.Value);
					}
				}
				if ((Object)(object)ZoneSystem.instance != (Object)null)
				{
					foreach (ZoneVegetation item13 in ZoneSystem.instance.m_vegetation)
					{
						TreeBase val9 = ((item13 != null && item13.m_enable && Object.op_Implicit((Object)(object)item13.m_prefab)) ? item13.m_prefab.GetComponent<TreeBase>() : null);
						if ((Object)(object)val9 != (Object)null)
						{
							Or(dictionary11, ((object)Unsafe.As<PlayerStatType, PlayerStatType>(ref val9.m_treeStatType)/*cast due to .constrained prefix*/).ToString(), (int)item13.m_biome);
						}
					}
				}
			}
			catch (Exception ex2)
			{
				_log.LogWarning((object)("Fish/tree biome scan: " + ex2.Message));
			}
			Dictionary<string, List<string>> dictionary12 = new Dictionary<string, List<string>>();
			try
			{
				foreach (GameObject prefab5 in ZNetScene.instance.m_prefabs)
				{
					Fish val10 = (Object.op_Implicit((Object)(object)prefab5) ? prefab5.GetComponent<Fish>() : null);
					if (!((Object)(object)val10 == (Object)null) && !string.IsNullOrEmpty(val10.m_name) && !dictionary12.ContainsKey(val10.m_name))
					{
						List<string> list9 = (from b in val10.m_baits
							where b != null && Object.op_Implicit((Object)(object)b.m_bait)
							orderby b.m_chance descending
							select Tok(b.m_bait)).Distinct().ToList();
						if (list9.Count > 0)
						{
							dictionary12[val10.m_name] = list9;
						}
					}
				}
			}
			catch (Exception ex3)
			{
				_log.LogWarning((object)("Fish bait scan: " + ex3.Message));
			}
			Dictionary<string, PieceInfo> dictionary13 = new Dictionary<string, PieceInfo>();
			foreach (ItemDrop value10 in _itemByToken.Values)
			{
				PieceTable buildPieces = value10.m_itemData.m_shared.m_buildPieces;
				if ((Object)(object)buildPieces == (Object)null)
				{
					continue;
				}
				string text4 = Tok(value10);
				Name(text4);
				foreach (GameObject piece in buildPieces.m_pieces)
				{
					Piece val11 = (Object.op_Implicit((Object)(object)piece) ? piece.GetComponent<Piece>() : null);
					if (!((Object)(object)val11 == (Object)null) && !string.IsNullOrEmpty(val11.m_name) && !dictionary13.ContainsKey(((Object)piece).name))
					{
						Name(val11.m_name);
						dictionary13[((Object)piece).name] = new PieceInfo(val11.m_name, text4, ((object)Unsafe.As<PieceCategory, PieceCategory>(ref val11.m_category)/*cast due to .constrained prefix*/).ToString(), StationTok(val11.m_craftingStation), val11.m_enabled, Mats(val11.m_resources));
					}
				}
			}
			foreach (string key3 in _itemByToken.Keys)
			{
				Name(key3);
			}
			_catalogJson = Json.Write(new Catalog(++_catalogVersion, DateTime.Now.ToString("HH:mm:ss", CultureInfo.InvariantCulture), list, ModdedRequirements(), dictionary2, dictionary3, list4, list5, list6, dictionary4, dictionary5, dictionary9, dictionary10, dictionary12, dictionary11, dictionary13, _names));
			_log.LogInfo((object)$"Catalog v{_catalogVersion}: {_achs.Count} achievements, {dictionary.Count} crafted items, {list4.Count} cooking conversions");
			static void Or(Dictionary<string, int> d, string k, int f)
			{
				d[k] = (d.TryGetValue(k, out var value8) ? value8 : 0) | f;
			}
		}

		private static void AddDict(AchRef ar, string kind, List<DictStatRequirement> list)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			foreach (DictStatRequirement item in list)
			{
				ar.Reqs.Add(new Req
				{
					Kind = kind,
					Key = item.m_stat,
					Need = item.m_amount,
					Op = item.m_operator
				});
			}
		}

		private static string ItemTokenFor(Req r)
		{
			switch (r.Kind)
			{
			case "craft":
			case "food":
			case "pickup":
			case "pickable":
			{
				if (r.Key == null)
				{
					return null;
				}
				if (r.Key.StartsWith("$"))
				{
					return r.Key;
				}
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(r.Key);
				ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
				if (!((Object)(object)val != (Object)null))
				{
					return null;
				}
				return Tok(val);
			}
			default:
				return null;
			}
		}

		private List<object[]> Mats(Requirement[] res)
		{
			List<object[]> list = new List<object[]>();
			if (res != null)
			{
				foreach (Requirement val in res)
				{
					if (!((Object)(object)val?.m_resItem == (Object)null))
					{
						string text = Tok(val.m_resItem);
						Name(text);
						list.Add(Rows.Material(text, val.m_amount, val.m_upgraderResource));
					}
				}
			}
			return list;
		}

		private void NameRow(string[] row)
		{
			Name(row[0]);
			Name(row[1]);
			Name(row[2]);
		}

		private string StationTok(CraftingStation cs)
		{
			if ((Object)(object)cs == (Object)null)
			{
				return null;
			}
			Name(cs.m_name);
			return cs.m_name;
		}

		private static string PieceTok(GameObject go)
		{
			Piece component = go.GetComponent<Piece>();
			if (!((Object)(object)component != (Object)null) || string.IsNullOrEmpty(component.m_name))
			{
				return null;
			}
			return component.m_name;
		}

		private static string Tok(ItemDrop id)
		{
			object obj = id?.m_itemData?.m_shared?.m_name;
			if (obj == null)
			{
				if (id == null)
				{
					return null;
				}
				obj = ((Object)id).name;
			}
			return (string)obj;
		}

		private void Name(string key)
		{
			if (string.IsNullOrEmpty(key) || _names.ContainsKey(key))
			{
				return;
			}
			string text = null;
			if (key.StartsWith("$"))
			{
				_creaturePrefab.TryGetValue(key, out var value);
				ItemDrop value2;
				string itemPrefab = ((_itemByToken.TryGetValue(key, out value2) && Object.op_Implicit((Object)(object)value2)) ? ((Object)value2).name : null);
				text = DisplayNames.ForToken(key, Loc(key), value, itemPrefab);
			}
			else
			{
				GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(key);
				ItemDrop val = (Object.op_Implicit((Object)(object)itemPrefab2) ? itemPrefab2.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val != (Object)null)
				{
					text = Loc(val.m_itemData.m_shared.m_name);
				}
				else
				{
					GameObject prefab = ZNetScene.instance.GetPrefab(key);
					if (Object.op_Implicit((Object)(object)prefab))
					{
						Piece component = prefab.GetComponent<Piece>();
						Character component2 = prefab.GetComponent<Character>();
						Pickable component3 = prefab.GetComponent<Pickable>();
						if ((Object)(object)component != (Object)null && !string.IsNullOrEmpty(component.m_name))
						{
							text = Loc(component.m_name);
						}
						else if ((Object)(object)component2 != (Object)null && !string.IsNullOrEmpty(component2.m_name))
						{
							text = Loc(component2.m_name);
						}
						else if ((Object)(object)component3 != (Object)null && !string.IsNullOrEmpty(component3.m_overrideName))
						{
							text = Loc(component3.m_overrideName);
						}
					}
				}
			}
			_names[key] = (string.IsNullOrEmpty(text) ? key : text);
		}

		private static string Loc(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return s ?? "";
			}
			try
			{
				string text = ((Localization.instance != null) ? Localization.instance.Localize(s) : s);
				return string.IsNullOrEmpty(text) ? s : DisplayNames.StripRichText(text);
			}
			catch
			{
				return s;
			}
		}

		private static string F(float f)
		{
			return f.ToString("0.###", CultureInfo.InvariantCulture);
		}

		private void BuildState(Player player)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected I4, but got Unknown
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0274: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			PlayerProfile playerProfile = Game.instance.GetPlayerProfile();
			List<object[]> list = new List<object[]>();
			Dictionary<string, float> dictionary = new Dictionary<string, float>();
			foreach (AchRef ach in _achs)
			{
				int num = (int)ach.A.m_difficultyRequirement;
				PlayerStats val = ((num >= 0 && num < playerProfile.m_playerStats.Length) ? playerProfile.m_playerStats[num] : playerProfile.m_playerStats[1]);
				PlayerStats ps = playerProfile.m_playerStats[0];
				float[] array = new float[ach.Reqs.Count];
				Dictionary<int, float> dictionary2 = new Dictionary<int, float>();
				for (int i = 0; i < ach.Reqs.Count; i++)
				{
					Req req = ach.Reqs[i];
					float num2 = Value(val, req);
					float num3 = ((req.Kind == "other") ? num2 : Value(ps, req));
					array[i] = num2;
					if (req.Kind == "stat" && RunningStat.TryGetValue(req.Stat, out var value))
					{
						dictionary[req.Key] = (val.m_stats.TryGetValue(value, out var value2) ? value2 : 0f);
					}
					if (num3 != num2)
					{
						dictionary2[i] = num3;
					}
				}
				list.Add(Rows.Achievement(ach.A.m_unlocked, array, dictionary2));
			}
			Dictionary<string, int> dictionary3 = new Dictionary<string, int>();
			foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems())
			{
				string text = allItem?.m_shared?.m_name;
				if (text != null)
				{
					dictionary3.TryGetValue(text, out var value3);
					dictionary3[text] = value3 + allItem.m_stack;
				}
			}
			Dictionary<string, float> dictionary4 = new Dictionary<string, float>();
			Vector3 position = ((Component)player).transform.position;
			foreach (KeyValuePair<string, List<Container>> item in _chestsByTok)
			{
				float num4 = float.MaxValue;
				foreach (Container item2 in item.Value)
				{
					if (Object.op_Implicit((Object)(object)item2))
					{
						num4 = Mathf.Min(num4, Vector3.Distance(position, ((Component)item2).transform.position));
					}
				}
				if (num4 < float.MaxValue)
				{
					dictionary4[item.Key] = Mathf.Round(num4 * 10f) / 10f;
				}
			}
			_stateJson = Json.Write(new State(Ok: true, _catalogVersion, DateTime.Now.ToString("HH:mm:ss", CultureInfo.InvariantCulture), playerProfile.GetName(), ((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetWorldName() : "", Safe<string>(() => ((object)Achievements.GetCurrentAchievementDifficulty()/*cast due to .constrained prefix*/).ToString(), "?"), new CheatInfo(Safe(() => Achievements.CanGetAchievements(false), fallback: true), playerProfile.m_usedCheats, Safe(() => ((Humanoid)player).GetInventory().AnyCheatedItem(), fallback: false), Game.isModded), list, dictionary, dictionary3, Stations(player), _avail, dictionary4, _known, new Perf((float)_lastTickMs, (float)_maxTickMs, (float)_catalogMs, (float)_availMs, _stateJson.Length)));
		}

		private static float Value(PlayerStats ps, Req r)
		{
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, float> dictionary;
			switch (r.Kind)
			{
			case "stat":
			{
				if (!ps.m_stats.TryGetValue(r.Stat, out var value))
				{
					return 0f;
				}
				return value;
			}
			case "world":
				dictionary = ps.m_knownWorlds;
				break;
			case "worldkey":
				dictionary = ps.m_knownWorldKeys;
				break;
			case "command":
				dictionary = ps.m_knownCommands;
				break;
			case "kill":
				dictionary = ((r.Mod >= 0 && r.Mod < ps.m_enemyStats.Length) ? ps.m_enemyStats[r.Mod] : null);
				break;
			case "pickup":
				dictionary = ps.m_itemPickupStats;
				break;
			case "craft":
				dictionary = ps.m_itemCraftStats;
				break;
			case "pickable":
				dictionary = ps.m_pickableStats;
				break;
			case "food":
				dictionary = ps.m_foodEatenStats;
				break;
			case "piece":
				dictionary = ps.m_piecesPlacedStats;
				break;
			case "other":
				if (!((Object)(object)r.Other != (Object)null) || !r.Other.m_unlocked)
				{
					return 0f;
				}
				return 1f;
			default:
				return 0f;
			}
			if (dictionary == null || r.Key == null || !dictionary.TryGetValue(r.Key, out var value2))
			{
				return 0f;
			}
			return value2;
		}

		private List<Component> StationObjects()
		{
			if (Time.unscaledTime < _nextStationScan)
			{
				return _stationCache;
			}
			_nextStationScan = Time.unscaledTime + 5f;
			if (_stationPrefabs == null)
			{
				_stationPrefabs = new HashSet<int>();
				foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
				{
					if (Object.op_Implicit((Object)(object)prefab) && (Object.op_Implicit((Object)(object)prefab.GetComponent<CookingStation>()) || Object.op_Implicit((Object)(object)prefab.GetComponent<CraftingStation>()) || Object.op_Implicit((Object)(object)prefab.GetComponent<Fermenter>())))
					{
						_stationPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)prefab).name));
					}
				}
			}
			List<Component> list = new List<Component>();
			if (InstancesField?.GetValue(ZNetScene.instance) is Dictionary<ZDO, ZNetView> dictionary)
			{
				foreach (KeyValuePair<ZDO, ZNetView> item in dictionary)
				{
					if (item.Key != null && _stationPrefabs.Contains(item.Key.GetPrefab()) && Object.op_Implicit((Object)(object)item.Value))
					{
						Component component = (Component)(object)((Component)item.Value).GetComponent<CookingStation>();
						if (!Object.op_Implicit((Object)(object)component))
						{
							component = (Component)(object)((Component)item.Value).GetComponent<CraftingStation>();
						}
						if (!Object.op_Implicit((Object)(object)component))
						{
							component = (Component)(object)((Component)item.Value).GetComponent<Fermenter>();
						}
						if (Object.op_Implicit((Object)(object)component))
						{
							list.Add(component);
						}
					}
				}
			}
			_stationCache = list;
			return list;
		}

		private List<StationInfo> Stations(Player player)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0348: Unknown result type (might be due to invalid IL or missing references)
			List<StationInfo> list = new List<StationInfo>();
			Vector3 position = ((Component)player).transform.position;
			long sessionID = ZDOMan.GetSessionID();
			Dictionary<long, string> names = new Dictionary<long, string>();
			try
			{
				List<KeyValuePair<long, string>> list2 = new List<KeyValuePair<long, string>>();
				foreach (PlayerInfo player2 in ZNet.instance.GetPlayerList())
				{
					if (player2.m_characterID != ZDOID.None)
					{
						ZDOID characterID = player2.m_characterID;
						list2.Add(new KeyValuePair<long, string>(((ZDOID)(ref characterID)).UserID, player2.m_name));
					}
				}
				names = StationOwners.Names(list2, ZNet.instance.GetServerPeer()?.m_uid);
				_ownerLookupError = null;
			}
			catch (Exception ex)
			{
				if (ex.Message != _ownerLookupError)
				{
					_log.LogWarning((object)("Station owner lookup: " + ex.Message));
				}
				_ownerLookupError = ex.Message;
			}
			HashSet<int> hashSet = new HashSet<int>();
			foreach (Component item in StationObjects())
			{
				if (!Object.op_Implicit((Object)(object)item))
				{
					continue;
				}
				Vector3 val = item.transform.position - position;
				if (((Vector3)(ref val)).sqrMagnitude > 900f)
				{
					continue;
				}
				CookingStation val2 = (CookingStation)(object)((item is CookingStation) ? item : null);
				CraftingStation val3 = (CraftingStation)(object)((item is CraftingStation) ? item : null);
				Fermenter val4 = (Fermenter)(object)((item is Fermenter) ? item : null);
				if (((Object)(object)val3 != (Object)null && (Object)(object)((Component)val3).GetComponent<CookingStation>() != (Object)null) || !hashSet.Add(((Object)item.gameObject).GetInstanceID()))
				{
					continue;
				}
				ZNetView componentInParent = item.GetComponentInParent<ZNetView>();
				if ((Object)(object)componentInParent == (Object)null || !componentInParent.IsValid())
				{
					continue;
				}
				ZDO zDO = componentInParent.GetZDO();
				List<object[]> list3 = null;
				if ((Object)(object)val2 != (Object)null && val2.m_slots != null)
				{
					list3 = new List<object[]>();
					for (int i = 0; i < val2.m_slots.Length; i++)
					{
						string text = zDO.GetString("slot" + i, "");
						if (!string.IsNullOrEmpty(text))
						{
							GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(text);
							ItemDrop val5 = (Object.op_Implicit((Object)(object)itemPrefab) ? itemPrefab.GetComponent<ItemDrop>() : null);
							list3.Add(Rows.Slot(text, zDO.GetInt("slotstatus" + i, 0), ((Object)(object)val5 != (Object)null) ? Loc(val5.m_itemData.m_shared.m_name) : text));
						}
					}
				}
				long owner = zDO.GetOwner();
				list.Add(new StationInfo(((Object)(object)val2 != (Object)null) ? "cook" : (((Object)(object)val3 != (Object)null) ? "craft" : "ferment"), Loc(PieceTok(item.gameObject) ?? (((Object)(object)val3 != (Object)null) ? val3.m_name : (((Object)(object)val2 != (Object)null) ? val2.m_name : (((Object)(object)val4 != (Object)null) ? val4.m_name : ((Object)item).name)))), Utils.GetPrefabName(item.gameObject), Mathf.Round(Vector3.Distance(position, item.transform.position) * 10f) / 10f, componentInParent.IsOwner(), StationOwners.Label(owner, sessionID, names), ((Object)(object)val3 != (Object)null) ? new int?(val3.GetLevel(true)) : ((int?)null), list3));
			}
			return list;
		}

		private static T Safe<T>(Func<T> f, T fallback)
		{
			try
			{
				return f();
			}
			catch
			{
				return fallback;
			}
		}
	}
	internal sealed record AvailabilityInfo(string Time, string Station, string StationTok, int Level, string Tool, Dictionary<string, object[]> Items, Dictionary<string, object[]> Pieces, int Chests, Dictionary<string, int> ChestInv, VerifyInfo Verify, float Ms);
	internal sealed record VerifyInfo(int Checked, int Mismatches, string Last);
	internal sealed record Catalog(int V, string Built, List<AchievementInfo> Achievements, Dictionary<string, string> Modded, Dictionary<string, List<RecipeInfo>> Recipes, Dictionary<string, ItemStats> ItemInfo, List<string[]> Cook, List<string[]> Ferment, List<string[]> Smelt, Dictionary<string, HashSet<string>> Drops, Dictionary<string, HashSet<string>> Pickables, Dictionary<string, object[]> Creatures, Dictionary<string, int> FishBiomes, Dictionary<string, List<string>> FishBaits, Dictionary<string, int> TreeBiomes, Dictionary<string, PieceInfo> Pieces, Dictionary<string, string> Names);
	internal sealed record AchievementInfo(string Id, string Name, string Desc, bool Secret, bool Dynamic, bool Lenient, string Diff, int List, List<object[]> Reqs);
	internal sealed record RecipeInfo(string Station, int Level, bool Upgrader, int Amount, bool Enabled, bool UpgradeOnly, bool OneOf, List<object[]> Mats);
	internal sealed record ItemStats([property: JsonProperty("t")] int ItemType, [property: JsonProperty("ao")] int AttachOverride, [property: JsonProperty("sk")] int SkillType, [property: JsonProperty("am")] string AmmoType, [property: JsonProperty("an")] string AttackAnimation, [property: JsonProperty("dmg")] float TotalDamage, [property: JsonProperty("f")] float[] Food, [property: JsonProperty("se")] bool HasConsumeEffect, [property: JsonProperty("arm")] float Armor, [property: JsonProperty("dur")] float Durability, [property: JsonProperty("blk")] float BlockPower, [property: JsonProperty("tbb")] float TimedBlockBonus, [property: JsonProperty("adr")] float MaxAdrenaline, [property: JsonProperty("lsw")] int ListSortWeight, [property: JsonProperty("ap")] float[] AppendedFood);
	internal sealed record PieceInfo(string Name, string Tool, string Cat, string Station, bool Enabled, List<object[]> Mats);
	internal static class DisplayNames
	{
		private static readonly Regex RichText = new Regex("</?(color|b|i|size|material|quad|sprite)(=[^>]*)?>", RegexOptions.IgnoreCase);

		private static readonly Regex CamelHump = new Regex("([a-z])([A-Z])");

		public static string StripRichText(string s)
		{
			return RichText.Replace(s, "");
		}

		public static bool IsUntranslated(string token, string localized)
		{
			if (!string.IsNullOrEmpty(localized) && !(localized == token))
			{
				return localized.StartsWith("[");
			}
			return true;
		}

		public static string ForToken(string token, string localized, string creaturePrefab, string itemPrefab)
		{
			if (!IsUntranslated(token, localized))
			{
				return localized;
			}
			if (creaturePrefab != null)
			{
				return PrettyPrefab(creaturePrefab);
			}
			if (itemPrefab != null)
			{
				return CamelHump.Replace(PrettyPrefab(itemPrefab), "$1 $2");
			}
			return localized;
		}

		public static string PrettyPrefab(string prefab)
		{
			if (prefab.Length > "_spiritcaller".Length && prefab.EndsWith("_spiritcaller", StringComparison.OrdinalIgnoreCase))
			{
				string text = prefab.Substring(0, prefab.Length - "_spiritcaller".Length);
				return "Spirit " + char.ToUpperInvariant(text[0]) + text.Substring(1) + " (Spirit Caller summon)";
			}
			return prefab.Replace('_', ' ');
		}
	}
	internal static class Json
	{
		private sealed class FloatConverter : JsonConverter<float>
		{
			public override bool CanRead => false;

			public override void WriteJson(JsonWriter writer, float value, JsonSerializer serializer)
			{
				writer.WriteRawValue((float.IsNaN(value) || float.IsInfinity(value)) ? "0" : value.ToString("0.###", CultureInfo.InvariantCulture));
			}

			public override float ReadJson(JsonReader reader, Type objectType, float existingValue, bool hasExistingValue, JsonSerializer serializer)
			{
				throw new NotSupportedException();
			}
		}

		private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
		{
			ContractResolver = (IContractResolver)new DefaultContractResolver
			{
				NamingStrategy = (NamingStrategy)new CamelCaseNamingStrategy()
			},
			Converters = { (JsonConverter)(object)new FloatConverter() }
		};

		public static string Write(object value)
		{
			return JsonConvert.SerializeObject(value, Settings);
		}
	}
	internal sealed record KnownRecipes(Dictionary<string, object[]> Items, Dictionary<string, object[]> Pieces);
	internal sealed record Mat(string Token, int Amount, bool UpgradeOnly, int MaxQuality);
	internal sealed class MaterialCounts
	{
		private readonly int _worldLevel;

		private readonly Dictionary<string, Dictionary<int, int>> _byQuality = new Dictionary<string, Dictionary<int, int>>();

		public MaterialCounts(int worldLevel)
		{
			_worldLevel = worldLevel;
		}

		public void Add(string token, int quality, int stack, int itemWorldLevel)
		{
			if (itemWorldLevel >= _worldLevel)
			{
				if (!_byQuality.TryGetValue(token, out var value))
				{
					value = (_byQuality[token] = new Dictionary<int, int>());
				}
				value.TryGetValue(quality, out var value2);
				value[quality] = value2 + stack;
			}
		}

		public int Best(string token, int maxQuality)
		{
			if (!_byQuality.TryGetValue(token, out var value))
			{
				return 0;
			}
			int num = 0;
			foreach (KeyValuePair<int, int> item in value)
			{
				if (item.Key >= 1 && item.Key <= maxQuality && item.Value > num)
				{
					num = item.Value;
				}
			}
			return num;
		}

		public int Total(string token)
		{
			if (!_byQuality.TryGetValue(token, out var value))
			{
				return 0;
			}
			int num = 0;
			foreach (int value2 in value.Values)
			{
				num += value2;
			}
			return num;
		}

		public bool CanCraft(IEnumerable<Mat> mats, bool oneOf, bool? stationUpgrader)
		{
			bool flag = false;
			bool flag2 = true;
			foreach (Mat mat in mats)
			{
				if (Materials.UsedAt(mat, stationUpgrader))
				{
					bool flag3 = Best(mat.Token, mat.MaxQuality) >= mat.Amount;
					flag = flag || flag3;
					flag2 = flag2 && flag3;
				}
			}
			if (!oneOf)
			{
				return flag2;
			}
			return flag;
		}

		public bool CanBuild(IEnumerable<Mat> mats)
		{
			foreach (Mat mat in mats)
			{
				if (mat.Amount > 0 && Total(mat.Token) < mat.Amount)
				{
					return false;
				}
			}
			return true;
		}
	}
	internal static class Materials
	{
		public static bool UsedAt(Mat m, bool? stationUpgrader)
		{
			return m.UpgradeOnly == (stationUpgrader == true);
		}

		public static bool Needed(Mat m, bool? stationUpgrader)
		{
			if (m.Amount > 0)
			{
				return UsedAt(m, stationUpgrader);
			}
			return false;
		}

		public static bool StationOk(string needed, int minLevel, string at, int atLevel)
		{
			if (needed != null)
			{
				if (at != null && at == needed)
				{
					return atLevel >= minLevel;
				}
				return false;
			}
			return true;
		}
	}
	internal interface IWalkVisitor
	{
		bool Enter(object o, string plugin, string source);

		string SourceOf(object o);
	}
	internal sealed class ObjectWalk
	{
		private readonly IWalkVisitor _visitor;

		private readonly HashSet<Assembly> _modAsms;

		private readonly int _maxDepth;

		private readonly int _maxVisits;

		private readonly int _maxPerCollection;

		private readonly HashSet<object> _seen = new HashSet<object>(ReferenceComparer.Instance);

		public int Visits { get; private set; }

		public ObjectWalk(IWalkVisitor visitor, HashSet<Assembly> modAsms, int maxDepth = 5, int maxVisits = 300000, int maxPerCollection = 20000)
		{
			_visitor = visitor;
			_modAsms = modAsms;
			_maxDepth = maxDepth;
			_maxVisits = maxVisits;
			_maxPerCollection = maxPerCollection;
		}

		public bool FirstVisit(object o)
		{
			return _seen.Add(o);
		}

		public bool IsModType(Type t)
		{
			return _modAsms.Contains(t.Assembly);
		}

		public static bool Worth(Type t)
		{
			if (!t.IsPrimitive && !t.IsEnum && !(t == typeof(string)) && !(t == typeof(decimal)) && !(t == typeof(DateTime)) && !typeof(Delegate).IsAssignableFrom(t) && !t.IsPointer && !(t == typeof(Type)))
			{
				return !typeof(MemberInfo).IsAssignableFrom(t);
			}
			return false;
		}

		public void Walk(object v, string plugin, string source, int depth = 0)
		{
			if (v == null || depth > _maxDepth || Visits > _maxVisits)
			{
				return;
			}
			Type type = v.GetType();
			if (!type.IsClass || !Worth(type) || !_visitor.Enter(v, plugin, source) || !_seen.Add(v))
			{
				return;
			}
			Visits++;
			if (v is IDictionary dictionary)
			{
				int num = 0;
				{
					foreach (DictionaryEntry item in dictionary)
					{
						if (++num > _maxPerCollection)
						{
							break;
						}
						Walk(item.Value, plugin, source, depth + 1);
					}
					return;
				}
			}
			if (v is IEnumerable enumerable)
			{
				int num2 = 0;
				{
					foreach (object item2 in enumerable)
					{
						if (++num2 > _maxPerCollection)
						{
							break;
						}
						Walk(item2, plugin, source, depth + 1);
					}
					return;
				}
			}
			if (!IsModType(type))
			{
				return;
			}
			string source2 = _visitor.SourceOf(v) ?? source;
			for (Type type2 = type; type2 != null && type2 != typeof(object) && IsModType(type2); type2 = type2.BaseType)
			{
				FieldInfo[] fields;
				try
				{
					fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				}
				catch
				{
					continue;
				}
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					if (Worth(fieldInfo.FieldType))
					{
						object value;
						try
						{
							value = fieldInfo.GetValue(v);
						}
						catch
						{
							continue;
						}
						Walk(value, plugin, source2, depth + 1);
					}
				}
			}
		}
	}
	internal static class ModNames
	{
		public static string Pick(bool runtime, string sourceMod, string bundleOwner, string plugin)
		{
			if (!runtime && bundleOwner == null)
			{
				return null;
			}
			return sourceMod ?? bundleOwner ?? plugin ?? "Unknown mod";
		}
	}
	internal sealed class ReferenceComparer : IEqualityComparer<object>
	{
		public static readonly ReferenceComparer Instance = new ReferenceComparer();

		private ReferenceComparer()
		{
		}

		bool IEqualityComparer<object>.Equals(object a, object b)
		{
			return a == b;
		}

		int IEqualityComparer<object>.GetHashCode(object o)
		{
			return RuntimeHelpers.GetHashCode(o);
		}
	}
	internal static class Rows
	{
		public static object[] Requirement(string kind, string key, float need, int op, int mod, string itemToken)
		{
			return new object[6] { kind, key, need, op, mod, itemToken };
		}

		public static object[] Material(string token, int amount, bool upgradeOnly)
		{
			return new object[3]
			{
				token,
				amount,
				upgradeOnly ? 1 : 0
			};
		}

		public static object[] Creature(string token, string prefab, int naturalBiomes, int raidBiomes, bool boss, HashSet<string> raids)
		{
			return new object[6] { token, prefab, naturalBiomes, raidBiomes, boss, raids };
		}

		public static string[] Cook(string output, string station, string input, string seconds, bool fuel, string prefab)
		{
			return new string[6]
			{
				output,
				station,
				input,
				seconds,
				fuel ? "1" : "0",
				prefab
			};
		}

		public static string[] Ferment(string output, string station, string input, string produced, string prefab)
		{
			return new string[5] { output, station, input, produced, prefab };
		}

		public static string[] Smelt(string output, string station, string input, string prefab)
		{
			return new string[4] { output, station, input, prefab };
		}

		public static object[] Achievement(bool unlocked, float[] values, Dictionary<int, float> raw)
		{
			return new object[3] { unlocked, values, raw };
		}

		public static object[] Slot(string itemPrefab, int status, string displayName)
		{
			return new object[3] { itemPrefab, status, displayName };
		}

		public static object[] AvailItem(bool canCraftNow, bool materials, bool known, List<string> undiscovered, int stationLevelKnown)
		{
			return new object[5] { canCraftNow, materials, known, undiscovered, stationLevelKnown };
		}

		public static object[] AvailPiece(bool canBuildNow, bool stationInRange, bool materials, bool known, List<string> undiscovered)
		{
			return new object[5] { canBuildNow, stationInRange, materials, known, undiscovered };
		}

		public static object[] KnownItem(bool known, List<string> undiscovered, int stationLevelKnown)
		{
			return new object[3] { known, undiscovered, stationLevelKnown };
		}

		public static object[] KnownPiece(bool known, List<string> undiscovered)
		{
			return new object[2] { known, undiscovered };
		}
	}
	internal sealed record Spawner(string Prefab, int Biome, bool Gated);
	internal sealed record RaidSpawn(string Prefab, int Biome, string Event);
	internal static class SpawnBiomes
	{
		public static bool IsGated(string requiredPersistentEvent, string requiredGlobalKey)
		{
			if (string.IsNullOrEmpty(requiredPersistentEvent))
			{
				return (requiredGlobalKey ?? "").StartsWith("defeated_", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}

		public static Dictionary<string, int> Natural(IEnumerable<Spawner> spawners)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			Dictionary<string, int> dictionary2 = new Dictionary<string, int>();
			foreach (Spawner spawner in spawners)
			{
				Dictionary<string, int> dictionary3 = (spawner.Gated ? dictionary2 : dictionary);
				dictionary3[spawner.Prefab] = (dictionary3.TryGetValue(spawner.Prefab, out var value) ? value : 0) | spawner.Biome;
			}
			foreach (KeyValuePair<string, int> item in dictionary2)
			{
				if (!dictionary.ContainsKey(item.Key))
				{
					dictionary[item.Key] = ((item.Value != -1) ? item.Value : 0);
				}
			}
			return dictionary;
		}

		public static Dictionary<string, int> Raids(IEnumerable<RaidSpawn> spawns, Dictionary<string, HashSet<string>> names)
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>();
			foreach (RaidSpawn spawn in spawns)
			{
				dictionary[spawn.Prefab] = (dictionary.TryGetValue(spawn.Prefab, out var value) ? value : 0) | spawn.Biome;
				if (!names.TryGetValue(spawn.Prefab, out var value2))
				{
					value2 = (names[spawn.Prefab] = new HashSet<string>());
				}
				value2.Add(spawn.Event);
			}
			return dictionary;
		}
	}
	internal sealed record State(bool Ok, int CatalogV, string Time, string Player, string World, string CurrentDiff, CheatInfo Cheat, List<object[]> Ach, Dictionary<string, float> Current, Dictionary<string, int> Inv, List<StationInfo> Stations, AvailabilityInfo Avail, Dictionary<string, float> ChestDist, KnownRecipes Known, Perf Perf);
	internal sealed record NotReady(bool Ok, string Reason, int CatalogV);
	internal sealed record CheatInfo(bool CanGet, bool UsedCheats, bool CheatedItem, bool Modded);
	internal sealed record Perf(float TickMs, float MaxTickMs, float CatalogMs, float AvailMs, int Bytes);
	internal sealed record StationInfo(string Type, string Name, string Prefab, float Dist, bool Owner, string OwnerName, [property: JsonProperty(/*Could not decode attribute arguments.*/)] int? Level, [property: JsonProperty(/*Could not decode attribute arguments.*/)] List<object[]> Slots);
	internal static class StationOwners
	{
		public static Dictionary<long, string> Names(IEnumerable<KeyValuePair<long, string>> players, long? serverId)
		{
			Dictionary<long, string> dictionary = new Dictionary<long, string>();
			foreach (KeyValuePair<long, string> player in players)
			{
				dictionary[player.Key] = player.Value;
			}
			if (serverId.HasValue)
			{
				long valueOrDefault = serverId.GetValueOrDefault();
				if (!dictionary.ContainsKey(valueOrDefault))
				{
					dictionary[valueOrDefault] = "the server";
				}
			}
			return dictionary;
		}

		public static string Label(long ownerId, long myId, IReadOnlyDictionary<long, string> names)
		{
			if (ownerId != 0L)
			{
				if (ownerId != myId)
				{
					if (!names.TryGetValue(ownerId, out var value))
					{
						return "unknown (" + ownerId + ")";
					}
					return value;
				}
				return "you";
			}
			return "nobody";
		}
	}
	internal static class BuildInfo
	{
		internal const string Version = "1.1.0";
	}
}