Decompiled source of CasualtiesPreparedStandalone v1.1.0

CasPreparedStandalone/CasPreparedStandalone.dll

Decompiled 2 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.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CUCoreLib.Data;
using CUCoreLib.Helpers;
using CUCoreLib.Networking;
using CUCoreLib.Registries;
using CUCoreLib.Saving;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Rendering.Universal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("CUCoreLib")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("CasPreparedStandalone")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+18ba622b5260433d3ecab5808b4df5aacf3a3fcf")]
[assembly: AssemblyProduct("CasPrepared Standalone - single-player spawn loadouts")]
[assembly: AssemblyTitle("CasPreparedStandalone")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CasPrepared
{
	internal static class GameAssets
	{
		private const int MaxAttempts = 10;

		private const float RetryInterval = 2f;

		private static Sprite _small;

		private static Sprite _nano;

		private static Font _font;

		private static int _attempts;

		private static float _nextAttempt;

		public static Sprite UiBlockSmall
		{
			get
			{
				Search();
				return _small;
			}
		}

		public static Sprite UiBlockNano
		{
			get
			{
				Search();
				return _nano;
			}
		}

		public static Font PixelFont
		{
			get
			{
				Search();
				return _font;
			}
		}

		public static float UiScale => 0f;

		private static void Search()
		{
			if (((Object)(object)_small != (Object)null && (Object)(object)_nano != (Object)null && (Object)(object)_font != (Object)null) || _attempts >= 10 || Time.unscaledTime < _nextAttempt)
			{
				return;
			}
			_nextAttempt = Time.unscaledTime + 2f;
			_attempts++;
			try
			{
				if ((Object)(object)_small == (Object)null || (Object)(object)_nano == (Object)null)
				{
					Sprite[] sprites = Resources.FindObjectsOfTypeAll<Sprite>();
					if ((Object)(object)_small == (Object)null)
					{
						_small = FindSprite(sprites, "uiBlockSmall") ?? Exact(sprites, "uiBlock");
					}
					if ((Object)(object)_nano == (Object)null)
					{
						_nano = FindSprite(sprites, "uiBlockNano");
					}
				}
				if ((Object)(object)_font == (Object)null)
				{
					_font = FindFont();
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("UI asset search failed: " + ex.Message));
			}
			if ((Object)(object)_small != (Object)null && (Object)(object)_nano != (Object)null && (Object)(object)_font != (Object)null)
			{
				Plugin.Logger.LogInfo((object)("UI assets found: " + ((Object)_small).name + ", " + ((Object)_nano).name + ", font '" + ((Object)_font).name + "'."));
			}
			else if (_attempts >= 10)
			{
				Plugin.Logger.LogWarning((object)("Some UI assets were not found (frames: " + (((Object)(object)_small != (Object)null && (Object)(object)_nano != (Object)null) ? "ok" : "generated") + ", font: " + (((Object)(object)_font != (Object)null) ? ((Object)_font).name : "default") + ")."));
			}
		}

		private static Sprite Exact(Sprite[] sprites, string name)
		{
			return ((IEnumerable<Sprite>)sprites).FirstOrDefault((Func<Sprite, bool>)((Sprite s) => (Object)(object)s != (Object)null && ((Object)s).name == name));
		}

		private static Sprite FindSprite(Sprite[] sprites, string name)
		{
			return Exact(sprites, name) ?? ((IEnumerable<Sprite>)sprites).FirstOrDefault((Func<Sprite, bool>)((Sprite s) => (Object)(object)s != (Object)null && ((Object)s).name.Contains(name)));
		}

		private static Font FindFont()
		{
			List<Font> source = (from f in Resources.FindObjectsOfTypeAll<Font>()
				where (Object)(object)f != (Object)null && IsRetro(((Object)f).name)
				select f).ToList();
			Font val = ((IEnumerable<Font>)source).FirstOrDefault((Func<Font, bool>)((Font f) => f.dynamic && !((Object)f).name.Contains("FIXED"))) ?? ((IEnumerable<Font>)source).FirstOrDefault((Func<Font, bool>)((Font f) => f.dynamic)) ?? source.FirstOrDefault();
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
			foreach (TMP_FontAsset val2 in array)
			{
				if ((Object)(object)val2 != (Object)null && IsRetro(((Object)val2).name) && (Object)(object)val2.sourceFontFile != (Object)null)
				{
					return val2.sourceFontFile;
				}
			}
			return null;
			static bool IsRetro(string n)
			{
				if (n != null)
				{
					return n.Replace(" ", "").IndexOf("retrogaming", StringComparison.OrdinalIgnoreCase) >= 0;
				}
				return false;
			}
		}
	}
	internal static class LoadoutClient
	{
		private enum RunState
		{
			None,
			Used,
			Expired
		}

		private sealed class RunSaveProvider : ICustomSaveProvider
		{
			public int GetVersion()
			{
				return 1;
			}

			public JToken Capture()
			{
				//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_0041: Expected O, but got Unknown
				string text = ((_record == RunState.Used) ? "used" : ((_record == RunState.Expired || _pending) ? "expired" : null));
				if (text != null)
				{
					return (JToken)new JObject { ["state"] = JToken.op_Implicit(text) };
				}
				return null;
			}

			public void Restore(JToken payload, int version, SaveRestoreContext context)
			{
				string text = ((payload != null) ? payload.Value<string>((object)"state") : null);
				if (text == "used")
				{
					_record = RunState.Used;
				}
				else
				{
					if (!(text == "expired") || _record == RunState.Used)
					{
						return;
					}
					_record = RunState.Expired;
				}
				_pending = false;
				LoadoutUI.Close();
				Plugin.Logger.LogInfo((object)("Restored loadout state for this run: " + text + "."));
			}
		}

		private const float SettleSeconds = 3f;

		private const float TeleportJump = 5f;

		private const string StateUsed = "used";

		private const string StateExpired = "expired";

		private static RunState _record;

		private static bool _pending;

		private static Vector2 _origin;

		private static float _settledSince = -1f;

		private static Vector2? _lastBodyPos;

		private static bool _mpNoticeShown;

		public static bool IsAvailable => _pending;

		public static bool BuyInFlight => false;

		public static int Budget => ModConfig.Budget.Value;

		public static float Multiplier => ModConfig.PriceMultiplier.Value;

		public static float MaxDistance => ModConfig.MaxDistance.Value;

		public static float Distance { get; private set; }

		private static bool IsTutorial
		{
			get
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0018: Invalid comparison between Unknown and I4
				if ((Object)(object)WorldGeneration.world != (Object)null)
				{
					return (int)WorldGeneration.world.biomeOverride == 1;
				}
				return false;
			}
		}

		public static void Init()
		{
			SaveRegistry.RegisterGlobalProvider("casprepared.solo", (ICustomSaveProvider)(object)new RunSaveProvider());
		}

		private static bool WorldReady()
		{
			WorldGeneration world = WorldGeneration.world;
			if ((Object)(object)world != (Object)null)
			{
				return world.worldExists;
			}
			return false;
		}

		public static void Tick()
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			if (!WorldReady() || IsTutorial)
			{
				return;
			}
			if (MultiplayerBridge.IsRunning)
			{
				if (_pending)
				{
					LoadoutUI.Close();
				}
				if (!_mpNoticeShown)
				{
					_mpNoticeShown = true;
					Plugin.Logger.LogInfo((object)"Multiplayer session detected: the standalone build stays idle. Use the multiplayer build of CasPrepared.");
				}
			}
			else
			{
				if (!ModConfig.Enabled.Value)
				{
					return;
				}
				Body val = (((Object)(object)PlayerCamera.main != (Object)null) ? PlayerCamera.main.body : null);
				if ((Object)(object)val == (Object)null)
				{
					_settledSince = -1f;
					return;
				}
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				UpdateSettled(val, realtimeSinceStartup);
				if (_pending)
				{
					string text = Evaluate(val);
					if (text != null)
					{
						Expire(text);
					}
				}
				else if (_record == RunState.None && IsSettled(realtimeSinceStartup))
				{
					OpenWindow(val);
				}
				if (Input.GetKeyDown(ModConfig.MenuKey.Value) && !LoadoutUI.IsSearchFocused)
				{
					ToggleMenu();
				}
			}
		}

		private static void OpenWindow(Body body)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			if (body.alive && !WorldGeneration.world.generatingWorld)
			{
				_pending = true;
				_origin = Vector2.op_Implicit(((Component)body).transform.position);
				Distance = 0f;
				Plugin.Logger.LogInfo((object)$"Loadout window opened at {_origin}.");
				LoadoutUI.Open();
				Alert($"Loadout menu available ({ModConfig.MenuKey.Value}). It closes if you move {ModConfig.MaxDistance.Value:0} tiles away.");
			}
		}

		private static string Evaluate(Body body)
		{
			//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_001e: Unknown result type (might be due to invalid IL or missing references)
			if (!body.alive)
			{
				return "died";
			}
			Distance = Vector2.Distance(Vector2.op_Implicit(((Component)body).transform.position), _origin);
			if (Distance > ModConfig.MaxDistance.Value)
			{
				return "moved too far from spawn";
			}
			return null;
		}

		private static void Expire(string reason)
		{
			_pending = false;
			_record = RunState.Expired;
			LoadoutUI.Close();
			Plugin.Logger.LogInfo((object)("Loadout window closed: " + reason + "."));
			Alert("Loadout window closed: " + reason + ".");
		}

		public static void ToggleMenu()
		{
			if (LoadoutUI.IsOpen)
			{
				LoadoutUI.Close();
			}
			else if (_pending)
			{
				LoadoutUI.Open();
			}
			else
			{
				Alert((!ModConfig.Enabled.Value) ? "The loadout menu is turned off." : (MultiplayerBridge.IsRunning ? "The standalone build does not work in multiplayer." : ((_record == RunState.Used) ? "Loadout already taken this run." : ((_record == RunState.Expired) ? "Loadout window has closed." : "Loadout is not available yet."))));
			}
		}

		public static void Buy(Dictionary<string, int> selection)
		{
			Body val = (((Object)(object)PlayerCamera.main != (Object)null) ? PlayerCamera.main.body : null);
			if (!_pending)
			{
				LoadoutUI.SetMessage("Loadout is not available.");
				return;
			}
			if ((Object)(object)val == (Object)null || !val.alive)
			{
				LoadoutUI.SetMessage("Your character is not in the world.");
				return;
			}
			string text = Evaluate(val);
			if (text != null)
			{
				Expire(text);
				return;
			}
			List<LoadoutOrder.Line> order;
			long cost;
			int total;
			string text2 = LoadoutOrder.Build(selection, out order, out cost, out total);
			if (text2 != null)
			{
				LoadoutUI.SetMessage(text2);
				return;
			}
			try
			{
				LoadoutOrder.Spawn(val, order);
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("Loadout spawn failed: " + ex));
				LoadoutUI.SetMessage("Error while spawning the loadout.");
				return;
			}
			_pending = false;
			_record = RunState.Used;
			Plugin.Logger.LogInfo((object)$"Loadout received ({total} items, cost {cost}/{ModConfig.Budget.Value}).");
			LoadoutUI.Close();
			LoadoutUI.ClearSelection();
			Alert("Supply crate delivered at your feet.");
		}

		public static string DescribeState()
		{
			if (!WorldReady())
			{
				return "not in a run";
			}
			if (IsTutorial)
			{
				return "tutorial (mod inactive)";
			}
			if (!ModConfig.Enabled.Value)
			{
				return "loadout menu is off";
			}
			if (_pending)
			{
				return $"available ({Distance:0.0}/{ModConfig.MaxDistance.Value:0} tiles from spawn)";
			}
			return _record switch
			{
				RunState.Used => "loadout taken", 
				RunState.Expired => "window closed", 
				_ => "waiting for spawn", 
			};
		}

		private static bool LocalLoadingDone()
		{
			WorldGeneration world = WorldGeneration.world;
			if ((Object)(object)world == (Object)null || !world.worldExists || world.generatingWorld)
			{
				return false;
			}
			if ((Object)(object)world.loadingObject != (Object)null && world.loadingObject.activeSelf)
			{
				return false;
			}
			return true;
		}

		private static void UpdateSettled(Body body, float now)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = Vector2.op_Implicit(((Component)body).transform.position);
			bool flag = _lastBodyPos.HasValue && Vector2.Distance(val, _lastBodyPos.Value) > 5f;
			_lastBodyPos = val;
			if (!LocalLoadingDone() || !body.alive || flag)
			{
				_settledSince = -1f;
			}
			else if (_settledSince < 0f)
			{
				_settledSince = now;
			}
		}

		private static bool IsSettled(float now)
		{
			if (_settledSince >= 0f)
			{
				return now - _settledSince >= 3f;
			}
			return false;
		}

		private static void Alert(string text)
		{
			if ((Object)(object)PlayerCamera.main != (Object)null)
			{
				PlayerCamera.main.DoAlert(text, false);
			}
			if ((Object)(object)ConsoleScript.instance != (Object)null)
			{
				ConsoleScript.instance.LogToConsole("[CasPrepared] " + text);
			}
		}

		public static void ResetLocal()
		{
			_record = RunState.None;
			_pending = false;
			Distance = 0f;
			_settledSince = -1f;
			_lastBodyPos = null;
			_mpNoticeShown = false;
			LoadoutUI.Close();
			LoadoutUI.ClearSelection();
		}
	}
	[BepInPlugin("com.casprepared.standalone", "CasPrepared Standalone", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInIncompatibility("com.casprepared.loadout")]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGUID = "com.casprepared.standalone";

		public const string MultiplayerGUID = "com.casprepared.loadout";

		public const string ModName = "CasPrepared Standalone";

		public const string ModVersion = "1.1.0";

		internal static ManualLogSource Logger;

		private readonly Harmony _harmony = new Harmony("com.casprepared.standalone");

		private float _nextErrorLogTime;

		private float _nextGuiErrorLogTime;

		public void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			ModConfig.Init(((BaseUnityPlugin)this).Config);
			ItemRulesStore.Load();
			SupplyCrate.Register();
			LoadoutClient.Init();
			LoadoutCommands.Register();
			_harmony.PatchAll();
			Logger.LogInfo((object)"CasPrepared Standalone v1.1.0 loaded.");
		}

		public void Update()
		{
			try
			{
				LoadoutClient.Tick();
				LoadoutUI.RangeTick();
			}
			catch (Exception ex)
			{
				if (Time.unscaledTime >= _nextErrorLogTime)
				{
					_nextErrorLogTime = Time.unscaledTime + 5f;
					Logger.LogError((object)("Tick failed: " + ex));
				}
			}
		}

		public void OnGUI()
		{
			try
			{
				SoloMenu.Draw();
				LoadoutUI.Draw();
			}
			catch (Exception ex)
			{
				if (Time.unscaledTime >= _nextGuiErrorLogTime)
				{
					_nextGuiErrorLogTime = Time.unscaledTime + 5f;
					Logger.LogError((object)("GUI failed: " + ex));
				}
			}
		}
	}
	internal static class SoloMenu
	{
		private const string SwitchOn = "LOADOUT MENU: ON";

		private const string SwitchOff = "LOADOUT MENU: OFF";

		private const string NoteOn = "Loadout menu opens after you spawn.";

		private const string NoteOff = "No loadout menu this run.";

		public static void Draw()
		{
			if (!((Object)(object)WorldGeneration.world != (Object)null))
			{
				PreRunScript instance = PreRunScript.instance;
				if (!((Object)(object)instance == (Object)null) && IsRunSettingsOpen(instance))
				{
					DrawSwitch();
				}
			}
		}

		private static bool IsRunSettingsOpen(PreRunScript pre)
		{
			if ((Object)(object)pre.runSettingsScreen != (Object)null && pre.runSettingsScreen.activeInHierarchy)
			{
				return !pre.startedLoading;
			}
			return false;
		}

		private static void DrawSwitch()
		{
			//IL_015c: 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_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			//IL_0045: 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_0063: Expected O, but got Unknown
			//IL_005e: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			PixelSkin.Ensure();
			float unit = PixelSkin.Unit;
			bool value = ModConfig.Enabled.Value;
			string text = (value ? "Loadout menu opens after you spawn." : "No loadout menu this run.");
			GUIStyle val = (value ? PixelSkin.Accent : PixelSkin.Muted);
			float num = Mathf.Max(PixelSkin.BigButton.CalcSize(new GUIContent("LOADOUT MENU: OFF")).x + unit * 2f, val.CalcSize(new GUIContent(text)).x + unit * 2f);
			float num2 = unit * 4.6f;
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(unit * 0.6f, unit * 0.6f, num, num2);
			GUISkin skin = GUI.skin;
			GUI.skin = PixelSkin.Skin;
			try
			{
				GUI.Box(val2, GUIContent.none, PixelSkin.Panel);
				Rect val3 = default(Rect);
				((Rect)(ref val3))..ctor(((Rect)(ref val2)).x + unit * 0.5f, ((Rect)(ref val2)).y + unit * 0.5f, ((Rect)(ref val2)).width - unit, unit * 2.2f);
				GUIContent val4 = new GUIContent(value ? "LOADOUT MENU: ON" : "LOADOUT MENU: OFF");
				if (GUI.Button(val3, val4, PixelSkin.BigButton))
				{
					ModConfig.Enabled.Value = !value;
					try
					{
						PlayerCamera.PlayUISound("click", 1f);
					}
					catch
					{
					}
				}
				Rect val5 = new Rect(((Rect)(ref val2)).x, ((Rect)(ref val3)).yMax + unit * 0.2f, ((Rect)(ref val2)).width, unit * 1.4f);
				GUIStyle val6 = new GUIStyle(val)
				{
					alignment = (TextAnchor)4
				};
				GUI.Label(val5, text, val6);
			}
			finally
			{
				GUI.skin = skin;
			}
		}
	}
	[HarmonyPatch(typeof(WorldGeneration), "Awake")]
	internal static class WorldGeneration_Awake_CampaignPatch
	{
		private static void Postfix()
		{
			LoadoutClient.ResetLocal();
		}
	}
	internal sealed class ItemRules
	{
		private const string KeyPrices = "prices";

		private const string KeyBanned = "banned";

		private const string KeyAdded = "added";

		private readonly Dictionary<string, float> _prices = new Dictionary<string, float>(StringComparer.Ordinal);

		private readonly HashSet<string> _banned = new HashSet<string>(StringComparer.Ordinal);

		private readonly HashSet<string> _added = new HashSet<string>(StringComparer.Ordinal);

		public const float MaxPrice = 1000000f;

		public IReadOnlyDictionary<string, float> Prices => _prices;

		public IEnumerable<string> Banned => _banned;

		public IEnumerable<string> Added => _added;

		public int BannedCount => _banned.Count;

		public int AddedCount => _added.Count;

		public int Revision { get; private set; }

		public string Hash { get; private set; }

		public ItemRules()
		{
			Hash = ComputeHash();
		}

		public bool TryGetPrice(string id, out float price)
		{
			return _prices.TryGetValue(id, out price);
		}

		public bool IsBanned(string id)
		{
			return _banned.Contains(id);
		}

		public bool IsAdded(string id)
		{
			return _added.Contains(id);
		}

		public void SetPrice(string id, float price)
		{
			_prices[id] = price;
			Changed();
		}

		public bool ResetPrice(string id)
		{
			bool num = _prices.Remove(id);
			if (num)
			{
				Changed();
			}
			return num;
		}

		public int ResetAllPrices()
		{
			int count = _prices.Count;
			_prices.Clear();
			if (count > 0)
			{
				Changed();
			}
			return count;
		}

		public bool Ban(string id)
		{
			bool num = _banned.Add(id);
			if (num)
			{
				Changed();
			}
			return num;
		}

		public bool Unban(string id)
		{
			bool num = _banned.Remove(id);
			if (num)
			{
				Changed();
			}
			return num;
		}

		public int UnbanAll()
		{
			int count = _banned.Count;
			_banned.Clear();
			if (count > 0)
			{
				Changed();
			}
			return count;
		}

		public bool Add(string id)
		{
			bool num = _added.Add(id);
			if (num)
			{
				Changed();
			}
			return num;
		}

		public bool Remove(string id)
		{
			if (!_added.Remove(id))
			{
				return false;
			}
			_prices.Remove(id);
			_banned.Remove(id);
			Changed();
			return true;
		}

		private void Changed()
		{
			Revision++;
			Hash = ComputeHash();
		}

		public JObject ToJson()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_00c1: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Expected O, but got Unknown
			//IL_0101: Expected O, but got Unknown
			JObject val = new JObject();
			foreach (KeyValuePair<string, float> item in _prices.OrderBy<KeyValuePair<string, float>, string>((KeyValuePair<string, float> p) => p.Key, StringComparer.Ordinal))
			{
				val[item.Key] = JToken.op_Implicit(item.Value);
			}
			return new JObject
			{
				["prices"] = (JToken)(object)val,
				["banned"] = (JToken)new JArray((object)_banned.OrderBy<string, string>((string x) => x, StringComparer.Ordinal)),
				["added"] = (JToken)new JArray((object)_added.OrderBy<string, string>((string x) => x, StringComparer.Ordinal))
			};
		}

		public void ReplaceWith(JToken json, string hash = null)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Invalid comparison between Unknown and I4
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Invalid comparison between Unknown and I4
			_prices.Clear();
			_banned.Clear();
			_added.Clear();
			JObject val = (JObject)(object)((json is JObject) ? json : null);
			if (val != null)
			{
				JToken obj = val["prices"];
				JObject val2 = (JObject)(object)((obj is JObject) ? obj : null);
				if (val2 != null)
				{
					foreach (JProperty item in val2.Properties())
					{
						if (!string.IsNullOrWhiteSpace(item.Name))
						{
							float num = (((int)item.Value.Type == 7 || (int)item.Value.Type == 6) ? Extensions.Value<float>((IEnumerable<JToken>)item.Value) : float.NaN);
							if (IsValidPrice(num))
							{
								_prices[item.Name] = num;
							}
						}
					}
				}
				ReadSet(val["banned"], _banned);
				ReadSet(val["added"], _added);
			}
			Revision++;
			Hash = (string.IsNullOrEmpty(hash) ? ComputeHash() : hash);
		}

		public static bool IsValidPrice(float price)
		{
			if (!float.IsNaN(price) && !float.IsInfinity(price) && price >= 0f)
			{
				return price <= 1000000f;
			}
			return false;
		}

		private static void ReadSet(JToken token, HashSet<string> into)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Invalid comparison between Unknown and I4
			JArray val = (JArray)(object)((token is JArray) ? token : null);
			if (val == null)
			{
				return;
			}
			foreach (JToken item in val)
			{
				string text = (((int)item.Type == 8) ? Extensions.Value<string>((IEnumerable<JToken>)item) : null);
				if (!string.IsNullOrWhiteSpace(text))
				{
					into.Add(text);
				}
			}
		}

		private string ComputeHash()
		{
			string s = ((JToken)ToJson()).ToString((Formatting)0, Array.Empty<JsonConverter>());
			ulong num = 14695981039346656037uL;
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			foreach (byte b in bytes)
			{
				num ^= b;
				num *= 1099511628211L;
			}
			return num.ToString("x16", CultureInfo.InvariantCulture);
		}
	}
	internal static class ItemRulesStore
	{
		public static readonly ItemRules Local = new ItemRules();

		public static string FilePath => Path.Combine(Paths.ConfigPath, "com.casprepared.standalone.items.json");

		public static void Load()
		{
			try
			{
				if (File.Exists(FilePath))
				{
					Local.ReplaceWith(JToken.Parse(File.ReadAllText(FilePath)));
					Plugin.Logger.LogInfo((object)$"Item rules loaded: {Local.Prices.Count} custom prices, {Local.BannedCount} hidden, {Local.AddedCount} added.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("Could not read " + FilePath + ": " + ex.Message + ". Item rules are empty; the broken file is kept as .bad."));
				try
				{
					File.Copy(FilePath, FilePath + ".bad", overwrite: true);
				}
				catch
				{
				}
			}
		}

		public static void Save()
		{
			try
			{
				File.WriteAllText(FilePath, ((JToken)Local.ToJson()).ToString((Formatting)1, Array.Empty<JsonConverter>()));
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogError((object)("Could not write " + FilePath + ": " + ex.Message));
				throw new Exception("Could not save the item rules file. See the BepInEx log.");
			}
		}
	}
	internal sealed class CatalogEntry
	{
		public string Id;

		public string Name;

		public string Category;

		public string Group;

		public string Description;

		public float BaseValue;

		public float VanillaValue;

		public bool Extra;

		private bool _iconResolved;

		private Sprite _icon;

		public Sprite Icon
		{
			get
			{
				if (_iconResolved)
				{
					return _icon;
				}
				_iconResolved = true;
				_icon = LoadoutCatalog.SpriteOf(Id);
				return _icon;
			}
		}
	}
	internal static class LoadoutCatalog
	{
		public const int MaxPerItem = 50;

		public const int MaxTotalItems = 200;

		public static Func<ItemRules> RulesProvider = () => ItemRulesStore.Local;

		private static List<CatalogEntry> _base;

		private static Dictionary<string, CatalogEntry> _baseById;

		private static List<CatalogEntry> _entries;

		private static List<string> _groups;

		private static Dictionary<string, CatalogEntry> _byId;

		private static ItemRules _builtRules;

		private static int _builtRevision = -1;

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

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

		private static readonly string[] GroupOrder = new string[11]
		{
			"Weapons", "Ammo", "Gear", "Medical", "Drug", "Food", "Water", "Tool", "Utility", "Container",
			"Other"
		};

		public static int Version { get; private set; }

		public static IReadOnlyList<CatalogEntry> Entries
		{
			get
			{
				EnsureBuilt();
				IReadOnlyList<CatalogEntry> entries = _entries;
				return entries ?? Array.Empty<CatalogEntry>();
			}
		}

		public static IReadOnlyList<string> Groups
		{
			get
			{
				EnsureBuilt();
				IReadOnlyList<string> groups = _groups;
				return groups ?? Array.Empty<string>();
			}
		}

		public static bool IsLoaded
		{
			get
			{
				EnsureBuilt();
				return _base != null;
			}
		}

		public static IEnumerable<string> BaseIds
		{
			get
			{
				EnsureBuilt();
				return _base?.Select((CatalogEntry e) => e.Id) ?? Enumerable.Empty<string>();
			}
		}

		public static IEnumerable<string> AllItemIds
		{
			get
			{
				if (Item.GlobalItems != null)
				{
					return Item.GlobalItems.Keys.Where((string k) => !string.IsNullOrEmpty(k) && k != "casprep_supplycrate");
				}
				return Enumerable.Empty<string>();
			}
		}

		public static bool TryGet(string id, out CatalogEntry entry)
		{
			EnsureBuilt();
			entry = null;
			if (id != null && _byId != null)
			{
				return _byId.TryGetValue(id, out entry);
			}
			return false;
		}

		public static bool TryGetBase(string id, out CatalogEntry entry)
		{
			EnsureBuilt();
			entry = null;
			if (id != null && _baseById != null)
			{
				return _baseById.TryGetValue(id, out entry);
			}
			return false;
		}

		public static bool IsGameItem(string id)
		{
			if (id != null && id != "casprep_supplycrate" && Item.GlobalItems != null)
			{
				return Item.GlobalItems.ContainsKey(id);
			}
			return false;
		}

		public static string NameOf(string id)
		{
			if (id != null && Item.GlobalItems != null && Item.GlobalItems.TryGetValue(id, out var value) && value != null && !string.IsNullOrEmpty(value.fullName))
			{
				return value.fullName;
			}
			return id;
		}

		public static int TraderValueOf(string id)
		{
			if (id == null || Item.GlobalItems == null || !Item.GlobalItems.TryGetValue(id, out var value) || value == null)
			{
				return 0;
			}
			if (value.value <= 0)
			{
				return 0;
			}
			try
			{
				return Math.Max(0, value.DefaultValue());
			}
			catch
			{
				return 0;
			}
		}

		public static long PriceOf(CatalogEntry entry, float multiplier, int count = 1)
		{
			if (count <= 0)
			{
				return 0L;
			}
			double num = (double)entry.BaseValue * (double)Math.Max(0f, multiplier) * (double)count;
			return Math.Max(0L, (long)Math.Ceiling(num - 1E-06));
		}

		public static bool IsSpawnable(string id)
		{
			return (Object)(object)GetPrefab(id) != (Object)null;
		}

		private static GameObject GetPrefab(string id)
		{
			if (PrefabCache.TryGetValue(id, out var value))
			{
				return value;
			}
			try
			{
				Object obj = Resources.Load(id);
				value = (GameObject)(object)((obj is GameObject) ? obj : null);
			}
			catch
			{
				value = null;
			}
			PrefabCache[id] = value;
			return value;
		}

		private static AmmoScript GetAmmo(string id)
		{
			GameObject prefab = GetPrefab(id);
			if (!((Object)(object)prefab != (Object)null))
			{
				return null;
			}
			return prefab.GetComponent<AmmoScript>();
		}

		private static void EnsureBuilt()
		{
			if (_base == null)
			{
				BuildBase();
			}
			if (_base != null)
			{
				ItemRules itemRules = RulesProvider?.Invoke() ?? ItemRulesStore.Local;
				if (_entries == null || itemRules != _builtRules || itemRules.Revision != _builtRevision)
				{
					_builtRules = itemRules;
					_builtRevision = itemRules.Revision;
					BuildEffective(itemRules);
				}
			}
		}

		private static void BuildEffective(ItemRules rules)
		{
			List<CatalogEntry> list = new List<CatalogEntry>();
			foreach (CatalogEntry item in _base)
			{
				if (!rules.IsBanned(item.Id))
				{
					list.Add(rules.TryGetPrice(item.Id, out var price) ? Copy(item, price) : item);
				}
			}
			foreach (string item2 in rules.Added)
			{
				if (!rules.IsBanned(item2) && !_baseById.ContainsKey(item2) && IsGameItem(item2))
				{
					float num = TraderValueOf(item2);
					float price2;
					bool num2 = rules.TryGetPrice(item2, out price2);
					float num3 = (num2 ? price2 : num);
					if (num2 || !(num3 <= 0f))
					{
						CatalogEntry catalogEntry = NewEntry(item2, Item.GlobalItems[item2], num3);
						catalogEntry.VanillaValue = num;
						catalogEntry.Extra = true;
						list.Add(catalogEntry);
					}
				}
			}
			list.Sort((CatalogEntry a, CatalogEntry b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
			_entries = list;
			_byId = list.ToDictionary((CatalogEntry e) => e.Id, (CatalogEntry e) => e);
			_groups = list.Select((CatalogEntry e) => e.Group).Distinct().OrderBy(delegate(string g)
			{
				int num4 = Array.IndexOf(GroupOrder, g);
				return (num4 < 0) ? GroupOrder.Length : num4;
			})
				.ThenBy<string, string>((string g) => g, StringComparer.OrdinalIgnoreCase)
				.ToList();
			Version++;
		}

		private static CatalogEntry Copy(CatalogEntry b, float price)
		{
			return new CatalogEntry
			{
				Id = b.Id,
				Name = b.Name,
				Category = b.Category,
				Group = b.Group,
				Description = b.Description,
				BaseValue = price,
				VanillaValue = b.VanillaValue
			};
		}

		private static void BuildBase()
		{
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Invalid comparison between Unknown and I4
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			if (Item.GlobalItems == null || Item.GlobalItems.Count == 0)
			{
				return;
			}
			List<CatalogEntry> list = new List<CatalogEntry>();
			List<(string, ItemInfo, AmmoScript)> list2 = new List<(string, ItemInfo, AmmoScript)>();
			Dictionary<AmmoType, float> dictionary = new Dictionary<AmmoType, float>();
			foreach (KeyValuePair<string, ItemInfo> globalItem in Item.GlobalItems)
			{
				string key = globalItem.Key;
				ItemInfo value = globalItem.Value;
				if (value == null || string.IsNullOrEmpty(key) || key == "casprep_supplycrate" || value.untradeable || value.secret)
				{
					continue;
				}
				if (value.value <= 0)
				{
					AmmoScript ammo = GetAmmo(key);
					if ((Object)(object)ammo != (Object)null && (int)ammo.itemType == 0)
					{
						list2.Add((key, value, ammo));
					}
					continue;
				}
				int num;
				try
				{
					num = value.DefaultValue();
				}
				catch
				{
					continue;
				}
				if (num <= 0)
				{
					continue;
				}
				AmmoScript ammo2 = GetAmmo(key);
				if ((Object)(object)ammo2 != (Object)null && (int)ammo2.itemType == 1 && ammo2.maxRounds > 0)
				{
					float num2 = (float)num / (float)ammo2.maxRounds;
					if (!dictionary.TryGetValue(ammo2.ammoType, out var value2) || num2 < value2)
					{
						dictionary[ammo2.ammoType] = num2;
					}
				}
				list.Add(NewEntry(key, value, num));
			}
			foreach (var (id, info, val) in list2)
			{
				if (dictionary.TryGetValue(val.ammoType, out var value3) && value3 > 0f)
				{
					list.Add(NewEntry(id, info, value3));
				}
			}
			if (list.Count == 0)
			{
				return;
			}
			foreach (CatalogEntry item in list)
			{
				item.VanillaValue = item.BaseValue;
			}
			_base = list;
			_baseById = list.ToDictionary((CatalogEntry e) => e.Id, (CatalogEntry e) => e);
		}

		private static CatalogEntry NewEntry(string id, ItemInfo info, float value)
		{
			return new CatalogEntry
			{
				Id = id,
				Name = (string.IsNullOrEmpty(info.fullName) ? id : info.fullName),
				Category = (info.category ?? string.Empty),
				Group = GroupOf(id, info),
				Description = (info.description ?? string.Empty),
				BaseValue = value
			};
		}

		private static string GroupOf(string id, ItemInfo info)
		{
			GameObject prefab = GetPrefab(id);
			if ((Object)(object)prefab != (Object)null)
			{
				if ((Object)(object)prefab.GetComponent<AmmoScript>() != (Object)null)
				{
					return "Ammo";
				}
				if ((Object)(object)prefab.GetComponent<GunScript>() != (Object)null)
				{
					return "Weapons";
				}
			}
			if (info.wearable)
			{
				return "Gear";
			}
			string text = (info.category ?? string.Empty).Trim();
			if (text.Length == 0 || text.Equals("custom", StringComparison.OrdinalIgnoreCase) || text.Equals("trash", StringComparison.OrdinalIgnoreCase))
			{
				return "Other";
			}
			return char.ToUpperInvariant(text[0]) + text.Substring(1).ToLowerInvariant();
		}

		internal static Sprite SpriteOf(string id)
		{
			if (SpriteCache.TryGetValue(id, out var value))
			{
				return value;
			}
			Sprite val = null;
			GameObject prefab = GetPrefab(id);
			if ((Object)(object)prefab != (Object)null)
			{
				SpriteRenderer val2 = prefab.GetComponent<SpriteRenderer>();
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = prefab.GetComponentInChildren<SpriteRenderer>(true);
				}
				if ((Object)(object)val2 != (Object)null && (Object)(object)val2.sprite != (Object)null)
				{
					val = val2.sprite;
				}
			}
			SpriteCache[id] = val;
			return val;
		}

		public static void PrepareSpawned(GameObject go)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			AmmoScript val = default(AmmoScript);
			if ((Object)(object)go != (Object)null && go.TryGetComponent<AmmoScript>(ref val) && (int)val.itemType == 1)
			{
				val.rounds = val.maxRounds;
			}
		}
	}
	internal static class LoadoutCommands
	{
		private sealed class Sub
		{
			public string Name;

			public string Help;

			public (string, string)[] Params = Array.Empty<(string, string)>();

			public Func<int, List<string>> Fill;

			public Action<string[]> Run;

			public (string, string)[] Description;
		}

		private enum FillKind
		{
			Listed,
			Priced,
			Bannable,
			Banned,
			Addable,
			Added
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static Action <0>__Execute;

			public static Action<string[]> <1>__SetPrice;

			public static Action<string[]> <2>__ResetPrice;

			public static Action<string[]> <3>__Ban;

			public static Action<string[]> <4>__Unban;

			public static Action<string[]> <5>__AddItem;

			public static Action<string[]> <6>__RemoveItem;
		}

		public const string Name = "casprep";

		private static readonly List<Sub> Subs = new List<Sub>();

		private static readonly (string, string)[] RootArgs = new(string, string)[1] { ("command", "Type a command, Tab completes. casprep help lists them.") };

		private static Command _command;

		private static List<string> _subNames;

		private static Dictionary<int, List<string>> _rootFill;

		private static readonly Dictionary<int, List<string>> HintFill = new Dictionary<int, List<string>>();

		private const string HostOnly = "";

		private static readonly List<string> OnOffList = new List<string> { "on", "off" };

		private static readonly Dictionary<FillKind, (string stamp, List<string> list)> FillCache = new Dictionary<FillKind, (string, List<string>)>();

		public static void Register()
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//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_00e0: Expected O, but got Unknown
			AddSubs();
			foreach (Sub sub in Subs)
			{
				sub.Description = new(string, string)[1] { (sub.Name, sub.Help + HostTag(sub)) }.Concat(sub.Params).ToArray();
			}
			_subNames = Subs.Select((Sub s) => s.Name).ToList();
			_rootFill = new Dictionary<int, List<string>> { [0] = _subNames };
			object obj = <>O.<0>__Execute;
			if (obj == null)
			{
				Action val = Execute;
				<>O.<0>__Execute = val;
				obj = (object)val;
			}
			_command = new Command("casprep", "CasPrepared loadout menu: settings and item list. casprep help lists the commands.", (Action)obj, _rootFill, RootArgs);
			ConsoleCommandRegistry.Register(_command);
		}

		private static string HostTag(Sub s)
		{
			if (!(s.Name == "menu") && !(s.Name == "help") && !(s.Name == "giveloadout") && !(s.Name == "cheats"))
			{
				return "";
			}
			return string.Empty;
		}

		private static void AddSubs()
		{
			Add("menu", "Open or close the loadout menu.", delegate
			{
				LoadoutClient.ToggleMenu();
			}, null);
			Add("help", "List the commands.", delegate
			{
				Help();
			}, null);
			Add("status", Describe("show the settings", "list players and their loadout state"), delegate
			{
				Status();
			}, null);
			Add("enable", Describe("turn the loadout menu on or off for new runs", "turn the loadout menu on or off for sessions you host"), delegate(string[] p)
			{
				if (p.Length >= 1)
				{
					RequireConfigAccess();
					ModConfig.Enabled.Value = ParseBool(p[0]);
				}
				Log("Loadout menu: " + (ModConfig.Enabled.Value ? "ON" : "OFF"));
			}, (int i) => (i != 0) ? null : OnOffList, ("on/off", "Omit to show the current state."));
			Add("budget", "Show or set the loadout budget.", delegate(string[] p)
			{
				IntSetting(p, "Budget", delegate(int v)
				{
					ModConfig.Budget.Value = v;
				}, () => ModConfig.Budget.Value);
			}, null, ("number", "New budget. Omit to show the current value."));
			Add("mult", "Show or set the price multiplier.", delegate(string[] p)
			{
				FloatSetting(p, "Price multiplier", delegate(float v)
				{
					ModConfig.PriceMultiplier.Value = v;
				}, () => ModConfig.PriceMultiplier.Value);
			}, null, ("number", "Multiplier for all prices (1.0 = trader price)."));
			Add("radius", "Show or set how far (tiles) a player may move from spawn before the menu closes.", delegate(string[] p)
			{
				FloatSetting(p, "Max distance", delegate(float v)
				{
					ModConfig.MaxDistance.Value = v;
				}, () => ModConfig.MaxDistance.Value);
			}, null, ("tiles", "Distance in world units."));
			Add("cratetime", "Show or set the supply crate lifetime in seconds.", delegate(string[] p)
			{
				IntSetting(p, "Crate lifetime", delegate(int v)
				{
					ModConfig.CrateLifetimeSeconds.Value = v;
				}, () => ModConfig.CrateLifetimeSeconds.Value);
			}, null, ("seconds", "Lifetime in seconds."));
			Add("setprice", "Set a custom base price for an item (before the multiplier).", SetPrice, (int i) => (i != 0) ? null : Fill(FillKind.Listed), ("item", "Item from the list."), ("price", "Price per unit before the multiplier."));
			Add("resetprice", "Remove a custom price (back to the trader price).", ResetPrice, (int i) => (i != 0) ? null : Fill(FillKind.Priced), ("item/all", "Item with a custom price, or 'all'."));
			Add("ban", "Hide an item from the list.", Ban, (int i) => (i != 0) ? null : Fill(FillKind.Bannable), ("item", "Item to hide."));
			Add("unban", "Show a hidden item again.", Unban, (int i) => (i != 0) ? null : Fill(FillKind.Banned), ("item/all", "Hidden item, or 'all'."));
			Add("additem", "Add an item that traders do not sell.", AddItem, (int i) => (i != 0) ? null : Fill(FillKind.Addable), ("item", "Any game item."), ("price", "Base price. Optional when the item has a trader price."));
			Add("removeitem", "Remove an added item.", RemoveItem, (int i) => (i != 0) ? null : Fill(FillKind.Added), ("item", "Item added with casprep additem."));
			Add("items", "List custom prices, hidden and added items.", delegate
			{
				ListRules();
			}, null);
		}

		private static string Describe(string standalone, string multiplayer)
		{
			return char.ToUpperInvariant(standalone[0]) + standalone.Substring(1) + ".";
		}

		private static void Add(string name, string help, Action<string[]> run, Func<int, List<string>> fill = null, params (string, string)[] parameters)
		{
			Subs.Add(new Sub
			{
				Name = name,
				Help = help,
				Run = run,
				Fill = fill,
				Params = (parameters ?? Array.Empty<(string, string)>())
			});
		}

		private static Sub Find(string name)
		{
			if (name != null)
			{
				return Subs.FirstOrDefault((Sub s) => s.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
			}
			return null;
		}

		private static void Execute(string[] args)
		{
			if (args.Length < 2)
			{
				Help();
			}
			else
			{
				(Find(args[1]) ?? throw new Exception("Unknown command '" + args[1] + "'. Type: casprep help")).Run(args.Skip(2).ToArray());
			}
		}

		private static void Help()
		{
			Log("CasPrepared commands (casprep <command> [value]):");
			foreach (Sub sub in Subs)
			{
				string text = ((sub.Params.Length == 0) ? string.Empty : (" [" + string.Join("] [", sub.Params.Select(((string, string) p) => p.Item1)) + "]"));
				Log("  " + sub.Name + text + " - " + sub.Help + HostTag(sub));
			}
		}

		internal static void PrepareHints(string[] args)
		{
			if (_command == null || args == null || args.Length == 0 || !"casprep".Equals(args[0], StringComparison.OrdinalIgnoreCase))
			{
				return;
			}
			Sub sub = ((args.Length >= 3) ? Find(args[1]) : null);
			if (sub == null)
			{
				_command.argDescription = RootArgs;
				_command.argAutofill = _rootFill;
				return;
			}
			_command.argDescription = sub.Description;
			HintFill.Clear();
			HintFill[0] = _subNames;
			int num = args.Length - 3;
			if (num >= 0 && sub.Fill != null)
			{
				List<string> list = sub.Fill(num);
				if (list != null)
				{
					HintFill[num + 1] = list;
				}
			}
			_command.argAutofill = HintFill;
		}

		private static List<string> Fill(FillKind kind)
		{
			ItemRules rules = ItemRulesStore.Local;
			string text = rules.Revision + ":" + (Item.GlobalItems?.Count ?? 0) + ":" + LoadoutCatalog.IsLoaded;
			if (FillCache.TryGetValue(kind, out (string, List<string>) value) && value.Item1 == text)
			{
				return value.Item2;
			}
			IEnumerable<string> source;
			switch (kind)
			{
			case FillKind.Listed:
				source = ListedIds();
				break;
			case FillKind.Priced:
				source = rules.Prices.Keys.Concat(new string[1] { "all" });
				break;
			case FillKind.Bannable:
				source = from id in ListedIds()
					where !rules.IsBanned(id)
					select id;
				break;
			case FillKind.Banned:
				source = rules.Banned.Concat(new string[1] { "all" });
				break;
			case FillKind.Addable:
			{
				HashSet<string> listed = new HashSet<string>(ListedIds());
				source = LoadoutCatalog.AllItemIds.Where((string id) => !listed.Contains(id));
				break;
			}
			default:
				source = rules.Added;
				break;
			}
			List<string> list = source.Distinct().OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase).ToList();
			FillCache[kind] = (text, list);
			return list;
		}

		private static IEnumerable<string> ListedIds()
		{
			return LoadoutCatalog.BaseIds.Concat(ItemRulesStore.Local.Added);
		}

		private static void SetPrice(string[] p)
		{
			RequireConfigAccess();
			if (p.Length < 2)
			{
				throw new Exception("Usage: casprep setprice <item> <price>");
			}
			string known;
			string text = ResolveItem(p[0], ListedIds(), out known);
			if (text == null)
			{
				throw new Exception((known != null) ? ("'" + known + "' is not in the list. Add it with: casprep additem " + known + " <price>") : UnknownItem(p[0]));
			}
			float num = ParsePrice(p[1]);
			ItemRulesStore.Local.SetPrice(text, num);
			ItemRulesStore.Save();
			CatalogEntry entry;
			float v = (LoadoutCatalog.TryGetBase(text, out entry) ? entry.VanillaValue : ((float)LoadoutCatalog.TraderValueOf(text)));
			Log(LoadoutCatalog.NameOf(text) + " (" + text + "): base price " + Num(num) + " (trader " + Num(v) + "), x" + Num(ModConfig.PriceMultiplier.Value) + " multiplier on top.");
		}

		private static void ResetPrice(string[] p)
		{
			RequireConfigAccess();
			if (p.Length < 1)
			{
				throw new Exception("Usage: casprep resetprice <item | all>");
			}
			ItemRules local = ItemRulesStore.Local;
			if (IsAll(p[0]))
			{
				int num = local.ResetAllPrices();
				ItemRulesStore.Save();
				Log($"Removed {num} custom price(s).");
				return;
			}
			string known;
			string text = ResolveItem(p[0], local.Prices.Keys, out known) ?? throw new Exception("'" + p[0] + "' has no custom price.");
			local.ResetPrice(text);
			ItemRulesStore.Save();
			Log(LoadoutCatalog.NameOf(text) + " (" + text + "): back to the trader price.");
			if (local.IsAdded(text) && LoadoutCatalog.TraderValueOf(text) <= 0)
			{
				Log("It has no trader price, so it stays out of the list until you set one: casprep setprice " + text + " <price>");
			}
		}

		private static void Ban(string[] p)
		{
			RequireConfigAccess();
			if (p.Length < 1)
			{
				throw new Exception("Usage: casprep ban <item>");
			}
			string known;
			string text = ResolveItem(p[0], ListedIds(), out known) ?? throw new Exception((known != null) ? ("'" + known + "' is not in the list anyway.") : UnknownItem(p[0]));
			if (!ItemRulesStore.Local.Ban(text))
			{
				throw new Exception("'" + text + "' is already hidden.");
			}
			ItemRulesStore.Save();
			Log(LoadoutCatalog.NameOf(text) + " (" + text + ") is hidden from the list.");
		}

		private static void Unban(string[] p)
		{
			RequireConfigAccess();
			if (p.Length < 1)
			{
				throw new Exception("Usage: casprep unban <item | all>");
			}
			ItemRules local = ItemRulesStore.Local;
			if (IsAll(p[0]))
			{
				int num = local.UnbanAll();
				ItemRulesStore.Save();
				Log($"{num} item(s) back in the list.");
			}
			else
			{
				string known;
				string text = ResolveItem(p[0], local.Banned, out known) ?? throw new Exception("'" + p[0] + "' is not hidden.");
				local.Unban(text);
				ItemRulesStore.Save();
				Log(LoadoutCatalog.NameOf(text) + " (" + text + ") is back in the list.");
			}
		}

		private static void AddItem(string[] p)
		{
			RequireConfigAccess();
			if (p.Length < 1)
			{
				throw new Exception("Usage: casprep additem <item> [price]");
			}
			if (!LoadoutCatalog.IsLoaded)
			{
				throw new Exception("The item list is not loaded yet.");
			}
			ItemRules local = ItemRulesStore.Local;
			string known;
			string text = ResolveItem(p[0], LoadoutCatalog.AllItemIds, out known) ?? throw new Exception(UnknownItem(p[0]));
			if (LoadoutCatalog.TryGetBase(text, out var _))
			{
				throw new Exception(local.IsBanned(text) ? ("'" + text + "' is a trader item that you hid. Use: casprep unban " + text) : ("'" + text + "' is already in the list (traders sell it)."));
			}
			if (local.IsAdded(text))
			{
				throw new Exception("'" + text + "' is already added.");
			}
			if (!LoadoutCatalog.IsSpawnable(text))
			{
				throw new Exception("'" + text + "' cannot be spawned.");
			}
			float? num = ((p.Length >= 2) ? new float?(ParsePrice(p[1])) : ((float?)null));
			int num2 = LoadoutCatalog.TraderValueOf(text);
			if (!num.HasValue && num2 <= 0)
			{
				throw new Exception("'" + text + "' has no trader price. Give one: casprep additem " + text + " <price>");
			}
			local.Add(text);
			if (num.HasValue)
			{
				local.SetPrice(text, num.Value);
			}
			ItemRulesStore.Save();
			Log(LoadoutCatalog.NameOf(text) + " (" + text + ") added, base price " + Num(num ?? ((float)num2)) + ".");
		}

		private static void RemoveItem(string[] p)
		{
			RequireConfigAccess();
			if (p.Length < 1)
			{
				throw new Exception("Usage: casprep removeitem <item>");
			}
			string known;
			string text = ResolveItem(p[0], ItemRulesStore.Local.Added, out known) ?? throw new Exception("'" + p[0] + "' was not added with casprep additem.");
			ItemRulesStore.Local.Remove(text);
			ItemRulesStore.Save();
			Log(LoadoutCatalog.NameOf(text) + " (" + text + ") removed from the list.");
		}

		private static void ListRules()
		{
			ItemRules local = ItemRulesStore.Local;
			if (local.Prices.Count == 0 && local.BannedCount == 0 && local.AddedCount == 0)
			{
				Log("No item rules: the list matches the traders.");
				Log("File: " + ItemRulesStore.FilePath);
				return;
			}
			if (local.AddedCount > 0)
			{
				Log("Added:");
				foreach (string item in local.Added.OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
				{
					Log("  " + LoadoutCatalog.NameOf(item) + " (" + item + ")" + (local.IsBanned(item) ? " - hidden" : string.Empty));
				}
			}
			if (local.Prices.Count > 0)
			{
				Log("Custom prices (before the multiplier):");
				foreach (KeyValuePair<string, float> item2 in local.Prices.OrderBy<KeyValuePair<string, float>, string>((KeyValuePair<string, float> x) => x.Key, StringComparer.OrdinalIgnoreCase))
				{
					CatalogEntry entry;
					float v = (LoadoutCatalog.TryGetBase(item2.Key, out entry) ? entry.VanillaValue : ((float)LoadoutCatalog.TraderValueOf(item2.Key)));
					Log("  " + LoadoutCatalog.NameOf(item2.Key) + " (" + item2.Key + "): " + Num(item2.Value) + " (trader " + Num(v) + ")");
				}
			}
			if (local.BannedCount > 0)
			{
				Log("Hidden:");
				foreach (string item3 in local.Banned.OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase))
				{
					Log("  " + LoadoutCatalog.NameOf(item3) + " (" + item3 + ")");
				}
			}
			Log("File: " + ItemRulesStore.FilePath);
		}

		private static string ResolveItem(string text, IEnumerable<string> pool, out string known)
		{
			known = null;
			if (!LoadoutCatalog.IsLoaded)
			{
				throw new Exception("The item list is not loaded yet.");
			}
			List<string> list = pool.Distinct().ToList();
			if (list.Contains(text))
			{
				return text;
			}
			List<string> list2 = list.Where((string id) => id.Equals(text, StringComparison.OrdinalIgnoreCase)).ToList();
			if (list2.Count == 1)
			{
				return list2[0];
			}
			known = LoadoutCatalog.AllItemIds.FirstOrDefault((string id) => id.Equals(text, StringComparison.OrdinalIgnoreCase));
			return null;
		}

		private static string UnknownItem(string text)
		{
			return "Unknown item '" + text + "'. Type the start of its id and press Tab.";
		}

		private static bool IsAll(string s)
		{
			return s.Equals("all", StringComparison.OrdinalIgnoreCase);
		}

		private static float ParsePrice(string s)
		{
			if (!float.TryParse(s.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || !ItemRules.IsValidPrice(result))
			{
				throw new Exception($"\"{s}\" is not a valid price (0 - {1000000f:0}).");
			}
			return result;
		}

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

		private static string RulesSummary()
		{
			ItemRules local = ItemRulesStore.Local;
			return $"Item rules: {local.Prices.Count} custom price(s), {local.BannedCount} hidden, {local.AddedCount} added (casprep items).";
		}

		private static void Status()
		{
			Log("Loadout menu: " + (ModConfig.Enabled.Value ? "ON" : "OFF"));
			Log($"Budget {ModConfig.Budget.Value}, multiplier x{Num(ModConfig.PriceMultiplier.Value)}, " + string.Format("radius {0}, crate {1}s", ModConfig.MaxDistance.Value.ToString("0.#", CultureInfo.InvariantCulture), ModConfig.CrateLifetimeSeconds.Value));
			Log(RulesSummary());
			Log("This run: " + LoadoutClient.DescribeState());
		}

		private static void IntSetting(string[] p, string label, Action<int> set, Func<int> get)
		{
			if (p.Length >= 1)
			{
				RequireConfigAccess();
				if (!int.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
				{
					throw new Exception("\"" + p[0] + "\" is not a valid integer.");
				}
				set(result);
			}
			Log($"{label}: {get()}");
		}

		private static void FloatSetting(string[] p, string label, Action<float> set, Func<float> get)
		{
			if (p.Length >= 1)
			{
				RequireConfigAccess();
				if (!float.TryParse(p[0].Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
				{
					throw new Exception("\"" + p[0] + "\" is not a valid number.");
				}
				set(result);
			}
			Log(label + ": " + get().ToString("0.###", CultureInfo.InvariantCulture));
		}

		private static bool ParseBool(string s)
		{
			switch (s.Trim().ToLowerInvariant())
			{
			case "1":
			case "on":
			case "yes":
			case "true":
			case "enable":
				return true;
			case "0":
			case "no":
			case "off":
			case "false":
			case "disable":
				return false;
			default:
				throw new Exception("\"" + s + "\" is not on/off.");
			}
		}

		public static string ConfigLockReason()
		{
			if ((Object)(object)WorldGeneration.world != (Object)null)
			{
				return "Settings are locked during a run. Change them in the main menu.";
			}
			return null;
		}

		private static void RequireConfigAccess()
		{
			string text = ConfigLockReason();
			if (text != null)
			{
				throw new Exception(text);
			}
		}

		private static void Log(string text)
		{
			ConsoleScript instance = ConsoleScript.instance;
			if (instance != null)
			{
				instance.LogToConsole(text);
			}
		}
	}
	[HarmonyPatch]
	internal static class ConsoleHintPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(ConsoleScript), "HandleDescriptionText")]
		private static void BeforeDescription(string[] args)
		{
			Safe(args);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(ConsoleScript), "TryFinishCommandPart")]
		private static void BeforeComplete(string[] args)
		{
			Safe(args);
		}

		private static void Safe(string[] args)
		{
			try
			{
				LoadoutCommands.PrepareHints(args);
			}
			catch
			{
			}
		}
	}
	internal static class LoadoutOrder
	{
		public sealed class Line
		{
			public CatalogEntry Entry;

			public int Count;
		}

		public static string Build(IEnumerable<KeyValuePair<string, int>> items, out List<Line> order, out long cost, out int total)
		{
			order = new List<Line>();
			cost = 0L;
			total = 0;
			if (items == null)
			{
				return "Nothing selected.";
			}
			float value = ModConfig.PriceMultiplier.Value;
			foreach (KeyValuePair<string, int> item in items)
			{
				if (!LoadoutCatalog.TryGet(item.Key, out var entry) || !LoadoutCatalog.IsSpawnable(entry.Id))
				{
					return "Item is not available: " + item.Key;
				}
				int value2 = item.Value;
				if (value2 > 0)
				{
					if (value2 > 50)
					{
						return $"Too many of {entry.Name} (max {50}).";
					}
					total += value2;
					cost += LoadoutCatalog.PriceOf(entry, value, value2);
					order.Add(new Line
					{
						Entry = entry,
						Count = value2
					});
				}
			}
			if (order.Count == 0)
			{
				return "Nothing selected.";
			}
			if (total > 200)
			{
				return $"Too many items (max {200}).";
			}
			if (cost > ModConfig.Budget.Value)
			{
				return $"Loadout costs {cost}, budget is {ModConfig.Budget.Value}.";
			}
			return null;
		}

		public static void Spawn(Body body, List<Line> order)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			Vector2 val = Vector2.op_Implicit(((Component)body).transform.position);
			GameObject val2 = Utils.Create("casprep_supplycrate", val, 0f);
			Container val3 = (((Object)(object)val2 != (Object)null) ? val2.GetComponent<Container>() : null);
			if ((Object)(object)val3 == (Object)null)
			{
				Plugin.Logger.LogWarning((object)"Supply crate failed to spawn, items will be dropped on the floor.");
			}
			foreach (Line item in order)
			{
				for (int i = 0; i < item.Count; i++)
				{
					GameObject val4 = Utils.Create(item.Entry.Id, val, 0f);
					LoadoutCatalog.PrepareSpawned(val4);
					if (!((Object)(object)val4 == (Object)null) && !((Object)(object)val3 == (Object)null))
					{
						Item component = val4.GetComponent<Item>();
						if ((Object)(object)component != (Object)null && val3.CanHoldItem(component))
						{
							val3.LoadItem(component);
						}
					}
				}
			}
		}
	}
	internal static class LoadoutUI
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static WindowFunction <0>__DrawWindow;
		}

		private const int WindowId = 13261289;

		private const string SearchControl = "casprep_search";

		private const string AllGroup = "All";

		private static bool _searchFocused;

		private static int _prunedVersion = -1;

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

		private static Rect _window;

		private static bool _placed;

		private static string _search = string.Empty;

		private static string _group = "All";

		private static string _filterKey;

		private static List<CatalogEntry> _filtered = new List<CatalogEntry>();

		private static Vector2 _catalogScroll;

		private static Vector2 _selectedScroll;

		private static float _catalogViewHeight = 2000f;

		private static float _selectedViewHeight = 2000f;

		private static string _message;

		private static CatalogEntry _hovered;

		private static CatalogEntry _hoveredNext;

		private const float RangeWarnFraction = 0.5f;

		private const float RangeRearmFraction = 0.4f;

		private const string RangeWarning = "STAY NEAR YOUR SPAWN";

		private static bool _rangeWarned;

		private static GUIStyle _countStyle;

		private static GUIStyle _countSource;

		public static bool IsOpen { get; private set; }

		public static bool IsSearchFocused
		{
			get
			{
				if (!_searchFocused)
				{
					return PresetPanel.NameFocused;
				}
				return true;
			}
		}

		public static bool BlocksGameInput
		{
			get
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: 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_003f: Unknown result type (might be due to invalid IL or missing references)
				if (!IsOpen)
				{
					return false;
				}
				if (IsSearchFocused)
				{
					return true;
				}
				Vector3 mousePosition = Input.mousePosition;
				Vector2 val = default(Vector2);
				((Vector2)(ref val))..ctor(mousePosition.x, (float)Screen.height - mousePosition.y);
				if (!((Rect)(ref _window)).Contains(val))
				{
					return PresetPanel.ContainsMouse(val);
				}
				return true;
			}
		}

		public static bool HasSelection => Selected.Count > 0;

		private static float RangeFraction
		{
			get
			{
				float maxDistance = LoadoutClient.MaxDistance;
				if (!(maxDistance > 0f))
				{
					return 0f;
				}
				return LoadoutClient.Distance / maxDistance;
			}
		}

		public static void Open()
		{
			IsOpen = true;
			_message = null;
			_filterKey = null;
		}

		public static void Close()
		{
			IsOpen = false;
			_searchFocused = false;
			_hovered = (_hoveredNext = null);
		}

		public static void ClearSelection()
		{
			Selected.Clear();
		}

		public static Dictionary<string, int> SelectionSnapshot()
		{
			return new Dictionary<string, int>(Selected);
		}

		public static int LoadSelection(IEnumerable<KeyValuePair<string, int>> items)
		{
			Selected.Clear();
			int num = 0;
			int num2 = 0;
			foreach (KeyValuePair<string, int> item in items)
			{
				if (item.Value <= 0)
				{
					continue;
				}
				if (!LoadoutCatalog.TryGet(item.Key, out var _))
				{
					num++;
					continue;
				}
				int num3 = Mathf.Min(new int[3]
				{
					item.Value,
					50,
					200 - num2
				});
				if (num3 < item.Value)
				{
					num++;
				}
				if (num3 > 0)
				{
					Selected[item.Key] = num3;
					num2 += num3;
				}
			}
			_message = null;
			return num;
		}

		public static void SetMessage(string message)
		{
			_message = message;
		}

		public static void Draw()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			if (!IsOpen)
			{
				return;
			}
			PixelSkin.Ensure();
			PlaceWindow();
			GUISkin skin = GUI.skin;
			GUI.skin = PixelSkin.Skin;
			try
			{
				Rect window = _window;
				object obj = <>O.<0>__DrawWindow;
				if (obj == null)
				{
					WindowFunction val = DrawWindow;
					<>O.<0>__DrawWindow = val;
					obj = (object)val;
				}
				_window = GUI.Window(13261289, window, (WindowFunction)obj, GUIContent.none, PixelSkin.Window);
				_window = ClampToScreen(_window);
				PresetPanel.Draw(_window);
			}
			finally
			{
				GUI.skin = skin;
			}
		}

		private static void PlaceWindow()
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			float unit = PixelSkin.Unit;
			float num = Mathf.Min(48f * unit, (float)Screen.width - 2f * unit);
			float num2 = Mathf.Min(37f * unit, (float)Screen.height - 2f * unit);
			if (!_placed || !Mathf.Approximately(((Rect)(ref _window)).width, num) || !Mathf.Approximately(((Rect)(ref _window)).height, num2))
			{
				Vector2 val = (Vector2)(_placed ? ((Rect)(ref _window)).center : new Vector2((float)Screen.width / 2f, (float)Screen.height / 2f));
				_window = new Rect(val.x - num / 2f, val.y - num2 / 2f, num, num2);
				_placed = true;
			}
		}

		private static Rect ClampToScreen(Rect r)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			((Rect)(ref r)).x = Mathf.Clamp(((Rect)(ref r)).x, 0f, Mathf.Max(0f, (float)Screen.width - ((Rect)(ref r)).width));
			((Rect)(ref r)).y = Mathf.Clamp(((Rect)(ref r)).y, 0f, Mathf.Max(0f, (float)Screen.height - ((Rect)(ref r)).height));
			return r;
		}

		private static void DrawWindow(int id)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			GUI.skin = PixelSkin.Skin;
			float unit = PixelSkin.Unit;
			int budget = LoadoutClient.Budget;
			float multiplier = LoadoutClient.Multiplier;
			long num = TotalCost(multiplier);
			int count = Selected.Values.Sum();
			bool overBudget = num > budget;
			if ((int)Event.current.type == 8)
			{
				_hovered = _hoveredNext;
				_hoveredNext = null;
			}
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			DrawTitleBar(unit);
			DrawStatusStrip(unit, multiplier);
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) });
			DrawCatalog(unit, multiplier);
			GUILayout.Space(unit * 0.4f);
			DrawSelection(unit, multiplier, count);
			GUILayout.EndHorizontal();
			DrawDescription(unit);
			DrawFooter(unit, budget, num, count, overBudget);
			GUILayout.EndVertical();
			_searchFocused = GUI.GetNameOfFocusedControl() == "casprep_search";
			GUI.DragWindow(new Rect(0f, 0f, 10000f, unit * 2.2f));
		}

		private static void DrawTitleBar(float u)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 1.8f) });
			GUILayout.Label("SUPPLY DROP", PixelSkin.Title, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) });
			GUILayout.Label($"[{ModConfig.MenuKey.Value}] toggle menu", PixelSkin.Muted, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) });
			GUILayout.FlexibleSpace();
			if (GUILayout.Button(PresetPanel.IsOpen ? "PRESETS <" : "PRESETS >", PresetPanel.IsOpen ? PixelSkin.TabActive : PixelSkin.SmallButton, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(u * 6.5f),
				GUILayout.Height(u * 1.6f)
			}))
			{
				PresetPanel.Toggle();
			}
			GUILayout.Space(u * 0.3f);
			if (GUILayout.Button("X", PixelSkin.SmallButton, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(u * 1.6f),
				GUILayout.Height(u * 1.6f)
			}))
			{
				Close();
			}
			GUILayout.EndHorizontal();
		}

		private static void DrawStatusStrip(float u, float mult)
		{
			GUILayout.BeginHorizontal(PixelSkin.Inset, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 1.7f) });
			GUILayout.Label("PRICES", PixelSkin.Muted, Array.Empty<GUILayoutOption>());
			GUILayout.Label("x" + mult.ToString("0.##", CultureInfo.InvariantCulture), Mathf.Approximately(mult, 1f) ? PixelSkin.Label : PixelSkin.Accent, Array.Empty<GUILayoutOption>());
			GUILayout.Space(u);
			float rangeFraction = RangeFraction;
			GUILayout.Label("RANGE", PixelSkin.Muted, Array.Empty<GUILayoutOption>());
			GUILayout.Label($"{LoadoutClient.Distance:0.0}/{LoadoutClient.MaxDistance:0}", (rangeFraction > 0.85f) ? PixelSkin.Danger : ((rangeFraction > 0.5f) ? PixelSkin.Warning : PixelSkin.Label), Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			if (rangeFraction > 0.5f)
			{
				GUILayout.Label("STAY NEAR YOUR SPAWN", PixelSkin.Danger, Array.Empty<GUILayoutOption>());
			}
			GUILayout.EndHorizontal();
		}

		public static void RangeTick()
		{
			if (!LoadoutClient.IsAvailable)
			{
				_rangeWarned = false;
				return;
			}
			float rangeFraction = RangeFraction;
			if (rangeFraction < 0.4f)
			{
				_rangeWarned = false;
			}
			else if (rangeFraction > 0.5f && !_rangeWarned)
			{
				_rangeWarned = true;
				if (!IsOpen && (Object)(object)PlayerCamera.main != (Object)null)
				{
					PlayerCamera.main.DoAlert($"Stay near your spawn: the loadout menu closes {LoadoutClient.MaxDistance:0} tiles away.", false);
				}
			}
		}

		private static void DrawCatalog(float u, float mult)
		{
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Invalid comparison between Unknown and I4
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: 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)
			GUILayout.BeginVertical(PixelSkin.Panel, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(((Rect)(ref _window)).width * 0.56f),
				GUILayout.ExpandHeight(true)
			});
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("SEARCH", PixelSkin.Muted, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 1.6f) });
			GUI.SetNextControlName("casprep_search");
			_search = GUILayout.TextField(_search ?? string.Empty, 40, PixelSkin.Field, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Height(u * 1.6f),
				GUILayout.ExpandWidth(true)
			});
			if (GUILayout.Button("X", PixelSkin.SmallButton, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(u * 1.6f),
				GUILayout.Height(u * 1.6f)
			}))
			{
				_search = string.Empty;
				GUI.FocusControl((string)null);
			}
			GUILayout.EndHorizontal();
			DrawGroupTabs(u);
			RefreshFilter();
			float num = Mathf.Round(u * 1.7f);
			_catalogScroll = GUILayout.BeginScrollView(_catalogScroll, false, true, GUIStyle.none, GUI.skin.verticalScrollbar, GUIStyle.none, Array.Empty<GUILayoutOption>());
			if (_filtered.Count == 0)
			{
				GUILayout.Label((LoadoutCatalog.Entries.Count == 0) ? "Item list is still loading..." : "No items found.", PixelSkin.Muted, Array.Empty<GUILayoutOption>());
			}
			else
			{
				Rect rect = GUILayoutUtility.GetRect(10f, (float)_filtered.Count * num, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
				Rect row = default(Rect);
				for (int i = 0; i < _filtered.Count; i++)
				{
					((Rect)(ref row))..ctor(((Rect)(ref rect)).x, ((Rect)(ref rect)).y + (float)i * num, ((Rect)(ref rect)).width, num - 1f);
					if (!(((Rect)(ref row)).yMax < _catalogScroll.y) && !(((Rect)(ref row)).y > _catalogScroll.y + _catalogViewHeight))
					{
						DrawCatalogRow(row, _filtered[i], mult, u);
					}
				}
			}
			GUILayout.EndScrollView();
			if ((int)Event.current.type == 7)
			{
				Rect lastRect = GUILayoutUtility.GetLastRect();
				_catalogViewHeight = ((Rect)(ref lastRect)).height;
			}
			GUILayout.Label("click: +1   shift+click: +5", PixelSkin.Small, Array.Empty<GUILayoutOption>());
			GUILayout.EndVertical();
		}

		private static void DrawGroupTabs(float u)
		{
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			IReadOnlyList<string> groups = LoadoutCatalog.Groups;
			if (groups.Count == 0)
			{
				return;
			}
			List<string> list = new List<string> { "All" };
			list.AddRange(groups);
			if (!list.Contains(_group))
			{
				_group = "All";
			}
			int num = Mathf.Clamp(Mathf.FloorToInt(((Rect)(ref _window)).width * 0.56f / (u * 5.2f)), 3, list.Count);
			for (int i = 0; i < list.Count; i += num)
			{
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				for (int j = i; j < i + num; j++)
				{
					if (j >= list.Count)
					{
						GUILayout.Label(GUIContent.none, PixelSkin.TabFiller, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 1.3f) });
						continue;
					}
					bool flag = list[j] == _group;
					if (GUILayout.Button(list[j], flag ? PixelSkin.TabActive : PixelSkin.Tab, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 1.3f) }) && !flag)
					{
						_group = list[j];
						_catalogScroll = Vector2.zero;
					}
				}
				GUILayout.EndHorizontal();
			}
		}

		private static void DrawCatalogRow(Rect row, CatalogEntry entry, float mult, float u)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			Selected.TryGetValue(entry.Id, out var value);
			if (GUI.Button(row, GUIContent.none, PixelSkin.Row))
			{
				Add(entry.Id, (!Event.current.shift) ? 1 : 5);
			}
			if (((Rect)(ref row)).Contains(Event.current.mousePosition))
			{
				_hoveredNext = entry;
			}
			float num = u * 0.3f;
			Rect rect = default(Rect);
			((Rect)(ref rect))..ctor(((Rect)(ref row)).x + num, ((Rect)(ref row)).y + 2f, ((Rect)(ref row)).height - 4f, ((Rect)(ref row)).height - 4f);
			PixelSkin.DrawSprite(rect, entry.Icon);
			float num2 = u * 4.5f;
			PixelSkin.MarqueeLabel(new Rect(((Rect)(ref rect)).xMax + num, ((Rect)(ref row)).y, ((Rect)(ref row)).width - ((Rect)(ref rect)).width - num2 - num * 4f, ((Rect)(ref row)).height), entry.Name, (value > 0) ? PixelSkin.ItemNameAccent : PixelSkin.ItemName, "c:" + entry.Id, ((Rect)(ref row)).Contains(Event.current.mousePosition));
			GUI.Label(new Rect(((Rect)(ref row)).xMax - num2 - num, ((Rect)(ref row)).y, num2, ((Rect)(ref row)).height), UnitPrice(entry, mult), PixelSkin.ItemPrice);
		}

		private static void DrawSelection(float u, float mult, int count)
		{
			//IL_0107: 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_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: 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_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Invalid comparison between Unknown and I4
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(PixelSkin.Panel, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.ExpandWidth(true),
				GUILayout.ExpandHeight(true)
			});
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("SELECTED", PixelSkin.Muted, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 1.6f) });
			GUILayout.Label(count + " / " + 200, PixelSkin.Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 1.6f) });
			GUILayout.FlexibleSpace();
			bool enabled = GUI.enabled;
			GUI.enabled = enabled && Selected.Count > 0;
			if (GUILayout.Button("CLEAR", PixelSkin.SmallButton, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(u * 4.5f),
				GUILayout.Height(u * 1.6f)
			}))
			{
				Selected.Clear();
			}
			GUI.enabled = enabled;
			GUILayout.EndHorizontal();
			float num = Mathf.Round(u * 1.7f);
			_selectedScroll = GUILayout.BeginScrollView(_selectedScroll, false, true, GUIStyle.none, GUI.skin.verticalScrollbar, GUIStyle.none, Array.Empty<GUILayoutOption>());
			if (Selected.Count == 0)
			{
				GUILayout.Label("Nothing selected yet.", PixelSkin.Muted, Array.Empty<GUILayoutOption>());
				GUILayout.Label("Pick items on the left. They arrive in a supply crate at your feet.", PixelSkin.Small, Array.Empty<GUILayoutOption>());
			}
			else
			{
				List<KeyValuePair<string, int>> list = Selected.ToList();
				Rect rect = GUILayoutUtility.GetRect(10f, (float)list.Count * num, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
				Rect row = default(Rect);
				for (int i = 0; i < list.Count; i++)
				{
					if (LoadoutCatalog.TryGet(list[i].Key, out var entry))
					{
						((Rect)(ref row))..ctor(((Rect)(ref rect)).x, ((Rect)(ref rect)).y + (float)i * num, ((Rect)(ref rect)).width, num - 1f);
						if (!(((Rect)(ref row)).yMax < _selectedScroll.y) && !(((Rect)(ref row)).y > _selectedScroll.y + _selectedViewHeight))
						{
							DrawSelectedRow(row, entry, list[i].Value, mult, u);
						}
					}
				}
			}
			GUILayout.EndScrollView();
			if ((int)Event.current.type == 7)
			{
				Rect lastRect = GUILayoutUtility.GetLastRect();
				_selectedViewHeight = ((Rect)(ref lastRect)).height;
			}
			GUILayout.EndVertical();
		}

		private static void DrawSelectedRow(Rect row, CatalogEntry entry, int amount, float mult, float u)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_00e6: 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_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Expected O, but got Unknown
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: 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_0182: Unknown result type (might be due to invalid IL or missing references)
			bool flag = ((Rect)(ref row)).Contains(Event.current.mousePosition);
			if (flag)
			{
				_hoveredNext = entry;
			}
			float num = u * 0.3f;
			float num2 = ((Rect)(ref row)).height - 2f;
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(((Rect)(ref row)).xMax - num2, ((Rect)(ref row)).y + 1f, num2, num2);
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(((Rect)(ref val)).x - num2 - 2f, ((Rect)(ref row)).y + 1f, num2, num2);
			if (GUI.Button(val, "+", PixelSkin.SmallButton))
			{
				Add(entry.Id, (!Event.current.shift) ? 1 : 5);
			}
			if (GUI.Button(val2, "-", PixelSkin.SmallButton))
			{
				Add(entry.Id, Event.current.shift ? (-5) : (-1));
			}
			EnsureCountStyle();
			float x = PixelSkin.ItemPrice.CalcSize(new GUIContent("9999")).x;
			Rect val3 = default(Rect);
			((Rect)(ref val3))..ctor(((Rect)(ref val2)).x - x - num, ((Rect)(ref row)).y, x, ((Rect)(ref row)).height);
			GUI.Label(val3, LoadoutCatalog.PriceOf(entry, mult, amount).ToString(), PixelSkin.ItemPrice);
			float x2 = _countStyle.CalcSize(new GUIContent("x" + 50)).x;
			Rect val4 = default(Rect);
			((Rect)(ref val4))..ctor(((Rect)(ref val3)).x - x2, ((Rect)(ref row)).y, x2, ((Rect)(ref row)).height);
			if (amount > 1)
			{
				GUI.Label(val4, "x" + amount, _countStyle);
			}
			Rect rect = default(Rect);
			((Rect)(ref rect))..ctor(((Rect)(ref row)).x + num, ((Rect)(ref row)).y + 2f, ((Rect)(ref row)).height - 4f, ((Rect)(ref row)).height - 4f);
			PixelSkin.DrawSprite(rect, entry.Icon);
			PixelSkin.MarqueeLabel(new Rect(((Rect)(ref rect)).xMax + num, ((Rect)(ref row)).y, ((Rect)(ref val4)).x - ((Rect)(ref rect)).xMax - num * 2f, ((Rect)(ref row)).height), entry.Name, PixelSkin.ItemName, "s:" + entry.Id, flag);
		}

		private static void EnsureCountStyle()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			if (_countStyle == null || _countSource != PixelSkin.ItemNameAccent)
			{
				_countSource = PixelSkin.ItemNameAccent;
				_countStyle = new GUIStyle(_countSource)
				{
					alignment = (TextAnchor)5
				};
			}
		}

		private static void DrawDescription(float u)
		{
			string text = ((_hovered == null) ? " " : (string.IsNullOrEmpty(_hovered.Description) ? _hovered.Name : (_hovered.Name + ": " + _hovered.Description)));
			GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 3.6f) });
			if (!string.IsNullOrEmpty(_message))
			{
				GUILayout.Label(_message, PixelSkin.Danger, Array.Empty<GUILayoutOption>());
			}
			GUILayout.Label(text, PixelSkin.Small, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) });
			GUILayout.EndVertical();
		}

		private static void DrawFooter(float u, int budget, long cost, int count, bool overBudget)
		{
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(PixelSkin.Inset, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 3.5f) });
			GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("BUDGET", PixelSkin.Muted, Array.Empty<GUILayoutOption>());
			GUILayout.Label(budget.ToString(), PixelSkin.Label, Array.Empty<GUILayoutOption>());
			GUILayout.Space(u);
			GUILayout.Label("COST", PixelSkin.Muted, Array.Empty<GUILayoutOption>());
			GUILayout.Label(cost.ToString(), overBudget ? PixelSkin.Danger : PixelSkin.Label, Array.Empty<GUILayoutOption>());
			GUILayout.Space(u);
			GUILayout.Label(overBudget ? "OVER BUDGET" : "LEFT", overBudget ? PixelSkin.Danger : PixelSkin.Muted, Array.Empty<GUILayoutOption>());
			if (!overBudget)
			{
				GUILayout.Label((budget - cost).ToString(), PixelSkin.Success, Array.Empty<GUILayoutOption>());
			}
			GUILayout.FlexibleSpace();
			GUILayout.EndHorizontal();
			PixelSkin.DrawBar(GUILayoutUtility.GetRect(10f, u * 0.9f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }), (budget > 0) ? ((float)cost / (float)budget) : ((cost > 0) ? 1f : 0f), overBudget);
			GUILayout.EndVertical();
			GUILayout.Space(u * 0.5f);
			bool flag = LoadoutClient.IsAvailable && !LoadoutClient.BuyInFlight && count > 0 && !overBudget;
			bool enabled = GUI.enabled;
			GUI.enabled = enabled && flag;
			if (GUILayout.Button(LoadoutClient.BuyInFlight ? "SPAWNING..." : "SPAWN", PixelSkin.BigButton, (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(u * 8f),
				GUILayout.ExpandHeight(true)
			}))
			{
				_message = null;
				LoadoutClient.Buy(new Dictionary<string, int>(Selected));
			}
			GUI.enabled = enabled;
			GUILayout.EndHorizontal();
		}

		private static void Add(string id, int delta)
		{
			Selected.TryGetValue(id, out var value);
			int num = Selected.Values.Sum();
			if (delta > 0)
			{
				delta = Mathf.Min(new int[3]
				{
					delta,
					50 - value,
					200 - num
				});
				if (delta <= 0)
				{
					return;
				}
			}
			value += delta;
			if (value <= 0)
			{
				Selected.Remove(id);
			}
			else
			{
				Selected[id] = value;
			}
		}

		private static long TotalCost(float mult)
		{
			long num = 0L;
			foreach (KeyValuePair<string, int> item in Selected)
			{
				if (LoadoutCatalog.TryGet(item.Key, out var entry))
				{
					num += LoadoutCatalog.PriceOf(entry, mult, item.Value);
				}
			}
			return num;
		}

		private static string UnitPrice(CatalogEntry entry, float mult)
		{
			float num = entry.BaseValue * Mathf.Max(0f, mult);
			if (!Mathf.Approximately(num, Mathf.Round(num)))
			{
				return num.ToString("0.##", CultureInfo.InvariantCulture);
			}
			return Mathf.RoundToInt(num).ToString();
		}

		private static void RefreshFilter()
		{
			IReadOnlyList<CatalogEntry> entries = LoadoutCatalog.Entries;
			if (_prunedVersion != LoadoutCatalog.Version && LoadoutCatalog.IsLoaded)
			{
				_prunedVersion = LoadoutCatalog.Version;
				foreach (string item in Selected.Keys.ToList())
				{
					if (!LoadoutCatalog.TryGet(item, out var _))
					{
						Selected.Remove(item);
					}
				}
			}
			string text = _group + "\n" + _search + "\n" + entries.Count + "\n" + LoadoutCatalog.Version;
			if (!(_filterKey == text))
			{
				_filterKey = text;
				string query = (_search ?? string.Empty).Trim();
				_filtered = (from e in LoadoutCatalog.Entries
					where _group == "All" || e.Group == _group
					where query.Length == 0 || e.Name.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0 || e.Id.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0 || e.Group.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0
					select e).ToList();
			}
		}
	}
	[HarmonyPatch(typeof(PlayerCamera), "HandleInput")]
	internal static class PlayerCamera_HandleInput_LoadoutPatch
	{
		private static bool Prefix()
		{
			return !LoadoutUI.BlocksGameInput;
		}
	}
	internal static class ModConfig
	{
		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<int> Budget;

		public static ConfigEntry<float> PriceMultiplier;

		public static ConfigEntry<float> MaxDistance;

		public static ConfigEntry<int> CrateLifetimeSeconds;

		public static ConfigEntry<KeyCode> MenuKey;

		private const string Section = "Loadout";

		private const string KeySection = "Loadout";

		public static void Init(ConfigFile cfg)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			Enabled = cfg.Bind<bool>("Loadout", "Enabled", true, "Loadout menu after spawning in a new run. Also toggled on the character select screen or with 'casprep enable' (main menu only).");
			Budget = cfg.Bind<int>("Loadout", "Budget", 100, new ConfigDescription("Loadout budget per player (in trader value units).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000000), Array.Empty<object>()));
			PriceMultiplier = cfg.Bind<float>("Loadout", "PriceMultiplier", 1f, new ConfigDescription("Multiplier applied to base trader prices.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			MaxDistance = cfg.Bind<float>("Loadout", "MaxDistance", 100f, new ConfigDescription("How far (tiles) a player may move from the spawn point before the menu closes.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10000f), Array.Empty<object>()));
			CrateLifetimeSeconds = cfg.Bind<int>("Loadout", "CrateLifetimeSeconds", 300, new ConfigDescription("Supply crate lifetime. When it breaks, its contents drop on the floor.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(10, 86400), Array.Empty<object>()));
			MenuKey = cfg.Bind<KeyCode>("Loadout", "MenuKey", (KeyCode)287, "Key that toggles the loadout menu.");
		}
	}
	internal static class PixelIcons
	{
		public enum Icon
		{
			Load,
			Save,
			Delete
		}

		private static readonly Dictionary<Icon, string[]> Masks = new Dictionary<Icon, string[]>
		{
			[Icon.Load] = new string[9] { "...###...", "...###...", "...###...", ".#######.", "..#####..", "...###...", "....#....", "#.......#", "#########" },
			[Icon.Save] = new string[9] { "#######..", "#.#####.#", "#.#####.#", "#.......#", "#.......#", "#.#####.#", "#.#...#.#", "#.#####.#", "#########" },
			[Icon.Delete] = new string[9] { "...###...", "#########", ".........", ".#######.", ".#.#.#.#.", ".#.#.#.#.", ".#.#.#.#.", ".#.#.#.#.", ".#######." }
		};

		private static readonly Dictionary<Icon, Texture2D> Textures = new Dictionary<Icon, Texture2D>();

		public static void Draw(Rect rect, Icon icon, Color color)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			//IL_0058: 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_008a: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			if ((int)Event.current.type == 7)
			{
				Texture2D val = Get(icon);
				int num = Mathf.Max(1, Mathf.FloorToInt(Mathf.Min(((Rect)(ref rect)).width, ((Rect)(ref rect)).height) * 0.6f / (float)((Texture)val).width));
				float num2 = ((Texture)val).width * num;
				float num3 = ((Texture)val).height * num;
				Rect val2 = new Rect(Mathf.Round(((Rect)(ref rect)).center.x - num2 / 2f), Mathf.Round(((Rect)(ref rect)).center.y - num3 / 2f), num2, num3);
				Color color2 = GUI.color;
				GUI.color = color;
				GUI.DrawTexture(val2, (Texture)(object)val);
				GUI.color = color2;
			}
		}

		private static Texture2D Get(Icon icon)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Expected O, but got Unknown
			//IL_0090: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			if (Textures.TryGetValue(icon, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			string[] array = Masks[icon];
			int num = array.Length;
			int length = array[0].Length;
			value = new Texture2D(length, num, (TextureFormat)4, false)
			{
				filterMode = (FilterMode)0,
				wrapMode = (TextureWrapMode)1,
				hideFlags = (HideFlags)61
			};
			Color[] array2 = (Color[])(object)new Color[length * num];
			for (int i = 0; i < num; i++)
			{
				for (int j = 0; j < length; j++)
				{
					array2[(num - 1 - i) * length + j] = ((j < array[i].Length && array[i][j] == '#') ? Color.white : Color.clear);
				}
			}
			value.SetPixels(array2);
			value.Apply();
			Textures[icon] = value;
			return value;
		}
	}
	internal static class PixelSkin
	{
		private sealed class Frame
		{
			public readonly int Border;

			public readonly Texture2D Normal;

			public readonly Texture2D Dim;

			public readonly Texture2D Hover;

			public readonly Texture2D Active;

			public Frame(int border, Texture2D normal, Texture2D dim, Texture2D hover, Texture2D active)
			{
				Border = Mathf.Max(1, border);
				Normal = normal;
				Dim = dim;
				Hover = hover;
				Active = active;
			}

			public static Frame Generated(int pixel, int borderPixels)
			{
				//IL_001a: 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_003a: 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_0059: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_006a: 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_008e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0094: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
				Color val = default(Color);
				((Color)(ref val))..ctor(0.95f, 0.95f, 0.95f);
				return new Frame(pixel * borderPixels, PixelSkin.Generated(pixel, val, new Color(0.055f, 0.055f, 0.055f, 0.97f)), PixelSkin.Generated(pixel, val * 0.85f, new Color(0.06f, 0.06f, 0.06f, 0.85f)), PixelSkin.Generated(pixel, val * 0.65f, new Color(0.12f, 0.12f, 0.12f, 0.9f)), PixelSkin.Generated(pixel, val * 0.45f, new Color(0.2f, 0.2f, 0.2f, 0.9f)));
			}
		}

		public static readonly Color TextColor = Hex(15132390);

		public static readonly Color MutedColor = Hex(10724259);

		public static readonly Color AccentColor = Hex(9556479);

		public static readonly Color SuccessColor = Hex(10676399);

		public static readonly Color WarningColor = Hex(16762900);

		public static readonly Color DangerColor = Hex(16746375);

		public static GUIStyle Window;

		public static GUIStyle Panel;

		public static GUIStyle Inset;

		public static GUIStyle Title;

		public static GUIStyle Label;

		public static GUIStyle Muted;

		public static GUIStyle Small;

		public static GUIStyle Right;

		public static GUIStyle RightMuted;

		public static GUIStyle Accent;

		public static GUIStyle Success;

		public static GUIStyle Warning;

		public static GUIStyle Danger;

		public static GUIStyle Button;

		public static GUIStyle BigButton;

		public static GUIStyle SmallButton;

		public static GUIStyle Row;

		public static GUIStyle Field;

		public static GUIStyle Tab;

		public static GUIStyle TabActive;

		public static GUIStyle TabFiller;

		public static GUIStyle BarBack;

		public static GUIStyle BarFill;

		public static GUIStyle BarFillDanger;

		public static GUIStyle Banner;

		public static GUIStyle ItemName;

		public static GUIStyle ItemNameAccent;

		public static GUIStyle ItemPrice;

		private static float _builtScale = -1f;

		private static Font _builtFont;

		private static bool _builtWithTogether;

		private static int _builtW;

		private static int _builtH;

		private static readonly List<Texture2D> OwnedTextures = new List<Texture2D>();

		private const float BaseFontSize = 20f;

		private const float MarqueeDelay = 0.5f;

		private const float MarqueeEdgePause = 1f;

		private const float MarqueeSpeedUnits = 3f;

		private static string _marqueeKey;

		private static float _marqueeSince;

		private static int _marqueeFrame = -10;

		public static GUISkin Skin { get; private set; }

		public static int FontSize { get; private set; } = 20;

		public static float Unit => FontSize;

		private static Sprite TogetherSmall => GameAssets.UiBlockSmall;

		private static Sprite TogetherNano => GameAssets.UiBlockNano;

		private static Font GameFont => GameAssets.PixelFont;

		private static float UiScale => GameAssets.UiScale;

		public static void Ensure()
		{
			float num = CurrentScale();
			bool flag = (Object)(object)TogetherSmall != (Object)null && (Object)(object)TogetherNano != (Object)null;
			if (!((Object)(object)Skin != (Object)null) || !Mathf.Approximately(num, _builtScale) || !((Object)(object)_builtFont == (Object)(object)GameFont) || flag != _builtWithTogether || _builtW != Screen.width || _builtH != Screen.height)
			{
				_builtW = Screen.width;
				_builtH = Screen.height;
				Build(num, flag);
			}
		}

		private static float CurrentScale()
		{
			float num = UiScale;
			if (num <= 0.01f || float.IsNaN(num))
			{
				num = (float)Screen.height / 1080f;
			}
			return Mathf.Clamp(num, 0.4f, 6f);
		}

		private static void Build(float scale, bool withTogether)
		{
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0281: Unknown result type (might be due to invalid IL or missing references)
			//IL_028b: Expected O, but got Unknown
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Expected O, but got Unknown
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_0328: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_036a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0380: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0404: Unknown result type (might be due to invalid IL or missing references)
			//IL_0409: Unknown result type (might be due to invalid IL or missing references)
			//IL_041a: Unknown result type (might be due to invalid IL or missing references)
			//IL_043f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0449: Expected O, but got Unknown
			//IL_0449: Unknown result type (might be due to invalid IL or missing references)