Decompiled source of Flap Spyglass v1.0.0

plugins/Spyglass.dll

Decompiled 4 days ago
using System;
using System.Collections;
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.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using HeaveHo.Shared;
using Microsoft.CodeAnalysis;
using Nick.Shared;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyMetadata("AI_Assisted_Creation", "This assembly was partially or fully created with the assistance of Generative AI.")]
[assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[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;
		}
	}
}
internal sealed class ConfigurationManagerAttributes
{
	public bool? IsAdvanced;
}
namespace HeaveHo.Shared
{
	internal sealed class ServerSettings : IDisposable
	{
		public enum ServerMod
		{
			NotConnected,
			Checking,
			Installed,
			Missing
		}

		private sealed class ConfigurationManagerAttributes
		{
			public bool? ReadOnly;
		}

		private sealed class SyncedText
		{
			public string Key;

			public Func<string> Own;

			public Action<string> Use;

			public string Given;

			public bool FromServer;

			public bool Pending;

			public byte[] Packed;

			public bool TooBig;

			public MemoryStream Incoming;

			public int NextPart;
		}

		private sealed class Sending
		{
			public ZRpc Rpc;

			public string Key;

			public byte[] Data;

			public int Next;

			public int Parts;
		}

		private const int Protocol = 2;

		private const float ChangeSendGap = 0.5f;

		private const float AnswerWait = 20f;

		private const float FileWait = 1f;

		private const int PartSize = 65536;

		private const int CompressFrom = 1024;

		private const int WarnBytes = 262144;

		private const int MaxBytes = 8388608;

		private const int PaceBelow = 10240;

		private readonly string _send;

		private readonly string _ask;

		private readonly string _dAsk;

		private readonly string _dHello;

		private readonly string _dSend;

		private readonly string _edit;

		private readonly string _dTextAsk;

		private readonly string _dText;

		private readonly string _dAgain;

		private readonly ConfigFile _config;

		private readonly ManualLogSource _log;

		private readonly string _name;

		private readonly List<ConfigEntryBase> _entries = new List<ConfigEntryBase>();

		private readonly Dictionary<ConfigEntryBase, object> _own = new Dictionary<ConfigEntryBase, object>();

		private readonly Dictionary<ConfigEntryBase, object> _server = new Dictionary<ConfigEntryBase, object>();

		private readonly List<GameObject> _guardedPieces = new List<GameObject>();

		private readonly List<Recipe> _guardedRecipes = new List<Recipe>();

		private ZRoutedRpc _registeredOn;

		private bool _applying;

		private bool _reloading;

		private bool _changePending;

		private float _nextChangeSend;

		private float _askedAt = -1f;

		private int _serverProtocol;

		private bool _directSeen;

		private readonly HashSet<ZRpc> _directPeers = new HashSet<ZRpc>();

		private readonly List<SyncedText> _texts = new List<SyncedText>();

		private readonly Dictionary<ZRpc, HashSet<string>> _textPeers = new Dictionary<ZRpc, HashSet<string>>();

		private bool _textPending;

		private float _nextTextSend;

		private bool _readOnlyShown;

		private float _nextAdminCheck;

		private FileSystemWatcher _watcher;

		private volatile bool _fileTouched;

		private float _reloadAt = -1f;

		private string _fileText;

		private readonly List<Sending> _outbox = new List<Sending>();

		private static readonly MethodInfo UpdateAvailablePieces = AccessTools.Method(typeof(Player), "UpdateAvailablePiecesList", (Type[])null, (Type[])null);

		private static readonly List<ServerSettings> Live = new List<ServerSettings>();

		private static Harmony _saveHarmony;

		public string Version { get; }

		public bool FromServer => _server.Count > 0;

		public ServerMod Server { get; private set; }

		public string ServerVersion { get; private set; }

		public bool CanEditServer
		{
			get
			{
				if (!IsServer)
				{
					if (Server == ServerMod.Installed && _serverProtocol >= 1 && (Object)(object)ZNet.instance != (Object)null)
					{
						return ZNet.instance.LocalPlayerIsAdminOrHost();
					}
					return false;
				}
				return true;
			}
		}

