Decompiled source of CasualtiesPrepared v1.0.1
CasPrepared/CasPrepared.dll
Decompiled 2 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using CUCoreLib.Data; using CUCoreLib.Helpers; using CUCoreLib.Networking; using CUCoreLib.Registries; using CUCoreLib.Saving; using CasualtiesTogetherUtils; using HarmonyLib; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Linq; using Together; using UnityEngine; using UnityEngine.Rendering.Universal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("CasualtiesMP")] [assembly: IgnoresAccessChecksTo("CUCoreLib")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1+83132d825c020760800bbe382172edbcf5fd7fd9")] [assembly: AssemblyProduct("CasPrepared - multiplayer spawn loadouts")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.1.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 { [HarmonyPatch(typeof(WorldGeneration), "Awake")] internal static class WorldGeneration_Awake_CampaignPatch { private static void Postfix() { LoadoutServer.OnNewWorld(); LoadoutClient.ResetLocal(); } } internal sealed class CatalogEntry { public string Id; public string Name; public string Category; public string Group; public string Description; public float BaseValue; 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; private static List<CatalogEntry> _entries; private static List<string> _groups; private static Dictionary<string, CatalogEntry> _byId; private static readonly Dictionary<string, GameObject> PrefabCache = new Dictionary<string, GameObject>(); private static readonly string[] GroupOrder = new string[11] { "Weapons", "Ammo", "Gear", "Medical", "Drug", "Food", "Water", "Tool", "Utility", "Container", "Other" }; 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 TryGet(string id, out CatalogEntry entry) { EnsureBuilt(); entry = null; return id != null && _byId != null && _byId.TryGetValue(id, out entry); } 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); return ((Object)(object)prefab != (Object)null) ? prefab.GetComponent<AmmoScript>() : null; } private static void EnsureBuilt() { //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Invalid comparison between Unknown and I4 //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Invalid comparison between Unknown and I4 //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) if ((_entries != null && _entries.Count > 0) || 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)); } } 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 num3 = Array.IndexOf(GroupOrder, g); return (num3 >= 0) ? num3 : GroupOrder.Length; }) .ThenBy<string, string>((string g) => g, StringComparer.OrdinalIgnoreCase) .ToList(); } 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) { GameObject prefab = GetPrefab(id); if ((Object)(object)prefab == (Object)null) { return null; } SpriteRenderer val = prefab.GetComponent<SpriteRenderer>(); if ((Object)(object)val == (Object)null) { val = prefab.GetComponentInChildren<SpriteRenderer>(true); } if ((Object)(object)val != (Object)null && (Object)(object)val.sprite != (Object)null) { return val.sprite; } return null; } public static void PrepareSpawned(GameObject go) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: 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 LoadoutClient { private const float PollInterval = 2f; private const float IdlePollInterval = 10f; private const float RequestTimeout = 10f; private const int MissedRepliesForNoMod = 3; private const float NoModPollInterval = 60f; private const float SettleSeconds = 3f; private const float TeleportJump = 5f; private static float _settledSince = -1f; private static Vector2? _lastBodyPos; private static bool _statusInFlight; private static float _statusSentAt; private static float _buySentAt; private static float _nextPoll; private static bool _wasRunning; private static int _missedReplies; public static JObject Status { get; private set; } public static float StatusReceivedAt { get; private set; } public static bool BuyInFlight { get; private set; } public static bool HostLacksMod { get; private set; } public static string State { get { JObject status = Status; return ((status != null) ? ((JToken)status).Value<string>((object)"state") : null) ?? "waiting"; } } public static bool IsAvailable => State == "available"; public static bool IsFinished => State == "used" || State == "expired"; public static bool HasStatus => Status != null; public static bool IsDisabled => State == "disabled"; public static int Budget { get { JObject status = Status; return ((status != null) ? ((JToken)status).Value<int?>((object)"budget") : ((int?)null)).GetValueOrDefault(); } } public static float Multiplier { get { JObject status = Status; return ((status != null) ? ((JToken)status).Value<float?>((object)"mult") : ((float?)null)) ?? 1f; } } public static float MaxDistance { get { JObject status = Status; return ((status != null) ? ((JToken)status).Value<float?>((object)"maxDistance") : ((float?)null)).GetValueOrDefault(); } } public static float Distance { get { JObject status = Status; return ((status != null) ? ((JToken)status).Value<float?>((object)"distance") : ((float?)null)).GetValueOrDefault(); } } public static bool HasTimeLimit { get { JObject status = Status; return ((status != null) ? ((JToken)status).Value<float?>((object)"remaining") : ((float?)null)).GetValueOrDefault() >= 0f; } } public static float RemainingSeconds { get { JObject status = Status; float valueOrDefault = ((status != null) ? ((JToken)status).Value<float?>((object)"remaining") : ((float?)null)).GetValueOrDefault(); return Mathf.Max(0f, valueOrDefault - (Time.realtimeSinceStartup - StatusReceivedAt)); } } public static void Tick() { //IL_0156: Unknown result type (might be due to invalid IL or missing references) if (!Net.IsRunning) { if (_wasRunning) { ResetLocal(); } _wasRunning = false; return; } _wasRunning = true; if (!LoadoutServer.WorldReady()) { return; } if (HasStatus && !IsDisabled && !SteamManager.disableAchievements) { AchievementBreakSync.ApplyLocal(true); } ScavPlayer localPlayer = ScavPlayer.LocalPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)localPlayer.body == (Object)null) { _settledSince = -1f; return; } float realtimeSinceStartup = Time.realtimeSinceStartup; UpdateSettled(localPlayer.body, realtimeSinceStartup); if (_statusInFlight && realtimeSinceStartup - _statusSentAt > 10f) { OnStatusTimeout(realtimeSinceStartup); } if (BuyInFlight && realtimeSinceStartup - _buySentAt > 10f) { BuyInFlight = false; LoadoutUI.SetMessage("Host did not answer. Try again."); } if (IsSettled(realtimeSinceStartup) && !_statusInFlight && realtimeSinceStartup >= _nextPoll) { _nextPoll = realtimeSinceStartup + ((IsFinished || IsDisabled) ? 10f : 2f); RequestStatus(); } if (Input.GetKeyDown(ModConfig.MenuKey.Value) && !LoadoutUI.IsSearchFocused) { ToggleMenu(); } } public static void ToggleMenu() { if (LoadoutUI.IsOpen) { LoadoutUI.Close(); } else if (IsAvailable) { LoadoutUI.Open(); } else { Alert((HostLacksMod && !HasStatus) ? "The host does not have CasPrepared installed." : (IsDisabled ? "The host has turned the loadout menu off." : ((State == "used") ? "Loadout already taken this campaign." : ((State == "expired") ? "Loadout window has closed." : "Loadout is not available yet.")))); } } public static void RequestStatus() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown _statusInFlight = true; _statusSentAt = Time.realtimeSinceStartup; if (!Send("casprepared.status", new JObject { ["ready"] = JToken.op_Implicit(true) }, OnStatus)) { _statusInFlight = false; } } 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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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) { return _settledSince >= 0f && now - _settledSince >= 3f; } public static void Buy(Dictionary<string, int> selection) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0081: 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_00b3: Expected O, but got Unknown if (BuyInFlight) { return; } JObject val = new JObject(); foreach (KeyValuePair<string, int> item in selection) { if (item.Value > 0) { val[item.Key] = JToken.op_Implicit(item.Value); } } BuyInFlight = true; _buySentAt = Time.realtimeSinceStartup; if (!Send("casprepared.buy", new JObject { ["items"] = (JToken)(object)val }, OnBuy)) { BuyInFlight = false; LoadoutUI.SetMessage("Could not reach the host."); } } private static bool Send(string channel, JObject payload, Action<JToken> onResponse) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (Net.IsServer) { ScavPlayer localPlayer = ScavPlayer.LocalPlayer; if ((Object)(object)localPlayer == (Object)null) { return false; } onResponse(LoadoutServer.HandleLocal(channel, localPlayer.playerId.id, (JToken)(object)payload)); return true; } return MultiplayerApi.RequestServer(channel, (object)payload, onResponse, true); } private static void OnStatusTimeout(float now) { _statusInFlight = false; if (!HasStatus) { _missedReplies++; if (_missedReplies >= 3 && !HostLacksMod) { HostLacksMod = true; Alert("The host does not have CasPrepared installed. Loadout menu is unavailable."); } if (HostLacksMod) { _nextPoll = now + 60f; } } } private static void OnStatus(JToken response) { _statusInFlight = false; _missedReplies = 0; HostLacksMod = false; JObject val = (JObject)(object)((response is JObject) ? response : null); if (val != null) { ApplyStatus(val); } } private static void OnBuy(JToken response) { BuyInFlight = false; JObject val = (JObject)(object)((response is JObject) ? response : null); if (val != null) { JToken obj = val["status"]; JObject val2 = (JObject)(object)((obj is JObject) ? obj : null); if (val2 != null) { ApplyStatus(val2); } if (((JToken)val).Value<bool?>((object)"ok") == true) { LoadoutUI.Close(); LoadoutUI.ClearSelection(); Alert("Supply crate delivered at your feet."); } else { LoadoutUI.SetMessage(((JToken)val).Value<string>((object)"error") ?? "Purchase failed."); } } } private static void ApplyStatus(JObject status) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) bool isAvailable = IsAvailable; Status = status; StatusReceivedAt = Time.realtimeSinceStartup; if (IsAvailable && !isAvailable) { LoadoutUI.Open(); Alert($"Loadout menu available ({ModConfig.MenuKey.Value})."); } else if (isAvailable && !IsAvailable && !BuyInFlight) { LoadoutUI.Close(); string text = ((JToken)status).Value<string>((object)"reason"); if (State == "expired") { Alert("Loadout window closed" + (string.IsNullOrEmpty(text) ? "." : (": " + text + "."))); } else if (IsDisabled) { Alert("The host has turned the loadout menu off."); } } } public static void Give(string target) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown JObject val = new JObject(); if (!string.IsNullOrWhiteSpace(target)) { val["target"] = JToken.op_Implicit(target.Trim()); } if (!Send("casprepared.give", val, OnGive)) { Log("Could not reach the host."); } } private static void OnGive(JToken response) { JObject val = (JObject)(object)((response is JObject) ? response : null); if (val != null) { if (((JToken)val).Value<bool?>((object)"ok") == true) { Log(((JToken)val).Value<string>((object)"message") ?? "Loadout menu granted."); _nextPoll = 0f; } else { Log("GiveLoadout failed: " + (((JToken)val).Value<string>((object)"error") ?? "unknown error")); } JToken obj = val["status"]; JObject val2 = (JObject)(object)((obj is JObject) ? obj : null); if (val2 != null) { ApplyStatus(val2); } } } private static void Log(string text) { if ((Object)(object)ConsoleScript.instance != (Object)null) { ConsoleScript.instance.LogToConsole("[CasPrepared] " + text); } } 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() { Status = null; _missedReplies = 0; HostLacksMod = false; _settledSince = -1f; _lastBodyPos = null; _statusInFlight = false; BuyInFlight = false; _nextPoll = 0f; LoadoutUI.Close(); LoadoutUI.ClearSelection(); } } internal static class LoadoutCommands { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Action <>9__2_0; public static Action <>9__2_1; public static Action <>9__2_2; public static Action<int> <>9__2_11; public static Func<int> <>9__2_12; public static Action <>9__2_3; public static Action<float> <>9__2_13; public static Func<float> <>9__2_14; public static Action <>9__2_4; public static Action<int> <>9__2_15; public static Func<int> <>9__2_16; public static Action <>9__2_5; public static Action<float> <>9__2_17; public static Func<float> <>9__2_18; public static Action <>9__2_6; public static Action<int> <>9__2_19; public static Func<int> <>9__2_20; public static Action <>9__2_7; public static Action <>9__2_8; public static Action <>9__2_9; public static Action <>9__2_10; internal void <Register>b__2_0(string[] args) { if (args.Length >= 2) { RequireConfigAccess(); ModConfig.Enabled.Value = ParseBool(args[1]); } Log("Loadout menu: " + (ModConfig.Enabled.Value ? "ON (achievements are disabled while hosting)" : "OFF")); } internal void <Register>b__2_1(string[] args) { Log("sv_cheats: " + OnOff(Multiplayer.rules.sv_cheats) + ", AllowClientCheatCommands: " + OnOff(Multiplayer.rules.AllowClientCheatCommands)); if (!Net.IsRunning) { Log("Not in a multiplayer session. casprep_giveloadout works once you host or join one."); return; } string text = LoadoutServer.CheatBlockReason(Net.IsServer); Log((text == null) ? "casprep_giveloadout: available." : ("casprep_giveloadout: blocked - " + text)); } internal void <Register>b__2_2(string[] args) { if (!Net.IsRunning) { throw new Exception("Only works in a multiplayer session."); } string text = LoadoutServer.CheatBlockReason(Net.IsServer); if (text != null) { throw new Exception(text); } string target = ((args.Length >= 2) ? string.Join(" ", args, 1, args.Length - 1) : null); LoadoutClient.Give(target); } internal void <Register>b__2_3(string[] args) { IntSetting(args, "Budget", delegate(int v) { ModConfig.Budget.Value = v; }, () => ModConfig.Budget.Value); } internal void <Register>b__2_11(int v) { ModConfig.Budget.Value = v; } internal int <Register>b__2_12() { return ModConfig.Budget.Value; } internal void <Register>b__2_4(string[] args) { FloatSetting(args, "Price multiplier", delegate(float v) { ModConfig.PriceMultiplier.Value = v; }, () => ModConfig.PriceMultiplier.Value); } internal void <Register>b__2_13(float v) { ModConfig.PriceMultiplier.Value = v; } internal float <Register>b__2_14() { return ModConfig.PriceMultiplier.Value; } internal void <Register>b__2_5(string[] args) { if (args.Length >= 2 && IsOff(args[1])) { args = new string[2] { args[0], "0" }; } IntSetting(args, "Window seconds", delegate(int v) { ModConfig.WindowSeconds.Value = v; }, () => ModConfig.WindowSeconds.Value); if (ModConfig.WindowSeconds.Value <= 0) { Log("Time limit is off: only the distance limit applies."); } } internal void <Register>b__2_15(int v) { ModConfig.WindowSeconds.Value = v; } internal int <Register>b__2_16() { return ModConfig.WindowSeconds.Value; } internal void <Register>b__2_6(string[] args) { FloatSetting(args, "Max distance", delegate(float v) { ModConfig.MaxDistance.Value = v; }, () => ModConfig.MaxDistance.Value); } internal void <Register>b__2_17(float v) { ModConfig.MaxDistance.Value = v; } internal float <Register>b__2_18() { return ModConfig.MaxDistance.Value; } internal void <Register>b__2_7(string[] args) { IntSetting(args, "Crate lifetime", delegate(int v) { ModConfig.CrateLifetimeSeconds.Value = v; }, () => ModConfig.CrateLifetimeSeconds.Value); } internal void <Register>b__2_19(int v) { ModConfig.CrateLifetimeSeconds.Value = v; } internal int <Register>b__2_20() { return ModConfig.CrateLifetimeSeconds.Value; } internal void <Register>b__2_8(string[] args) { RequireHost(); Log("Loadout menu: " + (ModConfig.Enabled.Value ? "ON" : "OFF")); Log(string.Format("Budget {0}, multiplier x{1}, ", ModConfig.Budget.Value, ModConfig.PriceMultiplier.Value.ToString("0.##", CultureInfo.InvariantCulture)) + string.Format("window {0}, radius {1}, crate {2}s", (ModConfig.WindowSeconds.Value <= 0) ? "off" : (ModConfig.WindowSeconds.Value + "s"), ModConfig.MaxDistance.Value.ToString("0.#", CultureInfo.InvariantCulture), ModConfig.CrateLifetimeSeconds.Value)); foreach (string item in LoadoutServer.DescribePlayers()) { Log(item); } } internal void <Register>b__2_9(string[] args) { RequireConfigAccess(); if (args.Length < 2) { throw new Exception("Usage: casprep_reset <player name | steamid | all>"); } string text = string.Join(" ", args, 1, args.Length - 1); Log($"Reset {LoadoutServer.Reset(text)} record(s) for '{text}'."); } internal void <Register>b__2_10(string[] args) { LoadoutClient.ToggleMenu(); } } private const string Prefix = "CasPrepared (host): "; private const string EnableHelp = "CasPrepared (host): show or set whether the loadout menu is on for sessions you host."; public static void Register() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Expected O, but got Unknown //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Expected O, but got Unknown //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Expected O, but got Unknown //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Expected O, but got Unknown //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Expected O, but got Unknown //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Expected O, but got Unknown //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Expected O, but got Unknown object obj = <>c.<>9__2_0; if (obj == null) { Action val = delegate(string[] args) { if (args.Length >= 2) { RequireConfigAccess(); ModConfig.Enabled.Value = ParseBool(args[1]); } Log("Loadout menu: " + (ModConfig.Enabled.Value ? "ON (achievements are disabled while hosting)" : "OFF")); }; <>c.<>9__2_0 = val; obj = (object)val; } ConsoleCommandRegistry.Register("casprep_enable", "CasPrepared (host): show or set whether the loadout menu is on for sessions you host.", (Action)obj, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("bool value", "on/off, true/false or 1/0.") }); object obj2 = <>c.<>9__2_1; if (obj2 == null) { Action val2 = delegate { Log("sv_cheats: " + OnOff(Multiplayer.rules.sv_cheats) + ", AllowClientCheatCommands: " + OnOff(Multiplayer.rules.AllowClientCheatCommands)); if (!Net.IsRunning) { Log("Not in a multiplayer session. casprep_giveloadout works once you host or join one."); } else { string text = LoadoutServer.CheatBlockReason(Net.IsServer); Log((text == null) ? "casprep_giveloadout: available." : ("casprep_giveloadout: blocked - " + text)); } }; <>c.<>9__2_1 = val2; obj2 = (object)val2; } ConsoleCommandRegistry.Register("casprep_cheats", "CasPrepared: show whether Together cheat rules allow casprep_giveloadout.", (Action)obj2, (Dictionary<int, List<string>>)null, Array.Empty<(string, string)>()); object obj3 = <>c.<>9__2_2; if (obj3 == null) { Action val3 = delegate(string[] args) { if (!Net.IsRunning) { throw new Exception("Only works in a multiplayer session."); } string text = LoadoutServer.CheatBlockReason(Net.IsServer); if (text != null) { throw new Exception(text); } string target = ((args.Length >= 2) ? string.Join(" ", args, 1, args.Length - 1) : null); LoadoutClient.Give(target); }; <>c.<>9__2_2 = val3; obj3 = (object)val3; } ConsoleCommandRegistry.Register("casprep_giveloadout", "CasPrepared (cheat): open the loadout menu again. Needs sv_cheats (and AllowClientCheatCommands for clients).", (Action)obj3, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("target", "Optional player name or SteamID. Omit for yourself.") }); object obj4 = <>c.<>9__2_3; if (obj4 == null) { Action val4 = delegate(string[] args) { IntSetting(args, "Budget", delegate(int v) { ModConfig.Budget.Value = v; }, () => ModConfig.Budget.Value); }; <>c.<>9__2_3 = val4; obj4 = (object)val4; } ConsoleCommandRegistry.Register("casprep_budget", "CasPrepared (host): show or set the loadout budget.", (Action)obj4, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("int value", "New budget. Omit to show the current value.") }); object obj5 = <>c.<>9__2_4; if (obj5 == null) { Action val5 = delegate(string[] args) { FloatSetting(args, "Price multiplier", delegate(float v) { ModConfig.PriceMultiplier.Value = v; }, () => ModConfig.PriceMultiplier.Value); }; <>c.<>9__2_4 = val5; obj5 = (object)val5; } ConsoleCommandRegistry.Register("casprep_mult", "CasPrepared (host): show or set the price multiplier.", (Action)obj5, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("float value", "Multiplier for trader prices (1.0 = trader price).") }); object obj6 = <>c.<>9__2_5; if (obj6 == null) { Action val6 = delegate(string[] args) { if (args.Length >= 2 && IsOff(args[1])) { args = new string[2] { args[0], "0" }; } IntSetting(args, "Window seconds", delegate(int v) { ModConfig.WindowSeconds.Value = v; }, () => ModConfig.WindowSeconds.Value); if (ModConfig.WindowSeconds.Value <= 0) { Log("Time limit is off: only the distance limit applies."); } }; <>c.<>9__2_5 = val6; obj6 = (object)val6; } ConsoleCommandRegistry.Register("casprep_window", "CasPrepared (host): show or set how long (seconds) the menu stays available after spawn. 0 or off disables the timer.", (Action)obj6, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("int seconds", "Window length in seconds. 0 / off = no time limit.") }); object obj7 = <>c.<>9__2_6; if (obj7 == null) { Action val7 = delegate(string[] args) { FloatSetting(args, "Max distance", delegate(float v) { ModConfig.MaxDistance.Value = v; }, () => ModConfig.MaxDistance.Value); }; <>c.<>9__2_6 = val7; obj7 = (object)val7; } ConsoleCommandRegistry.Register("casprep_radius", "CasPrepared (host): show or set how far (tiles) a player may move from spawn before the menu closes.", (Action)obj7, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("float distance", "Distance in world units.") }); object obj8 = <>c.<>9__2_7; if (obj8 == null) { Action val8 = delegate(string[] args) { IntSetting(args, "Crate lifetime", delegate(int v) { ModConfig.CrateLifetimeSeconds.Value = v; }, () => ModConfig.CrateLifetimeSeconds.Value); }; <>c.<>9__2_7 = val8; obj8 = (object)val8; } ConsoleCommandRegistry.Register("casprep_cratetime", "CasPrepared (host): show or set the supply crate lifetime in seconds.", (Action)obj8, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("int seconds", "Lifetime in seconds.") }); object obj9 = <>c.<>9__2_8; if (obj9 == null) { Action val9 = delegate { RequireHost(); Log("Loadout menu: " + (ModConfig.Enabled.Value ? "ON" : "OFF")); Log(string.Format("Budget {0}, multiplier x{1}, ", ModConfig.Budget.Value, ModConfig.PriceMultiplier.Value.ToString("0.##", CultureInfo.InvariantCulture)) + string.Format("window {0}, radius {1}, crate {2}s", (ModConfig.WindowSeconds.Value <= 0) ? "off" : (ModConfig.WindowSeconds.Value + "s"), ModConfig.MaxDistance.Value.ToString("0.#", CultureInfo.InvariantCulture), ModConfig.CrateLifetimeSeconds.Value)); foreach (string item in LoadoutServer.DescribePlayers()) { Log(item); } }; <>c.<>9__2_8 = val9; obj9 = (object)val9; } ConsoleCommandRegistry.Register("casprep_status", "CasPrepared (host): list players and their loadout state.", (Action)obj9, (Dictionary<int, List<string>>)null, Array.Empty<(string, string)>()); object obj10 = <>c.<>9__2_9; if (obj10 == null) { Action val10 = delegate(string[] args) { RequireConfigAccess(); if (args.Length < 2) { throw new Exception("Usage: casprep_reset <player name | steamid | all>"); } string text = string.Join(" ", args, 1, args.Length - 1); Log($"Reset {LoadoutServer.Reset(text)} record(s) for '{text}'."); }; <>c.<>9__2_9 = val10; obj10 = (object)val10; } ConsoleCommandRegistry.Register("casprep_reset", "CasPrepared (host): let a player pick a loadout again (opens a new window on their next spawn check).", (Action)obj10, (Dictionary<int, List<string>>)null, new(string, string)[1] { ("target", "Player name, SteamID or 'all'.") }); object obj11 = <>c.<>9__2_10; if (obj11 == null) { Action val11 = delegate { LoadoutClient.ToggleMenu(); }; <>c.<>9__2_10 = val11; obj11 = (object)val11; } ConsoleCommandRegistry.Register("casprep_menu", "CasPrepared: open/close the loadout menu.", (Action)obj11, (Dictionary<int, List<string>>)null, Array.Empty<(string, string)>()); } private static void IntSetting(string[] args, string label, Action<int> set, Func<int> get) { if (args.Length >= 2) { RequireConfigAccess(); if (!int.TryParse(args[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { throw new Exception("\"" + args[1] + "\" is not a valid integer."); } set(result); } Log($"{label}: {get()}"); } private static void FloatSetting(string[] args, string label, Action<float> set, Func<float> get) { if (args.Length >= 2) { RequireConfigAccess(); if (!float.TryParse(args[1].Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { throw new Exception("\"" + args[1] + "\" 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 "true": case "yes": case "enable": return true; case "0": case "off": case "false": case "no": case "disable": return false; default: throw new Exception("\"" + s + "\" is not on/off."); } } private static bool IsOff(string s) { switch (s.Trim().ToLowerInvariant()) { case "off": case "false": case "no": case "disable": case "none": return true; default: return false; } } private static string OnOff(bool v) { return v ? "on" : "off"; } public static string ConfigLockReason() { if (Net.IsRunning && !Net.IsServer) { return "Host only."; } if (Net.IsRunning && (Object)(object)WorldGeneration.world != (Object)null && !Multiplayer.rules.sv_cheats) { return "Settings are locked during a running campaign. Change them in the main menu or enable sv_cheats."; } return null; } private static void RequireHost() { if (Net.IsRunning && !Net.IsServer) { throw new Exception("Host only."); } } 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); } } } 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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) 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 LoadoutProtocol { public const string StatusChannel = "casprepared.status"; public const string BuyChannel = "casprepared.buy"; public const string GiveChannel = "casprepared.give"; public const string StateWaiting = "waiting"; public const string StateAvailable = "available"; public const string StateUsed = "used"; public const string StateExpired = "expired"; public const string StateDisabled = "disabled"; public const string KeyState = "state"; public const string KeyBudget = "budget"; public const string KeyMultiplier = "mult"; public const string KeyRemaining = "remaining"; public const string KeyDistance = "distance"; public const string KeyMaxDistance = "maxDistance"; public const string KeyReason = "reason"; public const string KeyItems = "items"; public const string KeyReady = "ready"; public const string KeyOk = "ok"; public const string KeyError = "error"; public const string KeyStatus = "status"; public const string KeyTarget = "target"; public const string KeyMessage = "message"; } internal static class LoadoutServer { private enum RecordState { Used, Expired } private sealed class Pending { public ushort ClientId; public Vector2 Origin; public float StartTime; } private sealed class PlayersSaveProvider : ICustomSaveProvider { public int GetVersion() { return 1; } public JToken Capture() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown if (Net.IsRunning && !Net.IsServer) { return null; } JObject val = new JObject(); foreach (KeyValuePair<string, RecordState> record in Records) { val[record.Key] = JToken.op_Implicit((record.Value == RecordState.Used) ? "used" : "expired"); } foreach (string key in PendingByKey.Keys) { if (val[key] == null) { val[key] = JToken.op_Implicit("expired"); } } return (JToken)new JObject { ["players"] = (JToken)(object)val }; } public void Restore(JToken payload, int version, SaveRestoreContext context) { if (Net.IsRunning && !Net.IsServer) { return; } JToken obj = ((payload != null) ? payload[(object)"players"] : null); JObject val = (JObject)(object)((obj is JObject) ? obj : null); if (val == null) { return; } foreach (JProperty item in val.Properties()) { RecordState value = ((!(Extensions.Value<string>((IEnumerable<JToken>)item.Value) == "used")) ? RecordState.Expired : RecordState.Used); if (!Records.TryGetValue(item.Name, out var value2) || value2 != RecordState.Used) { Records[item.Name] = value; } PendingByKey.Remove(item.Name); } Plugin.Logger.LogInfo((object)$"Restored loadout records for {Records.Count} player(s)."); } } private static readonly Dictionary<string, RecordState> Records = new Dictionary<string, RecordState>(); private static readonly Dictionary<string, Pending> PendingByKey = new Dictionary<string, Pending>(); private static bool _wasRunning; private static bool _achievementsLocked; private static float _nextTick; public static bool Enabled => ModConfig.Enabled.Value; public static void Init() { SaveRegistry.RegisterGlobalProvider("casprepared.players", (ICustomSaveProvider)(object)new PlayersSaveProvider()); MultiplayerBridge.RegisterServerHandler("casprepared.status", (Func<uint, JToken, JToken>)((uint sender, JToken payload) => HandleStatus(sender, payload))); MultiplayerBridge.RegisterServerHandler("casprepared.buy", (Func<uint, JToken, JToken>)((uint sender, JToken payload) => HandleBuy(sender, payload))); MultiplayerBridge.RegisterServerHandler("casprepared.give", (Func<uint, JToken, JToken>)((uint sender, JToken payload) => HandleGive(sender, payload, fromHost: false))); } public static JToken HandleLocal(string channel, uint sender, JToken payload) { if (!(channel == "casprepared.buy")) { if (channel == "casprepared.give") { return HandleGive(sender, payload, fromHost: true); } return HandleStatus(sender, payload); } return HandleBuy(sender, payload); } public static bool WorldReady() { return (Object)(object)WorldGeneration.world != (Object)null && WorldGeneration.world.worldExists; } public static void Tick() { if (!Net.IsRunning) { if (_wasRunning) { _achievementsLocked = false; } _wasRunning = false; return; } _wasRunning = true; if (Net.IsServer && WorldReady() && Enabled && !(Time.unscaledTime < _nextTick)) { _nextTick = Time.unscaledTime + 0.5f; LockAchievements(); TrackPlayers(); } } private static void LockAchievements() { if (!_achievementsLocked) { _achievementsLocked = true; AchievementBreakSync.ApplyLocal(true); AchievementBreakSync.Server_Broadcast(true, (List<knetid>)null); Plugin.Logger.LogInfo((object)"Achievements disabled for this session (CasPrepared active)."); } } private static void TrackPlayers() { //IL_0082: Unknown result type (might be due to invalid IL or missing references) HashSet<string> present = new HashSet<string>(); foreach (ScavPlayer item in ScavPlayer.AllPlayers.ToList()) { if ((Object)(object)item == (Object)null) { continue; } string text = KeyOf(item); present.Add(text); if (!Records.ContainsKey(text) && PendingByKey.TryGetValue(text, out var value)) { value.ClientId = item.playerId.id; float remaining; float distance; string text2 = Evaluate(value, item, out remaining, out distance); if (text2 != null) { Expire(text, item.playerName, text2); } } } foreach (string item2 in PendingByKey.Keys.Where((string k) => !present.Contains(k)).ToList()) { Expire(item2, item2, "left the game"); } } private static string Evaluate(Pending pending, ScavPlayer plr, out float remaining, out float distance) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) distance = 0f; if (ModConfig.WindowSeconds.Value <= 0) { remaining = -1f; } else { remaining = (float)ModConfig.WindowSeconds.Value - (Time.realtimeSinceStartup - pending.StartTime); if (remaining <= 0f) { return "time ran out"; } } Body body = plr.body; if ((Object)(object)body == (Object)null) { return null; } if (!body.alive) { return "died"; } distance = Vector2.Distance(Vector2.op_Implicit(((Component)body).transform.position), pending.Origin); if (distance > ModConfig.MaxDistance.Value) { return "moved too far from spawn"; } return null; } private static void Expire(string key, string name, string reason) { PendingByKey.Remove(key); Records[key] = RecordState.Expired; Plugin.Logger.LogInfo((object)("Loadout window closed for " + name + ": " + reason + ".")); } private static string KeyOf(ScavPlayer plr) { return (plr.SteamId != 0L) ? ("steam:" + plr.SteamId) : ("name:" + plr.playerName); } private static ScavPlayer FindPlayer(uint clientId) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) ScavPlayer.ClientIdToPlayerDict.TryGetValue(new knetid((ushort)clientId), out var value); return value; } private static JObject BuildStatus(ScavPlayer plr) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown JObject val = new JObject { ["budget"] = JToken.op_Implicit(ModConfig.Budget.Value), ["mult"] = JToken.op_Implicit(ModConfig.PriceMultiplier.Value), ["maxDistance"] = JToken.op_Implicit(ModConfig.MaxDistance.Value), ["state"] = JToken.op_Implicit("waiting") }; if (!Enabled) { val["state"] = JToken.op_Implicit("disabled"); return val; } if ((Object)(object)plr == (Object)null) { return val; } string key = KeyOf(plr); if (Records.TryGetValue(key, out var value)) { val["state"] = JToken.op_Implicit((value == RecordState.Used) ? "used" : "expired"); return val; } if (PendingByKey.TryGetValue(key, out var value2)) { float remaining; float distance; string text = Evaluate(value2, plr, out remaining, out distance); if (text != null) { Expire(key, plr.playerName, text); val["state"] = JToken.op_Implicit("expired"); val["reason"] = JToken.op_Implicit(text); return val; } val["state"] = JToken.op_Implicit("available"); val["remaining"] = JToken.op_Implicit(remaining); val["distance"] = JToken.op_Implicit(distance); } return val; } private static JToken HandleStatus(uint sender, JToken payload) { if (!Net.IsServer) { return null; } ScavPlayer plr = FindPlayer(sender); if (payload != null && payload.Value<bool?>((object)"ready") == true) { TryOpenWindow(plr); } return (JToken)(object)BuildStatus(plr); } private static void TryOpenWindow(ScavPlayer plr) { //IL_008b: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) if (Enabled && !((Object)(object)plr == (Object)null) && !((Object)(object)plr.body == (Object)null) && plr.body.alive && WorldReady() && !WorldGeneration.world.generatingWorld) { string text = KeyOf(plr); if (!Records.ContainsKey(text) && !PendingByKey.ContainsKey(text)) { PendingByKey[text] = new Pending { ClientId = plr.playerId.id, Origin = Vector2.op_Implicit(((Component)plr.body).transform.position), StartTime = Time.realtimeSinceStartup }; Plugin.Logger.LogInfo((object)$"Loadout window opened for {plr.playerName} ({text}) at {((Component)plr.body).transform.position}."); } } } public static void OnNewWorld() { Records.Clear(); PendingByKey.Clear(); _achievementsLocked = false; } private static JToken HandleBuy(uint sender, JToken payload) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown if (!Net.IsServer) { return null; } ScavPlayer plr = FindPlayer(sender); try { string text = TryBuy(plr, payload); return (JToken)new JObject { ["ok"] = JToken.op_Implicit(text == null), ["error"] = JToken.op_Implicit(text), ["status"] = (JToken)(object)BuildStatus(plr) }; } catch (Exception ex) { Plugin.Logger.LogError((object)("Loadout purchase failed: " + ex)); return (JToken)new JObject { ["ok"] = JToken.op_Implicit(false), ["error"] = JToken.op_Implicit("Host error while spawning the loadout."), ["status"] = (JToken)(object)BuildStatus(plr) }; } } private static string TryBuy(ScavPlayer plr, JToken payload) { if (!Enabled) { return "The host has turned the loadout menu off."; } if ((Object)(object)plr == (Object)null) { return "Player not found on host."; } string key = KeyOf(plr); if (Records.TryGetValue(key, out var value)) { return (value == RecordState.Used) ? "Loadout already taken this campaign." : "Loadout window has closed."; } if (!PendingByKey.TryGetValue(key, out var value2)) { return "Loadout is not available yet."; } float remaining; float distance; string text = Evaluate(value2, plr, out remaining, out distance); if (text != null) { Expire(key, plr.playerName, text); return "Loadout window has closed: " + text + "."; } if ((Object)(object)plr.body == (Object)null || !plr.body.alive) { return "Your character is not in the world."; } JToken obj = ((payload != null) ? payload[(object)"items"] : null); JObject val = (JObject)(object)((obj is JObject) ? obj : null); if (val == null || !((JToken)val).HasValues) { return "Nothing selected."; } List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(); foreach (JProperty item in val.Properties()) { int value3; try { value3 = Extensions.Value<int>((IEnumerable<JToken>)item.Value); } catch { CatalogEntry entry; return "Bad amount for " + (LoadoutCatalog.TryGet(item.Name, out entry) ? entry.Name : item.Name); } list.Add(new KeyValuePair<string, int>(item.Name, value3)); } List<LoadoutOrder.Line> order; long cost; int total; string text2 = LoadoutOrder.Build(list, out order, out cost, out total); if (text2 != null) { return text2; } LoadoutOrder.Spawn(plr.body, order); PendingByKey.Remove(key); Records[key] = RecordState.Used; string text3 = $"{plr.playerName} received a loadout ({total} items, cost {cost}/{ModConfig.Budget.Value})."; Plugin.Logger.LogInfo((object)text3); if ((Object)(object)ConsoleScript.instance != (Object)null) { ConsoleScript.instance.LogToConsole(text3); } return null; } private static JToken HandleGive(uint sender, JToken payload, bool fromHost) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown if (!Net.IsServer) { return null; } ScavPlayer val = FindPlayer(sender); string text = null; string message = null; try { text = TryGive(val, (payload != null) ? payload.Value<string>((object)"target") : null, fromHost, out message); } catch (Exception ex) { Plugin.Logger.LogError((object)("GiveLoadout failed: " + ex)); text = "Host error while granting the loadout."; } return (JToken)new JObject { ["ok"] = JToken.op_Implicit(text == null), ["error"] = JToken.op_Implicit(text), ["message"] = JToken.op_Implicit(message), ["status"] = (JToken)(object)BuildStatus(val) }; } public static string CheatBlockReason(bool fromHost) { if (!Multiplayer.rules.sv_cheats) { return "Server rule 'sv_cheats' is disabled."; } if (!fromHost && !Multiplayer.rules.AllowClientCheatCommands) { return "Server rule 'AllowClientCheatCommands' is disabled."; } return null; } private static string TryGive(ScavPlayer requester, string target, bool fromHost, out string message) { message = null; if (!Enabled) { return "The loadout menu is turned off on the host."; } string text = CheatBlockReason(fromHost); if (text != null) { return text; } ScavPlayer val = requester; if (!string.IsNullOrWhiteSpace(target)) { val = ScavPlayer.AllPlayers.FirstOrDefault((Func<ScavPlayer, bool>)((ScavPlayer p) => (Object)(object)p != (Object)null && (string.Equals(p.playerName, target, StringComparison.OrdinalIgnoreCase) || p.SteamId.ToString() == target))); if ((Object)(object)val == (Object)null) { return "No player named '" + target + "'."; } } if ((Object)(object)val == (Object)null) { return "Player not found on host."; } string key = KeyOf(val); Records.Remove(key); PendingByKey.Remove(key); TryOpenWindow(val); message = (PendingByKey.ContainsKey(key) ? ("Loadout menu granted to " + val.playerName + ".") : ("Loadout menu granted to " + val.playerName + "; it opens once they are in the world.")); Plugin.Logger.LogInfo((object)("GiveLoadout: " + message + " (requested by " + (requester?.playerName ?? "?") + ")")); return null; } public static IEnumerable<string> DescribePlayers() { foreach (ScavPlayer plr in ScavPlayer.AllPlayers.ToList()) { if (!((Object)(object)plr == (Object)null)) { string key = KeyOf(plr); string state; if (Records.TryGetValue(key, out var rec)) { state = rec.ToString().ToLowerInvariant(); } else { state = ((!PendingByKey.TryGetValue(key, out var p)) ? "waiting for spawn" : ((ModConfig.WindowSeconds.Value <= 0) ? "available (no time limit)" : $"available ({Mathf.Max(0f, (float)ModConfig.WindowSeconds.Value - (Time.realtimeSinceStartup - p.StartTime)):0}s left)")); p = null; } yield return plr.playerName + " [" + key + "] - " + state; } } } public static int Reset(string target) { if (string.Equals(target, "all", StringComparison.OrdinalIgnoreCase)) { int result = Records.Count + PendingByKey.Count; Records.Clear(); PendingByKey.Clear(); return result; } HashSet<string> hashSet = new HashSet<string>(); foreach (ScavPlayer item in ScavPlayer.AllPlayers.ToList()) { if (!((Object)(object)item == (Object)null) && (string.Equals(item.playerName, target, StringComparison.OrdinalIgnoreCase) || item.SteamId.ToString() == target)) { hashSet.Add(KeyOf(item)); } } hashSet.Add("steam:" + target); hashSet.Add("name:" + target); int num = 0; foreach (string item2 in hashSet) { if (Records.Remove(item2)) { num++; } if (PendingByKey.Remove(item2)) { num++; } } return num; } } 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 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; public static bool IsOpen { get; private set; } public static bool IsSearchFocused { get; private set; } public static bool BlocksGameInput { get { //IL_001e: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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) if (!IsOpen) { return false; } if (IsSearchFocused) { return true; } Vector3 mousePosition = Input.mousePosition; return ((Rect)(ref _window)).Contains(new Vector2(mousePosition.x, (float)Screen.height - mousePosition.y)); } } public static void Open() { IsOpen = true; _message = null; _filterKey = null; } public static void Close() { IsOpen = false; IsSearchFocused = false; _hovered = (_hoveredNext = null); } public static void ClearSelection() { Selected.Clear(); } public static void SetMessage(string message) { _message = message; } public static void Draw() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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); } finally { GUI.skin = skin; } } private static void PlaceWindow() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: 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_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: 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_0063: 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_0067: 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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Invalid comparison between Unknown and I4 //IL_00fb: 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(); IsSearchFocused = GUI.GetNameOfFocusedControl() == "casprep_search"; GUI.DragWindow(new Rect(0f, 0f, 10000f, unit * 2.2f)); } private static void DrawTitleBar(float u) { 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("loadout", PixelSkin.Muted, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) }); GUILayout.FlexibleSpace(); 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("TIME", PixelSkin.Muted, Array.Empty<GUILayoutOption>()); if (LoadoutClient.HasTimeLimit) { float remainingSeconds = LoadoutClient.RemainingSeconds; TimeSpan timeSpan = TimeSpan.FromSeconds(remainingSeconds); GUILayout.Label($"{(int)timeSpan.TotalMinutes:00}:{timeSpan.Seconds:00}", (remainingSeconds < 20f) ? PixelSkin.Danger : ((remainingSeconds < 60f) ? PixelSkin.Warning : PixelSkin.Label), Array.Empty<GUILayoutOption>()); } else { GUILayout.Label("NO LIMIT", PixelSkin.Label, Array.Empty<GUILayoutOption>()); } GUILayout.Space(u); float maxDistance = LoadoutClient.MaxDistance; float distance = LoadoutClient.Distance; float num = ((maxDistance > 0f) ? (distance / maxDistance) : 0f); GUILayout.Label("RANGE", PixelSkin.Muted, Array.Empty<GUILayoutOption>()); GUILayout.Label($"{distance:0.0}/{maxDistance:0}", (num > 0.85f) ? PixelSkin.Danger : ((num > 0.6f) ? PixelSkin.Warning : PixelSkin.Label), Array.Empty<GUILayoutOption>()); GUILayout.Space(u); 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.FlexibleSpace(); GUILayout.Label("stay near your spawn", PixelSkin.Muted, Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); } private static void DrawCatalog(float u, float mult) { //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Invalid comparison between Unknown and I4 //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_020d: 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_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: 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) 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; Rect rect2 = default(Rect); ((Rect)(ref rect2))..ctor(((Rect)(ref rect)).xMax + num, ((Rect)(ref row)).y, ((Rect)(ref row)).width - ((Rect)(ref rect)).width - num2 - num * 4f, ((Rect)(ref row)).height); PixelSkin.FitLabel(rect2, entry.Name, (value > 0) ? PixelSkin.ItemNameAccent : PixelSkin.ItemName); Rect val = default(Rect); ((Rect)(ref val))..ctor(((Rect)(ref row)).xMax - num2 - num, ((Rect)(ref row)).y, num2, ((Rect)(ref row)).height); GUI.Label(val, UnitPrice(entry, mult), PixelSkin.ItemPrice); } private static void DrawSelection(float u, float mult, int count) { //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Invalid comparison between Unknown and I4 //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_0240: 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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Expected O, but got Unknown //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) if (((Rect)(ref row)).Contains(Event.current.mousePosition)) { _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)); } float num3 = u * 3.6f; Rect val3 = default(Rect); ((Rect)(ref val3))..ctor(((Rect)(ref val2)).x - num3 - num, ((Rect)(ref row)).y, num3, ((Rect)(ref row)).height); GUI.Label(val3, LoadoutCatalog.PriceOf(entry, mult, amount).ToString(), PixelSkin.ItemPrice); 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); Rect rect2 = default(Rect); ((Rect)(ref rect2))..ctor(((Rect)(ref rect)).xMax + num, ((Rect)(ref row)).y, ((Rect)(ref val3)).x - ((Rect)(ref rect)).xMax - num * 2f, ((Rect)(ref row)).height); if (amount > 1) { GUIContent val4 = new GUIContent("x" + amount); float x = PixelSkin.ItemNameAccent.CalcSize(val4).x; Rect rect3 = default(Rect); ((Rect)(ref rect3))..ctor(((Rect)(ref rect2)).x, ((Rect)(ref rect2)).y, Mathf.Max(0f, ((Rect)(ref rect2)).width - x), ((Rect)(ref rect2)).height); PixelSkin.FitLabel(rect3, entry.Name, PixelSkin.ItemName); GUI.Label(new Rect(((Rect)(ref rect3)).xMax, ((Rect)(ref rect2)).y, x, ((Rect)(ref rect2)).height), val4, PixelSkin.ItemNameAccent); } else { PixelSkin.FitLabel(rect2, entry.Name, PixelSkin.ItemName); } } private static void DrawDescription(float u) { string text = ((_hovered == null) ? " " : (string.IsNullOrEmpty(_hovered.Description) ? _hovered.Name : (_hovered.Name + ": " + _hovered.Description))); GUILayout.Label(text, PixelSkin.Small, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(u * 2.1f) }); } private static void DrawFooter(float u, int budget, long cost, int count, bool overBudget) { //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_023b: 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(); Rect rect = GUILayoutUtility.GetRect(10f, u * 0.9f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) }); PixelSkin.DrawBar(rect, (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(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (!string.IsNullOrEmpty(_message)) { GUILayout.Label(_message, PixelSkin.Danger, Array.Empty<GUILayoutOption>()); } GUILayout.FlexibleSpace(); GUILayout.Label($"[{ModConfig.MenuKey.Value}] toggle menu you can walk while it is open", PixelSkin.Small, Array.Empty<GUILayoutOption>()); 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); return Mathf.Approximately(num, Mathf.Round(num)) ? Mathf.RoundToInt(num).ToString() : num.ToString("0.##", CultureInfo.InvariantCulture); } private static void RefreshFilter() { string text = _group + "\n" + _search + "\n" + LoadoutCatalog.Entries.Count; 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<int> WindowSeconds; public static ConfigEntry<float> MaxDistance; public static ConfigEntry<int> CrateLifetimeSeconds; public static ConfigEntry<KeyCode> MenuKey; private const string Section = "Host"; private const string KeySection = "Client"; public static void Init(ConfigFile cfg) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: 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 //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown Enabled = cfg.Bind<bool>("Host", "Enabled", true, "Loadout menu for multiplayer sessions you host. When on, achievements are disabled for the session. Also toggled from Together's Server settings or with casprep_enable."); Budget = cfg.Bind<int>("Host", "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>("Host", "PriceMultiplier", 1f, new ConfigDescription("Multiplier applied to base trader prices.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); WindowSeconds = cfg.Bind<int>("Host", "WindowSeconds", 300, new ConfigDescription("How long after spawning the loadout menu stays available. 0 = no time limit.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 86400), Array.Empty<object>())); MaxDistance = cfg.Bind<float>("Host", "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>("Host", "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>("Client", "MenuKey", (KeyCode)287, "Key that toggles the loadout menu."); } } 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_005a: 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_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0084: 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_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: 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>(); public static GUISkin Skin { get; private set; } public static int FontSize { get; private set; } = 20; public static float Unit => FontSize; private static Sprite TogetherSmall => UIManager.uiBlockSmall; private static Sprite TogetherNano => UIManager.uiBlockNano; private static Font GameFont => CoopModAssets.gamefont; private static float UiScale => UIBullshit.uiScale; private static float BaseFontSize => UIBullshit.DEFAULT_RETROGAME_FONTSIZE; 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_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Expected O, but got Unknown //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Expected O, but got Unknown //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_039d: Unknown result type (might be due to invalid IL or missing references) //IL_03b3: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_041d: Unknown result type (might be due to invalid IL or missing references) //IL_0438: Unknown result type (might be due to invalid IL or missing references) //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_044f: Unknown result type (might be due to invalid IL or missing references) //IL_0474: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Expected O, but got Unknown //IL_047f: Unknown result type (might be due to invalid IL or missing references) //IL_0484: Unknown result type (might be due to invalid IL or missing references) //IL_048e: Expected O, but got Unknown //IL_048f: Unknown result type (might be due to invalid IL or missing references) //IL_0490: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Expected O, but got Unknown //IL_05bf: Unknown result type (might be due to invalid IL or missing references) //IL_0660: Unknown result type (might be due to invalid IL or missing references) //IL_066a: Expected O, but got Unknown //IL_0675: Unknown result type (might be due to invalid IL or missing references) //IL_067a: Unknown result type (might be due to invalid IL or missing references) //IL_0686: Unknown result type (might be due to invalid IL or missing references) //IL_068f: Unknown result type (might be due to invalid IL or missing references) //IL_0697: Unknown result type (might be due to invalid IL or missing references) //IL_06a9: Unknown result type (might be due to invalid IL or missing references) //IL_06b0: Unknown result type (might be due to invalid IL or missing references) //IL_06ba: Expected O, but got Unknown //IL_06bb: Unknown result type (might be due to invalid IL or missing references) //IL_06c0: Unknown result type (might be due to invalid IL or missing references) //IL_06ca: Expected O, but got Unknown //IL_06cb: Unknown result type (might be due to invalid IL or missing references) //IL_06d0: Unknown result type (might be due to invalid IL or missing references) //IL_06da: Expected O, but got Unknown //IL_06e0: Expected O, but got Unknown //IL_075d: Unknown result type (might be due to invalid IL or missing references) //IL_07ab: Unknown result type (might be due to invalid IL or missing references) //IL_07c0: Unknown result type (might be due to invalid IL or missing references) //IL_07d0: Unknown result type (might be due to invalid IL or missing references) //IL_07da: Expected O, but got Unknown //IL_080a: Unknown result type (might be due to invalid IL or missing references) //IL_081a: Unknown result type (might be due to invalid IL or missing references) //IL_0824: Expected O, but got Unknown //IL_0869: Unknown result type (might be due to invalid IL or missing references) //IL_086e: Unknown result type (might be due to invalid IL or missing references) //IL_087a: Unknown result type (might be due to invalid IL or missing references) //IL_0883: Unknown result type (might be due to invalid IL or missing references) //IL_088b: Unknown result type (might be due to invalid IL or missing references) //IL_089d: Unknown result type (might be due to invalid IL or missing references) //IL_08bc: Unknown result type (might be due to invalid IL or missing references) //IL_08c6: Expected O, but got Unknown //IL_08c7: Unknown result type (might be due to invalid IL or missing references) //IL_08cc: Unknown result type (might be due to invalid IL or missing references) //IL_08d6: Expected O, but got Unknown //IL_08d7: Unknown result type (might be due to invalid IL or missing references) //IL_08df: Unknown result type (might be due to invalid IL or missing references) //IL_08ec: Expected O, but got Unknown //IL_096d: Unknown result type (might be due to invalid IL or missing references) //IL_0982: Unknown result type (might be due to invalid IL or missing references) //IL_09ba: Unknown result type (might be due to invalid IL or missing references) //IL_0a41: Unknown result type (might be due to invalid IL or missing references) //IL_0a4b: Expected O, but got Unknown //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) _builtScale = scale; _builtFont = GameFont; _builtWithTogether = withTogether; FontSize = Mathf.Max(10, Mathf.RoundToInt(BaseFontSize * scale)); if ((Object)(object)Skin != (Object)null) { Object.Destroy((Object)(object)Skin); } Skin = Object.Instantiate<GUISkin>(GUI.skin); ((Object)Skin).hideFlags = (HideFlags)61; if ((Object)(object)GameFont != (Object)null) { Skin.font = GameFont; } foreach (Texture2D ownedTexture in OwnedTextures) { if ((Object)(object)ownedTexture != (Object)null) { Object.Destroy((Object)(object)ownedTexture); } } OwnedTextures.Clear(); int num = Mathf.Max(1, Mathf.RoundToInt(3f * scale)); Frame frame = null; Frame frame2 = null; Texture2D val = null; if (withTogether) { try { frame = FromSprite(TogetherSmall, num, 4, (b: 1f, a: 0.97f), (b: 1f, a: 0.85f), (b: 0.65f, a: 0.75f), (b: 0.4f, a: 0.75f)); frame2 = FromSprite(TogetherNano, num, 2, (b: 1f, a: 0.9f), (b: 1f, a: 0.8f), (b: 0.65f, a: 0.7f), (b: 0.4f, a: 0.7f)); val = Tinted(TogetherNano, num, 0.45f, 0.6f); } catch (Exception ex) { Plugin.Logger.LogWarning((object)("Together UI sprites unusable, using generated frames: " + ex.Message)); frame = (frame2 = null); } } if (frame == null || frame2 == null || (Object)(object)val == (Object)null) { frame = Frame.Generated(num, 2); frame2 = Frame.Generated(Mathf.Max(1, num / 2), 2); val = Generated(num, new Color(0.35f, 0.35f, 0.35f), new Color(0.05f, 0.05f, 0.05f, 0.7f)); } Texture2D tex = Solid(AccentColor); Texture2D tex2 = Solid(DangerColor); int fontSize = FontSize; int num2 = Mathf.Max(2, Mathf.RoundToInt((float)fontSize * 0.35f)); Label = Text(Skin.label, TextColor, fontSize); Label.wordWrap = false; Label.alignment = (TextAnchor)3; Label.padding = new RectOffset(num2 / 2, num2 / 2, 0, 0); Label.margin = new RectOffset(2, 2, 2, 2); Muted = Text(Label, MutedColor, fontSize); Small = Text(Label, MutedColor, Mathf.RoundToInt((float)fontSize * 0.8f)); Small.wordWrap = true; Small.alignment = (TextAnchor)0; Right = Text(Label, TextColor, fontSize); Right.alignment = (TextAnchor)5; RightMuted =