Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of CommandQueueRemastered v0.4.1
CommandQueueRemastered.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using CommandQueueRemastered.Core; using CommandQueueRemastered.Game; using CommandQueueRemastered.Integrations; using EntityStates; using EntityStates.Drifter; using EntityStates.HallowedCauldron; using HG; using HarmonyLib; using Microsoft.CodeAnalysis; using RoR2; using RoR2.Artifacts; using RoR2.Orbs; using RoR2.UI; using TMPro; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("CommandQueueRemastered")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.4.1.0")] [assembly: AssemblyInformationalVersion("0.4.1")] [assembly: AssemblyProduct("CommandQueueRemastered")] [assembly: AssemblyTitle("CommandQueueRemastered")] [assembly: AssemblyVersion("0.4.1.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace CommandQueueRemastered { [BepInPlugin("local.commandqueue.remastered", "CommandQueue Remastered", "0.4.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInIncompatibility("com.kuberoot.commandqueuewithsave")] [BepInIncompatibility("local.commandqueue.iconfix")] [BepInIncompatibility("ProperSave_CommandQueueExtended")] public sealed class RemasteredPlugin : BaseUnityPlugin { public const string Guid = "local.commandqueue.remastered"; public const string Name = "CommandQueue Remastered"; public const string Version = "0.4.1"; internal const float ItemIconBaseSize = 51.2f; internal static RemasteredPlugin Instance; internal readonly QueueState Queue = new QueueState(ItemGroups.GroupOf); internal PresetStore Presets; internal readonly Dictionary<string, ConfigEntry<bool>> GroupOptions = new Dictionary<string, ConfigEntry<bool>>(StringComparer.Ordinal); internal ConfigEntry<bool> RotateRepeatedItems; internal ConfigEntry<bool> DistributionEnabled; internal ConfigEntry<bool> DistributeChests; internal ConfigEntry<bool> DistributeExchangePools; internal ConfigEntry<bool> DistributeTeleporterRewards; internal ConfigEntry<bool> HexGroupsOfSeven; internal ConfigEntry<DrifterSalvageMode> DrifterSalvage; internal ConfigEntry<string> ExcludedDistributionStages; internal ConfigEntry<GameplayInputBlocking> BlockGameplayInput; internal ConfigEntry<float> ItemScale; internal ConfigEntry<float> MenuScale; internal ConfigEntry<SpecialPickupBehavior> TemporaryItemBehavior; internal ConfigEntry<SpecialPickupBehavior> EtherealItemBehavior; internal ConfigEntry<bool> IgnoreTemporaryItems; internal ConfigEntry<bool> IgnoreEtherealItems; internal ConfigEntry<ExclusiveItemBehavior> ExclusiveItemSelection; internal ConfigEntry<bool> AutoCollectQueuedItems; internal ConfigEntry<bool> AutoPickupCommandEssence; internal ConfigEntry<bool> ExcludePausedPlayers; private PausedPlayerSync pausedPlayerSync; private float autoPickupRetryAfter; private int lastEssenceWorkFrame = -1; internal ConfigEntry<InventoryCountMode> FewestItemsCount; internal ConfigEntry<LimiterItemCount> LimiterCountMode; internal readonly Dictionary<ItemTier, ConfigEntry<EssenceDropMode>> EssenceDropModes = new Dictionary<ItemTier, ConfigEntry<EssenceDropMode>>(); internal Sprite ModIcon; internal Texture2D ModIconTexture; private Harmony harmony; private ProperSaveAdapter properSave; private readonly HashSet<PickupPickerController> pendingSelections = new HashSet<PickupPickerController>(); private readonly HashSet<PickupPickerController> manualDisplays = new HashSet<PickupPickerController>(); private static readonly MethodInfo localParticipantGetter = AccessTools.PropertyGetter(typeof(NetworkUIPromptController), "currentLocalParticipant"); private readonly List<ScoreboardQueueUI> scoreboardViews = new List<ScoreboardQueueUI>(); private float nextScoreboardScan; private Inventory selectionInventory; private readonly Dictionary<Inventory, PendingItemSelections> pendingLimitedItems = new Dictionary<Inventory, PendingItemSelections>(); internal bool presetsReadFailed; internal bool SuppressPauseShortcut => scoreboardViews.Any((ScoreboardQueueUI view) => Object.op_Implicit((Object)(object)view) && view.SuppressPauseShortcut); internal static bool InteractionActive(NetworkUIPromptController prompt, LocalUser user) { if (Object.op_Implicit((Object)(object)prompt) && user != null) { return localParticipantGetter.Invoke(prompt, null) == user; } return false; } private void Awake() { //IL_0592: Unknown result type (might be due to invalid IL or missing references) //IL_059c: Expected O, but got Unknown //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02e8: Unknown result type (might be due to invalid IL or missing references) //IL_0477: Unknown result type (might be due to invalid IL or missing references) //IL_0481: Expected O, but got Unknown //IL_04b5: Unknown result type (might be due to invalid IL or missing references) //IL_04bf: Expected O, but got Unknown Instance = this; if (new string[3] { "com.kuberoot.commandqueuewithsave", "local.commandqueue.iconfix", "ProperSave_CommandQueueExtended" }.Any(Chainloader.PluginInfos.ContainsKey)) { ((BaseUnityPlugin)this).Logger.LogError((object)"Disable CommandQueueExtended, IconFix and ProperSave_CommandQueueExtended before using Remastered. Remastered initialization stopped to avoid conflicting queue handlers."); ((Behaviour)this).enabled = false; return; } try { string[] names = ItemGroups.Names; foreach (string text in names) { GroupOptions.Add(text, ((BaseUnityPlugin)this).Config.Bind<bool>("Groups", text, true, "Enable the " + text + " queue group.")); } RotateRepeatedItems = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RotateRepeatedItems", true, "Move collected repeated items to the queue end.\n\nWhen disabled, keep displayed order and quantities while cycling through every queued item internally."); AutoCollectQueuedItems = BindAutoCollectOption(); AutoPickupCommandEssence = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AutoPickupCommandEssence", false, "Automatically open nearby Command essences when your active queue has a matching item, including while the scoreboard is open.\n\nEmpty or paused queues are left alone. Other menus, dialogs, text entry and active interactions remain protected.\n\nExclusiveItemSelection Automatic alone does not open an essence; that item must also be in the queue.\n\nUses normal interaction range; does not collect the selected item unless AutoCollectQueuedItems is enabled."); LimiterCountMode = ((BaseUnityPlugin)this).Config.Bind<LimiterItemCount>("General", "LimiterItemCount", LimiterItemCount.PermanentOnly, "Item stacks counted toward each Limiter target.\n\nPermanentOnly: permanent items.\n\nIncludeTemporary: permanent and temporary items.\n\nIncludeEthereal: permanent and ethereal items.\n\nIncludeBoth: permanent, temporary and ethereal items.\n\nApplies to limit checks and owned/limit badges. Special pickup selection/consumption still follows TemporaryItemBehavior and EtherealItemBehavior, including UseQueueNormally."); LimiterCountMode.SettingChanged += delegate { pendingLimitedItems.Clear(); }; ExcludePausedPlayers = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ExcludePausedPlayers", false, "Skip players whose queue group is paused when distributing essences.\n\nOther groups can still receive drops.\n\nHost setting. Remote players need the updated mod to share their pause state; unknown states remain eligible.\n\nIf everyone is excluded, keep the original drop location."); FewestItemsCount = ((BaseUnityPlugin)this).Config.Bind<InventoryCountMode>("Essence drops", "FewestItemsCount", InventoryCountMode.AllItems, "AllItems: count permanent stacks across all items.\n\nSameTier: count permanent stacks only in the essence's actual tier.\n\nTemporary and ethereal items do not count. Outstanding permanent essence assignments count until collected or cancelled.\n\nThe host's setting applies to all players in the run. Joining players' settings have no effect.\n\nWhen FewestItems is selected and multiple players share the lowest item count, essence drops alternate between those players. Each item tier tracks this order separately, even with AllItems."); DistributionEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Item Distribution Rules", "Enabled", true, "Enable item essence distribution.\n\nWhen off, keep original drop locations without changing per-tier modes, queue selection or collection settings. Host setting."); ExcludedDistributionStages = ((BaseUnityPlugin)this).Config.Bind<string>("Item Distribution Rules", "ExcludedStages", "bazaar, computationalexchange", "Stages where item distribution keeps original drop locations. Use Select stages in RiskOfOptions to choose named environments.\n\nDefaults:\n• Bazaar Between Time (bazaar)\n• Computational Exchange (computationalexchange)\n\nThe config file accepts comma-separated internal scene names; empty allows every stage. Host setting; applies immediately."); ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>("Migration", "StageSelectorVersion", 0, "Internal stage-selector migration marker. Retains later user choices."); if (val.Value < 1) { HashSet<string> hashSet = StageExclusions.Parse(ExcludedDistributionStages.Value); hashSet.UnionWith(StageExclusions.Parse("bazaar, computationalexchange")); ExcludedDistributionStages.Value = StageExclusions.Encode(hashSet); val.Value = 1; } DistributeChests = ((BaseUnityPlugin)this).Config.Bind<bool>("Item Distribution Rules", "Chests", true, "Distribute Command essences from standard and option chests, including money shop terminals.\n\nWhen off, these drops stay at their original location. Host setting."); DistributeExchangePools = ((BaseUnityPlugin)this).Config.Bind<bool>("Item Distribution Rules", "ExchangePools", true, "Distribute Command essences from cleansing pools and Hallowed cauldrons.\n\nWhen off, these drops stay at their original location. Host setting; custom mod sources may use other paths."); DistributeTeleporterRewards = ((BaseUnityPlugin)this).Config.Bind<bool>("Item Distribution Rules", "TeleporterBossRewards", true, "Distribute teleporter boss reward essences.\n\nWhen off, rewards stay at their original location. Other boss groups keep their normal per-tier distribution. Host setting."); DrifterSalvage = BindDrifterSalvageOption(); HexGroupsOfSeven = ((BaseUnityPlugin)this).Config.Bind<bool>("Item Distribution Rules", "HexGroupsOfSeven", false, "Distribute Hex essences in blocks of seven, counting all permanent Hex items together.\n\nComplete an unfinished block before starting the next player. With several unfinished blocks, finish the closest to seven first and keep serving that player until complete.\n\nOutstanding assignments count. After a complete block, rotate to the next eligible living player. Overrides the Hex recipient mode except Original. Host setting."); foreach (ItemTier value in Enum.GetValues(typeof(ItemTier))) { if (ItemGroups.Group(value) != null) { string text2 = OptionsPresentation.Name("Essence drops", ((object)value/*cast due to .constrained prefix*/).ToString()); EssenceDropModes[value] = ((BaseUnityPlugin)this).Config.Bind<EssenceDropMode>("Essence drops", ((object)value/*cast due to .constrained prefix*/).ToString(), EssenceDropMode.Original, "Command item essence location for " + text2 + ".\n\nOriginal: keep the source location.\n\nRoundRobin: alternate between living players.\n\nKiller: use the killing player (including owned minions).\n\nFewestItems: use FewestItemsCount.\n\nMissing/dead killer or non-kill source falls back to RoundRobin; no living players keeps the original drop.\n\nApplies to all Command item droplet sources, not equipment. Actual Void tiers are independent.\n\nHost/server setting, applies immediately; no client installation needed for relocation."); } } BlockGameplayInput = ((BaseUnityPlugin)this).Config.Bind<GameplayInputBlocking>("General", "BlockGameplayInput", GameplayInputBlocking.On, "On: block gameplay in both scoreboard views.\n\nCommandQueueOnly: block only in Command Queue, allow gameplay in Players.\n\nOff: allow gameplay in both views, including while clicking, hovering, typing or confirming. UI actions can also trigger gameplay.\n\nThe actual pause menu retains native control. Applies immediately."); Queue.RotateRepeatedItems = RotateRepeatedItems.Value; Queue.IsPickupAllowed = PickupAllowed; RotateRepeatedItems.SettingChanged += delegate { Queue.RotateRepeatedItems = RotateRepeatedItems.Value; }; TemporaryItemBehavior = ((BaseUnityPlugin)this).Config.Bind<SpecialPickupBehavior>("Special items", "TemporaryItemBehavior", SpecialPickupBehavior.ManualMenu, "Behavior for timed temporary Command pickups.\n\nManualMenu: open the normal picker.\n\nUseQueueWithoutConsuming: select the next available queued item of the same tier without changing quantities, order or Repeat progress.\n\nUseQueueNormally: select and consume normally.\n\nSkip entries unavailable in this temporary or ethereal essence, leaving them queued. If no eligible queued item is available, open the normal picker."); EtherealItemBehavior = ((BaseUnityPlugin)this).Config.Bind<SpecialPickupBehavior>("Special items", "EtherealItemBehavior", SpecialPickupBehavior.ManualMenu, "Behavior for ethereal Command pickups.\n\nManualMenu: open the normal picker.\n\nUseQueueWithoutConsuming: select the next available queued item of the same tier without changing quantities, order or Repeat progress.\n\nUseQueueNormally: select and consume normally.\n\nSkip entries unavailable in this temporary or ethereal essence, leaving them queued. If no eligible queued item is available, open the normal picker."); IgnoreTemporaryItems = ((BaseUnityPlugin)this).Config.Bind<bool>("Special items", "IgnoreTemporaryItems", false, "Ignore temporary Command items for distribution.\n\nPersonal setting: exclude only your own player from distribution of this item type, independently of queue pause or Behaviour. The host's setting does not change other players' choices.\n\nAlso disable automatic proximity opening for this type. Manual interaction still follows its configured Behaviour.\n\nRequires updated host/client support to report remote preferences. Unknown or stale remote states remain eligible; with no eligible recipient, drops keep their original location."); IgnoreEtherealItems = ((BaseUnityPlugin)this).Config.Bind<bool>("Special items", "IgnoreEtherealItems", false, "Ignore ethereal Command items for distribution.\n\nPersonal setting: exclude only your own player from distribution of this item type, independently of queue pause or Behaviour. The host's setting does not change other players' choices.\n\nAlso disable automatic proximity opening for this type. Manual interaction still follows its configured Behaviour.\n\nRequires updated host/client support to report remote preferences. Unknown or stale remote states remain eligible; with no eligible recipient, drops keep their original location."); ExclusiveItemSelection = ((BaseUnityPlugin)this).Config.Bind<ExclusiveItemBehavior>("Special items", "ExclusiveItemSelection", ExclusiveItemBehavior.Default, "Halcyon Seed, Newly Hatched Zoea, Exposed Cerebellum, Encrypted Cerebellum, Prison Matrix and Sentry Key.\n\nDefault: select from their exclusive Command essence when queued at any position.\n\nAutomatic: also select without a queue entry after you interact with the essence.\n\nAutomatic does not open the essence by itself. AutoPickupCommandEssence opens it only if that item is also in your active queue.\n\nExisting entries follow normal consumption and Repeat rules."); MenuScale = ((BaseUnityPlugin)this).Config.Bind<float>("General", "MenuScale", 1f, new ConfigDescription("Queue menu scale; capped to fit the screen.\n\nDefault: 1.0x.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>())); ItemScale = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ItemScale", 1f, new ConfigDescription("Item button scale.\n\n1.0x uses the compact 51.2-unit base size.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>())); Presets = new PresetStore(Path.Combine(Paths.ConfigPath, "commandQueueRemastered.presets.json")); try { Presets.Load(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Preset file could not be loaded; existing file retained: " + ex)); presetsReadFailed = true; } if (!presetsReadFailed) { try { int num = Presets.ImportLegacy(Path.Combine(Paths.ConfigPath, "commandQueueSaves.json")); if (num > 0) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Imported " + num + " legacy CommandQueue presets. Source file retained unchanged.")); } } catch (Exception ex2) { ((BaseUnityPlugin)this).Logger.LogError((object)("Legacy preset import failed; no presets imported. Import will retry on next startup: " + ex2)); } } harmony = new Harmony("local.commandqueue.remastered"); harmony.PatchAll(typeof(RemasteredPlugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Scoreboard gameplay input hooks registered (Update and CanSendBodyInput)."); LookingGlassCommandCompatibility.Register(harmony, this); Run.onRunStartGlobal += OnRunStart; Run.onRunDestroyGlobal += OnRunEnd; pausedPlayerSync = new PausedPlayerSync(this); RoR2Application.onLoad = (Action)Delegate.Combine(RoR2Application.onLoad, new Action(RegisterOptions)); properSave = new ProperSaveAdapter(this); properSave.Initialize(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("CommandQueue Remastered 0.4.1 initialized. Interface: game scoreboard. Game: " + Application.version + ".")); } catch (Exception ex3) { ((BaseUnityPlugin)this).Logger.LogError((object)("Remastered initialization failed: " + ex3)); OnDestroy(); ((Behaviour)this).enabled = false; } } private void RegisterOptions() { RoR2Application.onLoad = (Action)Delegate.Remove(RoR2Application.onLoad, new Action(RegisterOptions)); OptionalOptions.Register(this, harmony); } private ConfigEntry<bool> BindAutoCollectOption() { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ConfigEntry<bool> result; try { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Item collection", "AutoCollectQueuedItems", false, "Moved to General."); bool value = val.Value; ((BaseUnityPlugin)this).Config.Remove(((ConfigEntryBase)val).Definition); result = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AutoCollectQueuedItems", value, "Automatically collect the item selected from your queue.\n\nWithout this option, the selected item drops on the ground.\n\nIn multiplayer, enable this on both the host and your client."); } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.Save(); } return result; } private ConfigEntry<DrifterSalvageMode> BindDrifterSalvageOption() { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ConfigEntry<DrifterSalvageMode> val3; try { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; ConfigEntry<string> val = ((BaseUnityPlugin)this).Config.Bind<string>("Item Distribution Rules", "DrifterSalvage", "SkillUser", "Migrated to a single choice."); ConfigEntry<string> val2 = ((BaseUnityPlugin)this).Config.Bind<string>("Item Distribution Rules", "DrifterSalvageTarget", "", "Replaced by DrifterSalvage."); if (!DrifterSalvageSettings.TryMigrate(val.Value, val2.Value, out var mode)) { LogWarning("Unrecognized Drifter Salvage setting; using Original."); } ((BaseUnityPlugin)this).Config.Remove(((ConfigEntryBase)val).Definition); ((BaseUnityPlugin)this).Config.Remove(((ConfigEntryBase)val2).Definition); val3 = ((BaseUnityPlugin)this).Config.Bind<DrifterSalvageMode>("Item Distribution Rules", "DrifterSalvage", DrifterSalvageMode.SkillUser, "Location of temporary Command drops from Drifter's Salvage special skill.\n\nOriginal: keep the skill's original drop location.\n\nSkillUser (default): send all drops to the Drifter who used this skill, independently for each Drifter; overrides per-tier modes.\n\nItemDistribution: use the normal per-tier distribution mode.\n\nMaster switch, stage exclusions, personal Ignore and optional paused-group exclusions still apply. Without an eligible recipient, keep the original drop location. Other temporary sources and queue/collection settings are unaffected. Host setting."); val3.Value = mode; } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.Save(); } return val3; } internal bool PlayerPaused(CharacterMaster master, string group) { return pausedPlayerSync?.IsPaused(master, group) ?? false; } internal bool PlayerIgnores(CharacterMaster master, UniquePickup pickup) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) return pausedPlayerSync?.IsIgnored(master, ((UniquePickup)(ref pickup)).isTempItem, pickup.isRental) ?? false; } internal void LogError(string context, Exception exception) { ((BaseUnityPlugin)this).Logger.LogError((object)(context + ": " + exception)); } internal void LogInfo(string message) { ((BaseUnityPlugin)this).Logger.LogInfo((object)message); } internal void LogWarning(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); } internal bool HasPendingSelection(PickupPickerController picker) { return pendingSelections.Contains(picker); } private SpecialPickupBehavior SelectionBehavior(UniquePickup pickup) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return SpecialPickupPolicy.Resolve(((UniquePickup)(ref pickup)).isTempItem, pickup.isRental, TemporaryItemBehavior.Value, EtherealItemBehavior.Value); } internal bool GroupEnabled(string group) { if (group != null && GroupOptions.TryGetValue(group, out var value)) { return value.Value; } return false; } internal MenuInputMode InputMode(LocalUser user) { return (from view in scoreboardViews where Object.op_Implicit((Object)(object)view) select view.InputMode(user)).FirstOrDefault((MenuInputMode mode) => mode != MenuInputMode.KeepNative); } internal bool BlocksGameplay(LocalUser user) { return InputMode(user) == MenuInputMode.Block; } private void Update() { AttachScoreboards(); properSave?.Update(); pausedPlayerSync?.Update(); FastAssignedEssence.Process(); } private void FixedUpdate() { if (lastEssenceWorkFrame == Time.frameCount) { return; } lastEssenceWorkFrame = Time.frameCount; if (Time.unscaledTime < autoPickupRetryAfter) { return; } try { TryPickupEssence(); } catch (Exception exception) { autoPickupRetryAfter = Time.unscaledTime + 5f; LogError("Automatic essence interaction failed; normal interaction remains available", exception); } } private void AttachScoreboards() { if (Time.unscaledTime < nextScoreboardScan) { return; } nextScoreboardScan = Time.unscaledTime + 0.5f; scoreboardViews.RemoveAll((ScoreboardQueueUI view) => !Object.op_Implicit((Object)(object)view)); HUD[] array = Object.FindObjectsOfType<HUD>(); foreach (HUD val in array) { if (!Object.op_Implicit((Object)(object)val.scoreboardPanel)) { continue; } ScoreboardController componentInChildren = val.scoreboardPanel.GetComponentInChildren<ScoreboardController>(true); if (Object.op_Implicit((Object)(object)componentInChildren) && !Object.op_Implicit((Object)(object)((Component)componentInChildren).GetComponent<ScoreboardQueueUI>())) { ScoreboardQueueUI scoreboardQueueUI = ((Component)componentInChildren).gameObject.AddComponent<ScoreboardQueueUI>(); try { scoreboardQueueUI.Initialize(this, val, componentInChildren); scoreboardViews.Add(scoreboardQueueUI); } catch (Exception exception) { scoreboardQueueUI.DisableAfterFailure(); LogError("Scoreboard initialization failed", exception); } } } } private void OnRunStart(Run run) { Queue.Reset(); pendingSelections.Clear(); pendingLimitedItems.Clear(); selectionInventory = null; ResetDrops(); pausedPlayerSync?.Reset(); } private void OnRunEnd(Run run) { Queue.Reset(); pendingSelections.Clear(); pendingLimitedItems.Clear(); selectionInventory = null; ResetDrops(); pausedPlayerSync?.Reset(); } private static void ResetDrops() { EssenceDrops.Distribution.Reset(); EssenceAssignments.Reset(); EssenceDrops.Killer = null; DistributionSourceContext.Current = DropSource.Other; DistributionSourceContext.SkillUser = null; AutomaticCollection.Selecting.Clear(); FastAssignedEssence.Reset(); EssenceWorkRegistry.ResetInteractions(); } private void OnDestroy() { RoR2Application.onLoad = (Action)Delegate.Remove(RoR2Application.onLoad, new Action(RegisterOptions)); foreach (ScoreboardQueueUI scoreboardView in scoreboardViews) { if (Object.op_Implicit((Object)(object)scoreboardView)) { Object.Destroy((Object)(object)scoreboardView); } } scoreboardViews.Clear(); properSave?.Dispose(); pausedPlayerSync?.Dispose(); Run.onRunStartGlobal -= OnRunStart; Run.onRunDestroyGlobal -= OnRunEnd; Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } ResetDrops(); EssenceWorkRegistry.Clear(); if (Object.op_Implicit((Object)(object)ModIcon)) { Object.Destroy((Object)(object)ModIcon); } if (Object.op_Implicit((Object)(object)ModIconTexture)) { Object.Destroy((Object)(object)ModIconTexture); } if ((Object)(object)Instance == (Object)(object)this) { Instance = null; } } internal bool ScheduleSelection(PickupPickerController picker, LocalUser user, NetworkUIPromptController prompt, CameraRigController camera) { //IL_0226: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)picker) || manualDisplays.Contains(picker)) { return false; } if (pendingSelections.Contains(picker)) { return true; } if (user == null || !Object.op_Implicit((Object)(object)Run.instance) || picker.options == null || !Object.op_Implicit((Object)(object)prompt)) { return false; } GameObject commandCubePrefab = CommandArtifactManager.commandCubePrefab; PickupPickerController val = (Object.op_Implicit((Object)(object)commandCubePrefab) ? commandCubePrefab.GetComponent<PickupPickerController>() : null); if (!Object.op_Implicit((Object)(object)val) || (Object)(object)picker.panelPrefab != (Object)(object)val.panelPrefab || picker.isDelusionChoice || picker.isRebirthChoice) { return false; } selectionInventory = (Object.op_Implicit((Object)(object)user.cachedMaster) ? user.cachedMaster.inventory : null); CommandOption[] array = SelectionOptions(picker); string text = SourceTier(picker); int num = FindSelection(array, text); if (array.Any((CommandOption option) => ItemGroups.GroupOfTier(option.Tier) == "Void")) { LogInfo("Void command essence: source tier=" + (text ?? "not received") + "; option tiers=" + string.Join(",", (from option in array select option.Tier into tier where tier != null select tier).Distinct()) + "; queue choice=" + ((num < 0) ? "manual menu" : (array[num].Pickup + " (" + array[num].Tier + ")")) + "."); } if (num < 0) { return false; } CommandOption commandOption = array[num]; bool exclusive = CommandSelection.IsExclusiveEssence(array, ItemGroups.IsExclusivePickup); int num2 = SelectionHead(array, commandOption.Tier); QueueEntry plannedEntry = ((num2 < 0) ? null : Queue.Entries[num2]); SpecialPickupBehavior behavior = SelectionBehavior(picker.options[num].pickup); pendingSelections.Add(picker); try { ((MonoBehaviour)this).StartCoroutine(SubmitNextFrame(picker, num, commandOption.Pickup, commandOption.Tier, user, prompt, camera, behavior, exclusive, plannedEntry)); } catch { pendingSelections.Remove(picker); throw; } return true; } private bool HasQueuedChoice(PickupPickerController picker, LocalUser user) { selectionInventory = (Object.op_Implicit((Object)(object)user.cachedMaster) ? user.cachedMaster.inventory : null); if (!AutomaticCollection.IsCommand(picker) || picker.options == null) { return false; } uint ignored = SpecialPickupDistribution.IgnoreMask(IgnoreTemporaryItems.Value, IgnoreEtherealItems.Value); if (picker.options.Any((Option option) => SpecialPickupDistribution.Ignores(ignored, ((UniquePickup)(ref option.pickup)).isTempItem, option.pickup.isRental))) { return false; } CommandOption[] options = SelectionOptions(picker); return CommandSelection.HasQueuedChoice(Queue, options, SourceTier(picker), ItemGroups.TierOf, ItemGroups.IsExclusivePickup, ExclusiveItemSelection.Value); } private void TryPickupEssence() { //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: 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) //IL_0213: Invalid comparison between Unknown and I4 //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) if (AutoPickupCommandEssence == null || !AutoPickupCommandEssence.Value || !Object.op_Implicit((Object)(object)Run.instance) || Time.timeScale <= 0f || Queue.Entries.Count == 0 || pendingSelections.Count != 0) { return; } foreach (LocalUser user in LocalUserManager.readOnlyLocalUsersList) { CharacterBody cachedBody = user.cachedBody; bool flag = user.isUIFocused && !scoreboardViews.Any((ScoreboardQueueUI view) => Object.op_Implicit((Object)(object)view) && view.AllowsEssenceInteraction(user)); if (!Object.op_Implicit((Object)(object)cachedBody) || !Object.op_Implicit((Object)(object)cachedBody.healthComponent) || !cachedBody.healthComponent.alive || flag || EssenceWorkRegistry.Busy(user)) { continue; } Interactor component = ((Component)cachedBody).GetComponent<Interactor>(); if (!Object.op_Implicit((Object)(object)component)) { continue; } int num = Math.Min(32, EssenceWorkRegistry.Candidates.Count); int num2 = 0; EssenceCandidate item; for (int num3 = 0; num3 < num && num2 < 4 && EssenceWorkRegistry.Candidates.TryVisit(out item); num3++) { PickupPickerController picker = item.Picker; if (!Object.op_Implicit((Object)(object)picker)) { EssenceWorkRegistry.Candidates.Remove(item); } else { if (!((Behaviour)picker).isActiveAndEnabled || Time.unscaledTime < item.RetryAt) { continue; } Collider collider = item.Collider; float num4 = component.maxInteractionDistance * component.maxInteractionDistance; if (Object.op_Implicit((Object)(object)collider)) { if (!collider.enabled) { continue; } Bounds bounds = collider.bounds; if (((Bounds)(ref bounds)).SqrDistance(cachedBody.corePosition) > num4) { continue; } } Vector3 val = (Object.op_Implicit((Object)(object)collider) ? collider.ClosestPoint(cachedBody.corePosition) : ((Component)picker).transform.position); Vector3 val2 = val - cachedBody.corePosition; if (((Vector3)(ref val2)).sqrMagnitude > num4) { continue; } num2++; if (HasQueuedChoice(picker, user) && (int)picker.GetInteractability(component) == 2) { Vector3 corePosition = cachedBody.corePosition; LayerIndex world = LayerIndex.world; if (!Physics.Linecast(corePosition, val, LayerMask.op_Implicit(((LayerIndex)(ref world)).mask), (QueryTriggerInteraction)1)) { item.RetryAt = Time.unscaledTime + 1f; EssenceWorkRegistry.Request(user); component.AttemptInteraction(((Component)picker).gameObject); break; } } } } } } private CommandOption[] SelectionOptions(PickupPickerController picker) { return picker.options.Select(delegate(Option option) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: 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) PickupDef pickupDef = PickupCatalog.GetPickupDef(option.pickup.pickupIndex); ItemDef val = ((pickupDef == null) ? null : ItemCatalog.GetItemDef(pickupDef.itemIndex)); return new CommandOption(Object.op_Implicit((Object)(object)val) ? pickupDef.internalName : null, Object.op_Implicit((Object)(object)val) ? ((object)val.tier/*cast due to .constrained prefix*/).ToString() : null, option.available && Object.op_Implicit((Object)(object)val) && GroupEnabled(ItemGroups.Group(val)) && (SelectionBehavior(option.pickup) == SpecialPickupBehavior.UseQueueNormally || SelectionBehavior(option.pickup) == SpecialPickupBehavior.UseQueueWithoutConsuming) && PickupAllowed(Object.op_Implicit((Object)(object)val) ? pickupDef.internalName : null, LimiterCounting.PendingAmount(((UniquePickup)(ref option.pickup)).isTempItem, option.pickup.isRental, LimiterCountMode.Value)), ((UniquePickup)(ref option.pickup)).isTempItem || option.pickup.isRental); }).ToArray(); } private static string SourceTier(PickupPickerController picker) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) PickupDef pickupDef = PickupCatalog.GetPickupDef(picker.GetPickupIndex()); ItemDef val = ((pickupDef == null) ? null : ItemCatalog.GetItemDef(pickupDef.itemIndex)); if (!Object.op_Implicit((Object)(object)val)) { return null; } return ((object)val.tier/*cast due to .constrained prefix*/).ToString(); } private int FindSelection(CommandOption[] options, string sourceTier) { return CommandSelection.FindOption(Queue, options, sourceTier, ItemGroups.TierOf, ItemGroups.IsExclusivePickup, ExclusiveItemSelection.Value); } private bool PickupAllowed(string pickup) { return PickupAllowed(pickup, 1); } private bool PickupAllowed(string pickup, int amount) { ItemDef val = ItemGroups.Definition(pickup); if (!Object.op_Implicit((Object)(object)val)) { return true; } if (!Object.op_Implicit((Object)(object)selectionInventory)) { return true; } long num = CountForLimiter(selectionInventory, val); return !Queue.Limiter.Blocks(pickup, num + PendingCounts(selectionInventory).Count(pickup, num, Time.timeAsDouble) + Math.Max(0, amount - 1)); } internal long CountForLimiter(Inventory inventory, ItemDef item) { //IL_0015: 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_002d: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)inventory) || !Object.op_Implicit((Object)(object)item)) { return 0L; } return LimiterCounting.Count(inventory.GetItemCountPermanent(item.itemIndex), inventory.GetItemCountTemp(item.itemIndex), inventory.GetItemCountRented(item.itemIndex), LimiterCountMode.Value); } private PendingItemSelections PendingCounts(Inventory inventory) { if (!pendingLimitedItems.TryGetValue(inventory, out var value)) { value = (pendingLimitedItems[inventory] = new PendingItemSelections()); } return value; } private int SelectionHead(CommandOption[] options, string tier, bool resetRepeatCycle = false) { return CommandSelection.FindQueueEntry(Queue, options, tier, ItemGroups.TierOf, ItemGroups.IsExclusivePickup, resetRepeatCycle); } private IEnumerator SubmitNextFrame(PickupPickerController picker, int optionIndex, string pickup, string tier, LocalUser user, NetworkUIPromptController prompt, CameraRigController camera, SpecialPickupBehavior behavior, bool exclusive, QueueEntry plannedEntry) { yield return null; bool flag = false; PendingItemSelections.Ticket ticket = null; PendingItemSelections pendingItemSelections = null; try { if (!Object.op_Implicit((Object)(object)picker) || !InteractionActive(prompt, user) || Queue.IsPickupPaused(pickup) || picker.options == null || optionIndex >= picker.options.Length || !picker.options[optionIndex].available || PickupCatalog.GetPickupDef(picker.options[optionIndex].pickup.pickupIndex)?.internalName != pickup) { yield break; } selectionInventory = (Object.op_Implicit((Object)(object)user.cachedMaster) ? user.cachedMaster.inventory : null); CommandOption[] array = SelectionOptions(picker); if (FindSelection(array, SourceTier(picker)) != optionIndex || CommandSelection.IsExclusiveEssence(array, ItemGroups.IsExclusivePickup) != exclusive || array[optionIndex].Tier != tier) { yield break; } int num = SelectionHead(array, tier); if (plannedEntry == ((num < 0) ? null : Queue.Entries[num]) && SelectionBehavior(picker.options[optionIndex].pickup) == behavior && GroupEnabled(ItemGroups.GroupOf(pickup))) { if (behavior == SpecialPickupBehavior.UseQueueNormally && num >= 0) { num = SelectionHead(array, tier, resetRepeatCycle: true); } ItemDef val = ItemGroups.Definition(pickup); int num2 = LimiterCounting.PendingAmount(((UniquePickup)(ref picker.options[optionIndex].pickup)).isTempItem, picker.options[optionIndex].pickup.isRental, LimiterCountMode.Value); if (Object.op_Implicit((Object)(object)selectionInventory) && Object.op_Implicit((Object)(object)val) && num2 > 0 && Queue.Limiter.Limit(pickup).HasValue) { pendingItemSelections = PendingCounts(selectionInventory); ticket = pendingItemSelections.Reserve(pickup, CountForLimiter(selectionInventory, val), Time.timeAsDouble, num2); } AutomaticCollection.Submit(picker, prompt, optionIndex, num >= 0); flag = true; if (num >= 0) { SpecialPickupPolicy.CompleteSelection(Queue, num, tier, behavior); } } } catch (Exception exception) { LogError("Automatic command selection failed; queue retained where possible", exception); } finally { pendingSelections.Remove(picker); if (!flag) { pendingItemSelections?.Cancel(ticket); } if (!flag && Object.op_Implicit((Object)(object)picker) && InteractionActive(prompt, user) && Object.op_Implicit((Object)(object)camera)) { manualDisplays.Add(picker); try { AccessTools.Method(typeof(PickupPickerController), "OnDisplayBegin", (Type[])null, (Type[])null).Invoke(picker, new object[3] { prompt, user, camera }); } catch (Exception exception2) { LogError("Manual command picker fallback failed", exception2); } finally { manualDisplays.Remove(picker); } } } } } [HarmonyPatch(typeof(PickupPickerController), "OnDisplayBegin")] internal static class CommandSelectionPatch { private static bool Prefix(PickupPickerController __instance, NetworkUIPromptController networkUIPromptController, LocalUser localUser, CameraRigController cameraRigController) { try { return !(RemasteredPlugin.Instance?.ScheduleSelection(__instance, localUser, networkUIPromptController, cameraRigController) ?? false); } catch (Exception exception) { RemasteredPlugin.Instance?.LogError("Command selection hook failed; opening vanilla picker", exception); return true; } } } } namespace CommandQueueRemastered.Integrations { internal sealed class ItemDescriptions { private readonly RemasteredPlugin plugin; private MethodInfo enhanced; private float nextLookup; private bool failed; private bool reportedMismatch; public ItemDescriptions(RemasteredPlugin plugin) { this.plugin = plugin; FindIntegration(); } private void FindIntegration() { Type type = (from assembly in AppDomain.CurrentDomain.GetAssemblies() select assembly.GetType("LookingGlass.ItemStatsNameSpace.ItemStats")).FirstOrDefault((Type candidate) => candidate != null); enhanced = type?.GetMethod("GetItemDescription", BindingFlags.Static | BindingFlags.Public, null, new Type[5] { typeof(ItemDef), typeof(int), typeof(CharacterMaster), typeof(bool), typeof(bool) }, null); if (type != null && enhanced == null && !reportedMismatch) { reportedMismatch = true; plugin.LogWarning("LookingGlass API differs; using vanilla descriptions."); } } public string Get(ItemDef item, CharacterMaster master) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) if (enhanced == null && Time.unscaledTime >= nextLookup) { nextLookup = Time.unscaledTime + 5f; FindIntegration(); } if (enhanced != null && !failed && Object.op_Implicit((Object)(object)master)) { try { int num = (Object.op_Implicit((Object)(object)master.inventory) ? master.inventory.GetItemCountEffective(item.itemIndex) : 0); string text = enhanced.Invoke(null, new object[5] { item, num, master, true, false }) as string; if (!string.IsNullOrEmpty(text)) { return text; } } catch (Exception exception) { failed = true; plugin.LogError("LookingGlass description failed; using vanilla descriptions", exception); } } string text2 = Language.GetString(item.descriptionToken); if (string.IsNullOrWhiteSpace(text2) || text2 == item.descriptionToken) { text2 = Language.GetString(item.pickupToken); } return text2; } } internal static class LookingGlassCommandCompatibility { private static readonly FieldInfo panelField = AccessTools.Field(typeof(PickupPickerController), "panelInstance"); internal static void Register(Harmony harmony, RemasteredPlugin plugin) { //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown Type type = (from assembly in AppDomain.CurrentDomain.GetAssemblies() select assembly.GetType("LookingGlass.CommandWindowBlur.NoWindowBlur")).FirstOrDefault((Type candidate) => candidate != null); if (type == null) { return; } MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "OnDisplayBegin", new Type[5] { typeof(Action<PickupPickerController, NetworkUIPromptController, LocalUser, CameraRigController>), typeof(PickupPickerController), typeof(NetworkUIPromptController), typeof(LocalUser), typeof(CameraRigController) }, (Type[])null); if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != typeof(void) || panelField == null) { plugin.LogWarning("LookingGlass Command panel API differs; automatic selection compatibility needs verification."); return; } try { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(LookingGlassCommandCompatibility), "GuardMissingPanel", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); plugin.LogInfo("LookingGlass Command panel compatibility registered for panel-free queue selection."); } catch (Exception exception) { plugin.LogError("LookingGlass Command panel compatibility could not be registered", exception); } } private static bool SkipPanelWork(PickupPickerController picker) { if (Object.op_Implicit((Object)(object)picker) && (Object)(object)RemasteredPlugin.Instance != (Object)null && RemasteredPlugin.Instance.HasPendingSelection(picker)) { object? value = panelField.GetValue(picker); return !Object.op_Implicit((Object)((value is GameObject) ? value : null)); } return false; } private static IEnumerable<CodeInstruction> GuardMissingPanel(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Expected O, but got Unknown //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Expected O, but got Unknown //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Expected O, but got Unknown //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); int num = list.FindIndex((CodeInstruction code) => code.opcode == OpCodes.Ldfld && object.Equals(code.operand, panelField)); if (num < 1 || list[num - 1].opcode != OpCodes.Ldarg_2 || !list.Take(num - 1).Any((CodeInstruction code) => code.opcode == OpCodes.Callvirt && code.operand is MethodInfo { Name: "Invoke" } methodInfo && methodInfo.DeclaringType == typeof(Action<PickupPickerController, NetworkUIPromptController, LocalUser, CameraRigController>))) { throw new InvalidOperationException("LookingGlass Command panel IL differs from the supported layout."); } int index = num - 1; object obj = typeof(ILGenerator).GetMethod("DefineLabel").Invoke(generator, null); FieldInfo? field = typeof(CodeInstruction).GetField("labels"); CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_2, (object)null); IList list2 = (IList)field.GetValue(list[index]); IList list3 = (IList)field.GetValue(val); foreach (object item in list2) { list3.Add(item); } list2.Clear(); list2.Add(obj); list.InsertRange(index, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4] { val, new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(LookingGlassCommandCompatibility), "SkipPanelWork", (Type[])null, (Type[])null)), new CodeInstruction(OpCodes.Brfalse, obj), new CodeInstruction(OpCodes.Ret, (object)null) }); return list; } } internal static class OptionalCategoryPaging { private static string loadingMod; internal static void Install(Harmony harmony, Assembly assembly, RemasteredPlugin plugin) { //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown //IL_00cb: Expected O, but got Unknown //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Expected O, but got Unknown //IL_0100: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown List<MethodBase> list = new List<MethodBase>(); try { Type? type = assembly.GetType("RiskOfOptions.Components.Panel.ModOptionPanelController", throwOnError: true); Type type2 = assembly.GetType("RiskOfOptions.Components.Panel.CategoryScrollRect", throwOnError: true); MethodInfo methodInfo = AccessTools.Method(type, "LoadModOptionsFromOptionCollection", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.PropertySetter(type2, "Categories"); MethodInfo methodInfo3 = AccessTools.Method(type2, "FixExtra", (Type[])null, (Type[])null); if (methodInfo == null || methodInfo2 == null || methodInfo3 == null || AccessTools.Field(type2, "categoryButtons") == null) { throw new NotSupportedException("Unexpected RiskOfOptions category API."); } list.Add(methodInfo); list.Add(methodInfo2); list.Add(methodInfo3); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(OptionalCategoryPaging), "BeginLoad", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(OptionalCategoryPaging), "EndLoad", (Type[])null), (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(OptionalCategoryPaging), "SetOwner", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(OptionalCategoryPaging), "PageCount", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(OptionalCategoryPaging), "FillerCount", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); plugin.LogInfo("RiskOfOptions category paging: three tabs per page for Remastered only."); } catch (Exception exception) { foreach (MethodBase item in list) { harmony.Unpatch(item, (HarmonyPatchType)0, harmony.Id); } plugin.LogError("RiskOfOptions custom paging unavailable; native paging retained", exception); } } private static void BeginLoad(string __0, out string __state) { __state = loadingMod; loadingMod = __0; } private static Exception EndLoad(string __state, Exception __exception) { loadingMod = __state; return __exception; } private static void SetOwner(Component __instance) { RemasteredCategoryLayout obj = __instance.GetComponent<RemasteredCategoryLayout>() ?? __instance.gameObject.AddComponent<RemasteredCategoryLayout>(); obj.IsRemastered = loadingMod == "local.commandqueue.remastered"; obj.Scroll = (ScrollRect)(object)((__instance is ScrollRect) ? __instance : null); obj.Buttons = AccessTools.Field(((object)__instance).GetType(), "categoryButtons"); } private static int Columns(object scroll) { object obj = ((scroll is Component) ? scroll : null); if (obj == null || ((Component)obj).GetComponent<RemasteredCategoryLayout>()?.IsRemastered != true) { return 4; } return 3; } private static float FloatColumns(object scroll) { return Columns(scroll); } private static IEnumerable<CodeInstruction> PageCount(IEnumerable<CodeInstruction> instructions) { return ReplaceConstant(instructions, floating: true); } private static IEnumerable<CodeInstruction> FillerCount(IEnumerable<CodeInstruction> instructions) { return ReplaceConstant(instructions, floating: false); } private static IEnumerable<CodeInstruction> ReplaceConstant(IEnumerable<CodeInstruction> instructions, bool floating) { List<CodeInstruction> list = instructions.ToList(); CodeInstruction[] matches = list.Where(delegate(CodeInstruction instruction) { if (!floating) { return instruction.opcode == OpCodes.Ldc_I4_4; } return instruction.opcode == OpCodes.Ldc_R4 && object.Equals(instruction.operand, 4f); }).ToArray(); if (matches.Length != 1) { throw new NotSupportedException("Unexpected RiskOfOptions page-capacity IL."); } foreach (CodeInstruction item in list) { if (item != matches[0]) { yield return item; continue; } item.opcode = OpCodes.Ldarg_0; item.operand = null; yield return item; yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(OptionalCategoryPaging), floating ? "FloatColumns" : "Columns", (Type[])null, (Type[])null)); } } } internal sealed class RemasteredCategoryLayout : MonoBehaviour { internal bool IsRemastered; internal ScrollRect Scroll; internal FieldInfo Buttons; private void LateUpdate() { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) if (!IsRemastered || !Object.op_Implicit((Object)(object)Scroll) || !Object.op_Implicit((Object)(object)Scroll.viewport) || Buttons == null || !(Buttons.GetValue(Scroll) is List<GameObject> { Count: not 0 } list) || !Object.op_Implicit((Object)(object)list[0])) { return; } HorizontalLayoutGroup component = ((Component)list[0].transform.parent).GetComponent<HorizontalLayoutGroup>(); Rect rect = Scroll.viewport.rect; float num = (((Rect)(ref rect)).width - (Object.op_Implicit((Object)(object)component) ? ((float)((LayoutGroup)component).padding.horizontal + 2f * ((HorizontalOrVerticalLayoutGroup)component).spacing) : 0f)) / 3f; if (num <= 1f) { return; } foreach (GameObject item in list) { if (Object.op_Implicit((Object)(object)item)) { LayoutElement component2 = item.GetComponent<LayoutElement>(); if (Object.op_Implicit((Object)(object)component2) && Mathf.Abs(component2.preferredWidth - num) > 0.1f) { component2.preferredWidth = num; } TextMeshProUGUI[] componentsInChildren = item.GetComponentsInChildren<TextMeshProUGUI>(); foreach (TextMeshProUGUI obj in componentsInChildren) { ((TMP_Text)obj).enableAutoSizing = true; ((TMP_Text)obj).fontSizeMin = 12f; ((TMP_Text)obj).fontSizeMax = 24f; ((TMP_Text)obj).enableWordWrapping = false; } } } } } internal static class OptionalOptions { public static void Register(RemasteredPlugin plugin, Harmony harmony) { Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly candidate) => candidate.GetType("RiskOfOptions.ModSettingsManager") != null); if (assembly == null) { plugin.LogInfo("RiskOfOptions not installed; using BepInEx configuration."); return; } foreach (ConfigEntry<bool> value in plugin.GroupOptions.Values) { RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)value); } RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.RotateRepeatedItems); RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)plugin.LimiterCountMode); RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)plugin.BlockGameplayInput); RegisterEntry(plugin, assembly, "SliderOption", "SliderConfig", (ConfigEntryBase)(object)plugin.MenuScale); RegisterEntry(plugin, assembly, "SliderOption", "SliderConfig", (ConfigEntryBase)(object)plugin.ItemScale); RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)plugin.TemporaryItemBehavior); RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)plugin.EtherealItemBehavior); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.IgnoreTemporaryItems); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.IgnoreEtherealItems); RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)plugin.ExclusiveItemSelection); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.AutoCollectQueuedItems); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.AutoPickupCommandEssence); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.ExcludePausedPlayers); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.DistributionEnabled); RegisterStageSelector(plugin, assembly); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.DistributeChests); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.DistributeExchangePools); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.DistributeTeleporterRewards); RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)plugin.DrifterSalvage); RegisterEntry(plugin, assembly, "CheckBoxOption", "CheckBoxConfig", (ConfigEntryBase)(object)plugin.HexGroupsOfSeven); RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)plugin.FewestItemsCount); foreach (ConfigEntry<EssenceDropMode> item in from pair in plugin.EssenceDropModes orderby Array.IndexOf(ItemGroups.Names, ItemGroups.Group(pair.Key)) select pair.Value) { RegisterEntry(plugin, assembly, "ChoiceOption", "ChoiceConfig", (ConfigEntryBase)(object)item); } RegisterIcon(plugin, assembly); OptionalCategoryPaging.Install(harmony, assembly, plugin); } private static void RegisterStageSelector(RemasteredPlugin plugin, Assembly assembly) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown try { object obj = Activator.CreateInstance(assembly.GetType("RiskOfOptions.Options.GenericButtonOption", throwOnError: true), "ExcludedStages", "Item Distribution Rules", StageExclusionDialog.Description(), "Select stages…", (object)(UnityAction)delegate { StageExclusionDialog.Open(plugin); }); assembly.GetType("RiskOfOptions.ModSettingsManager", throwOnError: true).GetMethod("AddOption", new Type[3] { assembly.GetType("RiskOfOptions.Options.BaseOption", throwOnError: true), typeof(string), typeof(string) }).Invoke(null, new object[3] { obj, "local.commandqueue.remastered", "CommandQueue Remastered" }); } catch (Exception exception) { plugin.LogError("Stage selection button unavailable; retaining text input", exception); RegisterEntry(plugin, assembly, "StringInputFieldOption", "InputFieldConfig", (ConfigEntryBase)(object)plugin.ExcludedDistributionStages); } } private static void RegisterEntry(RemasteredPlugin plugin, Assembly assembly, string optionName, string configName, ConfigEntryBase entry) { try { object obj = Activator.CreateInstance(assembly.GetType("RiskOfOptions.OptionConfigs." + configName, throwOnError: true)); string value = OptionsPresentation.Name(entry.Definition.Section, entry.Definition.Key); Set(obj, "name", value); Set(obj, "category", OptionsPresentation.Category(entry.Definition.Section)); Set(obj, "description", entry.Description.Description); Set(obj, "restartRequired", false); if ((object)entry == plugin.ItemScale) { Set(obj, "min", 0.5f); Set(obj, "max", 2f); Set(obj, "formatString", "{0:0.00}x"); } if ((object)entry == plugin.MenuScale) { Set(obj, "min", 0.5f); Set(obj, "max", 2f); Set(obj, "formatString", "{0:0.00}x"); } object obj2 = Activator.CreateInstance(assembly.GetType("RiskOfOptions.Options." + optionName, throwOnError: true), entry, obj); Type type = assembly.GetType("RiskOfOptions.ModSettingsManager", throwOnError: true); MethodInfo? method = type.GetMethod("AddOption", new Type[3] { assembly.GetType("RiskOfOptions.Options.BaseOption", throwOnError: true), typeof(string), typeof(string) }); if (method == null) { throw new MissingMethodException(type.FullName, "AddOption"); } method.Invoke(null, new object[3] { obj2, "local.commandqueue.remastered", "CommandQueue Remastered" }); plugin.LogInfo("RiskOfOptions registered " + entry.Definition.Key + "."); } catch (Exception exception) { plugin.LogError("RiskOfOptions registration failed for " + entry.Definition.Key, exception); } } private static void Set(object configuration, string name, object value) { FieldInfo? field = configuration.GetType().GetField(name); if (field == null) { throw new MissingFieldException(configuration.GetType().FullName, name); } field.SetValue(configuration, value); } private static void RegisterIcon(RemasteredPlugin plugin, Assembly assembly) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) try { using Stream stream = typeof(RemasteredPlugin).Assembly.GetManifestResourceStream("CommandQueueRemastered.icon.png"); if (stream == null) { plugin.LogWarning("Embedded mod icon is missing."); return; } using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); plugin.ModIconTexture = new Texture2D(2, 2, (TextureFormat)4, false); if (!ImageConversion.LoadImage(plugin.ModIconTexture, memoryStream.ToArray())) { throw new InvalidDataException("Invalid mod icon PNG."); } plugin.ModIcon = Sprite.Create(plugin.ModIconTexture, new Rect(0f, 0f, (float)((Texture)plugin.ModIconTexture).width, (float)((Texture)plugin.ModIconTexture).height), new Vector2(0.5f, 0.5f)); Type type = assembly.GetType("RiskOfOptions.ModSettingsManager", throwOnError: true); MethodInfo? method = type.GetMethod("SetModIcon", new Type[3] { typeof(Sprite), typeof(string), typeof(string) }); if (method == null) { throw new MissingMethodException(type.FullName, "SetModIcon"); } method.Invoke(null, new object[3] { plugin.ModIcon, "local.commandqueue.remastered", "CommandQueue Remastered" }); plugin.LogInfo("RiskOfOptions mod icon registered."); } catch (Exception exception) { plugin.LogError("RiskOfOptions mod icon registration failed", exception); } } } internal sealed class ProperSaveAdapter : IDisposable { private const string SaveKey = "local.CommandQueueRemastered.queue.v1"; private readonly RemasteredPlugin plugin; private readonly List<KeyValuePair<EventInfo, Delegate>> subscriptions = new List<KeyValuePair<EventInfo, Delegate>>(); private QueueDocument pending; private float loadedAt; public ProperSaveAdapter(RemasteredPlugin plugin) { this.plugin = plugin; } public void Initialize() { Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly candidate) => candidate.GetType("ProperSave.SaveFile") != null); if (assembly == null) { plugin.LogInfo("ProperSave not installed; run queue saving disabled."); return; } try { Subscribe(assembly.GetType("ProperSave.SaveFile", throwOnError: true), "OnGatherSaveData", Gather); Subscribe(assembly.GetType("ProperSave.Loading", throwOnError: true), "OnLoadingEnded", Loaded); Run.onRunDestroyGlobal += OnRunEnd; plugin.LogInfo("ProperSave integration registered (singleplayer / host)."); } catch (Exception exception) { Dispose(); plugin.LogError("ProperSave integration could not initialize", exception); } } private void Subscribe(Type type, string name, Action<object> callback) { EventInfo eventInfo = type.GetEvent(name, BindingFlags.Static | BindingFlags.Public); if (eventInfo == null) { throw new MissingMemberException(type.FullName, name); } ParameterInfo[] parameters = eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters(); if (parameters.Length != 1) { throw new InvalidOperationException("Unsupported ProperSave event: " + name); } ParameterExpression parameterExpression = Expression.Parameter(parameters[0].ParameterType); InvocationExpression body = Expression.Invoke(Expression.Constant(callback), Expression.Convert(parameterExpression, typeof(object))); Delegate obj = Expression.Lambda(eventInfo.EventHandlerType, body, parameterExpression).Compile(); eventInfo.AddEventHandler(null, obj); subscriptions.Add(new KeyValuePair<EventInfo, Delegate>(eventInfo, obj)); } private void Gather(object data) { try { if (NetworkServer.active && Object.op_Implicit((Object)(object)Run.instance)) { ((Dictionary<string, object>)data)["local.CommandQueueRemastered.queue.v1"] = QueueDocument.Capture(plugin.Queue).Encode(); plugin.LogInfo("ProperSave captured " + plugin.Queue.Entries.Sum((QueueEntry entry) => entry.Count) + " queued items."); } } catch (Exception exception) { plugin.LogError("ProperSave queue capture failed", exception); } } private void Loaded(object save) { pending = null; try { if (save != null && NetworkServer.active) { string text = save.GetType().GetMethods().Single((MethodInfo candidate) => candidate.Name == "TryGetModdedData" && candidate.IsGenericMethodDefinition && candidate.GetParameters().Length == 1) .MakeGenericMethod(typeof(string)) .Invoke(save, new object[1] { "local.CommandQueueRemastered.queue.v1" }) as string; if (string.IsNullOrEmpty(text)) { plugin.LogInfo("ProperSave file contains no Remastered queue."); return; } pending = QueueDocument.Decode(text); loadedAt = Time.unscaledTime; plugin.LogInfo("ProperSave queue read; waiting for the local player to spawn."); } } catch (Exception exception) { plugin.LogError("ProperSave queue read failed", exception); } } public void Update() { if (pending == null) { return; } LocalUser firstLocalUser = LocalUserManager.GetFirstLocalUser(); if (Object.op_Implicit((Object)(object)Run.instance) && Object.op_Implicit((Object)(object)((firstLocalUser != null) ? firstLocalUser.cachedBody : null)) && Time.unscaledTime - loadedAt >= 0.75f) { QueueDocument queueDocument = pending; pending = null; try { List<QueueEntry> list = queueDocument.Queue.Where((QueueEntry entry) => Object.op_Implicit((Object)(object)ItemGroups.Definition(entry.Pickup))).ToList(); int num = queueDocument.Queue.Except(list).Sum((QueueEntry entry) => entry.Count); queueDocument.Queue = list; queueDocument.Limits = queueDocument.Limits.Where((QueueEntry entry) => Object.op_Implicit((Object)(object)ItemGroups.Definition(entry.Pickup))).ToList(); queueDocument.Apply(plugin.Queue); plugin.LogInfo("ProperSave restored " + list.Sum((QueueEntry entry) => entry.Count) + " queued items; skipped " + num + " unavailable items."); return; } catch (Exception exception) { plugin.LogError("ProperSave queue restore failed", exception); return; } } if (Time.unscaledTime - loadedAt > 30f) { pending = null; plugin.LogWarning("ProperSave queue restore timed out waiting for a local player."); } } private void OnRunEnd(Run run) { pending = null; } public void Dispose() { foreach (KeyValuePair<EventInfo, Delegate> subscription in subscriptions) { try { subscription.Key.RemoveEventHandler(null, subscription.Value); } catch (Exception exception) { plugin.LogError("ProperSave event cleanup failed", exception); } } subscriptions.Clear(); pending = null; Run.onRunDestroyGlobal -= OnRunEnd; } } } namespace CommandQueueRemastered.Game { internal sealed class QueuedCollectionRequest : MonoBehaviour { internal QueuedCollectionTicket Ticket; } internal static class AutomaticCollection { internal const byte Message = 213; internal const uint Signature = 1129402933u; internal static readonly HashSet<PickupPickerController> Selecting = new HashSet<PickupPickerController>(); internal static bool IsCommand(PickupPickerController picker) { GameObject commandCubePrefab = CommandArtifactManager.commandCubePrefab; PickupPickerController val = (Object.op_Implicit((Object)(object)commandCubePrefab) ? commandCubePrefab.GetComponent<PickupPickerController>() : null); if (Object.op_Implicit((Object)(object)picker) && Object.op_Implicit((Object)(object)val) && (Object)(object)picker.panelPrefab == (Object)(object)val.panelPrefab && !picker.isDelusionChoice) { return !picker.isRebirthChoice; } return false; } internal static void Submit(PickupPickerController picker, NetworkUIPromptController prompt, int option, bool queued) { int num; if (queued) { num = (RemasteredPlugin.Instance.AutoCollectQueuedItems.Value ? 1 : 0); if (num != 0 && !NetworkServer.active) { NetworkWriter val = prompt.BeginMessageToServer(); val.Write((byte)213); val.Write(1129402933u); val.Write(option); prompt.FinishMessageToServer(val); } } else { num = 0; } if (num != 0 && NetworkServer.active) { Selecting.Add(picker); } try { picker.SubmitChoice(option); } finally { Selecting.Remove(picker); } } internal static bool Receive(PickupPickerController picker, NetworkReader reader) { //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) uint position = reader.Position; byte b; try { b = reader.ReadByte(); } catch { return false; } if (b != 213) { if (b == 1) { QueuedCollectionRequest component = ((Component)picker).GetComponent<QueuedCollectionRequest>(); if (Object.op_Implicit((Object)(object)component)) { component.Ticket = null; } } reader.SeekZero(); reader.ReadBytes((int)position); return true; } try { if (reader.ReadUInt32() != 1129402933) { return false; } int num = reader.ReadInt32(); RemasteredPlugin instance = RemasteredPlugin.Instance; NetworkUIPromptController component2 = ((Component)picker).GetComponent<NetworkUIPromptController>(); if (!NetworkServer.active || !Object.op_Implicit((Object)(object)instance) || !instance.AutoCollectQueuedItems.Value || !IsCommand(picker) || !Object.op_Implicit((Object)(object)component2) || !Object.op_Implicit((Object)(object)component2.currentParticipantMaster) || picker.options == null || num < 0 || num >= picker.options.Length || !picker.options[num].available) { return false; } QueuedCollectionRequest obj2 = ((Component)picker).GetComponent<QueuedCollectionRequest>() ?? ((Component)picker).gameObject.AddComponent<QueuedCollectionRequest>(); NetworkInstanceId netId = ((NetworkBehaviour)component2.currentParticipantMaster).netId; obj2.Ticket = new QueuedCollectionTicket(((NetworkInstanceId)(ref netId)).Value, num, Time.unscaledTime + 2f); } catch (Exception exception) { RemasteredPlugin.Instance?.LogError("Invalid queued collection marker ignored", exception); } return false; } } [HarmonyPatch(typeof(PickupPickerController), "HandleClientMessage")] internal static class QueuedCollectionMessagePatch { private static bool Prefix(PickupPickerController __instance, NetworkReader __0) { return AutomaticCollection.Receive(__instance, __0); } } [HarmonyPatch(typeof(PickupPickerController), "HandlePickupSelected")] internal static class QueuedCollectionSelectionPatch { private static void Prefix(PickupPickerController __instance, int __0, out bool __state) { //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) __state = false; QueuedCollectionRequest component = ((Component)__instance).GetComponent<QueuedCollectionRequest>(); if (!Object.op_Implicit((Object)(object)component)) { return; } QueuedCollectionTicket ticket = component.Ticket; component.Ticket = null; NetworkUIPromptController component2 = ((Component)__instance).GetComponent<NetworkUIPromptController>(); if (NetworkServer.active && Object.op_Implicit((Object)(object)RemasteredPlugin.Instance) && RemasteredPlugin.Instance.AutoCollectQueuedItems.Value && ticket != null && Object.op_Implicit((Object)(object)component2) && Object.op_Implicit((Object)(object)component2.currentParticipantMaster)) { NetworkInstanceId netId = ((NetworkBehaviour)component2.currentParticipantMaster).netId; if (ticket.TryConsume(((NetworkInstanceId)(ref netId)).Value, __0, Time.unscaledTime)) { __state = AutomaticCollection.Selecting.Add(__instance); } } } private static Exception Finalizer(PickupPickerController __instance, bool __state, Exception __exception) { if (__state) { AutomaticCollection.Selecting.Remove(__instance); } return __exception; } } [HarmonyPatch(typeof(PickupPickerController), "CreatePickup", new Type[] { typeof(UniquePickup) })] internal static class QueuedCollectionGrantPatch { private static bool Prefix(PickupPickerController __instance, UniquePickup __0) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Invalid comparison between Unknown and I4 //IL_0093: Unknown result type (might be due to invalid IL or missing references) if (!NetworkServer.active || !AutomaticCollection.Selecting.Remove(__instance) || !AutomaticCollection.IsCommand(__instance)) { return true; } PickupDef pickupDef = PickupCatalog.GetPickupDef(__0.pickupIndex); NetworkUIPromptController component = ((Component)__instance).GetComponent<NetworkUIPromptController>(); CharacterBody val = ((Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.currentParticipantMaster)) ? component.currentParticipantMaster.GetBody() : null); if (pickupDef == null || (int)pickupDef.itemIndex == -1 || !Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.inventory) || !Object.op_Implicit((Object)(object)val.healthComponent) || !val.healthComponent.alive) { return true; } __instance.AttemptGrantPickupDirectly(__0); return false; } } internal static class DistributionSourceContext { internal struct Snapshot { internal DropSource Source; internal CharacterMaster User; } internal static DropSource Current; internal static CharacterMaster SkillUser; } [HarmonyPatch] internal static class DistributionSourcePatch { private static IEnumerable<MethodBase> TargetMethods() { yield return AccessTools.Method(typeof(ChestBehavior), "BaseItemDrop", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(OptionChestBehavior), "ItemDrop", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(ShopTerminalBehavior), "DropPickup", new Type[1] { typeof(bool) }, (Type[])null); yield return AccessTools.Method(typeof(BossGroup), "DropRewards", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(GrantHexes), "SpawnHex", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(DrainingItems), "CreatePotentialServer", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(DrainingItems), "TakeItemServer", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(Salvage), "DropTempItemServer", (Type[])null, (Type[])null); } private static void Prefix(object __instance, out DistributionSourceContext.Snapshot __state) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Invalid comparison between Unknown and I4 //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Invalid comparison between Unknown and I4 __state = new DistributionSourceContext.Snapshot { Source = DistributionSourceContext.Current, User = DistributionSourceContext.SkillUser }; DistributionSourceContext.SkillUser = null; Salvage val = (Salvage)((__instance is Salvage) ? __instance : null); if (val != null) { DistributionSourceContext.Current = DropSource.DrifterSalvage; CharacterBody val2 = (Object.op_Implicit((Object)(object)((EntityState)val).outer) ? ((Component)((EntityState)val).outer).GetComponent<CharacterBody>() : null); DistributionSourceContext.SkillUser = (Object.op_Implicit((Object)(object)val2) ? val2.master : null); return; } if (__instance is ChestBehavior || __instance is OptionChestBehavior) { DistributionSourceContext.Current = DropSource.Chest; return; } ShopTerminalBehavior val3 = (ShopTerminalBehavior)((__instance is ShopTerminalBehavior) ? __instance : null); if (val3 != null) { PurchaseInteraction component = ((Component)val3).GetComponent<PurchaseInteraction>(); if ((Object.op_Implicit((Object)(object)component) && (int)component.costType == 9) || ((Object)val3).name.IndexOf("Cauldron", StringComparison.OrdinalIgnoreCase) >= 0) { DistributionSourceContext.Current = DropSource.ExchangePool; } else if (Object.op_Implicit((Object)(object)component) && (int)component.costType == 1) { DistributionSourceContext.Current = DropSource.Chest; } return; } BossGroup val4 = (BossGroup)((__instance is BossGroup) ? __instance : null); if (val4 != null) { if (Object.op_Implicit((Object)(object)TeleporterInteraction.instance) && (Object)(object)TeleporterInteraction.instance.bossGroup == (Object)(object)val4) { DistributionSourceContext.Current = DropSource.Teleporter; } } else { DistributionSourceContext.Current = DropSource.ExchangePool; } } private static Exception Finalizer(DistributionSourceContext.Snapshot __state, Exception __exception) { DistributionSourceContext.Current = __state.Source; DistributionSourceContext.SkillUser = __state.User; return __exception; } } internal sealed class EssenceAssignmentTag : MonoBehaviour { internal DistributionReservation Token; private void OnDestroy() { EssenceAssignments.ReleaseOwned(Token, ((Component)this).gameObject); } } internal static class EssenceAssignments { internal static readonly DistributionLedger Ledger = new DistributionLedger(); internal static DistributionReservation Current; private static readonly Dictionary<DistributionReservation, object> owners = new Dictionary<DistributionReservation, object>(); private static readonly Dictionary<ItemTransferOrb, DistributionReservation> orbs = new Dictionary<ItemTransferOrb, DistributionReservation>(); internal static void Attach(GameObject target, DistributionReservation token) { if (Object.op_Implicit((Object)(object)target) && token != null) { (target.GetComponent<EssenceAssignmentTag>() ?? target.AddComponent<EssenceAssignmentTag>()).Token = token; owners[token] = target; } } internal static void Release(DistributionReservation token) { Ledger.Release(token); if (token != null) { owners.Remove(token); } } internal static void ReleaseOwned(DistributionReservation token, object owner) { if (token != null && owners.TryGetValue(token, out var value) && value == owner) { Release(token); } } internal static DistributionReservation Token(Component component) { if (!Object.op_Implicit((Object)(object)component)) { return null; } return component.GetComponent<EssenceAssignmentTag>()?.Token; } internal static void CaptureOrb(ItemTransferOrb orb) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (Current == null || orb == null) { return; } if (orb.stack <= 0) { Release(Current); return; } CharacterMaster val = (Object.op_Implicit((Object)(object)orb.inventoryToGrantTo) ? ((Component)orb.inventoryToGrantTo).GetComponent<CharacterMaster>() : null); if (Object.op_Implicit((Object)(object)val)) { DistributionReservation current = Current; NetworkInstanceId netId = ((NetworkBehaviour)val).netId; current.Recipient = ((NetworkInstanceId)(ref netId)).Value; } owners[Current] = orb; orbs[orb] = Current; } internal static void Arrived(ItemTransferOrb orb) { if (orbs.TryGetValue(orb, out var value)) { Release(value); orbs.Remove(orb); } } internal static void CancelOrbs() { foreach (DistributionReservation value in orbs.Values) { Release(value); } orbs.Clear(); } internal static void Reset() { Current = null; Ledger.Reset(); owners.Clear(); orbs.Clear(); } } [HarmonyPatch] internal static class AssignmentScopePatch { private static IEnumerable<MethodBase> TargetMethods() { yield return AccessTools.Method(typeof(PickupDropletController), "CreatePickup", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(PickupPickerController), "HandlePickupSelected", new Type[1] { typeof(int) }, (Type[])null); } private static void Prefix(Component __instance, out DistributionReservation __state) { __state = EssenceAssignments.Current; EssenceAssignments.Current = EssenceAssignments.Token(__instance); } private static Exception Finalizer(DistributionReservation __state, Exception __exception) { EssenceAssignments.Current = __state; return __exception; } } [HarmonyPatch(typeof(PickupPickerController), "OnEnable")] internal static class AssignmentCubePatch { private static void Postfix(PickupPickerController __instance) { if (NetworkServer.active) { EssenceAssignments.Attach(((Component)__instance).gameObject, EssenceAssignments.Current); } } } [HarmonyPatch(typeof(GenericPickupController), "CreatePickup")] internal static class AssignmentPickupPatch { private static void Postfix(GenericPickupController __result) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (NetworkServer.active && Object.op_Implicit((Object)(object)__result)) { UniquePickup pickup = __result.pickup; if (((UniquePickup)(ref pickup)).isTempItem || __result.pickup.isRental) { EssenceAssignments.Release(EssenceAssignments.Current); } else { EssenceAssignments.Attach(((Component)__result).gameObject, EssenceAssignments.Current); } } } } [HarmonyPatch(typeof(GenericPickupController), "AttemptGrant")] internal static class AssignmentConsumedPatch { private static void Postfix(GenericPickupController __instance, bool ___consumed) { if (NetworkServer.active && ___consumed) { EssenceAssignments.Release(EssenceAssignments.Token((Component)(object)__instance)); } } } [HarmonyPatch(typeof(ItemTransferOrb), "DispatchItemTransferOrb", new Type[] { typeof(DispatchArgs) })] internal static class AssignmentOrbPatch { private static void Postfix(ItemTransferOrb __result) { EssenceAssignments.CaptureOrb(__result); } } [HarmonyPatch(typeof(ItemTransferOrb), "OnArrival")] internal static class AssignmentArrivalPatch { private static Exception Finalizer(ItemTransferOrb __instance, Exception __exception) { EssenceAssignments.Arrived(__instance); return __exception; } } [HarmonyPatch(typeof(OrbManager), "OnDisable")] internal static class AssignmentOrbCleanupPatch { private static void Prefix() { EssenceAssignments.CancelOrbs(); } } internal static class EssenceDrops { internal static readonly EssenceDistribution Distribution = new EssenceDistribution(); internal static CharacterMaster Killer; internal static CharacterMaster PlayerOwner(CharacterMaster master) { HashSet<CharacterMaster> hashSet = new HashSet<CharacterMaster>(); while (Object.op_Implicit((Object)(object)master) && hashSet.Add(master)) { if (Object.op_Implicit((Object)(object)master.playerCharacterMasterController)) { return master; } MinionOwnership component = ((Component)master).GetComponent<MinionOwnership>(); master = (Object.op_Implicit((Object)(object)component) ? component.ownerMaster : null); } return null; } internal static CharacterMaster Relocate(ref CreatePickupInfo info, ref Vector3 position, ref Vector3 velocity) { //IL_0032: 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_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Invalid comparison between Unknown and I4 //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Invalid comparison between Unknown and I4 //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Unknown result type (might be due to invalid IL or missing references) //IL_0324: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) RemasteredPlugin plugin = RemasteredPlugin.Instance; if (!NetworkServer.active || !Object.op_Implicit((Object)(object)plugin) || !Object.op_Implicit((Object)(object)Run.instance) || ((CreatePickupInfo)(ref info)).pickup.ignoreArtifactBasedPickupReplacements || (!CommandArtifactManager.IsCommandArtifactEnabled && (info.artifactFlag & 1) == 0) || (info.artifactFlag & 2) != 0) { return null; } if (!DistributionRules.Allows(plugin.DistributionEnabled.Value, Object.op_Implicit((Object)(object)SceneCatalog.mostRecentSceneDef) ? SceneCatalog.mostRecentSceneDef.baseSceneName : null, plugin.ExcludedDistributionStages.Value, DistributionSourceContext.Current, plugin.DistributeChests.Value, plugin.DistributeExchangePools.Value, plugin.DistributeTeleporterRewards.Value, plugin.DrifterSalvage.Value)) { return null; } PickupDef pickupDef = PickupCatalog.GetPickupDef(((CreatePickupInfo)(ref info)).pickup.pickupIndex); ItemDef val = ((pickupDef == null) ? null : ItemCatalog.GetItemDef(pickupDef.itemIndex)); if (pickupDef == null || (int)pickupDef.equipmentIndex != -1) { return null; } ItemTier tier = (Object.op_Implicit((Object)(object)val) ? val.tier : pickupDef.itemTier); bool skillUser = DistributionSourceContext.Current == DropSource.DrifterSalvage && plugin.DrifterSalvage.Value == DrifterSalvageMode.SkillUser; if (!plugin.EssenceDropModes.TryGetValue(tier, out var setting) || (!skillUser && setting.Value == EssenceDropMode.Original)) { return null; } CharacterMaster[] source = (from player in PlayerCharacterMasterController.instances select player.master into master where Object.op_Implicit((Object)(object)master) && Object.op_Implicit((Object)(object)master.inventory) && Object.op_Implicit((Object)(object)master.GetBody()) && Object.op_Implicit((Object)(object)master.GetBody().healthComponent) && master.GetBody().healthComponent.alive && (int)master.teamIndex == 1 select master).Distinct().ToArray(); UniquePickup uniquePickup = ((CreatePickupInfo)(ref info)).pickup; DropCandidate[] players = source.Select(delegate(CharacterMaster master) { //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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) NetworkInstanceId netId2 = ((NetworkBehaviour)master).netId; return new DropCandidate(((NetworkInstanceId)(ref netId2)).Value, (!skillUser && (setting.Value == EssenceDropMode.FewestItems || ((int)tier == 13 && plugin.HexGroupsOfSeven.Value))) ? Count(master) : 0, plugin.ExcludePausedPlayers.Value && plugin.PlayerPaused(master, ItemGroups.Group(tier)), plugin.PlayerIgnores(master, uniquePickup)); }).ToArray(); NetworkInstanceId netId; long? num; if (!skillUser) { EssenceDistribution distribution = Distribution; string? tier2 = ((object)Unsafe.As<ItemTier, ItemTier>(ref tier)/*cast due to .constrained prefix*/).ToString(); EssenceDropMode value = setting.Value; long? killer; if (!Object.op_Implicit((Object)(object)Killer)) { killer = null; } else { netId = ((NetworkBehaviour)Killer).netId; killer = ((NetworkInstanceId)(ref netId)).Value; } num = distribution.Choose(tier2, value, players, killer, plugin.ExcludePausedPlayers.Value, (int)tier == 13 && plugin.HexGroupsOfSeven.Value); } else { long? skillUser2; if (!Object.op_Implicit((Object)(object)DistributionSourceContext.SkillUser)) { skillUser2 = null; } else { netId = ((NetworkBehaviour)DistributionSourceContext.SkillUser).netId; skillUser2 = ((NetworkInstanceId)(ref netId)).Value; } num = EssenceDistribution.ChooseSkillUser(players, skillUser2, plugin.ExcludePausedPlayers.Value); } long? recipient = num; CharacterMaster val2 = ((IEnumerable<CharacterMaster>)source).FirstOrDefault((Func<CharacterMaster, bool>)delegate(CharacterMaster master) { //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) NetworkInstanceId netId2 = ((NetworkBehaviour)master).netId; return ((NetworkInstanceId)(ref netId2)).Value == recipient; }); CharacterBody val3 = (Object.op_Implicit((Object)(object)val2) ? val2.GetBody() : null); if (!Object.op_Implicit((Object)(object)val3)) { return null; } position = val3.corePosition; info.position = position; velocity = Vector3.zero; return val2; long Count(CharacterMaster master) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_009d: 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_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Invalid comparison between Unknown and I4 //IL_004a: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Invalid comparison between Unknown and I4 //IL_0070: Unknown result type (might be due to invalid IL or missing references) long num2 = 0L; Enumerator<ItemDef> enumerator = ItemCatalog.allItemDefs.GetEnumerator(); try { while (enumerator.MoveNext()) { ItemDef current = enumerator.Current; bool num3; if ((int)tier != 13 || !plugin.HexGroupsOfSeven.Value) { if (plugin.FewestItemsCount.Value == InventoryCountMode.AllItems) { goto IL_0068; } num3 = current.tier == tier; } else { num3 = (int)current.tier == 13; } if (!num3) { continue; } goto IL_0068; IL_0068: num2 += master.inventory.GetItemCountPermanent(current.itemIndex); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } long num4 = num2; DistributionLedger ledger = EssenceAssignments.Ledger; NetworkInstanceId netId2 = ((NetworkBehaviour)master).netId; return num4 + ledger.Count(((NetworkInstanceId)(ref netId2)).Value, ((object)Unsafe.As<ItemTier, ItemTier>(ref tier)/*cast due to .constrained prefix*/).ToString(), ((int)tier == 13 && plugin.HexGroupsOfSeven.Value) ? InventoryCountMode.SameTier : plugin.FewestItemsCount.Value); } } } [HarmonyPatch] internal static class DeathDropContextPatch { private static IEnumerable<MethodBase> TargetMethods() { yield return AccessTools.Method(typeof(GlobalEventManager), "OnCharacterDeath", new Type[1] { typeof(DamageReport) }, (Type[])null); yield return AccessTools.Method(typeof(GlobalEventManager), "HandleCharacterDeath", new Type[1] { typeof(DamageReport) }, (Type[])null); yield return AccessTools.Method(typeof(DeathRewards), "OnKilledServer", new Type[1] { typeof(DamageReport) }, (Type[])null); yield return AccessTools.Method(typeof(GlobalDeathRewards), "OnCharacterDeathGlobal", new Type[1] { typeof(DamageReport) }, (Type[])null); } private static void Prefix(DamageReport __0, out CharacterMaster __state) { __state = EssenceDrops.Killer; EssenceDrops.Killer = EssenceDrops.PlayerOwner(__0?.attackerMaster); } private static Exception Finalizer(Exception __exception, CharacterMaster __state) { EssenceDrops.Killer = __state; return __exception; } } [HarmonyPatch(typeof(PickupDropletController), "CreatePickupDroplet", new Type[] { typeof(CreatePickupInfo), typeof(Vector3), typeof(Vector3) })] internal static class EssenceLocationPatch { private static bool Prefix(ref CreatePickupInfo __0, ref Vector3 __1, ref Vector3 __2) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (FastAssignedEssence.BeginReplay()) { return true; } CreatePickupInfo info = __0; Vector3 position = __1; Vector3 velocity = __2; try { CharacterMaster val = EssenceDrops.Relocate(ref info, ref position, ref velocity); if (!Object.op_Implicit((Object)(object)val)) { return true; } FastAssignedEssence.Enqueue(__0, __1, __2, val); return false; } catch (Exception exception) { RemasteredPlugin.Instance?.LogError("Essence relocation failed; keeping normal drop", exception); return true; } } } internal sealed class EssenceCandidate { internal readonly PickupPickerController Picker; internal readonly Collider Collider; internal float RetryAt; internal EssenceCandidate(PickupPickerController picker) { Picker = picker; Collider = ((Component)picker).GetComponent<Collider>(); } } internal static class EssenceWorkRegistry { internal const int DistanceBudget = 32; internal const int ChoiceBudget = 4; internal static readonly BoundedWorkQueue<EssenceCandidate> Candidates = new BoundedWorkQueue<EssenceCandidate>(); private static readonly Dictionary<PickupPickerController, EssenceCandidate> entries = new Dictionary<PickupPickerController, EssenceCandidate>(); private static readonly Dictionary<LocalUser, NetworkUIPromptController> activePrompts = new Dictionary<LocalUser, NetworkUIPromptController>(); private static readonly Dictionary<LocalUser, float> pendingInteractions = new Dictionary<LocalUser, float>(); private static re