		private static bool IsServer
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return ZNet.instance.IsServer();
				}
				return false;
			}
		}

		public event Action ServerChanged;

		public ServerSettings(string guid, ConfigFile config, ManualLogSource log)
		{
			_send = guid + ".settings";
			_ask = guid + ".settings.ask";
			_dAsk = guid + ".settings.d.ask";
			_dHello = guid + ".settings.d.hello";
			_dSend = guid + ".settings.d.values";
			_edit = guid + ".settings.d.edit";
			_dTextAsk = guid + ".settings.d.textask";
			_dAgain = guid + ".settings.d.again";
			_dText = guid + ".settings.d.text";
			_config = config;
			_log = log;
			BepInPlugin val = PluginOf(guid);
			_name = ((val != null) ? val.Name : null) ?? guid;
			Version = ((val == null) ? null : val.Version?.ToString()) ?? "";
			Live.Add(this);
			if (Live.Count == 1)
			{
				PatchSave();
			}
			WatchFile();
		}

		public ConfigEntry<T> Add<T>(ConfigEntry<T> entry)
		{
			if (entry == null || _entries.Contains((ConfigEntryBase)(object)entry))
			{
				return entry;
			}
			_entries.Add((ConfigEntryBase)(object)entry);
			entry.SettingChanged += OnChanged;
			GiveManagerAttributes((ConfigEntryBase)(object)entry);
			return entry;
		}

		private static void GiveManagerAttributes(ConfigEntryBase entry)
		{
			ConfigDescription description = entry.Description;
			if (description == null || description == ConfigDescription.Empty || (description.Tags ?? new object[0]).Any(IsManagerAttributes))
			{
				return;
			}
			try
			{
				object[] value = new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(description.Tags ?? new object[0]).ToArray();
				AccessTools.Field(typeof(ConfigDescription), "<Tags>k__BackingField")?.SetValue(description, value);
			}
			catch (Exception)
			{
			}
		}

		public ConfigEntry<T> Bind<T>(string section, string key, T value, string description, AcceptableValueBase range = null, params object[] tags)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			if (!description.Contains("[Synced with Server]"))
			{
				description += " [Synced with Server]";
			}
			return Add<T>(_config.Bind<T>(section, key, value, new ConfigDescription(description, range, tags ?? new object[0])));
		}

		public void NeedsServer(GameObject piecePrefab)
		{
			if (!((Object)(object)piecePrefab == (Object)null))
			{
				_guardedPieces.RemoveAll((GameObject p) => (Object)(object)p == (Object)null || ((Object)p).name == ((Object)piecePrefab).name);
				_guardedPieces.Add(piecePrefab);
				Guard();
			}
		}

		public void NeedsServer(Recipe recipe)
		{
			if (!((Object)(object)recipe == (Object)null))
			{
				_guardedRecipes.RemoveAll((Recipe r) => (Object)(object)r == (Object)null || (Object)(object)r == (Object)(object)recipe || (!string.IsNullOrEmpty(((Object)recipe).name) && ((Object)r).name == ((Object)recipe).name));
				_guardedRecipes.Add(recipe);
				Guard();
			}
		}

		public void AddText(string key, Func<string> own, Action<string> use)
		{
			if (string.IsNullOrEmpty(key) || own == null || use == null)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogError((object)"AddText needs a key, own and use");
				}
				return;
			}
			_texts.RemoveAll((SyncedText x) => x.Key == key);
			SyncedText syncedText = new SyncedText
			{
				Key = key,
				Own = own,
				Use = use
			};
			_texts.Add(syncedText);
			Give(syncedText, OwnText(syncedText));
			ZRpc val = ((!((Object)(object)ZNet.instance != (Object)null) || IsServer) ? null : ZNet.instance.GetServerPeer()?.m_rpc);
			if (_registeredOn != null && val != null)
			{
				val.Register<ZPackage>(_dText, (Action<ZRpc, ZPackage>)OnText);
				AskTexts(val);
			}
		}

		public void TextChanged(string key)
		{
			SyncedText syncedText = _texts.FirstOrDefault((SyncedText x) => x.Key == key);
			if (syncedText != null)
			{
				syncedText.Packed = null;
				if (!syncedText.FromServer)
				{
					Give(syncedText, OwnText(syncedText));
				}
				if (IsServer)
				{
					syncedText.Pending = true;
					_textPending = true;
				}
			}
		}

		public bool TextFromServer(string key)
		{
			return _texts.Any((SyncedText x) => x.Key == key && x.FromServer);
		}

		public void Update()
		{
			ZRoutedRpc instance = ZRoutedRpc.instance;
			if (instance != _registeredOn)
			{
				Unregister();
				Restore();
				RestoreTexts(give: true);
				_changePending = false;
				_textPending = false;
				SetServer(ServerMod.NotConnected, null, 0);
				if (instance != null)
				{
					Register(instance);
				}
			}
			float unscaledTime = Time.unscaledTime;
			if (_changePending && unscaledTime >= _nextChangeSend)
			{
				SendChange();
			}
			if (_textPending && unscaledTime >= _nextTextSend)
			{
				SendTexts();
			}
			if (_outbox.Count > 0)
			{
				Pump();
			}
			if (Server == ServerMod.Checking && _askedAt >= 0f && unscaledTime - _askedAt > 20f)
			{
				if (_guardedPieces.Count + _guardedRecipes.Count > 0)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)("The server didn't answer: " + _name + " isn't installed there (or its copy is older than 2026-10-11), so its pieces and items can't be made on this server."));
					}
				}
				else
				{
					ManualLogSource log2 = _log;
					if (log2 != null)
					{
						log2.LogInfo((object)("The server didn't answer: " + _name + " isn't installed there, or its copy is older" + (FromServer ? " (its settings apply)." : " (your own settings apply).")));
					}
				}
				SetServer(ServerMod.Missing, null, 0);
			}
			if (_fileTouched)
			{
				_fileTouched = false;
				_reloadAt = unscaledTime + 1f;
			}
			if (_reloadAt >= 0f && unscaledTime >= _reloadAt)
			{
				_reloadAt = -1f;
				ReloadFile();
			}
			if (FromServer && unscaledTime >= _nextAdminCheck)
			{
				_nextAdminCheck = unscaledTime + 1f;
				ShowReadOnly();
			}
		}

		public void Dispose()
		{
			Unregister();
			Restore();
			RestoreTexts(give: false);
			SetServer(ServerMod.NotConnected, null, 0);
			foreach (ConfigEntryBase entry in _entries)
			{
				Unsubscribe(entry);
			}
			_entries.Clear();
			_texts.Clear();
			try
			{
				_watcher?.Dispose();
			}
			catch (Exception)
			{
			}
			_watcher = null;
			Live.Remove(this);
			if (Live.Count == 0)
			{
				UnpatchSave();
			}
		}

		private void Register(ZRoutedRpc rpc)
		{
			Forget(rpc, _send);
			Forget(rpc, _ask);
			rpc.Register<ZPackage>(_send, (Action<long, ZPackage>)OnRoutedValues);
			rpc.Register(_ask, (Action<long>)OnRoutedAsk);
			rpc.m_onNewPeer = (Action<long>)Delegate.Combine(rpc.m_onNewPeer, new Action<long>(OnNewPeer));
			_registeredOn = rpc;
			if (IsServer)
			{
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					ListenTo(peer);
					if (peer != null)
					{
						ZRpc rpc2 = peer.m_rpc;
						if (rpc2 != null)
						{
							rpc2.Invoke(_dAgain, Array.Empty<object>());
						}
					}
				}
				return;
			}
			if ((Object)(object)ZNet.instance != (Object)null)
			{
				SetServer(ServerMod.Checking, null, 0);
				if (ZNet.instance.GetServerPeer() != null)
				{
					AskServer();
				}
			}
		}

		private void Unregister()
		{
			if (_registeredOn == null)
			{
				return;
			}
			ZRoutedRpc registeredOn = _registeredOn;
			registeredOn.m_onNewPeer = (Action<long>)Delegate.Remove(registeredOn.m_onNewPeer, new Action<long>(OnNewPeer));
			Forget(_registeredOn, _send);
			Forget(_registeredOn, _ask);
			if ((Object)(object)ZNet.instance != (Object)null)
			{
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer?.m_rpc != null)
					{
						string[] array = new string[7] { _dAsk, _dHello, _dSend, _edit, _dTextAsk, _dText, _dAgain };
						foreach (string name in array)
						{
							ForgetDirect(peer.m_rpc, name);
						}
					}
				}
			}
			_directPeers.Clear();
			_textPeers.Clear();
			_outbox.Clear();
			_directSeen = false;
			_registeredOn = null;
		}

		private static void Forget(ZRoutedRpc rpc, string name)
		{
			if (AccessTools.Field(typeof(ZRoutedRpc), "m_functions")?.GetValue(rpc) is IDictionary dictionary)
			{
				dictionary.Remove(StringExtensionMethods.GetStableHashCode(name));
			}
		}

		private static void ForgetDirect(ZRpc rpc, string name)
		{
			if (AccessTools.Field(typeof(ZRpc), "m_functions")?.GetValue(rpc) is IDictionary dictionary)
			{
				dictionary.Remove(StringExtensionMethods.GetStableHashCode(name));
			}
		}

		private void OnNewPeer(long uid)
		{
			if (IsServer)
			{
				ZNetPeer peer = ZNet.instance.GetPeer(uid);
				ListenTo(peer);
				if (peer?.m_rpc != null)
				{
					SendDirect(peer.m_rpc);
				}
				SendRouted(uid);
			}
			else if ((Object)(object)ZNet.instance != (Object)null)
			{
				ZNetPeer serverPeer = ZNet.instance.GetServerPeer();
				if (serverPeer != null && serverPeer.m_uid == uid)
				{
					AskServer();
				}
			}
		}

		private void ListenTo(ZNetPeer peer)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if (peer?.m_rpc != null)
			{
				peer.m_rpc.Register(_dAsk, new Method(OnDirectAsk));
				peer.m_rpc.Register<ZPackage>(_edit, (Action<ZRpc, ZPackage>)OnEdit);
				peer.m_rpc.Register<ZPackage>(_dTextAsk, (Action<ZRpc, ZPackage>)OnTextAsk);
			}
		}

		private void OnDirectAsk(ZRpc rpc)
		{
			if (IsServer)
			{
				_directPeers.Add(rpc);
				SendDirect(rpc);
			}
		}

		private void OnRoutedAsk(long sender)
		{
			if (IsServer)
			{
				SendRouted(sender);
			}
		}

		private void SendDirect(ZRpc rpc)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(2);
			val.Write(Version);
			rpc.Invoke(_dHello, new object[1] { val });
			if (_entries.Count > 0)
			{
				rpc.Invoke(_dSend, new object[1] { Values() });
			}
		}

		private void SendRouted(long target)
		{
			if (ZRoutedRpc.instance != null && _entries.Count > 0)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(target, _send, new object[1] { Values() });
			}
		}

		private ZPackage Values()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			ZPackage val = new ZPackage();
			val.Write(_entries.Count);
			foreach (ConfigEntryBase entry in _entries)
			{
				val.Write(entry.Definition.Section);
				val.Write(entry.Definition.Key);
				val.Write(TomlTypeConverter.ConvertToString(entry.BoxedValue, entry.SettingType));
			}
			return val;
		}

		private void AskServer()
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Expected O, but got Unknown
			ZNetPeer val = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetServerPeer() : null);
			if (val?.m_rpc == null)
			{
				return;
			}
			_askedAt = Time.unscaledTime;
			val.m_rpc.Register<ZPackage>(_dHello, (Action<ZRpc, ZPackage>)OnDirectHello);
			val.m_rpc.Register<ZPackage>(_dSend, (Action<ZRpc, ZPackage>)OnDirectValues);
			val.m_rpc.Register<ZPackage>(_dText, (Action<ZRpc, ZPackage>)OnText);
			val.m_rpc.Register(_dAgain, new Method(OnAskAgain));
			val.m_rpc.Invoke(_dAsk, Array.Empty<object>());
			AskTexts(val.m_rpc);
			try
			{
				ZRoutedRpc instance = ZRoutedRpc.instance;
				if (instance != null)
				{
					instance.InvokeRoutedRPC(val.m_uid, _ask, Array.Empty<object>());
				}
			}
			catch (Exception)
			{
			}
		}

		private static bool IsServerConnection(ZRpc rpc)
		{
			if (!IsServer)
			{
				ZNet instance = ZNet.instance;
				return ((instance == null) ? null : instance.GetServerPeer()?.m_rpc) == rpc;
			}
			return false;
		}

		private void OnAskAgain(ZRpc rpc)
		{
			if (IsServerConnection(rpc))
			{
				rpc.Invoke(_dAsk, Array.Empty<object>());
				AskTexts(rpc);
			}
		}

		private void OnDirectHello(ZRpc rpc, ZPackage pkg)
		{
			if (!IsServerConnection(rpc))
			{
				return;
			}
			try
			{
				int protocol = pkg.ReadInt();
				string text = pkg.ReadString();
				if (text != Version && text != ServerVersion)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)("The server has " + _name + " " + text + ", you have " + Version + ": some things may not match. Use the same version as the server."));
					}
				}
				_directSeen = true;
				SetServer(ServerMod.Installed, text, protocol);
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Could not read the server's hello: " + ex.Message));
				}
			}
		}

		private void OnDirectValues(ZRpc rpc, ZPackage pkg)
		{
			if (IsServerConnection(rpc))
			{
				TakeValues(pkg);
			}
		}

		private void OnRoutedValues(long sender, ZPackage pkg)
		{
			if (!_directSeen && !IsServer)
			{
				ZNetPeer val = (((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetServerPeer() : null);
				if (val != null && val.m_uid == sender)
				{
					TakeValues(pkg);
				}
			}
		}

		private void TakeValues(ZPackage pkg)
		{
			try
			{
				int num = pkg.ReadInt();
				List<string> list = new List<string>();
				for (int i = 0; i < num; i++)
				{
					string section = pkg.ReadString();
					string key = pkg.ReadString();
					string text = pkg.ReadString();
					ConfigEntryBase val = ((IEnumerable<ConfigEntryBase>)_entries).FirstOrDefault((Func<ConfigEntryBase, bool>)((ConfigEntryBase x) => x.Definition.Section == section && x.Definition.Key == key));
					if (val != null)
					{
						object obj;
						try
						{
							obj = TomlTypeConverter.ConvertToValue(text, val.SettingType);
						}
						catch (Exception)
						{
							continue;
						}
						if (!_own.ContainsKey(val))
						{
							_own[val] = val.BoxedValue;
						}
						_server[val] = obj;
						if (!object.Equals(val.BoxedValue, obj))
						{
							Apply(val, obj);
							list.Add(section + "/" + key + " = " + text);
						}
					}
				}
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogInfo((object)($"Settings from the server apply while you play here ({_server.Count})" + ((list.Count > 0) ? (": " + string.Join(", ", list.ToArray())) : "")));
				}
				ShowReadOnly();
			}
			catch (Exception ex2)
			{
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Could not read the server's settings: " + ex2.Message));
				}
			}
		}

		private void Apply(ConfigEntryBase e, object value)
		{
			bool saveOnConfigSet = _config.SaveOnConfigSet;
			_applying = true;
			try
			{
				_config.SaveOnConfigSet = false;
				e.BoxedValue = value;
			}
			finally
			{
				_config.SaveOnConfigSet = saveOnConfigSet;
				_applying = false;
			}
		}

		private void Restore()
		{
			if (_server.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<ConfigEntryBase, object> item in _own)
			{
				Apply(item.Key, item.Value);
			}
			_own.Clear();
			_server.Clear();
			ShowReadOnly();
			ManualLogSource log = _log;
			if (log != null)
			{
				log.LogInfo((object)"Your own settings apply again");
			}
		}

		private void OnChanged(object sender, EventArgs args)
		{
			if (_applying)
			{
				return;
			}
			ConfigEntryBase val = (ConfigEntryBase)((sender is ConfigEntryBase) ? sender : null);
			if (val == null)
			{
				return;
			}
			if (_server.TryGetValue(val, out var value))
			{
				if (!_reloading && CanEditServer)
				{
					SendEdit(val);
				}
				else
				{
					_own[val] = val.BoxedValue;
				}
				Apply(val, value);
			}
			else if (IsServer)
			{
				_changePending = true;
				if (Time.unscaledTime >= _nextChangeSend)
				{
					SendChange();
				}
			}
		}

		private void SendChange()
		{
			_changePending = false;
			_nextChangeSend = Time.unscaledTime + 0.5f;
			if (!IsServer)
			{
				return;
			}
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer?.m_rpc == null)
				{
					continue;
				}
				if (_directPeers.Contains(peer.m_rpc))
				{
					if (_entries.Count > 0)
					{
						peer.m_rpc.Invoke(_dSend, new object[1] { Values() });
					}
				}
				else
				{
					SendRouted(peer.m_uid);
				}
			}
		}

		private void SendEdit(ConfigEntryBase e)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			ZNet instance = ZNet.instance;
			ZNetPeer val = ((instance != null) ? instance.GetServerPeer() : null);
			if (val?.m_rpc != null)
			{
				ZPackage val2 = new ZPackage();
				val2.Write(e.Definition.Section);
				val2.Write(e.Definition.Key);
				val2.Write(TomlTypeConverter.ConvertToString(e.BoxedValue, e.SettingType));
				val.m_rpc.Invoke(_edit, new object[1] { val2 });
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogInfo((object)("Asked the server to set " + e.Definition.Section + "/" + e.Definition.Key));
				}
			}
		}

		private void OnEdit(ZRpc rpc, ZPackage pkg)
		{
			try
			{
				if (!IsServer)
				{
					return;
				}
				ISocket socket = rpc.GetSocket();
				string text = ((socket != null) ? socket.GetHostName() : null) ?? "";
				ZNetPeer val = ((IEnumerable<ZNetPeer>)ZNet.instance.GetPeers()).FirstOrDefault((Func<ZNetPeer, bool>)((ZNetPeer p) => p.m_rpc == rpc));
				string section = pkg.ReadString();
				string key = pkg.ReadString();
				string text2 = pkg.ReadString();
				if (!ZNet.instance.IsAdmin(text))
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)((val?.m_playerName ?? text) + " tried to change " + section + "/" + key + " but isn't on the admin list"));
					}
					if (_entries.Count > 0)
					{
						rpc.Invoke(_dSend, new object[1] { Values() });
					}
					return;
				}
				ConfigEntryBase val2 = ((IEnumerable<ConfigEntryBase>)_entries).FirstOrDefault((Func<ConfigEntryBase, bool>)((ConfigEntryBase x) => x.Definition.Section == section && x.Definition.Key == key));
				if (val2 != null)
				{
					val2.BoxedValue = TomlTypeConverter.ConvertToValue(text2, val2.SettingType);
					ManualLogSource log2 = _log;
					if (log2 != null)
					{
						log2.LogInfo((object)("Admin " + (val?.m_playerName ?? text) + " set " + section + "/" + key + " = " + text2));
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log3 = _log;
				if (log3 != null)
				{
					log3.LogWarning((object)("Could not take an admin's change: " + ex.Message));
				}
			}
		}

		private void ShowReadOnly()
		{
			bool flag = FromServer && !CanEditServer;
			if (flag == _readOnlyShown)
			{
				return;
			}
			_readOnlyShown = flag;
			foreach (ConfigEntryBase entry in _entries)
			{
				ConfigDescription description = entry.Description;
				object[] array = ((description != null) ? description.Tags : null) ?? new object[0];
				foreach (object obj in array)
				{
					if (IsManagerAttributes(obj))
					{
						try
						{
							AccessTools.Field(obj.GetType(), "ReadOnly")?.SetValue(obj, flag ? ((object)true) : null);
						}
						catch (Exception)
						{
						}
					}
				}
			}
		}

		private static bool IsManagerAttributes(object tag)
		{
			if (tag != null)
			{
				return tag.GetType().Name == "ConfigurationManagerAttributes";
			}
			return false;
		}

		private string OwnText(SyncedText t)
		{
			try
			{
				return t.Own() ?? "";
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Could not read " + t.Key + ": " + ex.Message));
				}
				return t.Given ?? "";
			}
		}

		private void Give(SyncedText t, string text)
		{
			if (t.Given != null && t.Given == text)
			{
				return;
			}
			t.Given = text;
			try
			{
				t.Use(text);
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Could not use " + t.Key + ": " + ex));
				}
			}
		}

		private void RestoreTexts(bool give)
		{
			foreach (SyncedText text in _texts)
			{
				text.Incoming = null;
				if (!text.FromServer)
				{
					continue;
				}
				text.FromServer = false;
				if (give)
				{
					Give(text, OwnText(text));
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogInfo((object)("Your own " + text.Key + " applies again"));
					}
				}
			}
		}

		private void AskTexts(ZRpc server)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			if (_texts.Count == 0 || server == null)
			{
				return;
			}
			ZPackage val = new ZPackage();
			val.Write(_texts.Count);
			foreach (SyncedText text in _texts)
			{
				val.Write(text.Key);
			}
			server.Invoke(_dTextAsk, new object[1] { val });
		}

		private void OnTextAsk(ZRpc rpc, ZPackage pkg)
		{
			try
			{
				if (!IsServer)
				{
					return;
				}
				int num = pkg.ReadInt();
				HashSet<string> hashSet = new HashSet<string>();
				for (int i = 0; i < num && i < 1000; i++)
				{
					string key = pkg.ReadString();
					if (_texts.Any((SyncedText x) => x.Key == key))
					{
						hashSet.Add(key);
					}
				}
				if (_textPeers.TryGetValue(rpc, out var value))
				{
					hashSet.UnionWith(value);
				}
				foreach (ZRpc item in _textPeers.Keys.Where((ZRpc r) => !r.IsConnected()).ToList())
				{
					_textPeers.Remove(item);
				}
				_textPeers[rpc] = hashSet;
				foreach (SyncedText text in _texts)
				{
					if (hashSet.Contains(text.Key))
					{
						SendText(rpc, text);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Could not answer a player's ask for server data: " + ex.Message));
				}
			}
		}

		private void SendTexts()
		{
			_textPending = false;
			_nextTextSend = Time.unscaledTime + 0.5f;
			if (!IsServer)
			{
				return;
			}
			foreach (SyncedText text in _texts)
			{
				if (!text.Pending)
				{
					continue;
				}
				text.Pending = false;
				foreach (ZNetPeer peer in ZNet.instance.GetPeers())
				{
					if (peer?.m_rpc != null && _textPeers.TryGetValue(peer.m_rpc, out var value) && value.Contains(text.Key))
					{
						SendText(peer.m_rpc, text);
					}
				}
			}
		}

		private void SendText(ZRpc rpc, SyncedText t)
		{
			byte[] array = Packed(t);
			if (array != null)
			{
				_outbox.RemoveAll((Sending s) => s.Rpc == rpc && s.Key == t.Key);
				_outbox.Add(new Sending
				{
					Rpc = rpc,
					Key = t.Key,
					Data = array,
					Parts = Math.Max(1, (array.Length + 65536 - 1) / 65536)
				});
				Pump();
			}
		}

		private void Pump()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Expected O, but got Unknown
			for (int num = _outbox.Count - 1; num >= 0; num--)
			{
				Sending sending = _outbox[num];
				try
				{
					while (sending.Next < sending.Parts && sending.Rpc.IsConnected() && sending.Rpc.GetSocket().GetSendQueueSize() < 10240)
					{
						int num2 = sending.Next * 65536;
						int num3 = Math.Min(65536, sending.Data.Length - num2);
						byte[] array = new byte[num3];
						Buffer.BlockCopy(sending.Data, num2, array, 0, num3);
						ZPackage val = new ZPackage();
						val.Write(sending.Key);
						val.Write(sending.Next);
						val.Write(sending.Parts);
						val.Write(array);
						sending.Rpc.Invoke(_dText, new object[1] { val });
						sending.Next++;
					}
					if (sending.Next >= sending.Parts || !sending.Rpc.IsConnected())
					{
						_outbox.RemoveAt(num);
					}
				}
				catch (Exception ex)
				{
					_outbox.RemoveAt(num);
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)("Could not send " + sending.Key + " to a player: " + ex.Message));
					}
				}
			}
		}

		private byte[] Packed(SyncedText t)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if (t.Packed == null)
			{
				string text = OwnText(t);
				ZPackage val = new ZPackage();
				val.Write(text);
				ZPackage val2 = new ZPackage();
				bool flag = text.Length > 1024;
				val2.Write(flag);
				if (flag)
				{
					val2.WriteCompressed(val);
				}
				else
				{
					val2.Write(val);
				}
				t.Packed = val2.GetArray();
				t.TooBig = t.Packed.Length > 8388608;
				string arg = $"{t.Packed.Length / 1024} KB" + (flag ? $" gzipped ({text.Length / 1024} KB of text)" : "");
				if (t.TooBig)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogError((object)$"{t.Key} is too big to send to players ({arg}, at most {8} MB): they keep their own.");
					}
				}
				else if (t.Packed.Length > 262144)
				{
					ManualLogSource log2 = _log;
					if (log2 != null)
					{
						log2.LogWarning((object)$"{t.Key} is big to send to every player who joins ({arg}): it takes about {(float)t.Packed.Length / 153600f:0} s of their connection, and their world loads slower meanwhile.");
					}
				}
			}
			if (!t.TooBig)
			{
				return t.Packed;
			}
			return null;
		}

		private void OnText(ZRpc rpc, ZPackage pkg)
		{
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			if (!IsServerConnection(rpc))
			{
				return;
			}
			SyncedText syncedText = null;
			try
			{
				string key = pkg.ReadString();
				int num = pkg.ReadInt();
				int num2 = pkg.ReadInt();
				byte[] array = pkg.ReadByteArray();
				syncedText = _texts.FirstOrDefault((SyncedText x) => x.Key == key);
				if (syncedText == null)
				{
					return;
				}
				if (num2 < 1 || num2 > 129 || num < 0 || num >= num2)
				{
					throw new InvalidDataException($"part {num} of {num2}");
				}
				if (num == 0)
				{
					syncedText.Incoming = new MemoryStream();
					syncedText.NextPart = 0;
				}
				if (syncedText.Incoming == null || num != syncedText.NextPart)
				{
					throw new InvalidDataException($"part {num} came out of order");
				}
				syncedText.Incoming.Write(array, 0, array.Length);
				syncedText.NextPart = num + 1;
				if (num >= num2 - 1)
				{
					ZPackage val = new ZPackage(syncedText.Incoming.ToArray());
					syncedText.Incoming = null;
					ZPackage val2 = (val.ReadBool() ? val.ReadCompressedPackage() : val.ReadPackage());
					string text = val2.ReadString();
					syncedText.FromServer = true;
					Give(syncedText, text);
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogInfo((object)$"The server's {key} applies while you play here ({text.Length / 1024} KB)");
					}
				}
			}
			catch (Exception ex)
			{
				if (syncedText != null)
				{
					syncedText.Incoming = null;
				}
				ManualLogSource log2 = _log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Could not read the server's data" + ((syncedText != null) ? (" for " + syncedText.Key) : "") + ": " + ex.Message));
				}
			}
		}

		private void SetServer(ServerMod state, string version, int protocol)
		{
			if (state != ServerMod.Checking)
			{
				_askedAt = -1f;
			}
			bool flag = state != Server || version != ServerVersion;
			Server = state;
			ServerVersion = version;
			_serverProtocol = protocol;
			if (!flag)
			{
				return;
			}
			Guard();
			try
			{
				this.ServerChanged?.Invoke();
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("ServerChanged: " + ex));
				}
			}
		}

		private void Guard()
		{
			bool flag = Server == ServerMod.NotConnected || Server == ServerMod.Installed;
			bool flag2 = false;
			foreach (GameObject guardedPiece in _guardedPieces)
			{
				Piece val = (((Object)(object)guardedPiece != (Object)null) ? guardedPiece.GetComponent<Piece>() : null);
				if ((Object)(object)val != (Object)null && val.m_enabled != flag)
				{
					val.m_enabled = flag;
					flag2 = true;
				}
			}
			foreach (Recipe guardedRecipe in _guardedRecipes)
			{
				if ((Object)(object)guardedRecipe != (Object)null && guardedRecipe.m_enabled != flag)
				{
					guardedRecipe.m_enabled = flag;
					flag2 = true;
				}
			}
			if (flag2 && (Object)(object)Player.m_localPlayer != (Object)null)
			{
				try
				{
					UpdateAvailablePieces?.Invoke(Player.m_localPlayer, null);
				}
				catch (Exception)
				{
				}
			}
		}

		private void WatchFile()
		{
			try
			{
				string configFilePath = _config.ConfigFilePath;
				_watcher = new FileSystemWatcher(Path.GetDirectoryName(configFilePath), Path.GetFileName(configFilePath))
				{
					NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite)
				};
				FileSystemEventHandler value = delegate
				{
					_fileTouched = true;
				};
				_watcher.Changed += value;
				_watcher.Created += value;
				_watcher.Renamed += delegate
				{
					_fileTouched = true;
				};
				_watcher.EnableRaisingEvents = true;
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Edits to the config file apply after a restart (can't watch it: " + ex.Message + ")"));
				}
			}
		}

		private void ReloadFile()
		{
			string text = ReadFile(_config.ConfigFilePath);
			if (text == null)
			{
				if (File.Exists(_config.ConfigFilePath))
				{
					_reloadAt = Time.unscaledTime + 1f;
				}
			}
			else
			{
				if (text == _fileText)
				{
					return;
				}
				_fileText = text;
				bool saveOnConfigSet = _config.SaveOnConfigSet;
				_reloading = true;
				try
				{
					_config.SaveOnConfigSet = false;
					_config.Reload();
				}
				catch (Exception ex)
				{
					ManualLogSource log = _log;
					if (log != null)
					{
						log.LogWarning((object)("Could not read the edited config file (check the line you changed): " + ex.Message));
					}
				}
				finally
				{
					_config.SaveOnConfigSet = saveOnConfigSet;
					_reloading = false;
				}
			}
		}

		private void PatchSave()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_0045: 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_0067: Expected O, but got Unknown
			//IL_0067: Expected O, but got Unknown
			try
			{
				_saveHarmony = new Harmony(_send + ".save");
				_saveHarmony.Patch((MethodBase)AccessTools.Method(typeof(ConfigFile), "Save", (Type[])null, (Type[])null), new HarmonyMethod(typeof(ServerSettings), "BeforeSave", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ServerSettings), "AfterSave", (Type[])null), (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogWarning((object)("Could not keep the server's values out of your config file: " + ex.Message));
				}
			}
		}

		private static void UnpatchSave()
		{
			try
			{
				Harmony saveHarmony = _saveHarmony;
				if (saveHarmony != null)
				{
					saveHarmony.UnpatchSelf();
				}
			}
			catch (Exception)
			{
			}
			_saveHarmony = null;
		}

		private static void BeforeSave(ConfigFile __instance)
		{
			foreach (ServerSettings item in Live)
			{
				if (item._config != __instance)
				{
					continue;
				}
				foreach (KeyValuePair<ConfigEntryBase, object> item2 in item._own)
				{
					SetQuietly(item2.Key, item2.Value);
				}
			}
		}

		private static Exception AfterSave(ConfigFile __instance, Exception __exception)
		{
			foreach (ServerSettings item in Live)
			{
				if (item._config != __instance)
				{
					continue;
				}
				foreach (KeyValuePair<ConfigEntryBase, object> item2 in item._server)
				{
					SetQuietly(item2.Key, item2.Value);
				}
				item._fileText = ReadFile(__instance.ConfigFilePath);
			}
			return __exception;
		}

		private static string ReadFile(string path)
		{
			try
			{
				return File.Exists(path) ? File.ReadAllText(path) : null;
			}
			catch (Exception)
			{
				return null;
			}
		}

		private static void SetQuietly(ConfigEntryBase e, object value)
		{
			AccessTools.Field(((object)e).GetType(), "_typedValue")?.SetValue(e, value);
		}

		private static BepInPlugin PluginOf(string guid)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			Type[] array;
			try
			{
				array = typeof(ServerSettings).Assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				array = ex.Types.Where((Type t) => t != null).ToArray();
			}
			Type[] array2 = array;
			foreach (Type type in array2)
			{
				object[] customAttributes = type.GetCustomAttributes(typeof(BepInPlugin), inherit: false);
				for (int num2 = 0; num2 < customAttributes.Length; num2++)
				{
					BepInPlugin val = (BepInPlugin)customAttributes[num2];
					if (val.GUID == guid || guid.StartsWith(val.GUID + "."))
					{
						return val;
					}
				}
			}
			return null;
		}

		private void Unsubscribe(ConfigEntryBase e)
		{
			((object)e).GetType().GetEvent("SettingChanged")?.RemoveEventHandler(e, new EventHandler(OnChanged));
		}
	}
}
namespace Spyglass
{
	internal static class Content
	{
		private class Sale
		{
			public string Trader;

			public TradeItem Item;

			public Func<bool> When;
		}

		private static readonly FieldInfo NamedField = AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs");

		private static readonly MethodInfo UpdateRegisters = AccessTools.Method(typeof(ObjectDB), "UpdateRegisters", (Type[])null, (Type[])null);

		private static readonly List<GameObject> OurItems = new List<GameObject>();

		private static readonly List<StatusEffect> OurEffects = new List<StatusEffect>();

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

		private static readonly List<(GameObject Station, string From, string To)> OurConversions = new List<(GameObject, string, string)>();

		private static readonly List<(GameObject Creature, string Item)> OurDrops = new List<(GameObject, string)>();

		private static readonly List<Sale> OurSales = new List<Sale>();

		private static Dictionary<int, GameObject> Named(ZNetScene scene)
		{
			return (Dictionary<int, GameObject>)NamedField.GetValue(scene);
		}

		private static bool Destroyed(Object o)
		{
			if (o != null)
			{
				return o == (Object)null;
			}
			return false;
		}

		public static void Item(GameObject prefab, ObjectDB db = null)
		{
			Items((IEnumerable<GameObject>)(object)new GameObject[1] { prefab }, db);
		}

		public static void Items(IEnumerable<GameObject> prefabs, ObjectDB db = null)
		{
			db = (((Object)(object)db != (Object)null) ? db : ObjectDB.instance);
			ZNetScene instance = ZNetScene.instance;
			bool flag = false;
			foreach (GameObject prefab in prefabs)
			{
				if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<ItemDrop>() == (Object)null)
				{
					continue;
				}
				if ((Object)(object)instance != (Object)null)
				{
					if (!instance.m_prefabs.Contains(prefab))
					{
						instance.m_prefabs.RemoveAll((GameObject p) => (Object)(object)p == (Object)null || ((Object)p).name == ((Object)prefab).name);
						instance.m_prefabs.Add(prefab);
					}
					Named(instance)[StringExtensionMethods.GetStableHashCode(((Object)prefab).name)] = prefab;
				}
				if ((Object)(object)db != (Object)null && !db.m_items.Contains(prefab))
				{
					db.m_items.RemoveAll((GameObject i) => (Object)(object)i == (Object)null || ((Object)i).name == ((Object)prefab).name);
					db.m_items.Add(prefab);
					flag = true;
				}
				if (!OurItems.Contains(prefab))
				{
					OurItems.Add(prefab);
				}
			}
			ItemExtras(prefabs, db);
			if (flag)
			{
				UpdateRegisters?.Invoke(db, null);
			}
		}

		public static void ItemExtras(IEnumerable<GameObject> prefabs, ObjectDB db = null)
		{
			db = (((Object)(object)db != (Object)null) ? db : ObjectDB.instance);
			foreach (GameObject prefab in prefabs)
			{
				ItemDrop val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				val.m_itemData.m_dropPrefab = prefab;
				if ((Object)(object)db == (Object)null)
				{
					continue;
				}
				SharedData shared = val.m_itemData.m_shared;
				StatusEffect[] array = (StatusEffect[])(object)new StatusEffect[4] { shared.m_consumeStatusEffect, shared.m_equipStatusEffect, shared.m_attackStatusEffect, shared.m_setStatusEffect };
				foreach (StatusEffect effect in array)
				{
					if ((Object)(object)effect == (Object)null)
					{
						continue;
					}
					if (!db.m_StatusEffects.Contains(effect))
					{
						db.m_StatusEffects.RemoveAll((StatusEffect e) => (Object)(object)e == (Object)null || ((Object)e).name == ((Object)effect).name);
						db.m_StatusEffects.Add(effect);
					}
					if (!OurEffects.Contains(effect))
					{
						OurEffects.Add(effect);
					}
				}
			}
		}

		public static void RemoveItems(IEnumerable<GameObject> prefabs)
		{
			ZNetScene instance = ZNetScene.instance;
			ObjectDB instance2 = ObjectDB.instance;
			HashSet<GameObject> gone = new HashSet<GameObject>(prefabs.Where((GameObject p) => p != null));
			foreach (GameObject item in gone)
			{
				OurItems.Remove(item);
				if ((Object)(object)instance != (Object)null)
				{
					instance.m_prefabs.Remove(item);
				}
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				if ((Object)(object)instance != (Object)null)
				{
					Dictionary<int, GameObject> dictionary = Named(instance);
					int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)item).name);
					if (dictionary.TryGetValue(stableHashCode, out var value) && (Object)(object)value == (Object)(object)item)
					{
						dictionary.Remove(stableHashCode);
					}
				}
				ItemDrop component = item.GetComponent<ItemDrop>();
				if (!((Object)(object)component != (Object)null) || !((Object)(object)instance2 != (Object)null))
				{
					continue;
				}
				SharedData shared = component.m_itemData.m_shared;
				StatusEffect[] array = (StatusEffect[])(object)new StatusEffect[4] { shared.m_consumeStatusEffect, shared.m_equipStatusEffect, shared.m_attackStatusEffect, shared.m_setStatusEffect };
				foreach (StatusEffect val in array)
				{
					if ((Object)(object)val != (Object)null && OurEffects.Remove(val))
					{
						instance2.m_StatusEffects.Remove(val);
					}
				}
			}
			if ((Object)(object)instance2 != (Object)null)
			{
				instance2.m_items.RemoveAll((GameObject i) => (Object)(object)i == (Object)null || gone.Contains(i));
				instance2.m_StatusEffects.RemoveAll((StatusEffect e) => (Object)(object)e == (Object)null);
				UpdateRegisters?.Invoke(instance2, null);
			}
		}

		public static Recipe Recipe(GameObject item, CraftingStation station, int level = 1, int amount = 1, Requirement[] cost = null, string costText = null, ManualLogSource log = null, string way = null, bool upgradeOnly = false, CraftingStation repairStation = null, ObjectDB db = null)
		{
			ItemDrop val = (((Object)(object)item != (Object)null) ? item.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			string name = "Recipe_" + ((Object)item).name + (string.IsNullOrEmpty(way) ? "" : ("_" + way));
			if (!OurRecipes.TryGetValue(name, out var value) || (Object)(object)value == (Object)null)
			{
				value = ScriptableObject.CreateInstance<Recipe>();
				((Object)value).name = name;
				value.m_item = val;
				value.m_amount = Mathf.Max(1, amount);
				value.m_craftingStation = station;
				value.m_repairStation = repairStation;
				value.m_minStationLevel = Mathf.Max(1, level);
				value.m_noCraftOnlyUpgrade = upgradeOnly;
				value.m_resources = (Requirement[])(((object)cost) ?? ((object)new Requirement[0]));
				if (costText != null)
				{
					Costs.Apply(value, costText, log);
				}
				OurRecipes[name] = value;
			}
			db = (((Object)(object)db != (Object)null) ? db : ObjectDB.instance);
			if ((Object)(object)db != (Object)null && !db.m_recipes.Contains(value))
			{
				db.m_recipes.RemoveAll((Recipe r) => (Object)(object)r == (Object)null || ((Object)r).name == name);
				db.m_recipes.Add(value);
			}
			return value;
		}

		public static void RemoveRecipe(Recipe recipe)
		{
			if (recipe == null)
			{
				return;
			}
			ObjectDB.instance?.m_recipes.RemoveAll((Recipe r) => (Object)(object)r == (Object)null || (Object)(object)r == (Object)(object)recipe);
			foreach (string item in (from kv in OurRecipes
				where (Object)(object)kv.Value == (Object)(object)recipe
				select kv.Key).ToList())
			{
				OurRecipes.Remove(item);
			}
			if ((Object)(object)recipe != (Object)null)
			{
				Object.Destroy((Object)(object)recipe);
			}
		}

		public static bool Conversion(GameObject stationPrefab, GameObject from, GameObject to, float cookSeconds = 10f, int makes = 4)
		{
			//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_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			ItemDrop val = (((Object)(object)from != (Object)null) ? from.GetComponent<ItemDrop>() : null);
			ItemDrop val2 = (((Object)(object)to != (Object)null) ? to.GetComponent<ItemDrop>() : null);
			if ((Object)(object)stationPrefab == (Object)null || (Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				return false;
			}
			RemoveConversion(stationPrefab, ((Object)from).name, ((Object)to).name, forget: false);
			bool flag = false;
			Smelter component = stationPrefab.GetComponent<Smelter>();
			if (component != null)
			{
				component.m_conversion.Add(new ItemConversion
				{
					m_from = val,
					m_to = val2
				});
				flag = true;
			}
			else
			{
				CookingStation component2 = stationPrefab.GetComponent<CookingStation>();
				if (component2 != null)
				{
					component2.m_conversion.Add(new ItemConversion
					{
						m_from = val,
						m_to = val2,
						m_cookTime = cookSeconds
					});
					flag = true;
				}
				else
				{
					Fermenter component3 = stationPrefab.GetComponent<Fermenter>();
					if (component3 != null)
					{
						component3.m_conversion.Add(new ItemConversion
						{
							m_from = val,
							m_to = val2,
							m_producedItems = Mathf.Max(1, makes)
						});
						flag = true;
					}
				}
			}
			if (flag && !OurConversions.Contains((stationPrefab, ((Object)from).name, ((Object)to).name)))
			{
				OurConversions.Add((stationPrefab, ((Object)from).name, ((Object)to).name));
			}
			return flag;
		}

		public static void RemoveConversion(GameObject stationPrefab, string from, string to)
		{
			RemoveConversion(stationPrefab, from, to, forget: true);
		}

		private static void RemoveConversion(GameObject stationPrefab, string from, string to, bool forget)
		{
			if (!((Object)(object)stationPrefab == (Object)null))
			{
				stationPrefab.GetComponent<Smelter>()?.m_conversion.RemoveAll((ItemConversion c) => c == null || Match(c.m_from, c.m_to));
				stationPrefab.GetComponent<CookingStation>()?.m_conversion.RemoveAll((ItemConversion c) => c == null || Match(c.m_from, c.m_to));
				stationPrefab.GetComponent<Fermenter>()?.m_conversion.RemoveAll((ItemConversion c) => c == null || Match(c.m_from, c.m_to));
				if (forget)
				{
					OurConversions.Remove((stationPrefab, from, to));
				}
			}
			bool Match(ItemDrop f, ItemDrop t)
			{
				if (!Destroyed((Object)(object)f) && !Destroyed((Object)(object)t))
				{
					if ((Object)(object)f != (Object)null && (Object)(object)t != (Object)null && ((Object)f).name == from)
					{
						return ((Object)t).name == to;
					}
					return false;
				}
				return true;
			}
		}

		public static Drop Drop(GameObject creaturePrefab, GameObject item, float chance = 1f, int min = 1, int max = 1, bool perLevel = true)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			if ((Object)(object)creaturePrefab == (Object)null || (Object)(object)item == (Object)null)
			{
				return null;
			}
			CharacterDrop val = creaturePrefab.GetComponent<CharacterDrop>();
			if ((Object)(object)val == (Object)null)
			{
				val = creaturePrefab.AddComponent<CharacterDrop>();
			}
			val.m_drops.RemoveAll((Drop d) => d == null || Destroyed((Object)(object)d.m_prefab) || ((Object)(object)d.m_prefab != (Object)null && ((Object)d.m_prefab).name == ((Object)item).name));
			min = Mathf.Max(0, min);
			Drop val2 = new Drop
			{
				m_prefab = item,
				m_chance = Mathf.Clamp01(chance),
				m_amountMin = min,
				m_amountMax = Mathf.Max(min, max) + 1,
				m_levelMultiplier = perLevel
			};
			val.m_drops.Add(val2);
			if (!OurDrops.Contains((creaturePrefab, ((Object)item).name)))
			{
				OurDrops.Add((creaturePrefab, ((Object)item).name));
			}
			return val2;
		}

		public static void RemoveDrop(GameObject creaturePrefab, string item)
		{
			if (!((Object)(object)creaturePrefab == (Object)null))
			{
				creaturePrefab.GetComponent<CharacterDrop>()?.m_drops.RemoveAll((Drop d) => d == null || Destroyed((Object)(object)d.m_prefab) || ((Object)(object)d.m_prefab != (Object)null && ((Object)d.m_prefab).name == item));
				OurDrops.Remove((creaturePrefab, item));
			}
		}

		public static TradeItem Sell(Harmony harmony, string trader, GameObject item, int price, int stack = 1, string globalKey = null, Func<bool> when = null)
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			ItemDrop val = (((Object)(object)item != (Object)null) ? item.GetComponent<ItemDrop>() : null);
			if (harmony == null || string.IsNullOrEmpty(trader) || (Object)(object)val == (Object)null)
			{
				return null;
			}
			Sale sale = OurSales.Find((Sale s) => s.Trader == trader && (Object)(object)s.Item.m_prefab != (Object)null && ((Object)s.Item.m_prefab).name == ((Object)item).name);
			if (sale == null)
			{
				List<Sale> ourSales = OurSales;
				Sale obj = new Sale
				{
					Trader = trader,
					Item = new TradeItem()
				};
				sale = obj;
				ourSales.Add(obj);
			}
			sale.Item.m_prefab = val;
			sale.Item.m_price = Mathf.Max(0, price);
			sale.Item.m_stack = Mathf.Max(1, stack);
			sale.Item.m_requiredGlobalKey = globalKey ?? "";
			sale.When = when;
			MethodInfo methodInfo = AccessTools.Method(typeof(Trader), "GetAvailableItems", (Type[])null, (Type[])null);
			MethodInfo postfix = AccessTools.Method(typeof(Content), "AddSales", (Type[])null, (Type[])null);
			Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo);
			if (patchInfo == null || !patchInfo.Postfixes.Any((Patch p) => p.owner == harmony.Id && p.PatchMethod == postfix))
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(postfix), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			return sale.Item;
		}

		public static void RemoveSale(string trader, string item)
		{
			OurSales.RemoveAll((Sale s) => s.Trader == trader && ((Object)(object)s.Item.m_prefab == (Object)null || ((Object)s.Item.m_prefab).name == item));
		}

		private static void AddSales(Trader __instance, List<TradeItem> __result)
		{
			if (__result == null || OurSales.Count == 0)
			{
				return;
			}
			string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject);
			foreach (Sale ourSale in OurSales)
			{
				if (!(ourSale.Trader != prefabName) && !((Object)(object)ourSale.Item.m_prefab == (Object)null) && !__result.Contains(ourSale.Item) && (string.IsNullOrEmpty(ourSale.Item.m_requiredGlobalKey) || (!((Object)(object)ZoneSystem.instance == (Object)null) && ZoneSystem.instance.GetGlobalKey(ourSale.Item.m_requiredGlobalKey))))
				{
					bool flag;
					try
					{
						flag = ourSale.When == null || ourSale.When();
					}
					catch
					{
						flag = false;
					}
					if (flag)
					{
						__result.Add(ourSale.Item);
					}
				}
			}
		}

		public static void RemoveAll(bool keepItems = false)
		{
			if (!keepItems)
			{
				if (OurItems.Count > 0)
				{
					RemoveItems(OurItems.ToList());
				}
				ObjectDB instance = ObjectDB.instance;
				if ((Object)(object)instance != (Object)null)
				{
					foreach (StatusEffect ourEffect in OurEffects)
					{
						instance.m_StatusEffects.Remove(ourEffect);
					}
				}
			}
			OurItems.Clear();
			OurEffects.Clear();
			foreach (Recipe item in OurRecipes.Values.ToList())
			{
				RemoveRecipe(item);
			}
			OurRecipes.Clear();
			foreach (var item2 in OurConversions.ToList())
			{
				RemoveConversion(item2.Station, item2.From, item2.To);
			}
			OurConversions.Clear();
			foreach (var item3 in OurDrops.ToList())
			{
				RemoveDrop(item3.Creature, item3.Item);
			}
			OurDrops.Clear();
			OurSales.Clear();
		}
	}
	internal static class Costs
	{
		public const string Help = "Item prefab names and amounts, separated by commas, like FineWood:12, BronzeNails:30 (Claude Tools' `prefabs <text>` shows exact names). A cost with a mistake in it keeps the last good one.";

		public const string StationHelp = "The crafting station's prefab name (piece_workbench, forge, piece_stonecutter, piece_artisanstation, blackforge, piece_magetable), or none.";

		public static Requirement[] Parse(string text, List<string> problems, bool forRecipe)
		{
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Expected O, but got Unknown
			problems = problems ?? new List<string>();
			int count = problems.Count;
			List<Requirement> list = new List<Requirement>();
			string[] array = (text ?? "").Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (string text2 in array)
			{
				string text3 = text2.Trim();
				if (text3.Length == 0)
				{
					continue;
				}
				string[] array2 = (from b in text3.Split(new char[1] { ':' })
					select b.Trim()).ToArray();
				if (array2.Length < 2 || array2.Length > 3 || !Whole(array2[1], out var value) || value < 1)
				{
					problems.Add("\"" + text3 + "\" isn't Name:amount");
					continue;
				}
				int value2 = 0;
				bool result = true;
				if (array2.Length == 3)
				{
					bool num;
					if (!forRecipe)
					{
						num = bool.TryParse(array2[2], out result);
					}
					else
					{
						if (!Whole(array2[2], out value2))
						{
							goto IL_0116;
						}
						num = value2 >= 0;
					}
					if (!num)
					{
						goto IL_0116;
					}
				}
				ItemDrop item = FindItem(array2[0]);
				if ((Object)(object)item == (Object)null)
				{
					problems.Add("no item called \"" + array2[0] + "\"");
					continue;
				}
				if (list.Any((Requirement r) => (Object)(object)r.m_resItem == (Object)(object)item))
				{
					problems.Add(array2[0] + " is listed twice");
					continue;
				}
				list.Add(new Requirement
				{
					m_resItem = item,
					m_amount = value,
					m_amountPerLevel = value2,
					m_recover = result
				});
				continue;
				IL_0116:
				problems.Add(forRecipe ? ("\"" + text3 + "\": the upgrade amount isn't a number") : ("\"" + text3 + "\": the last part isn't true or false"));
			}
			if (list.Count == 0 && problems.Count == count)
			{
				problems.Add("it's empty (nothing would be free: write at least one item)");
			}
			if (problems.Count != count)
			{
				return null;
			}
			return list.ToArray();
		}

		private static bool Whole(string text, out int value)
		{
			return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
		}

		public static string Write(IEnumerable<Requirement> cost, bool forRecipe)
		{
			return string.Join(", ", (from r in cost ?? Enumerable.Empty<Requirement>()
				where (Object)(object)r?.m_resItem != (Object)null
				select ((Object)r.m_resItem).name + ":" + r.m_amount + ((!forRecipe) ? (r.m_recover ? "" : ":false") : ((r.m_amountPerLevel > 0) ? (":" + r.m_amountPerLevel) : ""))).ToArray());
		}

		public static ItemDrop FindItem(string name)
		{
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(name) : null);
			if ((Object)(object)val == (Object)null && (Object)(object)ObjectDB.instance != (Object)null)
			{
				val = ObjectDB.instance.GetItemPrefab(name);
			}
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val.GetComponent<ItemDrop>();
		}

		public static CraftingStation FindStation(string name, out bool found)
		{
			name = (name ?? "").Trim();
			found = true;
			if (name.Length == 0 || name.Equals("none", StringComparison.OrdinalIgnoreCase))
			{
				return null;
			}
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(name) : null);
			CraftingStation val2 = (((Object)(object)val != (Object)null) ? val.GetComponent<CraftingStation>() : null);
			found = (Object)(object)val2 != (Object)null;
			return val2;
		}

		public static bool Apply(Piece piece, string text, ManualLogSource log)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return false;
			}
			List<string> problems = new List<string>();
			Requirement[] array = Parse(text, problems, forRecipe: false);
			Report(log, ((Object)piece).name, problems);
			if (array == null)
			{
				return false;
			}
			piece.m_resources = array;
			return true;
		}

		public static bool Apply(Recipe recipe, string text, ManualLogSource log)
		{
			if ((Object)(object)recipe == (Object)null)
			{
				return false;
			}
			List<string> problems = new List<string>();
			Requirement[] array = Parse(text, problems, forRecipe: true);
			Report(log, ((Object)recipe).name, problems);
			if (array == null)
			{
				return false;
			}
			recipe.m_resources = array;
			return true;
		}

		public static bool ApplyStation(Piece piece, string text, ManualLogSource log)
		{
			if ((Object)(object)piece == (Object)null)
			{
				return false;
			}
			bool found;
			CraftingStation craftingStation = FindStation((text ?? "").Split(new char[1] { ':' })[0], out found);
			if (!found)
			{
				if (log != null)
				{
					log.LogWarning((object)(((Object)piece).name + ": no crafting station called \"" + text + "\", it keeps its station"));
				}
				return false;
			}
			piece.m_craftingStation = craftingStation;
			return true;
		}

		public static bool ApplyStation(Recipe recipe, string text, ManualLogSource log)
		{
			if ((Object)(object)recipe == (Object)null)
			{
				return false;
			}
			string[] array = (text ?? "").Split(new char[1] { ':' });
			bool found;
			CraftingStation craftingStation = FindStation(array[0], out found);
			int value = 1;
			if (!found || (array.Length > 1 && (!Whole(array[1].Trim(), out value) || value < 1)))
			{
				if (log != null)
				{
					log.LogWarning((object)(((Object)recipe).name + ": \"" + text + "\" isn't a crafting station (and level), it keeps its station"));
				}
				return false;
			}
			recipe.m_craftingStation = craftingStation;
			recipe.m_minStationLevel = value;
			return true;
		}

		private static void Report(ManualLogSource log, string what, List<string> problems)
		{
			if (problems.Count > 0 && log != null)
			{
				log.LogWarning((object)(what + "'s cost setting has a mistake, so it keeps its last cost: " + string.Join("; ", problems.ToArray())));
			}
		}
	}
	internal static class Icon
	{
		private const int Size = 128;

		private static readonly Vector3 DefaultView = new Vector3(0.42f, 0.28f, -1f);

		private static int _layer = -1;

		private static readonly MethodInfo LoadImageMethod = Type.GetType("UnityEngine.ImageConversion, UnityEngine.ImageConversionModule")?.GetMethod("LoadImage", new Type[2]
		{
			typeof(Texture2D),
			typeof(byte[])
		});

		private static int Layer
		{
			get
			{
				if (_layer < 0)
				{
					_layer = 31;
					for (int num = 31; num >= 8; num--)
					{
						if (string.IsNullOrEmpty(LayerMask.LayerToName(num)))
						{
							_layer = num;
							break;
						}
					}
				}
				return _layer;
			}
		}

		private static bool CanDraw => (int)SystemInfo.graphicsDeviceType != 4;

		private static string ModName => typeof(Icon).Assembly.GetName().Name;

		internal static Sprite Make(GameObject prefab, Vector3? view = null, Action<GameObject> pose = null, string fallback = "icon.png")
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			Sprite val = null;
			try
			{
				val = DrawPiece(prefab, (Vector3)(((??)view) ?? DefaultView), pose);
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[" + ModName + "] could not draw the build icon: " + ex.Message));
			}
			if (!((Object)(object)val != (Object)null))
			{
				return LoadSprite(fallback);
			}
			return val;
		}

		internal static Sprite MakeItem(GameObject itemPrefab, bool setIcon = false, string fallback = null, Quaternion? look = null)
		{
			Sprite val = null;
			try
			{
				val = DrawItem(itemPrefab, look);
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("[" + ModName + "] could not draw the icon of " + (((Object)(object)itemPrefab != (Object)null) ? ((Object)itemPrefab).name : "an item") + ": " + ex.Message));
			}
			Sprite val2 = (((Object)(object)val != (Object)null) ? val : LoadSprite(fallback));
			if (setIcon && (Object)(object)val2 != (Object)null && (Object)(object)itemPrefab != (Object)null)
			{
				ItemDrop component = itemPrefab.GetComponent<ItemDrop>();
				if ((Object)(object)component != (Object)null)
				{
					SharedData shared = component.m_itemData.m_shared;
					Sprite[] array = (Sprite[])((shared.m_icons != null && shared.m_icons.Length > 1) ? ((Array)(Sprite[])shared.m_icons.Clone()) : ((Array)new Sprite[1]));
					array[0] = val2;
					shared.m_icons = array;
				}
			}
			return val2;
		}

		private static Sprite DrawPiece(GameObject prefab, Vector3 view, Action<GameObject> pose)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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)
			if ((Object)(object)prefab == (Object)null || !CanDraw)
			{
				return null;
			}
			Transform val = prefab.transform.Find("Model");
			return Draw(((Object)(object)val != (Object)null) ? ((Component)val).gameObject : prefab, (Object)(object)val == (Object)null, Quaternion.identity, pose, delegate(GameObject stage, Bounds bounds)
			{
				//IL_002a: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0040: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0069: Unknown result type (might be due to invalid IL or missing references)
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
				Camera val2 = AddCamera(stage);
				val2.fieldOfView = 24f;
				val2.nearClipPlane = 0.1f;
				val2.farClipPlane = 60f;
				Vector3 extents = ((Bounds)(ref bounds)).extents;
				float magnitude = ((Vector3)(ref extents)).magnitude;
				((Component)val2).transform.position = ((Bounds)(ref bounds)).center + ((Vector3)(ref view)).normalized * (magnitude / Mathf.Sin(val2.fieldOfView * 0.5f * ((float)Math.PI / 180f))) * 1.02f;
				((Component)val2).transform.LookAt(((Bounds)(ref bounds)).center);
				AddLight(stage, Quaternion.Euler(38f, 28f, 0f), 1.25f);
				return val2;
			}, 0.08f);
		}

		private static Sprite DrawItem(GameObject itemPrefab, Quaternion? look)
		{
			//IL_0054: 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)
			if ((Object)(object)itemPrefab == (Object)null || !CanDraw)
			{
				return null;
			}
			Transform val = itemPrefab.transform.Find("attach");
			return Draw(((Object)(object)val != (Object)null) ? ((Component)val).gameObject : itemPrefab, bare: true, ((Object)(object)val != (Object)null) ? val.localRotation : Quaternion.identity, null, delegate(GameObject stage, Bounds bounds)
			{
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: 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_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_008b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Unknown result type (might be due to invalid IL or missing references)
				//IL_0095: Unknown result type (might be due to invalid IL or missing references)
				//IL_009a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0079: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0083: Unknown result type (might be due to invalid IL or missing references)
				//IL_0088: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_005e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00da: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
				//IL_015b: Unknown result type (might be due to invalid IL or missing references)
				//IL_015c: Unknown result type (might be due to invalid IL or missing references)
				//IL_015e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0168: 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_0175: Unknown result type (might be due to invalid IL or missing references)
				//IL_017c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0183: Unknown result type (might be due to invalid IL or missing references)
				//IL_018a: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
				//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d1: 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_01e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e9: 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_0211: Unknown result type (might be due to invalid IL or missing references)
				//IL_0221: Unknown result type (might be due to invalid IL or missing references)
				//IL_0226: Unknown result type (might be due to invalid IL or missing references)
				//IL_022b: Unknown result type (might be due to invalid IL or missing references)
				//IL_022e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0230: Unknown result type (might be due to invalid IL or missing references)
				//IL_0231: Unknown result type (might be due to invalid IL or missing references)
				//IL_0236: Unknown result type (might be due to invalid IL or missing references)
				//IL_023b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0110: Unknown result type (might be due to invalid IL or missing references)
				//IL_0115: 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_011f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0121: 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_0127: Unknown result type (might be due to invalid IL or missing references)
				//IL_012b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0130: Unknown result type (might be due to invalid IL or missing references)
				//IL_0135: Unknown result type (might be due to invalid IL or missing references)
				//IL_013a: Unknown result type (might be due to invalid IL or missing references)
				//IL_013c: Unknown result type (might be due to invalid IL or missing references)
				//IL_013d: Unknown result type (might be due to invalid IL or missing references)
				//IL_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_0147: Unknown result type (might be due to invalid IL or missing references)
				//IL_0149: Unknown result type (might be due to invalid IL or missing references)
				//IL_014e: Unknown result type (might be due to invalid IL or missing references)
				Camera val2 = AddCamera(stage);
				val2.orthographic = true;
				Vector3 size = ((Bounds)(ref bounds)).size;
				Quaternion val3 = (look.HasValue ? look.Value : ((size.y <= size.x * 1.15f && size.y <= size.z * 1.15f) ? Quaternion.LookRotation(Vector3.down, Vector3.forward) : ((!(size.x <= size.z)) ? Quaternion.LookRotation(Vector3.forward, Vector3.up) : Quaternion.LookRotation(Vector3.right, Vector3.up))));
				if (!look.HasValue)
				{
					val3 *= Quaternion.Euler(0f, 0f, 45f);
				}
				((Component)val2).transform.rotation = val3;
				Vector3 val4 = Vector3.positiveInfinity;
				Vector3 val5 = Vector3.negativeInfinity;
				for (int i = 0; i < 8; i++)
				{
					Vector3 val6 = ((Bounds)(ref bounds)).center + Vector3.Scale(((Bounds)(ref bounds)).extents, new Vector3((float)(((i & 1) != 0) ? 1 : (-1)), (float)(((i & 2) != 0) ? 1 : (-1)), (float)(((i & 4) != 0) ? 1 : (-1))));
					Vector3 val7 = Quaternion.Inverse(val3) * (val6 - ((Bounds)(ref bounds)).center);
					val4 = Vector3.Min(val4, val7);
					val5 = Vector3.Max(val5, val7);
				}
				Vector3 val8 = (val4 + val5) * 0.5f;
				val2.orthographicSize = Mathf.Max(0.01f, Mathf.Max(val5.x - val4.x, val5.y - val4.y) * 0.5f * 1.08f);
				float num = val5.z - val4.z;
				((Component)val2).transform.position = ((Bounds)(ref bounds)).center + val3 * new Vector3(val8.x, val8.y, val4.z - 1f);
				val2.nearClipPlane = 0.01f;
				val2.farClipPlane = num + 2f;
				Vector3 val9 = val3 * new Vector3(0.4f, -0.5f, 1f);
				AddLight(stage, Quaternion.LookRotation(val9, val3 * Vector3.up), 1.3f);
				return val2;
			}, 0.02f);
		}

		private static Sprite Draw(GameObject source, bool bare, Quaternion turn, Action<GameObject> pose, Func<GameObject, Bounds, Camera> frame, float minCover)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: 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_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Expected O, but got Unknown
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Unknown result type (might be due to invalid IL or missing references)
			int layer = Layer;
			bool forceDisableInit = ZNetView.m_forceDisableInit;
			bool forceDisableTerrainOps = TerrainOp.m_forceDisableTerrainOps;
			RenderTexture active = RenderTexture.active;
			RenderTexture val = null;
			Camera val2 = null;
			GameObject val3 = new GameObject(ModName + "IconStage");
			val3.SetActive(false);
			val3.transform.position = new Vector3(0f, -3000f, 0f);
			try
			{
				ZNetView.m_forceDisableInit = true;
				TerrainOp.m_forceDisableTerrainOps = true;
				GameObject val4 = Object.Instantiate<GameObject>(source, val3.transform);
				val4.transform.localPosition = Vector3.zero;
				val4.transform.localRotation = turn;
				val4.SetActive(true);
				if (bare)
				{
					Strip(val4);
				}
				Transform[] componentsInChildren = val4.GetComponentsInChildren<Transform>(true);
				foreach (Transform val5 in componentsInChildren)
				{
					((Component)val5).gameObject.layer = layer;
				}
				if (!bare)
				{
					Renderer[] componentsInChildren2 = val4.GetComponentsInChildren<Renderer>(true);
					foreach (Renderer val6 in componentsInChildren2)
					{
						val6.enabled = true;
					}
				}
				val3.SetActive(true);
				pose?.Invoke(val4);
				Bounds arg = default(Bounds);
				bool flag = false;
				Renderer[] componentsInChildren3 = val4.GetComponentsInChildren<Renderer>();
				foreach (Renderer val7 in componentsInChildren3)
				{
					if (val7.enabled && !IsParticles(val7))
					{
						if (!flag)
						{
							arg = val7.bounds;
							flag = true;
						}
						else
						{
							((Bounds)(ref arg)).Encapsulate(val7.bounds);
						}
					}
				}
				if (!flag)
				{
					return null;
				}
				val2 = frame(val3, arg);
				val2.cullingMask = 1 << layer;
				val = (val2.targetTexture = RenderTexture.GetTemporary(256, 256, 24, (RenderTextureFormat)0));
				AmbientMode ambientMode = RenderSettings.ambientMode;
				Color ambientLight = RenderSettings.ambientLight;
				float reflectionIntensity = RenderSettings.reflectionIntensity;
				RenderSettings.ambientMode = (AmbientMode)3;
				RenderSettings.ambientLight = new Color(0.5f, 0.5f, 0.5f);
				RenderSettings.reflectionIntensity = 0.25f;
				try
				{
					val2.Render();
				}
				finally
				{
					RenderSettings.ambientMode = ambientMode;
					RenderSettings.ambientLight = ambientLight;
					RenderSettings.reflectionIntensity = reflectionIntensity;
				}
				RenderTexture.active = val;
				Texture2D val8 = new Texture2D(((Texture)val).width, ((Texture)val).height, (TextureFormat)4, false);
				val8.ReadPixels(new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), 0, 0);
				val8.Apply();
				if (LooksFine(val8, minCover))
				{
					return Sprite.Create(val8, new Rect(0f, 0f, (float)((Texture)val8).width, (float)((Texture)val8).height), new Vector2(0.5f, 0.5f), 100f);
				}
				Object.Destroy((Object)(object)val8);
				return null;
			}
			finally
			{
				ZNetView.m_forceDisableInit = forceDisableInit;
				TerrainOp.m_forceDisableTerrainOps = forceDisableTerrainOps;
				RenderTexture.active = active;
				if ((Object)(object)val2 != (Object)null)
				{
					val2.targetTexture = null;
				}
				if ((Object)(object)val != (Object)null)
				{
					RenderTexture.ReleaseTemporary(val);
				}
				Object.DestroyImmediate((Object)(object)val3);
			}
		}

		private static bool IsParticles(Renderer r)
		{
			if (!(r is TrailRenderer) && !(r is LineRenderer))
			{
				return ((object)r).GetType().Name == "ParticleSystemRenderer";
			}
			return true;
		}

		private static Camera AddCamera(GameObject stage)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("IconCamera");
			val.transform.SetParent(stage.transform, false);
			Camera val2 = val.AddComponent<Camera>();
			((Behaviour)val2).enabled = false;
			val2.clearFlags = (CameraClearFlags)2;
			val2.backgroundColor = new Color(0f, 0f, 0f, 0f);
			val2.allowHDR = false;
			val2.allowMSAA = false;
			val2.cullingMask = 1 << Layer;
			return val2;
		}

		private static void AddLight(GameObject stage, Quaternion rotation, float intensity)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("IconLight");
			val.transform.SetParent(stage.transform, false);
			val.transform.rotation = rotation;
			Light val2 = val.AddComponent<Light>();
			val2.type = (LightType)1;
			val2.intensity = intensity;
			val2.shadows = (LightShadows)0;
			val2.cullingMask = 1 << Layer;
		}

		private static void Strip(GameObject copy)
		{
			Transform[] componentsInChildren = copy.GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				List<MonoBehaviour> list = new List<MonoBehaviour>(((Component)val).GetComponents<MonoBehaviour>());
				for (int j = 0; j < 4; j++)
				{
					if (list.Count <= 0)
					{
						break;
					}
					for (int num = list.Count - 1; num >= 0; num--)
					{
						if ((Object)(object)list[num] == (Object)null)
						{
							list.RemoveAt(num);
						}
						else if (!Needed(list[num], list))
						{
							Object.DestroyImmediate((Object)(object)list[num]);
							list.RemoveAt(num);
						}
					}
				}
			}
			Collider[] componentsInChildren2 = copy.GetComponentsInChildren<Collider>(true);
			foreach (Collider val2 in componentsInChildren2)
			{
				val2.enabled = false;
			}
			Rigidbody[] componentsInChildren3 = copy.GetComponentsInChildren<Rigidbody>(true);
			foreach (Rigidbody val3 in componentsInChildren3)
			{
				val3.isKinematic = true;
				val3.detectCollisions = false;
			}
		}

		private static bool Needed(MonoBehaviour script, List<MonoBehaviour> others)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			Type type = ((object)script).GetType();
			foreach (MonoBehaviour other in others)
			{
				if ((Object)(object)other == (Object)null || (Object)(object)other == (Object)(object)script)
				{
					continue;
				}
				object[] customAttributes = ((object)other).GetType().GetCustomAttributes(typeof(RequireComponent), inherit: true);
				for (int i = 0; i < customAttributes.Length; i++)
				{
					RequireComponent val = (RequireComponent)customAttributes[i];
					if (Is(val.m_Type0, type) || Is(val.m_Type1, type) || Is(val.m_Type2, type))
					{
						return true;
					}
				}
			}
			return false;
		}

		private static bool Is(Type required, Type type)
		{
			if (required != null)
			{
				return required.IsAssignableFrom(type);
			}
			return false;
		}

		private static bool LooksFine(Texture2D tex, float minCover)
		{
			//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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			Color32[] pixels = tex.GetPixels32();
			int num = 0;
			long num2 = 0L;
			for (int i = 0; i < pixels.Length; i += 7)
			{
				Color32 val = pixels[i];
				if (val.a > 40)
				{
					num++;
					num2 += val.r + val.g + val.b;
				}
			}
			int num3 = pixels.Length / 7 + 1;
			if ((float)num > (float)num3 * minCover)
			{
				return num2 / Math.Max(1, num) > 60;
			}
			return false;
		}

		private static bool LoadImage(Texture2D tex, byte[] data)
		{
			if (LoadImageMethod != null)
			{
				return (bool)LoadImageMethod.Invoke(null, new object[2] { tex, data });
			}
			return false;
		}

		internal static Texture2D LoadEmbedded(string name)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			if (string.IsNullOrEmpty(name))
			{
				return null;
			}
			using Stream stream = typeof(Icon).Assembly.GetManifestResourceStream(name);
			if (stream == null)
			{
				return null;
			}
			byte[] array = new byte[stream.Length];
			stream.Read(array, 0, array.Length);
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			return LoadImage(val, array) ? val : null;
		}

		internal static Sprite LoadSprite(string name)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = LoadEmbedded(name);
			if (!((Object)(object)val == (Object)null))
			{
				return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
			}
			return null;
		}
	}
	internal static class ItemReload
	{
		private static readonly FieldInfo NamedField = AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs");

		private static readonly MethodInfo UpdateRegisters = AccessTools.Method(typeof(ObjectDB), "UpdateRegisters", (Type[])null, (Type[])null);

		public static bool KeepOnUnload => (Object)(object)ZNetScene.instance != (Object)null;

		public static void Replace(ZNetScene scene, ObjectDB db, IEnumerable<GameObject> items)
		{
			bool flag = false;
			foreach (GameObject item in items)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				if ((Object)(object)scene != (Object)null)
				{
					scene.m_prefabs.RemoveAll((GameObject p) => (Object)(object)p != (Object)(object)item && (Object)(object)p != (Object)null && ((Object)p).name == ((Object)item).name);
					if (!scene.m_prefabs.Contains(item))
					{
						scene.m_prefabs.Add(item);
					}
					((Dictionary<int, GameObject>)NamedField.GetValue(scene))[StringExtensionMethods.GetStableHashCode(((Object)item).name)] = item;
				}
				if ((Object)(object)db != (Object)null && !db.m_items.Contains(item))
				{
					db.m_items.RemoveAll((GameObject i) => (Object)(object)i == (Object)null || ((Object)(object)i != (Object)(object)item && ((Object)i).name == ((Object)item).name));
					db.m_items.Add(item);
					flag = true;
				}
			}
			if (flag)
			{
				UpdateRegisters?.Invoke(db, null);
			}
		}

		public static int Repoint(Func<string, GameObject> current, params ItemData[] more)
		{
			int n = 0;
			if ((Object)(object)Player.m_localPlayer != (Object)null)
			{
				foreach (ItemData allItem in ((Humanoid)Player.m_localPlayer).GetInventory().GetAllItems())
				{
					One(allItem);
				}
			}
			Container[] array = Object.FindObjectsByType<Container>((FindObjectsSortMode)0);
			foreach (Container val in array)
			{
				if (!((Object)(object)val != (Object)null) || val.GetInventory() == null)
				{
					continue;
				}
				foreach (ItemData allItem2 in val.GetInventory().GetAllItems())
				{
					One(allItem2);
				}
			}
			ItemDrop[] array2 = Object.FindObjectsByType<ItemDrop>((FindObjectsSortMode)0);
			foreach (ItemDrop val2 in array2)
			{
				if ((Object)(object)val2 != (Object)null)
				{
					One(val2.m_itemData);
				}
			}
			if (more != null)
			{
				foreach (ItemData item in more)
				{
					One(item);
				}
			}
			return n;
			void One(ItemData val4)
			{
				GameObject val3 = val4?.m_dropPrefab;
				if (!((Object)(object)val3 == (Object)null))
				{
					GameObject val5 = current(((Object)val3).name);
					if (!((Object)(object)val5 == (Object)null) && !((Object)(object)val5 == (Object)(object)val3))
					{
						SharedData val6 = val3.GetComponent<ItemDrop>()?.m_itemData.m_shared;
						val4.m_dropPrefab = val5;
						if (val6 != null && val4.m_shared == val6)
						{
							val4.m_shared = val5.GetComponent<ItemDrop>().m_itemData.m_shared;
						}
						n++;
					}
				}
			}
		}
	}
	internal static class Lens
	{
		private const string CanvasName = "nick_spyglass_lens";

		private const float CircleSize = 0.96f;

		private const int CrackSteps = 16;

		private const int DustSteps = 32;

		private static GameObject _root;

		private static CanvasGroup _group;

		private static RectTransform _circle;

		private static RectTransform _crack;

		private static RectTransform _haze;

		private static RectTransform _dust;

		private static RectTransform _left;

		private static RectTransform _right;

		private static RectTransform _top;

		private static RectTransform _bottom;

		private static GameObject _crackObject;

		private static GameObject _circleObject;

		private static GameObject _hazeObject;

		private static GameObject _dustObject;

		private static Texture2D _ringTexture;

		private static Texture2D _crackTexture;

		private static Texture2D _hazeTexture;

		private static Texture2D _dustTexture;

		private static RawImage _hazeImage;

		private static RawImage _dustImage;

		private static RawImage _crackImage;

		private static int _crackLevel = -1;

		private static int _dustLevel = -1;

		private static int _width;

		private static int _height;

		public static void Show(float amount, bool vignette, bool wearShows, float wear)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Invalid comparison between Unknown and I4
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			bool flag = wearShows && wear > 0.02f;
			if (amount <= 0.001f || (!vignette && !flag))
			{
				if ((Object)(object)_root != (Object)null && _root.activeSelf)
				{
					_root.SetActive(false);
				}
			}
			else
			{
				if ((int)SystemInfo.graphicsDeviceType == 4 || ((Object)(object)_root == (Object)null && !Build()))
				{
					return;
				}
				if (!_root.activeSelf)
				{
					_root.SetActive(true);
				}
				_group.alpha = amount;
				_hazeObject.SetActive(flag);
				_dustObject.SetActive(flag);
				_crackObject.SetActive(flag && wear > 0.06f);
				_circleObject.SetActive(vignette);
				((Component)_left).gameObject.SetActive(vignette);
				((Component)_right).gameObject.SetActive(vignette);
				((Component)_top).gameObject.SetActive(vignette);
				((Component)_bottom).gameObject.SetActive(vignette);
				if (flag)
				{
					((Graphic)_hazeImage).color = new Color(0.86f, 0.87f, 0.85f, 0.85f * Smooth(0.15f, 0.85f, wear));
					int num = Mathf.RoundToInt(Mathf.Clamp01(wear) * 32f);
					if (num != _dustLevel)
					{
						if ((Object)(object)_dustTexture != (Object)null)
						{
							Object.Destroy((Object)(object)_dustTexture);
						}
						_dustTexture = MakeDust(512, (float)num / 32f);
						_dustImage.texture = (Texture)(object)_dustTexture;
						_dustLevel = num;
					}
					int num2 = Mathf.RoundToInt(Mathf.Clamp01(wear) * 16f);
					if (num2 != _crackLevel && num2 >= 1)
					{
						if ((Object)(object)_crackTexture != (Object)null)
						{
							Object.Destroy((Object)(object)_crackTexture);
						}
						_crackTexture = MakeCrack(1024, (float)num2 / 16f);
						_crackImage.texture = (Texture)(object)_crackTexture;
						_crackLevel = num2;
					}
				}
				if (_width != Screen.width || _height != Screen.height)
				{
					Layout();
				}
			}
		}

		public static void Reset()
		{
			if ((Object)(object)_root != (Object)null)
			{
				Object.Destroy((Object)(object)_root);
			}
			if ((Object)(object)_ringTexture != (Object)null)
			{
				Object.Destroy((Object)(object)_ringTexture);
			}
			if ((Object)(object)_crackTexture != (Object)null)
			{
				Object.Destroy((Object)(object)_crackTexture);
			}
			if ((Object)(object)_hazeTexture != (Object)null)
			{
				Object.Destroy((Object)(object)_hazeTexture);
			}
			if ((Object)(object)_dustTexture != (Object)null)
			{
				Object.Destroy((Object)(object)_dustTexture);
			}
			_root = null;
			_group = null;
			_ringTexture = null;
			_crackTexture = null;
			_hazeTexture = null;
			_dustTexture = null;
			_circle = (_crack = (_haze = (_dust = (_left = (_right = (_top = (_bottom = null)))))));
			_crackObject = (_circleObject = (_hazeObject = (_dustObject = null)));
			_hazeImage = (_dustImage = (_crackImage = null));
			_crackLevel = -1;
			_dustLevel = -1;
		}

		private static bool Build()
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Canvas[] array = Object.FindObjectsByType<Canvas>((FindObjectsSortMode)0);
				foreach (Canvas val in array)
				{
					if ((Object)(object)val != (Object)null && ((Object)((Component)val).gameObject).name == "nick_spyglass_lens")
					{
						Object.Destroy((Object)(object)((Component)val).gameObject);
					}
				}
				_root = new GameObject("nick_spyglass_lens");
				Object.DontDestroyOnLoad((Object)(object)_root);
				Canvas val2 = _root.AddComponent<Canvas>();
				val2.renderMode = (RenderMode)0;
				val2.sortingOrder = -100;
				_group = _root.AddComponent<CanvasGroup>();
				_group.blocksRaycasts = false;
				_group.interactable = false;
				_ringTexture = MakeRing(512);
				_hazeTexture = MakeHaze(256);
				_dustTexture = MakeDust(512, 0f);
				_dustLevel = 0;
				_crackTexture = MakeCrack(1024, 0.0625f);
				_crackLevel = 1;
				_haze = Part("haze", (Texture)(object)_hazeTexture, new Color(1f, 1f, 1f, 0f), out _hazeObject);
				_hazeImage = ((Component)_haze).GetComponent<RawImage>();
				_dust = Part("dust", (Texture)(object)_dustTexture, Color.white, out _dustObject);
				_dustImage = ((Component)_dust).GetComponent<RawImage>();
				_crack = Part("crack", (Texture)(object)_crackTexture, Color.white, out _crackObject);
				_crackImage = ((Component)_crack).GetComponent<RawImage>();
				_circle = Part("circle", (Texture)(object)_ringTexture, Color.white, out _circleObject);
				_left = Part("left", (Texture)(object)Texture2D.whiteTexture, Color.black, out var go);
				_right = Part("right", (Texture)(object)Texture2D.whiteTexture, Color.black, out go);
				_top = Part("top", (Texture)(object)Texture2D.whiteTexture, Color.black, out go);
				_bottom = Part("bottom", (Texture)(object)Texture2D.whiteTexture, Color.black, out go);
				Layout();
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not build the lens overlay: " + ex));
				Reset();
				return false;
			}
		}

		private static RectTransform Part(string name, Texture texture, Color color, out GameObject go)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: 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)
			go = new GameObject(name);
			go.transform.SetParent(_root.transform, false);
			RawImage val = go.AddComponent<RawImage>();
			val.texture = texture;
			((Graphic)val).color = color;
			((Graphic)val).raycastTarget = false;
			RectTransform component = go.GetComponent<RectTransform>();
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0.5f, 0.5f);
			component.anchorMax = val2;
			component.anchorMin = val2;
			return component;
		}

		private static void Layout()
		{
			_width = Screen.width;
			_height = Screen.height;
			float num = _width;
			float num2 = _height;
			float num3 = num2 * 0.96f;
			Place(_circle, 0f, 0f, num3, num3);
			Place(_crack, 0f, 0f, num3, num3);
			Place(_haze, 0f, 0f, num3, num3);
			Place(_dust, 0f, 0f, num3, num3);
			float width = Mathf.Max(0f, (num - num3) * 0.5f) + 2f;
			Place(_left, (0f - (num + num3)) * 0.25f, 0f, width, num2 + 4f);
			Place(_right, (num + num3) * 0.25f, 0f, width, num2 + 4f);
			float height = Mathf.Max(0f, (num2 - num3) * 0.5f) + 2f;
			Place(_top, 0f, (num2 + num3) * 0.25f, num3 + 4f, height);
			Place(_bottom, 0f, (0f - (num2 + num3)) * 0.25f, num3 + 4f, height);
		}

		private static void Place(RectTransform rect, float x, float y, float width, float height)
		{
			//IL_0003: 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)
			rect.anchoredPosition = new Vector2(x, y);
			rect.sizeDelta = new Vector2(width, height);
		}

		private static Texture2D MakeRing(int size)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			Color32[] array = (Color32[])(object)new Color32[size * size];
			float num = (float)size * 0.5f;
			for (int i = 0; i < size; i++)
			{
				for (int j = 0; j < size; j++)
				{
					float x = Mathf.Sqrt(((float)j + 0.5f - num) * ((float)j + 0.5f - num) + ((float)i + 0.5f - num) * ((float)i + 0.5f - num)) / num;
					float num2 = 0.45f * Smooth(0.55f, 0.93f, x);
					float num3 = Smooth(0.93f, 0.985f, x);
					float num4 = Mathf.Clamp01(Mathf.Max(num2, num3));
					array[i * size + j] = new Color32((byte)0, (byte)0, (byte)0, (byte)Mathf.RoundToInt(num4 * 255f));
				}
			}
			return Finish(array, size);
		}

		private static float Smooth(float edge0, float edge1, float x)
		{
			float num = Mathf.Clamp01((x - edge0) / (edge1 - edge0));
			return num * num * (3f - 2f * num);
		}

		private static Texture2D MakeCrack(int size, float wear)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0362: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0152: 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_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0326: Unknown result type (might be due to invalid IL or missing references)
			//IL_0335: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025a: Unknown result type (might be