Decompiled source of SBG Archipelago v0.9.0
SBG-Archipelago.dll
Decompiled 17 hours 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; using Archipelago.MultiClient.Net; using Archipelago.MultiClient.Net.BounceFeatures.DeathLink; using Archipelago.MultiClient.Net.Enums; using Archipelago.MultiClient.Net.Helpers; using Archipelago.MultiClient.Net.MessageLog.Messages; using Archipelago.MultiClient.Net.Models; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Mirror; using Newtonsoft.Json; using SbgArchipelago.Ap; using SbgArchipelago.Core; using SbgArchipelago.Traps; using SbgArchipelago.Ui; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("GameAssembly")] [assembly: IgnoresAccessChecksTo("SharedAssembly")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("SBG-Archipelago")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.9.0.0")] [assembly: AssemblyInformationalVersion("0.9.0+3aee52d6832f348e419a2a5564f73897f4cae741")] [assembly: AssemblyProduct("SBG-Archipelago")] [assembly: AssemblyTitle("SBG-Archipelago")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.9.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace SbgArchipelago { [BepInPlugin("com.sbg.archipelago", "SBG-Archipelago", "0.9.0")] public class Plugin : BaseUnityPlugin { public const string GUID = "com.sbg.archipelago"; public const string NAME = "SBG-Archipelago"; public const string VERSION = "0.9.0"; private const string SECTION_CONNECTION = "Connection"; private const string SECTION_GENERAL = "General"; private const string DEFAULT_SERVER = "localhost:38281"; private const string SERVER_SENDER_NAME = "Server"; private const int MAX_FEED_LINES_PER_BATCH = 4; private const string SAVE_FOLDER = "SBG-Archipelago"; private const string SAVES_SUBFOLDER = "saves"; internal static ManualLogSource Log; internal static Plugin Instance; internal static ApClient Client; internal static ConfigEntry<string> Server; internal static ConfigEntry<string> SlotName; internal static ConfigEntry<string> Password; internal static ConfigEntry<bool> EnforceUnlocks; private void Awake() { //IL_01cd: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; Instance = this; Client = new ApClient(new ApSaveStore(Path.Combine(Paths.ConfigPath, "SBG-Archipelago", "saves"))); Client.RestoreLastSession(); Server = ((BaseUnityPlugin)this).Config.Bind<string>("Connection", "Server", "localhost:38281", "Archipelago server address and port, for example localhost:38281 or archipelago.gg:38281."); SlotName = ((BaseUnityPlugin)this).Config.Bind<string>("Connection", "SlotName", "", "Your player name exactly as written in your YAML."); Password = ((BaseUnityPlugin)this).Config.Bind<string>("Connection", "Password", "", "Server password. Leave empty if the server has none."); EnforceUnlocks = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "EnforceUnlocks", true, "Restrict the game to what you have unlocked in the loaded Archipelago seed. Turn off to play normally while the mod is installed. The console command 'apEnforce on|off' overrides this for the current session only and never changes this file."); ((Component)this).gameObject.AddComponent<ApOverlay>(); Client.UnlocksChanged += delegate { MainThread.Post(MatchSetupGate.RefreshAll); }; Client.NewItemReceived += OnNewItemReceived; Client.NewItemsReceived += delegate(IReadOnlyList<ReceivedItem> items) { MainThread.Post(delegate { ShowReceivedItems(items); }); }; Client.ItemSentToOtherPlayer += delegate(string item, string receiver) { MainThread.Post(delegate { ApOverlay.Show(FeedText.ForSent(item, receiver), FeedTone.Sent); }); }; Client.DeathLinkReceived += delegate(string source, string cause) { MainThread.Post(delegate { DeathLinkHandler.OnReceived(source, cause); }); }; Client.ServerReply += delegate(string text, bool isHint) { MainThread.Post(delegate { ChatReplies.Show(text, isHint); }); }; new Harmony("com.sbg.archipelago").PatchAll(); Log.LogInfo((object)"[SBG-AP] SBG-Archipelago v0.9.0 loaded."); } private static void ShowReceivedItems(IReadOnlyList<ReceivedItem> items) { SlotSettings settings = Client.Settings; int powerCapPercent = ((settings != null) ? Client.Unlocks.PowerCapPercent(settings.StartingPowerCap, settings.PowerCapIncrement) : 0); List<KeyValuePair<string, FeedTone>> list = new List<KeyValuePair<string, FeedTone>>(); foreach (ReceivedItem item in items) { bool isFromSelf = item.From == Client.OwnSlotName || item.From == "Server"; string text = FeedText.ForReceived(item.Kind, item.Name, item.From, isFromSelf, powerCapPercent); if (text != null) { list.Add(new KeyValuePair<string, FeedTone>(text, FeedText.ToneFor(item.Kind))); } } if (list.Count > 4) { ApOverlay.Show(FeedText.ForBatch(list.Count), FeedTone.Item); return; } foreach (KeyValuePair<string, FeedTone> item2 in list) { ApOverlay.Show(item2.Key, item2.Value); } } private static void OnNewItemReceived(string itemName, ItemKind kind, string sender) { switch (kind) { case ItemKind.Filler: MainThread.Post(FillerGrants.Enqueue); return; case ItemKind.Trap: case ItemKind.Buff: { if (TrapKinds.TryFromItemName(itemName, out var effect)) { MainThread.Post(delegate { TrapRunner.Enqueue(effect, sender); }); return; } break; } } if (kind == ItemKind.Trap || kind == ItemKind.Buff) { Log.LogWarning((object)("[SBG-AP] '" + itemName + "' is an effect this mod has nothing for; ignored.")); } } private void Update() { FillerGrants.Tick(); TrapRunner.Tick(); MainThread.Drain(delegate(Exception exception) { Log.LogError((object)$"[SBG-AP] A queued main-thread action failed: {exception}"); }); } private void OnDestroy() { Client?.Disconnect(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "SBG-Archipelago"; public const string PLUGIN_NAME = "SBG-Archipelago"; public const string PLUGIN_VERSION = "0.9.0"; } } namespace SbgArchipelago.Ui { internal sealed class ApOverlay : MonoBehaviour { private struct Entry { public FeedTone Tone; public string Text; public float ExpiresAt; public float Seconds; } private const float REFERENCE_SCREEN_HEIGHT = 1080f; private const float PANEL_WIDTH = 560f; private const float TOP_MARGIN = 18f; private const float LINE_PADDING = 8f; private const float ROW_GAP = 4f; private const float FADE_SECONDS = 0.6f; private const float DEFAULT_SECONDS = 6f; private const float REPEAT_SUPPRESS_SECONDS = 12f; private const int FONT_SIZE = 15; private const int MAX_VISIBLE = 4; private static ApOverlay instance; private readonly List<Entry> entries = new List<Entry>(); private readonly Dictionary<string, float> lastShownByKey = new Dictionary<string, float>(); private GUIStyle labelStyle; private static readonly Color HoleColor = new Color(0.35f, 0.88f, 0.4f); private static readonly Color ItemColor = new Color(0.4f, 0.8f, 1f); private static readonly Color TrapColor = new Color(1f, 0.38f, 0.38f); private static readonly Color SentColor = new Color(0.8f, 0.62f, 1f); private static readonly Color GoalColor = new Color(1f, 0.82f, 0.25f); private static readonly Color BuffColor = new Color(0.3f, 0.95f, 0.8f); private static readonly Color HintColor = new Color(1f, 0.6f, 0.85f); private const float ACCENT_WIDTH = 5f; private void Awake() { instance = this; } internal static void Show(string text, FeedTone tone = FeedTone.Info, float seconds = 6f) { if (!((Object)(object)instance == (Object)null)) { instance.entries.Add(new Entry { Text = text, Tone = tone, Seconds = seconds, ExpiresAt = Time.unscaledTime + seconds }); if (instance.entries.Count > 4) { instance.entries.RemoveAt(0); } } } internal static void ShowOnce(string key, string text, FeedTone tone = FeedTone.Info, float seconds = 6f) { if (!((Object)(object)instance == (Object)null) && (!instance.lastShownByKey.TryGetValue(key, out var value) || !(Time.unscaledTime - value < 12f))) { instance.lastShownByKey[key] = Time.unscaledTime; Show(text, tone, seconds); } } private static Color ColorFor(FeedTone tone) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_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) //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) return (Color)(tone switch { FeedTone.Hole => HoleColor, FeedTone.Item => ItemColor, FeedTone.Trap => TrapColor, FeedTone.Sent => SentColor, FeedTone.Goal => GoalColor, FeedTone.Buff => BuffColor, FeedTone.Hint => HintColor, _ => Color.white, }); } private void OnGUI() { //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) //IL_004e: 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_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected O, but got Unknown //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_014d: 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_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) entries.RemoveAll((Entry entry) => Time.unscaledTime >= entry.ExpiresAt); if (entries.Count == 0) { return; } labelStyle = (GUIStyle)(((object)labelStyle) ?? ((object)new GUIStyle(GUI.skin.box) { fontSize = 15, wordWrap = true, alignment = (TextAnchor)3, richText = false })); float num = (float)Screen.height / 1080f; GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f)); float num2 = ((float)Screen.width / num - 560f) / 2f; float num3 = 18f; foreach (Entry entry in entries) { float num4 = Mathf.Clamp01((entry.ExpiresAt - Time.unscaledTime) / 0.6f); Color val = ColorFor(entry.Tone); GUIContent val2 = new GUIContent(entry.Text); float num5 = labelStyle.CalcHeight(val2, 544f) + 16f; GUI.color = new Color(1f, 1f, 1f, num4); labelStyle.normal.textColor = val; GUI.Box(new Rect(num2, num3, 560f, num5), val2, labelStyle); GUI.color = new Color(val.r, val.g, val.b, num4); GUI.DrawTexture(new Rect(num2, num3, 5f, num5), (Texture)(object)Texture2D.whiteTexture); num3 += num5 + 4f; } GUI.color = Color.white; } } internal static class ChatReplies { private const string TAG_COLOR = "#6FD6FF"; internal static void Show(string text, bool isHint) { if (SingletonBehaviour<TextChatUi>.HasInstance) { TextChatUi.ShowMessage("<color=#6FD6FF>[AP]</color> " + GameManager.RichTextNoParse(text)); } if (isHint) { ApOverlay.Show(text, FeedTone.Hint); } } } } namespace SbgArchipelago.Traps { internal static class InverseControlsInput { private const float PRESSED_THRESHOLD = 0.5f; internal static bool IsJumpKeyHeld() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) GameControls controls = PlayerInput.Controls; object obj; if (controls == null) { obj = null; } else { GameplayActions gameplay = controls.Gameplay; obj = ((GameplayActions)(ref gameplay)).Jump; } InputAction val = (InputAction)obj; if (val != null) { return val.ReadValue<float>() > 0.5f; } return false; } } internal static class TrapEffects { private const int MINE_COUNT = 10; private const float MINE_RING_RADIUS = 4.5f; private const float MINE_SPAWN_HEIGHT = 1.5f; internal static bool ButterfingersArmed; private static float ControlSeconds => Plugin.Client.Settings.ControlTrapSeconds; internal static bool Apply(TrapKind kind, PlayerGolfer golfer) { return kind switch { TrapKind.IceBlock => FreezePlayer(golfer), TrapKind.PenaltyStroke => AddPenaltyStroke(golfer), TrapKind.BallReset => ResetBall(golfer), TrapKind.Butterfingers => ArmButterfingers(), TrapKind.MineField => SpawnMineField(golfer), TrapKind.HighWind => RaiseWind(), TrapKind.Flashbang => Flash(golfer), TrapKind.WalkingOnly => StartWalkingOnly(), TrapKind.Pickpocket => TakeEveryItem(golfer), TrapKind.AngleLock => LockAngle(golfer), TrapKind.InverseControls => Start(delegate { TrapState.StartInverseControls(ControlSeconds); }), TrapKind.InvertedMouse => Start(delegate { TrapState.StartInvertedMouse(ControlSeconds); }), TrapKind.FlippedMeter => Start(delegate { TrapState.StartFlippedMeter(ControlSeconds); }), TrapKind.Mulligan => GiveBackStroke(golfer), TrapKind.SpeedBoost => Start((Action)golfer.PlayerInfo.Movement.InformOfPerfectShotAtTeeOff), TrapKind.MagnetShield => Start(delegate { //IL_000b: Unknown result type (might be due to invalid IL or missing references) golfer.PlayerInfo.LocalPlayerActivateElectromagnetShield(ItemUseId.Invalid); }), TrapKind.PowerSurge => Start(delegate { TrapState.StartPowerSurge(Plugin.Client.Settings.PowerSurgeSeconds); }), TrapKind.GiantBurger => Start(delegate { //IL_000b: Unknown result type (might be due to invalid IL or missing references) golfer.PlayerInfo.LocalPlayerActivateJumboBurgerGiantForm(ItemUseId.Invalid); }), _ => throw new ArgumentOutOfRangeException("kind", kind, "No effect is written for this trap."), }; } private static bool FreezePlayer(PlayerGolfer golfer) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Invalid comparison between Unknown and I4 Hittable asHittable = golfer.PlayerInfo.AsHittable; asHittable.HitWithItem((ItemType)12, ItemUseId.Invalid, Vector3.zero, Vector3.up, Vector3.zero, 0f, (PlayerInventory)null, false, false, true, NetworkTime.predictedTime, 0uL); return (int)asHittable.FrozenState > 0; } private static bool AddPenaltyStroke(PlayerGolfer golfer) { CourseManager.AddPenaltyStroke(golfer, false); return true; } private static bool ResetBall(PlayerGolfer golfer) { //IL_0013: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) GolfBall ownBall = golfer.OwnBall; if ((Object)(object)ownBall == (Object)null) { return false; } Vector3 serverLastStrokePosition = ownBall.ServerLastStrokePosition; ownBall.AsEntity.InformWillTeleport(); Rigidbody rigidbody = ownBall.AsEntity.Rigidbody; rigidbody.linearVelocity = Vector3.zero; rigidbody.angularVelocity = Vector3.zero; rigidbody.position = serverLastStrokePosition; ((Component)ownBall).transform.position = serverLastStrokePosition; ownBall.AsEntity.InformTeleported(); return true; } private static bool ArmButterfingers() { ButterfingersArmed = true; return true; } private static bool SpawnMineField(PlayerGolfer golfer) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) PlayerInventory inventory = golfer.PlayerInfo.Inventory; if ((Object)(object)inventory == (Object)null) { return false; } Vector3 val = ((Component)golfer).transform.position + Vector3.up * 1.5f; for (int i = 0; i < 10; i++) { float num = (float)i * (MathF.PI / 5f); Vector3 val2 = new Vector3(Mathf.Cos(num), 0f, Mathf.Sin(num)) * 4.5f; CourseManager.ServerSpawnLandmine(val + val2, Quaternion.identity, Vector3.zero, Vector3.zero, (LandmineArmType)2, ItemUseId.Invalid, inventory); } return true; } private static bool RaiseWind() { if (!SingletonNetworkBehaviour<WindManager>.HasInstance) { return false; } SingletonNetworkBehaviour<WindManager>.Instance.NetworkcurrentWindSpeed = WindManager.MaxPossibleWindSpeed; return true; } private static bool Start(Action effect) { effect(); return true; } private static bool GiveBackStroke(PlayerGolfer golfer) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) CourseManager instance = SingletonNetworkBehaviour<CourseManager>.Instance; int num = default(int); if (!instance.TryGetPlayerStateIndex(((NetworkBehaviour)golfer).connectionToClient, ref num)) { return false; } PlayerState val = instance.playerStates[num]; if (val.matchStrokes <= 0) { return false; } val.matchStrokes--; val.courseStrokes--; instance.playerStates[num] = val; return true; } private static bool StartWalkingOnly() { TrapState.StartWalkingOnly(Plugin.Client.Settings.WalkingOnlyTrapSeconds); return true; } private static bool TakeEveryItem(PlayerGolfer golfer) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) PlayerInventory inventory = golfer.PlayerInfo.Inventory; if ((Object)(object)inventory == (Object)null) { return false; } for (int i = 0; i < inventory.slots.Count; i++) { if ((int)inventory.slots[i].itemType != 0) { inventory.RemoveItemAt(i, false, false); } } return true; } private static bool LockAngle(PlayerGolfer golfer) { UnlockState unlocks = Plugin.Client.Unlocks; float pitch = TrapState.StartAngleLock(Plugin.Client.Settings.AngleLockTrapSeconds, unlocks.UnlockedAngles(), unlocks.HasFreeAim); golfer.SetPitch(pitch); return true; } private static bool Flash(PlayerGolfer golfer) { golfer.PlayerInfo.UserCode_RpcInformOfFlashCameraHit__Single(0f); return true; } } internal static class TrapRunner { private const float SECONDS_BETWEEN_TRAPS = 4f; private const int MAX_ATTEMPTS = 3; private static readonly TrapQueue Queue = new TrapQueue(4f, 3); internal static void Enqueue(TrapKind kind, string sender) { Queue.Enqueue(kind, sender); Plugin.Log.LogInfo((object)$"[SBG-AP] Trap queued: {TrapKinds.DisplayName(kind)} from {sender}. {Queue.Count} waiting."); } internal static void Tick() { TrapState.Tick(); if (Queue.Count == 0) { return; } PlayerGolfer localGolferInPlay = PlayState.GetLocalGolferInPlay(); if (Queue.TryTakeNext(Time.unscaledTime, (Object)(object)localGolferInPlay != (Object)null, out var trap)) { if (TrapEffects.Apply(trap.Kind, localGolferInPlay)) { bool flag = TrapKinds.IsBuff(trap.Kind); ApOverlay.Show(TrapKinds.DisplayName(trap.Kind) + (flag ? " buff" : " trap") + "! Sent by " + trap.Sender + ".", flag ? FeedTone.Buff : FeedTone.Trap); Plugin.Log.LogInfo((object)("[SBG-AP] Trap fired: " + TrapKinds.DisplayName(trap.Kind) + " from " + trap.Sender + ".")); } else { bool flag2 = Queue.Requeue(trap); Plugin.Log.LogWarning((object)("[SBG-AP] The " + TrapKinds.DisplayName(trap.Kind) + " trap could not be applied" + (flag2 ? "; trying again." : " after several tries, so it was dropped."))); } } } } internal static class TrapState { private const float FREE_AIM_LOCK_STEP = 5f; private const float MAX_AIM_ANGLE = 60f; private static float walkingOnlyUntil; private static float angleLockUntil; private static float lockedAngle; private static float inverseControlsUntil; private static float invertedMouseUntil; private static float flippedMeterUntil; private static float powerSurgeUntil; internal static bool IsWalkingOnly => Time.unscaledTime < walkingOnlyUntil; internal static bool IsAngleLocked => Time.unscaledTime < angleLockUntil; internal static float LockedAngle => lockedAngle; internal static bool IsInverseControls => Time.unscaledTime < inverseControlsUntil; internal static bool IsInvertedMouse => Time.unscaledTime < invertedMouseUntil; internal static bool IsFlippedMeter => Time.unscaledTime < flippedMeterUntil; internal static bool IsPowerSurge => Time.unscaledTime < powerSurgeUntil; internal static void StartWalkingOnly(float seconds) { walkingOnlyUntil = Time.unscaledTime + seconds; } internal static void StartInverseControls(float seconds) { inverseControlsUntil = Time.unscaledTime + seconds; } internal static void StartInvertedMouse(float seconds) { invertedMouseUntil = Time.unscaledTime + seconds; } internal static void StartFlippedMeter(float seconds) { flippedMeterUntil = Time.unscaledTime + seconds; } internal static void StartPowerSurge(float seconds) { powerSurgeUntil = Time.unscaledTime + seconds; } internal static float StartAngleLock(float seconds, IReadOnlyList<int> usableAngles, bool hasFreeAim) { lockedAngle = (hasFreeAim ? ((float)Random.Range(0, 13) * 5f) : ((usableAngles.Count == 0) ? 0f : ((float)usableAngles[Random.Range(0, usableAngles.Count)]))); angleLockUntil = Time.unscaledTime + seconds; return lockedAngle; } internal static void Tick() { if ((IsWalkingOnly || IsAngleLocked || IsInverseControls || IsInvertedMouse || IsFlippedMeter || IsPowerSurge) && !PlayState.IsHoleUnderWay) { EndAll(); } ApplyMeterFlip(); if (IsInverseControls) { SetWalkHeld(InverseControlsInput.IsJumpKeyHeld()); } else if (IsWalkingOnly) { SetWalkHeld(held: true); } } private static void EndAll() { walkingOnlyUntil = 0f; angleLockUntil = 0f; inverseControlsUntil = 0f; invertedMouseUntil = 0f; flippedMeterUntil = 0f; powerSurgeUntil = 0f; } private static void SetWalkHeld(bool held) { PlayerInfo localPlayerInfo = GameManager.LocalPlayerInfo; if ((Object)(object)localPlayerInfo != (Object)null && (Object)(object)localPlayerInfo.Input != (Object)null) { localPlayerInfo.Input.IsHoldingWalk = held || IsWalkingOnly; } } private static void ApplyMeterFlip() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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) if (SingletonBehaviour<SwingPowerBarUi>.HasInstance) { Transform transform = ((Component)SingletonBehaviour<SwingPowerBarUi>.Instance).transform; Vector3 localScale = transform.localScale; float num = Mathf.Abs(localScale.y) * (IsFlippedMeter ? (-1f) : 1f); if (!Mathf.Approximately(localScale.y, num)) { transform.localScale = new Vector3(localScale.x, num, localScale.z); } } } } } namespace SbgArchipelago.Patches { [HarmonyPatch(typeof(PlayerGolfer), "ReleaseSwingChargeInternal")] internal static class PatchButterfingers { private static void Prefix(PlayerGolfer __instance, ref bool isForcedFumble) { if (!(!TrapEffects.ButterfingersArmed | isForcedFumble) && ((NetworkBehaviour)__instance).isLocalPlayer && __instance.IsChargingSwing) { TrapEffects.ButterfingersArmed = false; isForcedFumble = true; ApOverlay.Show("Butterfingers! The club slipped.", FeedTone.Trap); } } } [HarmonyPatch(typeof(TextChatManager), "SendChatMessage")] internal static class PatchChatCommands { private static bool Prefix(string message) { return !ChatCommands.TryHandle(message); } } [HarmonyPatch(typeof(PlayerMovement), "TryTriggerJump")] internal static class PatchJump { private static bool Prefix(PlayerMovement __instance, ref bool __result) { if (!UnlockGate.IsActive || !((NetworkBehaviour)__instance).isLocalPlayer || UnlockGate.IsJumpAllowed) { return true; } ApOverlay.ShowOnce("jump-locked", "Jumping is locked: find the Jump item."); __result = false; return false; } } [HarmonyPatch(typeof(PlayerInput), "Update")] internal static class PatchInverseMovement { private static bool isSwapped; private static void Prefix(PlayerInput __instance) { if (isSwapped && ((NetworkBehaviour)__instance).isLocalPlayer) { Negate(__instance.playerInfo.Movement); isSwapped = false; } } private static void Postfix(PlayerInput __instance) { if (TrapState.IsInverseControls && ((NetworkBehaviour)__instance).isLocalPlayer && !isSwapped) { Negate(__instance.playerInfo.Movement); isSwapped = true; } } private static void Negate(PlayerMovement movement) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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) movement.moveVector2d = -movement.moveVector2d; movement.rawMoveVector2d = -movement.rawMoveVector2d; } } [HarmonyPatch(typeof(PlayerInput), "StartWalk")] internal static class PatchSwapWalkPressed { private static bool Prefix(PlayerInput __instance) { if (!TrapState.IsInverseControls || !((NetworkBehaviour)__instance).isLocalPlayer) { return true; } __instance.playerInfo.Movement.TryTriggerJump(); return false; } } [HarmonyPatch(typeof(PlayerInput), "EndWalk")] internal static class PatchSwapWalkReleased { private static bool Prefix(PlayerInput __instance) { if (TrapState.IsInverseControls) { return !((NetworkBehaviour)__instance).isLocalPlayer; } return true; } } [HarmonyPatch(typeof(PlayerInput), "Jump")] internal static class PatchSwapJumpPressed { private static bool Prefix(PlayerInput __instance, ref bool __result) { if (!TrapState.IsInverseControls || !((NetworkBehaviour)__instance).isLocalPlayer) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(OrbitCameraModule), "Rotate")] internal static class PatchInvertOrbitCamera { private static void Prefix(ref Vector2 axis) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (TrapState.IsInvertedMouse) { axis = -axis; } } } [HarmonyPatch(typeof(FirstPersonCameraModule), "Rotate")] internal static class PatchInvertFirstPersonCamera { private static void Prefix(ref Vector2 axis) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (TrapState.IsInvertedMouse) { axis = -axis; } } } [HarmonyPatch(typeof(CourseManager), "InformPlayerEliminated")] internal static class PatchDeathLinkSend { private static void Postfix(PlayerGolfer eliminatedPlayer, EliminationReason reason) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (NetworkServer.active && !((Object)(object)eliminatedPlayer == (Object)null) && ((NetworkBehaviour)eliminatedPlayer).isLocalPlayer && (int)reason != 7) { DeathLinkHandler.OnLocalPlayerEliminated(DescribeReason(reason)); } } private static string DescribeReason(EliminationReason reason) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) if ((int)reason != 5) { if ((int)reason == 6) { return "fell into the water"; } return $"was eliminated ({reason})"; } return "went out of bounds"; } } [HarmonyPatch(typeof(PlayerMovement), "TryDiveInternal")] internal static class PatchDive { private static bool Prefix(PlayerMovement __instance, DiveType type, ref bool __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) if ((int)type != 0 || !UnlockGate.IsActive || !((NetworkBehaviour)__instance).isLocalPlayer || UnlockGate.IsDiveAllowed) { return true; } ApOverlay.ShowOnce("dive-locked", "Diving is locked: find the Dive item (or wait out the Walking Only trap)."); __result = false; return false; } } [HarmonyPatch(typeof(ItemSpawnerSettings), "GetItemPoolFor")] internal static class PatchSoloItemPool { private static void Postfix(ItemSpawnerSettings __instance, ref ItemPool __result) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) if (UnlockGate.IsActive && PlayState.IsHoleUnderWay && PlayState.IsOnlyPlayerInMatch) { List<ItemPoolData> itemPools = __instance.ItemPools; int num = Mathf.Clamp(Plugin.Client.Settings.SoloItemPool, 1, itemPools.Count) - 1; if (itemPools.Count > 0 && (Object)(object)__result == (Object)(object)itemPools[0].pool && num > 0) { __result = itemPools[num].pool; } } } } [HarmonyPatch(typeof(CourseManager), "InformPlayerScoredInternal")] internal static class PatchHoleScored { private static void Prefix(CourseManager __instance, PlayerGolfer playerAsGolfer, out bool __state) { __state = (Object)(object)playerAsGolfer != (Object)null && !__instance.matchScoredPlayers.Contains(playerAsGolfer); if (__state) { HoleStyleFlags.Reset(playerAsGolfer.PlayerInfo.PlayerId.Guid); } } private static void Postfix(PlayerGolfer playerAsGolfer, bool __state) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (__state && !((Object)(object)playerAsGolfer == (Object)null)) { PlayerState val = default(PlayerState); if (!CourseManager.TryGetPlayerState(playerAsGolfer.PlayerInfo, ref val)) { Plugin.Log.LogWarning((object)"[SBG-AP] A hole was scored but the player's state was not found; no check sent."); return; } ulong guid = playerAsGolfer.PlayerInfo.PlayerId.Guid; HoleCompletion.Handle(Plugin.Client, new HoleResult(SingletonBehaviour<DrivingRangeManager>.HasInstance, CourseManager.CurrentHoleGlobalIndex, val.matchStrokes, CourseManager.GetCurrentHolePar(), HoleStyleFlags.IsSpeedrun(guid), HoleStyleFlags.IsChipIn(guid))); } } } [HarmonyPatch(typeof(InfoFeed), "ShowSpeedrunMessage")] internal static class PatchSpeedrunMessage { private static void Prefix(PlayerInfo player) { if ((Object)(object)player != (Object)null) { HoleStyleFlags.MarkSpeedrun(player.PlayerId.Guid); } } } [HarmonyPatch(typeof(InfoFeed), "ShowChipInMessage")] internal static class PatchChipInMessage { private static void Prefix(PlayerInfo player) { if ((Object)(object)player != (Object)null) { HoleStyleFlags.MarkChipIn(player.PlayerId.Guid); } } } [HarmonyPatch(typeof(ItemSpawnerSettings), "GetRandomItemFor")] internal static class PatchItemBoxRoll { private static void Postfix(ItemSpawnerSettings __instance, PlayerInfo player, ref ItemType __result) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected I4, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (ItemBoxGate.IsRestricted && !ItemBoxGate.IsAllowed(__result)) { ItemType val = __result; __result = (ItemType)(int)ItemBoxGate.PickAllowed(__instance, __instance.GetItemPoolFor(player), Random.value); Plugin.Log.LogInfo((object)$"[SBG-AP] Item box gave {__result} (the game rolled {val}, which is not unlocked)."); } } } [HarmonyPatch(typeof(MatchSetupRules), "Initialize")] internal static class PatchItemOddsInitialize { private static void Postfix(MatchSetupRules __instance) { ItemOddsGate.Apply(__instance); RulesGate.Apply(__instance); } } [HarmonyPatch(typeof(PauseMenu), "UpdateItemProbabilites")] internal static class PatchPauseMenuItemOdds { private static void Postfix(PauseMenu __instance) { ItemOddsGate.ApplyToPauseMenu(__instance); } } [HarmonyPatch(typeof(MatchSetupRules), "UpdateCurrentItemPool")] internal static class PatchItemOddsPoolChanged { private static void Postfix(MatchSetupRules __instance) { ItemOddsGate.Apply(__instance); } } [HarmonyPatch(typeof(MatchSetupMenu), "InitializeCourses")] internal static class PatchMenuInitializeCourses { private static void Postfix(MatchSetupMenu __instance) { MatchSetupGate.Apply(__instance); } } [HarmonyPatch(typeof(MatchSetupMenu), "UpdateCourses")] internal static class PatchMenuUpdateCourses { private static void Postfix(MatchSetupMenu __instance) { MatchSetupGate.Apply(__instance); } } [HarmonyPatch(typeof(MatchSetupMenu), "SetCourse")] internal static class PatchMenuSetCourse { private static void Prefix(ref int courseIndex, bool fromSerialization) { if (!fromSerialization) { MatchSetupGate.TryRedirectToUnlockedHoles(ref courseIndex); } } } [HarmonyPatch(typeof(MatchSetupMenu), "OnHoleOrderChanged")] internal static class PatchMenuHoleOrderChanged { private static void Postfix(MatchSetupMenu __instance) { MatchSetupGate.Apply(__instance); } } [HarmonyPatch(typeof(MatchSetupMenu), "RefreshStartMatchButton")] internal static class PatchMenuRefreshStartButton { private static void Postfix(MatchSetupMenu __instance) { MatchSetupGate.ApplyStartBlock(__instance); } } [HarmonyPatch(typeof(MatchSetupMenu), "SetEnabled")] internal static class PatchMenuSetEnabled { private static void Postfix(MatchSetupMenu __instance, bool enabled) { if (enabled) { int courseIndex = __instance.activeCourse; if (MatchSetupGate.TryRedirectToUnlockedHoles(ref courseIndex)) { __instance.SetCourse(courseIndex, false); } MatchSetupGate.Apply(__instance); MatchSetupGate.ApplyStartBlock(__instance); } } } [HarmonyPatch(typeof(MatchSetupMenu), "StartOrCancelMatch")] internal static class PatchMenuStartOrCancelMatch { private static bool Prefix(MatchSetupMenu __instance) { string startBlockReason = MatchSetupGate.GetStartBlockReason(__instance); if (startBlockReason == null) { return true; } Plugin.Log.LogInfo((object)("[SBG-AP] Match start refused: " + startBlockReason)); ApOverlay.Show(startBlockReason); return false; } } [HarmonyPatch(typeof(PlayerGolfer), "SetPitchInternal")] internal static class PatchSetPitch { private static void Prefix(PlayerGolfer __instance, ref float pitch) { if (UnlockGate.IsActive && ((NetworkBehaviour)__instance).isLocalPlayer) { pitch = UnlockGate.AllowedPitch(pitch, __instance.SwingPitch); } } } [HarmonyPatch(typeof(PlayerGolfer), "TryStartChargingSwing")] internal static class PatchStartChargingSwing { private const float CHANGE_TOLERANCE = 0.01f; private static void Prefix(PlayerGolfer __instance) { if (UnlockGate.IsActive && ((NetworkBehaviour)__instance).isLocalPlayer) { float swingPitch = __instance.SwingPitch; float num = UnlockGate.AllowedPitch(swingPitch, swingPitch); if (!(Math.Abs(num - swingPitch) <= 0.01f)) { Plugin.Log.LogInfo((object)$"[SBG-AP] Aim angle {swingPitch:0.#} is locked; using {num:0.#} instead."); __instance.SetPitch(num); } } } } [HarmonyPatch(typeof(MatchSetupRules), "GetValue")] internal static class PatchLockedRules { private const float LOW_WIND = 1f; private static void Postfix(Rule rule, ref float __result) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 if (UnlockGate.IsActive) { if ((int)rule == 5) { __result = UnlockGate.PowerCapFraction; } else if ((int)rule == 20) { __result = 1f; } else if ((int)rule == 2) { __result = (Plugin.Client.Settings.ParTime ? 1f : 0f); } } } } [HarmonyPatch(typeof(SwingPowerBarUi), "SetNormalizedPower")] internal static class PatchPowerBarLabel { private static void Prefix(ref float labelNormalizedPower) { if (UnlockGate.IsActive) { labelNormalizedPower *= UnlockGate.PowerCapFraction; } } } } namespace SbgArchipelago.Core { internal static class AngleSnap { private const float MATCH_TOLERANCE = 0.01f; internal static float Snap(float requested, float current, IReadOnlyList<int> unlockedAscending) { if (unlockedAscending == null || unlockedAscending.Count == 0) { return requested; } foreach (int item in unlockedAscending) { if (Math.Abs((float)item - requested) <= 0.01f) { return requested; } } if (requested > current + 0.01f) { return NextAtOrAbove(requested, unlockedAscending); } if (requested < current - 0.01f) { return NextAtOrBelow(requested, unlockedAscending); } return Nearest(requested, unlockedAscending); } private static float NextAtOrAbove(float requested, IReadOnlyList<int> unlockedAscending) { foreach (int item in unlockedAscending) { if ((float)item >= requested) { return item; } } return unlockedAscending[unlockedAscending.Count - 1]; } private static float NextAtOrBelow(float requested, IReadOnlyList<int> unlockedAscending) { for (int num = unlockedAscending.Count - 1; num >= 0; num--) { if ((float)unlockedAscending[num] <= requested) { return unlockedAscending[num]; } } return unlockedAscending[0]; } private static float Nearest(float requested, IReadOnlyList<int> unlockedAscending) { float num = unlockedAscending[0]; foreach (int item in unlockedAscending) { if (Math.Abs((float)item - requested) < Math.Abs(num - requested)) { num = item; } } return num; } } internal enum BonusChecks { None, Par, Birdie, Eagle, Albatross, Condor } internal static class ChatCommand { private const char COMMAND_PREFIX = '!'; private const string HINT = "hint"; internal const string HINT_USAGE = "Hint what? Try: !hint power, !hint angle 45, !hint free aim, !hint dive, !hint jump, !hint hole cove, !hint coast 3, or !hint box airhorn."; internal static bool TryParse(string message, out string command, out string arguments) { command = string.Empty; arguments = string.Empty; string text = (message ?? string.Empty).Trim(); if (text.Length < 2 || text[0] != '!' || char.IsWhiteSpace(text[1])) { return false; } int num = text.IndexOf(' '); command = ((num < 0) ? text.Substring(1) : text.Substring(1, num - 1)).ToLowerInvariant(); arguments = ((num < 0) ? string.Empty : text.Substring(num + 1).Trim()); return true; } internal static bool IsHint(string command) { return string.Equals(command, "hint", StringComparison.Ordinal); } } internal sealed class DeathLinkPolicy { private readonly float cooldownSeconds; private readonly float suppressSendAfterReceiveSeconds; private float nextAcceptedReceiveTime; private float nextAllowedSendTime; internal DeathLinkPolicy(float cooldownSeconds, float suppressSendAfterReceiveSeconds) { this.cooldownSeconds = cooldownSeconds; this.suppressSendAfterReceiveSeconds = suppressSendAfterReceiveSeconds; } internal bool TryAcceptReceived(float now, string source, string ownName) { if (source == ownName || now < nextAcceptedReceiveTime) { return false; } nextAcceptedReceiveTime = now + cooldownSeconds; float num = now + suppressSendAfterReceiveSeconds; if (num > nextAllowedSendTime) { nextAllowedSendTime = num; } return true; } internal bool TryAcceptSend(float now) { if (now < nextAllowedSendTime) { return false; } nextAllowedSendTime = now + cooldownSeconds; return true; } } internal static class FeedText { internal static string ForReceived(ItemKind kind, string itemName, string sender, bool isFromSelf, int powerCapPercent) { string text; switch (kind) { case ItemKind.HoleAccess: text = "Hole unlocked: " + ItemNames.HoleFromAccessItem(itemName); break; case ItemKind.Course: text = "Course unlocked: " + ItemNames.CourseFromAccessItem(itemName); break; case ItemKind.Angle: { ItemNames.TryParseAngle(itemName, out var angle); text = $"Aim angle unlocked: {angle}°"; break; } case ItemKind.FreeAim: text = "Free Aim unlocked: aim at any angle"; break; case ItemKind.PowerCap: text = $"Power cap raised to {powerCapPercent}%"; break; case ItemKind.Dive: text = "Dive unlocked"; break; case ItemKind.Jump: text = "Jump unlocked"; break; case ItemKind.BoxItem: text = "Item boxes can now give: " + FriendlyItemType(ItemNames.BoxItemType(itemName)); break; case ItemKind.Filler: case ItemKind.Trap: case ItemKind.Buff: return null; default: text = "Received: " + itemName; break; } if (!isFromSelf) { return text + " (from " + sender + ")"; } return text; } internal static FeedTone ToneFor(ItemKind kind) { switch (kind) { case ItemKind.Course: case ItemKind.HoleAccess: return FeedTone.Hole; case ItemKind.Trap: return FeedTone.Trap; case ItemKind.Filler: return FeedTone.Info; case ItemKind.Buff: return FeedTone.Buff; default: return FeedTone.Item; } } internal static string ForSent(string itemName, string receiver) { return "Sent " + itemName + " to " + receiver; } internal static string ForGoalProgress(int holesDone, int holesRequired, ScoreNeeded goalScore) { return $"Goal: {holesDone} of {holesRequired} holes{DescribeGoalScore(goalScore)}"; } internal static string ForGoalProgress(GoalType goal, int holesDone, int holesRequired, int? underParTotal, int goalUnderPar, ScoreNeeded goalScore) { return goal switch { GoalType.UnderParTotal => $"Goal: {FormatUnderPar(underParTotal.GetValueOrDefault())} of -{goalUnderPar} over your best {holesRequired} holes " + $"({holesDone} played)", GoalType.AllChecks => $"Goal: {holesDone} of {holesRequired} holes with every check", _ => ForGoalProgress(holesDone, holesRequired, goalScore), }; } private static string FormatUnderPar(int strokesUnderPar) { if (strokesUnderPar <= 0) { if (strokesUnderPar >= 0) { return "E"; } return $"+{-strokesUnderPar}"; } return $"-{strokesUnderPar}"; } internal static string ForGoalComplete() { return "Goal complete! Every win condition is met."; } private static string DescribeGoalScore(ScoreNeeded goalScore) { return goalScore switch { ScoreNeeded.Par => " at par or better", ScoreNeeded.Birdie => " under par", ScoreNeeded.Eagle => " at eagle or better", _ => string.Empty, }; } internal static string ForBatch(int itemCount) { return $"Received {itemCount} items. Your unlocks are up to date."; } internal static string FriendlyItemType(string enumName) { StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < enumName.Length; i++) { if (i > 0 && char.IsUpper(enumName[i]) && char.IsLower(enumName[i - 1])) { stringBuilder.Append(' '); } stringBuilder.Append(enumName[i]); } return stringBuilder.ToString(); } } internal enum FeedTone { Info, Hole, Item, Trap, Sent, Goal, Buff, Hint } internal static class GoalProgressText { private const char ENTRY_SEPARATOR = ';'; internal static string NameOf(GoalType goal) { return goal switch { GoalType.AllHoles => "all_holes", GoalType.HoleCount => "hole_count", GoalType.UnderParTotal => "total_under_par", GoalType.AllChecks => "all_checks", _ => goal.ToString(), }; } internal static string Entry(GoalType goal, int value, int target, bool isMet) { return $"{NameOf(goal)}={value}/{target}:{(isMet ? 1 : 0)}"; } internal static string Join(IEnumerable<string> entries) { return string.Join(';'.ToString(), entries); } } internal enum GoalType { AllHoles, HoleCount, UnderParTotal, AllChecks } internal static class GoalRule { internal static int RequiredHoles(GoalType goal, int goalHoleCount, int holesInSeed) { return Math.Max((goal == GoalType.AllHoles) ? holesInSeed : Math.Min(goalHoleCount, holesInSeed), 1); } internal static int? BestHolesTotal(IEnumerable<int> bestUnderParPerHole, int holeCount) { List<int> list = new List<int>(bestUnderParPerHole); if (list.Count < holeCount) { return null; } list.Sort((int left, int right) => right.CompareTo(left)); int num = 0; for (int num2 = 0; num2 < holeCount; num2++) { num += list[num2]; } return num; } internal static bool IsMet(int qualifyingHoles, int requiredHoles) { return qualifyingHoles >= requiredHoles; } } internal sealed class HintContext { internal IReadOnlyList<string> HoleAccessItems { get; } internal IReadOnlyList<string> Courses { get; } internal bool UnlocksWholeCourses { get; } internal HintContext(IReadOnlyList<string> holeAccessItems, IReadOnlyList<string> courses, bool unlocksWholeCourses) { HoleAccessItems = holeAccessItems ?? new List<string>(); Courses = courses ?? new List<string>(); UnlocksWholeCourses = unlocksWholeCourses; } } internal readonly struct HintResolution { internal string ItemName { get; } internal IReadOnlyList<string> Choices { get; } internal bool IsResolved => ItemName != null; internal bool IsAmbiguous { get { if (ItemName == null && Choices != null) { return Choices.Count > 1; } return false; } } internal static HintResolution Nothing => new HintResolution(null, null); private HintResolution(string itemName, IReadOnlyList<string> choices) { ItemName = itemName; Choices = choices; } internal static HintResolution Found(string itemName) { return new HintResolution(itemName, null); } internal static HintResolution Several(IReadOnlyList<string> choices) { return new HintResolution(null, choices); } } internal static class HintResolver { private const int MAX_CHOICES = 5; private const int MIN_ANGLE = 5; private const int MAX_ANGLE = 60; private const int ANGLE_STEP = 5; private const string HOLE_PREFIX = "Hole Access: "; private const string BOX_PREFIX = "Item Box: "; private const string COURSE_SUFFIX = " Access"; private static readonly string[] BoxItemTypes = new string[17] { "Coffee", "DuelingPistol", "ElephantGun", "Airhorn", "SpringBoots", "GolfCart", "RocketLauncher", "Landmine", "Electromagnet", "OrbitalLaser", "RocketDriver", "FreezeBomb", "SmokeBomb", "FlashCamera", "Thunderstorm", "Railgun", "JumboBurger" }; private static readonly Dictionary<string, string> BoxAliases = new Dictionary<string, string> { ["magnet"] = "Electromagnet", ["camera"] = "FlashCamera", ["flash"] = "FlashCamera", ["flashbang"] = "FlashCamera", ["burger"] = "JumboBurger", ["pistol"] = "DuelingPistol", ["cart"] = "GolfCart", ["laser"] = "OrbitalLaser", ["freeze"] = "FreezeBomb", ["ice"] = "FreezeBomb", ["smoke"] = "SmokeBomb", ["boots"] = "SpringBoots", ["spring"] = "SpringBoots", ["mine"] = "Landmine", ["horn"] = "Airhorn", ["elephant"] = "ElephantGun", ["thunder"] = "Thunderstorm", ["storm"] = "Thunderstorm", ["coffee"] = "Coffee" }; private static readonly string[] BoxPrefixes = new string[4] { "item box ", "itembox ", "box ", "item " }; internal static HintResolution Resolve(string query, HintContext context) { string text = (query ?? string.Empty).Trim(); if (text.Length == 0) { return HintResolution.Nothing; } string text2 = ExactItemName(text, context); if (text2 != null) { return HintResolution.Found(text2); } string text3 = KeywordItem(Normalize(text)); if (text3 != null) { return HintResolution.Found(text3); } HintResolution result = ResolveBoxItem(text); if (!result.IsResolved && !result.IsAmbiguous) { return ResolveHoleOrCourse(text, context); } return result; } private static string ExactItemName(string text, HintContext context) { return context.HoleAccessItems.Concat(context.Courses.Select((string course) => course + " Access")).Concat(BoxItemTypes.Select((string type) => "Item Box: " + type)).FirstOrDefault((string name) => string.Equals(name, text, StringComparison.OrdinalIgnoreCase)); } private static string KeywordItem(string normalized) { switch (normalized) { case "powercap": case "power": case "power cap": case "progressive power": case "progressive power cap": return "Progressive Power Cap"; case "free aim": case "free": case "freeaim": return "Free Aim"; case "dive": return "Dive"; case "jump": return "Jump"; default: { if (!TryReadAngle(normalized, out var angle)) { return null; } return $"Angle {angle}"; } } } private static bool TryReadAngle(string normalized, out int angle) { if (int.TryParse(normalized.Replace("angle", string.Empty).Replace("degrees", string.Empty).Replace("degree", string.Empty) .Replace("°", string.Empty) .Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out angle) && angle >= 5 && angle <= 60) { return angle % 5 == 0; } return false; } private static HintResolution ResolveBoxItem(string text) { string normalized = Normalize(text); string text2 = (from prefix in BoxPrefixes where normalized.StartsWith(prefix) select normalized.Substring(prefix.Length)).FirstOrDefault(); string name = Compact(text2 ?? normalized); bool flag = text2 != null; if (BoxAliases.TryGetValue(name, out var value)) { return HintResolution.Found("Item Box: " + value); } List<string> list = BoxItemTypes.Where((string type) => Compact(type) == name).ToList(); if (list.Count == 0) { list = BoxItemTypes.Where((string type) => name.Length >= 4 && Compact(type).Contains(name)).ToList(); } if (list.Count == 1) { return HintResolution.Found("Item Box: " + list[0]); } if (list.Count <= 1 || (!flag && list.Count > 5)) { return HintResolution.Nothing; } return HintResolution.Several((from type in list.Take(5) select "Item Box: " + type).ToList()); } private static HintResolution ResolveHoleOrCourse(string text, HintContext context) { string normalized = Normalize(text); if (normalized.StartsWith("hole ")) { normalized = normalized.Substring("hole ".Length).Trim(); } string text2 = context.Courses.FirstOrDefault((string candidate) => Normalize(candidate) == normalized); if (text2 != null && context.UnlocksWholeCourses) { return HintResolution.Found(text2 + " Access"); } List<string> list = context.HoleAccessItems.Where((string item) => Normalize(HoleLabel(item).Split('-')[0]) == normalized).ToList(); List<string> list2 = ((list.Count > 0) ? list : context.HoleAccessItems.Where((string item) => Compact(HoleLabel(item)).Contains(Compact(normalized))).ToList()); if (list2.Count == 1) { return HintResolution.Found(list2[0]); } if (list2.Count <= 1 || Compact(normalized).Length <= 0) { return HintResolution.Nothing; } return HintResolution.Several(list2.Take(5).ToList()); } private static string HoleLabel(string holeAccessItem) { if (!holeAccessItem.StartsWith("Hole Access: ")) { return holeAccessItem; } return holeAccessItem.Substring("Hole Access: ".Length); } private static string Normalize(string text) { return string.Join(" ", text.ToLowerInvariant().Split(new char[3] { ' ', '\t', '_' }, StringSplitOptions.RemoveEmptyEntries)); } private static string Compact(string text) { return new string(text.ToLowerInvariant().Where(char.IsLetterOrDigit).ToArray()); } } internal sealed class HoleRecord { [JsonProperty("global_index")] public int GlobalIndex; [JsonProperty("course")] public string Course; [JsonProperty("course_hole_number")] public int CourseHoleNumber; [JsonProperty("name")] public string Name; [JsonProperty("par")] public int Par; [JsonProperty("scene")] public string Scene; } internal static class HoleCatalog { private const string EXPORT_FOLDER = "SBG-Archipelago"; private const string EXPORT_FILE = "holes.json"; internal static List<HoleRecord> ReadHoles() { List<HoleRecord> list = new List<HoleRecord>(); CourseCollection allCourses = GameManager.AllCourses; if ((Object)(object)allCourses == (Object)null) { return list; } foreach (HoleData allHole in allCourses.allHoles) { list.Add(new HoleRecord { GlobalIndex = allHole.GlobalIndex, Course = allHole.ParentCourse.LocalizedName.GetLocalizedString(), CourseHoleNumber = allHole.ParentCourseIndex + 1, Name = allHole.LocalizedName.GetLocalizedString(), Par = allHole.Par, Scene = allHole.Scene.Name }); } return list; } internal static string Export() { List<HoleRecord> list = ReadHoles(); if (list.Count == 0) { return null; } string text = Path.Combine(Paths.ConfigPath, "SBG-Archipelago"); Directory.CreateDirectory(text); string text2 = Path.Combine(text, "holes.json"); File.WriteAllText(text2, JsonConvert.SerializeObject((object)list, (Formatting)1)); return text2; } } internal static class HoleGate { private const int MAX_LISTED_LABELS = 5; internal static string CourseOf(int holeGlobalIndex, IReadOnlyList<string> courseOfHole) { if (courseOfHole == null || holeGlobalIndex < 0 || holeGlobalIndex >= courseOfHole.Count) { return null; } return courseOfHole[holeGlobalIndex]; } internal static bool IsHoleInSeed(int holeGlobalIndex, IReadOnlyList<string> courseOfHole, ISet<string> includedCourses) { string text = CourseOf(holeGlobalIndex, courseOfHole); if (text != null) { return includedCourses.Contains(text); } return false; } internal static bool IsHoleUnlocked(int holeGlobalIndex, IReadOnlyList<string> courseOfHole, ISet<string> includedCourses, Func<int, string, bool> isUnlockedByItems) { string text = CourseOf(holeGlobalIndex, courseOfHole); if (text == null) { return false; } if (includedCourses.Contains(text)) { return isUnlockedByItems(holeGlobalIndex, text); } return true; } internal static IReadOnlyList<int> LockedHoles(IEnumerable<int> holeGlobalIndices, IReadOnlyList<string> courseOfHole, ISet<string> includedCourses, Func<int, string, bool> isUnlockedByItems) { return (from index in holeGlobalIndices.Distinct() where !IsHoleUnlocked(index, courseOfHole, includedCourses, isUnlockedByItems) select index).ToList(); } internal static string DescribeBlocked(IReadOnlyList<string> lockedLabels) { string text = string.Join(", ", lockedLabels.Take(5)); int num = lockedLabels.Count - 5; string text2 = ((num > 0) ? $" and {num} more" : string.Empty); return "Archipelago: this course includes locked holes (" + text + text2 + "). Remove them or pick holes you have unlocked."; } } internal static class HoleReport { internal const int CONDOR_MIN_PAR = 6; internal const int CONDOR_TIER_COUNT = 5; internal static int TiersForPar(int par) { if (par < 6) { return Math.Min(par, 4); } return 5; } internal static IReadOnlyList<long> LocationsFor(int holeGlobalIndex, int strokes, int par, ScoreNeeded scoreNeeded, int bonusTierLimit, int seedPar, long holeLocationOffset, IReadOnlyList<long> tierLocationOffsets) { List<long> list = new List<long>(); if (ScoreRule.IsMet(scoreNeeded, strokes, par)) { list.Add(holeLocationOffset + holeGlobalIndex); } int num = Math.Min(Math.Min(bonusTierLimit, TiersForPar(seedPar)), tierLocationOffsets.Count); for (int i = 0; i < num; i++) { if (ScoreRule.MeetsTier(i, strokes, par)) { list.Add(tierLocationOffsets[i] + holeGlobalIndex); } } return list; } internal static long? StyleLocation(int holeGlobalIndex, bool isEarned, bool isEnabledInSeed, long locationOffset) { if (!(isEarned && isEnabledInSeed)) { return null; } return locationOffset + holeGlobalIndex; } } internal enum ItemBoxMode { Vanilla, UnlockedOnly } internal static class ItemBoxOdds { private const float PERCENT_SCALE = 100f; internal static IReadOnlyList<float> EffectiveWeights(IReadOnlyList<float> poolWeights, IReadOnlyList<bool> isAllowed, IReadOnlyList<float> fallbackWeights) { IReadOnlyList<float> readOnlyList = Mask(poolWeights, isAllowed); if (readOnlyList.Sum() > 0f || fallbackWeights == null) { return readOnlyList; } return Mask(fallbackWeights, isAllowed); } internal static float PercentOf(IReadOnlyList<float> effectiveWeights, int index) { float num = effectiveWeights.Sum(); if (!(num <= 0f)) { return effectiveWeights[index] / num * 100f; } return 0f; } private static IReadOnlyList<float> Mask(IReadOnlyList<float> weights, IReadOnlyList<bool> isAllowed) { return weights.Select((float weight, int index) => (!isAllowed[index]) ? 0f : weight).ToList(); } } internal static class ItemBoxRoll { internal static T Pick<T>(IReadOnlyList<KeyValuePair<T, float>> weightedEntries, Func<T, bool> isAllowed, float roll, T fallback) { float num = 0f; foreach (KeyValuePair<T, float> weightedEntry in weightedEntries) { if (weightedEntry.Value > 0f && isAllowed(weightedEntry.Key)) { num += weightedEntry.Value; } } if (num <= 0f) { return fallback; } float num2 = Math.Max(0f, Math.Min(roll, MathF.PI * 113f / 355f)) * num; float num3 = 0f; T result = fallback; foreach (KeyValuePair<T, float> weightedEntry2 in weightedEntries) { if (!(weightedEntry2.Value <= 0f) && isAllowed(weightedEntry2.Key)) { num3 += weightedEntry2.Value; result = weightedEntry2.Key; if (num2 < num3) { return weightedEntry2.Key; } } } return result; } } internal enum ItemKind { Unknown, Angle, FreeAim, PowerCap, Course, HoleAccess, BoxItem, Filler, Trap, Dive, Jump, Buff } internal enum JumpMode { FromStart, AsItem } internal enum DiveMode { FromStart, AsItem } internal static class ItemNames { internal const string FREE_AIM = "Free Aim"; internal const string POWER_CAP = "Progressive Power Cap"; internal const string DIVE = "Dive"; internal const string JUMP = "Jump"; private static readonly string[] BuffNames = new string[5] { "Mulligan", "Speed Boost", "Magnet Shield", "Power Surge", "Giant Burger" }; internal const string FILLER = "Item Box Pickup"; private const string ANGLE_PREFIX = "Angle "; private const string BOX_PREFIX = "Item Box: "; private const string HOLE_PREFIX = "Hole Access: "; private const string COURSE_SUFFIX = " Access"; private const string TRAP_SUFFIX = " Trap"; internal static ItemKind Classify(string itemName) { if (string.IsNullOrEmpty(itemName)) { return ItemKind.Unknown; } switch (itemName) { case "Free Aim": return ItemKind.FreeAim; case "Progressive Power Cap": return ItemKind.PowerCap; case "Dive": return ItemKind.Dive; case "Jump": return ItemKind.Jump; default: { if (Array.IndexOf(BuffNames, itemName) >= 0) { return ItemKind.Buff; } if (itemName == "Item Box Pickup") { return ItemKind.Filler; } if (itemName.StartsWith("Hole Access: ")) { return ItemKind.HoleAccess; } if (itemName.StartsWith("Item Box: ")) { return ItemKind.BoxItem; } if (itemName.StartsWith("Angle ") && TryParseAngle(itemName, out var _)) { return ItemKind.Angle; } if (itemName.EndsWith(" Trap")) { return ItemKind.Trap; } if (!itemName.EndsWith(" Access")) { return ItemKind.Unknown; } return ItemKind.Course; } } } internal static bool TryParseAngle(string itemName, out int angle) { angle = 0; if (itemName != null && itemName.StartsWith("Angle ")) { return int.TryParse(itemName.Substring("Angle ".Length), NumberStyles.None, CultureInfo.InvariantCulture, out angle); } return false; } internal static string CourseFromAccessItem(string itemName) { return itemName.Substring(0, itemName.Length - " Access".Length); } internal static string HoleFromAccessItem(string itemName) { return itemName.Substring("Hole Access: ".Length); } internal static string BoxItemType(string itemName) { return itemName.Substring("Item Box: ".Length); } } internal static class LateJoinPolicy { internal static bool ShouldSkipBacklog(bool hasSaveForThisSeedAndSlot, int locationsAlreadyChecked) { if (!hasSaveForThisSeedAndSlot) { return locationsAlreadyChecked > 0; } return false; } } internal static class MainThread { private static readonly ConcurrentQueue<Action> Pending = new ConcurrentQueue<Action>(); internal static void Post(Action action) { Pending.Enqueue(action); } internal static void Drain(Action<Exception> onError) { Action result; while (Pending.TryDequeue(out result)) { try { result(); } catch (Exception obj) { onError(obj); } } } } internal static class PowerScale { private const int MIN_PERCENT = 1; private const int MAX_PERCENT = 100; private const float PERCENT_DIVISOR = 100f; internal static float Fraction(int capPercent) { return (float)Math.Max(1, Math.Min(100, capPercent)) / 100f; } } internal enum ScoreNeeded { Any, Par, Birdie, Eagle } internal static class ScoreRule { private const int HOLE_IN_ONE_MAX_STROKES = 1; internal static bool IsMet(ScoreNeeded needed, int strokes, int par) { if (needed == ScoreNeeded.Any || strokes <= 1) { return true; } return par - strokes >= RequiredStrokesUnderPar(needed); } internal static bool MeetsTier(int tier, int strokes, int par) { if (strokes > 1) { return par - strokes >= tier; } return true; } private static int RequiredStrokesUnderPar(ScoreNeeded needed) { return (int)(needed - 1); } } internal sealed class TestProfile { private const int PUTT_ANGLE = 0; private const int MAX_ANGLE = 60; private const int MIN_CAP_PERCENT = 1; private const int MAX_CAP_PERCENT = 100; private const string FREE_AIM_WORD = "free"; internal IReadOnlyList<int> Angles { get; } internal bool HasFreeAim { get; } internal int PowerCapPercent { get; } private TestProfile(IReadOnlyList<int> angles, bool hasFreeAim, int powerCapPercent) { Angles = angles; HasFreeAim = hasFreeAim; PowerCapPercent = powerCapPercent; } internal static bool TryParse(string anglesText, int powerCapPercent, out TestProfile profile, out string error) { profile = null; error = null; if (powerCapPercent < 1 || powerCapPercent > 100) { error = $"The power cap must be {1} to {100}, not {powerCapPercent}."; return false; } string text = (anglesText ?? string.Empty).Trim().ToLowerInvariant(); if (text == "free") { profile = new TestProfile(new int[1], hasFreeAim: true, powerCapPercent); return true; } SortedSet<int> sortedSet = new SortedSet<int> { 0 }; string[] array = text.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text2 in array) { if (!int.TryParse(text2.Trim(), out var result) || result < 0 || result > 60) { error = $"'{text2.Trim()}' is not an angle from {0} to {60}. Use for example 0,60 or free."; return false; } sortedSet.Add(result); } profile = new TestProfile(sortedSet.ToList(), hasFreeAim: false, powerCapPercent); return true; } internal string Describe() { string arg = (HasFreeAim ? "free aim" : ("angles " + string.Join(",", Angles))); return $"{arg}, power cap {PowerCapPercent}%"; } } internal enum TrapKind { IceBlock, PenaltyStroke, BallReset, Butterfingers, MineField, HighWind, Flashbang, WalkingOnly, Pickpocket, AngleLock, InverseControls, InvertedMouse, FlippedMeter, Mulligan, SpeedBoost, MagnetShield, PowerSurge, GiantBurger } internal static class TrapKinds { internal static bool TryFromItemName(string itemName, out TrapKind kind) { switch (itemName) { case "Ice Block Trap": kind = TrapKind.IceBlock; return true; case "Penalty Stroke Trap": kind = TrapKind.PenaltyStroke; return true; case "Ball Reset Trap": kind = TrapKind.BallReset; return true; case "Butterfingers Trap": kind = TrapKind.Butterfingers; return true; case "Mine Field Trap": kind = TrapKind.MineField; return true; case "High Wind Trap": kind = TrapKind.HighWind; return true; case "Flashbang Trap": kind = TrapKind.Flashbang; return true; case "Walking Only Trap": kind = TrapKind.WalkingOnly; return true; case "Pickpocket Trap": kind = TrapKind.Pickpocket; return true; case "Angle Lock Trap": kind = TrapKind.AngleLock; return true; case "Inverse Controls Trap": kind = TrapKind.InverseControls; return true; case "Inverted Mouse Trap": kind = TrapKind.InvertedMouse; return true; case "Flipped Meter Trap": kind = TrapKind.FlippedMeter; return true; case "Mulligan": kind = TrapKind.Mulligan; return true; case "Speed Boost": kind = TrapKind.SpeedBoost; return true; case "Magnet Shield": kind = TrapKind.MagnetShield; return true; case "Power Surge": kind = TrapKind.PowerSurge; return true; case "Giant Burger": kind = TrapKind.GiantBurger; return true; default: kind = TrapKind.IceBlock; return false; } } internal static bool IsBuff(TrapKind kind) { return kind >= TrapKind.Mulligan; } internal static string DisplayName(TrapKind kind) { return kind switch { TrapKind.IceBlock => "Ice Block", TrapKind.PenaltyStroke => "Penalty Stroke", TrapKind.BallReset => "Ball Reset", TrapKind.Butterfingers => "Butterfingers", TrapKind.MineField => "Mine Field", TrapKind.HighWind => "High Wind", TrapKind.Flashbang => "Flashbang", TrapKind.WalkingOnly => "Walking Only", TrapKind.Pickpocket => "Pickpocket", TrapKind.AngleLock => "Angle Lock", TrapKind.InverseControls => "Inverse Controls", TrapKind.InvertedMouse => "Inverted Mouse", TrapKind.FlippedMeter => "Flipped Meter", TrapKind.Mulligan => "Mulligan", TrapKind.SpeedBoost => "Speed Boost", TrapKind.MagnetShield => "Magnet Shield", TrapKind.PowerSurge => "Power Surge", TrapKind.GiantBurger => "Giant Burger", _ => kind.ToString(), }; } } internal struct PendingTrap { internal TrapKind Kind; internal string Sender; internal int Attempts; } internal sealed class TrapQueue { private readonly List<PendingTrap> pending = new List<PendingTrap>(); private readonly float secondsBetweenTraps; private readonly int maxAttempts; private float nextAllowedTime; internal int Count => pending.Count; internal TrapQueue(float secondsBetweenTraps, int maxAttempts) { this.secondsBetweenTraps = secondsBetweenTraps; this.maxAttempts = maxAttempts; } internal void Enqueue(TrapKind kind, string sender) { pending.Add(new PendingTrap { Kind = kind, Sender = sender }); } internal bool TryTakeNext(float now, bool canFireNow, out PendingTrap trap) { trap = default(PendingTrap); if (pending.Count == 0 || !canFireNow || now < nextAllowedTime) { return false; } trap = pending[0]; pending.RemoveAt(0); nextAllowedTime = now + secondsBetweenTraps; return true; } internal bool Requeue(PendingTrap trap) { trap.Attempts++; if (trap.Attempts >= maxAttempts) { return false; } pending.Insert(0, trap); return true; } } internal enum UnlockMode { IndividualHoles, WholeCourses } internal sealed class UnlockState { private const int PUTT_ANGLE = 0; private const int FULL_POWER_PERCENT = 100; private readonly object sync = new object(); private readonly HashSet<int> angles = new HashSet<int> { 0 }; private readonly HashSet<string> courses = new HashSet<string>(); private readonly HashSet<string> boxItems = new HashSet<string>(); private readonly HashSet<string> holeAccessItems = new HashSet<string>(); private bool hasFreeAim; private bool hasDive; private bool hasJump; private int powerCapSteps; internal bool HasFreeAim { get { lock (sync) { return hasFreeAim; } } } internal bool HasDive { get { lock (sync) { return hasDive; } } } internal bool HasJump { get { lock (sync) { return hasJump; } } } internal ItemKind Apply(string itemName) { ItemKind itemKind = ItemNames.Classify(itemName); lock (sync) { switch (itemKind) { case ItemKind.Angle: { if (ItemNames.TryParseAngle(itemName, out var angle)) { angles.Add(angle); } break; } case ItemKind.FreeAim: hasFreeAim = true; break; case ItemKind.PowerCap: powerCapSteps++; break; case ItemKind.Dive: hasDive = true; break; case ItemKind.Jump: hasJump = true; break; case ItemKind.Course: courses.Add(ItemNames.CourseFromAccessItem(itemName)); break; case ItemKind.HoleAccess: holeAccessItems.Add(itemName); break; case ItemKind.BoxItem: boxItems.Add(ItemNames.BoxItemType(itemName)); break; case ItemKind.Filler: case ItemKind.Trap: break; } } return itemKind; } internal bool IsAngleUnlocked(int angle) { lock (sync) { return hasFreeAim || angles.Contains(angle); } } internal IReadOnlyList<int> UnlockedAngles() { lock (sync) { return angles.OrderBy((int angle) => angle).ToList(); } } internal bool IsCourseUnlocked(string course) { lock (sync) { return courses.Contains(course); } } internal bool IsHoleAccessUnlocked(string holeAccessItemName) { lock (sync) { return holeAccessItems.Contains(holeAccessItemName); } } internal bool IsBoxItemUnlocked(string itemType) { lock (sync) { return boxItems.Contains(itemType); } } internal int PowerCapPercent(int startingCap, int increment) { lock (sync) { return Math.Min(100, startingCap + powerCapSteps * increment); } } internal string Summary(int startingCap, int increment) { lock (sync) { string text = (hasFreeAim ? "free aim" : string.Join(",", angles.OrderBy((int angle) => angle))); string text2 = ((courses.Count == 0) ? "none" : string.Join(",", courses.OrderBy((string course) => course))); int num = Math.Min(100, startingCap + powerCapSteps * increment); return $"angles: {text}; power cap: {num}%; courses: {text2}; holes: {holeAccessItems.Count}; " + $"item box items: {boxItems.Count}"; } } } internal static class WorldVersionCheck { internal const int SUPPORTED_MAJOR = 0; internal const int SUPPORTED_MINOR = 9; internal static string Check(string worldVersion) { string text = $"{0}.{9}.x"; if (string.IsNullOrWhiteSpace(worldVersion) || !Version.TryParse(worldVersion, out Version result)) { return "The seed reports apworld version '" + (worldVersion ?? "none") + "', which this mod cannot read. This mod supports apworld " + text + "; install the matching apworld and regenerate."; } if (result.Major == 0 && result.Minor == 9) { return null; } return "This seed was generated with apworld " + worldVersion + ", but this mod supports " + text + ". Update the mod or the apworld so the versions match, then regenerate the seed."; } } } namespace SbgArchipelago.Commands { internal static class ApCommands { [CCommand("apDumpHoles", "Write every hole (global index, course, name, par) to BepInEx/config/SBG-Archipelago/holes.json", false, false)] private static void ApDumpHoles() { string text = HoleCatalog.Export(); if (text == null) { Debug.Log((object)"[SBG-AP] No holes loaded yet. Open the course menu or enter a hole, then run apDumpHoles again."); } else { Debug.Log((object)$"[SBG-AP] Wrote {HoleCatalog.ReadHoles().Count} holes to {text}"); } } [CCommand("apConnect", "Connect to Archipelago: apConnect [server:port] [slot] [password]. Missing values come from the config file.", false, false)] private static void ApConnect(string server = "", string slot = "", string password = "") { string text = (string.IsNullOrWhiteSpace(server) ? Plugin.Server.Value : server); string text2 = (string.IsNullOrWhiteSpace(slot) ? Plugin.SlotName.Value : slot); string password2 = (string.IsNullOrEmpty(password) ? Plugin.Password.Value : password); if (string.IsNullOrWhiteSpace(text2)) { Debug.Log((object)"[SBG-AP] No slot name. Use: apConnect <server:port> <slot> [password], or set SlotName in the config file."); return; } Plugin.Client.ConnectAsync(text, text2, password2); Debug.Log((object)("[SBG-AP] Connecting to " + text + " as " + text2 + ". Run apStatus to see the result.")); } [CCommand("apDisconnect", "Disconnect from the Archipelago server.", false, false)] private static void ApDisconnect() { Plugin.Client.Disconnect(); Debug.Log((object)"[SBG-AP] Disconnected."); } [CCommand("apEnforce", "Turn the Archipelago restrictions on or off for this session: apEnforce [on|off]", false, false)] private static void ApEnforce(string state = "") { string text = (state ?? string.Empty).Trim().ToLowerInvariant(); if (text == "on" || text == "off") { UnlockGate.SetEnabledForSession(text == "on"); } else if (text.Length > 0) { Debug.Log((object)"[SBG-AP] Unknown argument. Use: apEnforce on, apEnforce off, or apEnforce to show the state."); return; } MatchSetupGate.RefreshAll(); Debug.Log((object)("[SBG-AP] Restrictions are " + (UnlockGate.IsEnabled ? "ON" : "OFF") + " for this session (config default: " + (Plugin.EnforceUnlocks.Value ? "on" : "off") + ")" + ((Plugin.Client.Settings == null) ? ". No seed is loaded, so nothing is restricted yet" : string.Empty) + ".")); } [CCommand("apPower", "Show the power cap and the game's overcharge settings.", false, false)] private static void ApPower() { string text = (UnlockGate.IsActive ? $"{UnlockGate.PowerCapPercent}% (shots scaled by {UnlockGate.PowerCapFraction:0.00})" : $"NOT applied: seed loaded = {Plugin.Client.Settings != null}, restrictions on = {UnlockGate.IsEnabled}"); Debug.Log((object)("[SBG-AP] Power cap: " + text + ". Game overcharge: charge can reach " + $"{1f + GameManager.GolfSettings.MaxSwingOvercharge:0.###}x of a full bar " + $"(MaxSwingOvercharge = {GameManager.GolfSettings.MaxSwingOvercharge:0.###}). " + $"Swing Power rule as read by gameplay: {MatchSetupRules.GetValue((Rule)5):0.###}.")); } [CCommand("apTest", "Play-test a hole with fixed aiming and power: apTest <angles|free> [powerCap], e.g. apTest 0,60 20. apTest off ends it.", false, false)] private static void ApTest(string angles = "", string powerCap = "100") { string text = (angles ?? string.Empty).Trim().ToLowerInvariant(); int result; TestProfile profile; string error; if (text == "off" || text.Length == 0) { bool num = UnlockGate.TestProfile != null; UnlockGate.TestProfile = null; Debug.Log((object)(num ? "[SBG-AP] Test profile off. Your seed's unlocks apply again." : "[SBG-AP] No test profile is set. Use: apTest <angles|free> [powerCap], for example apTest 0,60 20.")); } else if (!int.TryParse(powerCap, out result)) { Debug.Log((object)"[SBG-AP] The power cap must be a whole number from 1 to 100."); } else if (!TestProfile.TryParse(text, result, out profile, out error)) { Debug.Log((object)("[SBG-AP] " + error)); } else { UnlockGate.TestProfile = profile; string text2 = (UnlockGate.IsActive ? string.Empty : " Warning: no seed is loaded or restrictions are off, so nothing is applied yet."); Debug.Log((object)("[SBG-AP] Testing with " + profile.Describe() + ". Play the hole, then run apTestResult pass or fail." + text2)); } } [CCommand("apTestResult", "Record the play-test of the current hole: apTestResult <pass|fail> [note]", false, false)] private static void ApTestResult(string result = "", string note = "") { string text = (result ?? string.Empty).Trim().ToLowerInvariant(); if (text != "pass" && text != "fail") { Debug.Log((object)"[SBG-AP] Use: apTestResult pass [note] or apTestResult fail [note]."); return; } if (UnlockGate.TestProfile == null) { Debug.Log((object)"[SBG-AP] No test profile is set. Run apTest <angles|free> [powerCap] first."); return; } int currentHoleGlobalIndex = CourseManager.CurrentHoleGlobalIndex; if (currentHoleGlobalIndex < 0 || SingletonBehaviour<DrivingRangeManager>.HasInstance) { Debug.Log((object)"[SBG-AP] Run this while you are in a real hole (not the driving range or a menu)."); return; } string text2 = HoleTestLog.Append(currentHoleGlobalIndex, UnlockGate.TestProfile, text == "pass", note); Debug.Log((object)$"[SBG-AP] Recorded hole {currentHoleGlobalIndex}: {text} with {UnlockGate.TestProfile.Describe()}. File: {text2}"); } [CCommand("apEffect", "Fire a trap or buff on yourself to try it, during a hole: apEffect <name>, e.g. apEffect inversecontrols. apEffect alone lists them.", false, false)] private static void ApEffect(string name = "") { string text = (name ?? string.Empty).Replace(" ", string.Empty).ToLowerInvariant(); TrapKind[] array = (TrapKind[])Enum.GetValues(typeof(TrapKind)); TrapKind[] array2 = array; foreach (TrapKind kind in array2) { if (TrapKinds.DisplayName(kind).Replace(" ", string.Empty).ToLowerInvariant() == text) { TrapRunner.Enqueue(kind, "the console"); Debug.Log((object)("[SBG-AP] Queued " + TrapKinds.DisplayName(kind) + ". It fires while you are playing a hole.")); return; } } string text2 = string.Join(", ", array.Select((TrapKind kind2) => TrapKinds.DisplayName(kind2).Replace(" ", string.Empty).ToLowerInvariant())); Debug.Log((object)("[SBG-AP] Unknown effect '" + name + "'. Use one of: " + text2)); } [CCommand("apHint", "Ask Archipelago where an item is: apHint power | angle 45 | free aim | dive | jump | hole cove | box airhorn", false, false)] private static void ApHint(string a = "", string b = "", string c = "", string d = "", string e = "") { string text = string.Join(" ", new string[5] { a, b, c, d, e }.Where((string word) => !string.IsNullOrEmpty(word))); if (text.Length == 0) { Debug.Log((object)"[SBG-AP] Hint what? Try: !hint power, !hint angle 45, !hint free aim, !hint dive, !hint jump, !hint hole cove, !hint coast 3, or !hint box airhorn."); } else if (!ChatCommands.TryHandle("!hint " + text)) { Debug.Log((object)"[SBG-AP] No seed is loaded, so there is nothing to hint about. Use apConnect first."); } } [CCommand("apStatus", "Show the Archipelago connection status.", false, false)] private static void ApStatus() { Debug.Log((object)("[SBG-AP] " + Plugin.Client.DescribeStatus())); } } } namespace SbgArchipelago.Ap { internal enum ApConnectionState { Disconnected, Connecting, Connected } internal readonly struct ReceivedItem { internal string Name { get; } internal ItemKind Kind { get; } internal string From { get; } internal ReceivedItem(string name, ItemKind kind, string from) { Name = name; Kind = kind; From = from; } } internal readonly struct GoalProgress { internal GoalType Goal { get; } internal int HolesDone { get; } internal int HolesRequired { get; } internal bool IsMet { get; } internal int? UnderParTotal { get; } internal GoalProgress(GoalType goal, int holesDone, int holesRequired, bool isMet, int? underParTotal = null) { Goal = goal; HolesDone = holesDone; HolesRequired = holesRequired; IsMet = isMet; UnderParTotal = underParTotal; } } internal readonly struct GoalReport { internal IReadOnlyList<GoalProgress> Goals { get; } internal IReadOnlyList<GoalProgress> Moved { get; } internal bool AllMet { get { if (Goals != null && Goals.Count > 0) { return Goals.All((GoalProgress goal) => goal.IsMet); } return false; } } internal GoalReport(IReadOnlyList<GoalProgress> goals, IReadOnlyList<GoalProgress> moved) { Goals = goals; Moved = moved; } } internal sealed class ApClient { internal const string GAME_NAME = "Super Battle Golf"; private readonly ApSaveStore store; private readonly object checkLock = new object(); private readonly object itemLock = new object(); private readonly HashSet<long> reportedLocations = new HashSet<long>(); private readonly List<long> pendingLocations = new List<long>(); private readonly HashSet<long> inFlightLocations = new HashSet<long>(); private readonly List<string> receivedItemNames = new List<string>(); private ArchipelagoSession session; private DeathLinkService deathLinkService; private ApSave save; private int itemPosition; private bool skipBacklogEffects; private string ownSlotName; internal ApConnectionState State { get; private set; } internal string StatusDetail { get; private set; } = "Not connected."; internal SlotSettings Settings { get; private set; } internal UnlockState Unlocks { get; private set; } = new UnlockState(); internal string OwnSlotName => ownSlotName ?? string.Empty; internal event Action<string, ItemKind, string> NewItemReceived; internal event Action<IReadOnlyList<ReceivedItem>> NewItemsReceived; internal event Action<string, string> ItemSentToOtherPlayer; internal event Action<string, string> DeathLinkReceived; internal event Action<string, bool> ServerReply; internal event Action UnlocksChanged; internal ApClient(ApSaveStore store) { this.store = store; } internal string DescribeStatus() { string text = ((Settings == null) ? "no seed loaded" : Unlocks.Summary(Settings.StartingPowerCap, Settings.PowerCapIncrement)); int count; lock (checkLock) { count = pendingLocations.Count; } return $"{State}: {StatusDetail} Unlocks: {text}. Checks waiting to send: {count}."; } internal void RestoreLastSession() { ApSave apSave = store.LoadLastSession(); if (apSave?.SlotData == null) { return; } try { Settings = SlotSettings.Parse(apSave.SlotData); } catch (InvalidOperationException ex) { Plugin.Log.LogWarning((object)("[SBG-AP] Could not restore the last session (" + apSave.Slot + "): " + ex.Message)); return; } save = apSave; ResetForSave(apSave, null); Unlocks = new UnlockState(); receivedItemNames.AddRange(apSave.ReceivedItems); foreach (string receivedItem in apSave.ReceivedItems) { Unlocks.Apply(receivedItem); } StatusDetail = "Not connected. Restored the last session for slot " + apSave.Slot + " (offline)."; Plugin.Log.LogInfo((object)$"[SBG-AP] {StatusDetail} {apSave.PendingLocations.Count} check(s) waiting to send."); } internal void ConnectAsync(string server, string slotName, string password) { if (State != ApConnectionState.Disconnected) { Plugin.Log.LogWarning((object)$"[SBG-AP] Already {State}. Run apDisconnect first."); return; } State = ApConnectionState.Connecting; StatusDetail = "Connecting to " + server + " as " + slotName + "..."; Plugin.Log.LogInfo((object)("[SBG-AP] " + StatusDetail)); Task.Run(delegate { ConnectAndLogin(server, slotName, password); }); } internal void Disconnect() { ArchipelagoSession val = session; session = null; deathLinkService = null; State = ApConnectionState.Disconnected; StatusDetail = "Not connected."; try { if (val != null) { val.Socket.DisconnectAsync(); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("[SBG-AP] Error while disconnecting: " + ex.Message)); } } internal void ReportLocation(long locationId) { lock (checkLock) { if (save == null || !reportedLocations.Add(locationId)) { return; } pendingLocations.Add(locationId); SavePendingLocations(); } FlushPendingLocations(); } internal GoalReport UpdateGoal(int holeGlobalIndex, int strokes, int par) { SlotSettings settings = Settings; IReadOnlyList<GoalProgress> readOnlyList; IReadOnlyList<GoalProgress> readOnlyList2; lock (checkLock) { if (save == null || settings == null) { return default(GoalReport); } readOnlyList = ReadGoalsLocked(settings); if (ApplyHoleToGoalsLocked(settings, holeGlobalIndex, strokes, par)) { PersistSave(); } readOnlyList2 = ReadGoalsLocked(settings); } List<GoalProgress> list = new List<GoalProgress>(); for (int i = 0; i < readOnlyList2.Count; i++) { if (readOnlyList2[i].HolesDone != readOnlyList[i].HolesDone || readOnlyList2[i].UnderParTotal != readOnlyList[i].UnderParTotal) { list.Add(readOnlyList2[i]); } } GoalReport result = new GoalReport(readOnlyList2, list); PublishGoalProgress(settings, readOnlyList2); if (result.AllMet) { SendGoalIfMet(); } return result; } private bool ApplyHoleToGoalsLocked(SlotSettings settings, int hole, int strokes, int par) { bool result = false; if ((settings.Goals.Contains(GoalType.AllHoles) || settings.Goals.Contains(GoalType.HoleCount)) && ScoreRule.IsMet(settings.GoalScore, strokes, par) && !save.GoalHoles.Contains(hole)) { save.GoalHoles.Add(hole); result = true; } if (settings.Goals.Contains(GoalType.UnderParTotal)) { int num = par - strokes; if (!save.HoleBestUnderPar.TryGetValue(hole, out var value) || num > value) { save.HoleBestUnderPar[hole] = num; result = true; } } return result; } private IReadOnlyList<GoalProgress> ReadGoalsLocked(SlotSettings settings) { return settings.Goals.Select((GoalType goal) => ReadGoalLocked(settings, goal)).ToList(); } private GoalProgress ReadGoalLocked(SlotSettings settings, GoalType goal) { int num = settings.RequiredHolesFor(goal); switch (goal) { case GoalType.UnderParTotal: { int? num3 = GoalRule.BestHolesTotal(save.HoleBestUnderPar.Values, num); int value = num3 ?? GoalRule.BestHolesTotal(save.HoleBestUnderPar.Values, save.HoleBestUnderPar.Count).GetValueOrDefault(); bool isMet = num3.HasValue && num3.Value >= settings.GoalUnderPar; return new GoalProgress(goal, save.HoleBestUnderPar.Count, num, isMet, value); } case GoalType.AllChecks: { int num2 = settings.HolesWithLocations.Count((int hole) => settings.ExpectedLocationsFor(hole).All(reportedLocations.Contains)); return new GoalProgress(goal, num2, num, GoalRule.IsMet(num2, num)); } default: { int count = save.GoalHoles.Count; return new GoalProgress(goal, count, num, GoalRule.IsMet(count, num)); } } } private void PublishGoalProgress(SlotSettings settings, IReadOnlyList<GoalProgress> goals) { ArchipelagoSession activeSession = session; if (activeSession == null || State != ApConnectionState.Connected || string.IsNullOrEmpty(settings.GoalProgressKey)) { return; } string text = GoalProgressText.Join(goals.Select((GoalProgress goal) => (goal.Goal != GoalType.UnderParTotal) ? GoalProgressText.Entry(goal.Goal, goal.HolesDone, goal.HolesRequired, goal.IsMet) : GoalProgressText.Entry(goal.Goal, goal.UnderParTotal.GetValueOrDefault(), settings.GoalUnderPar, goal.IsMet))); Task.Run(delegate { try { activeSession.DataStorage[settings.GoalProgressKey] = DataStorageElement.op_Implicit(text); } catch (Exception ex) { Plugin.Log.LogWarning((object)("[SBG-AP] Could not publish the goal progress for the tracker: " + ex.Message)); } }); } private void SendGoalIfMet() { ArchipelagoSession activeSession = session; SlotSettings settings = Settings; bool flag; lock (checkLock) { flag = save != null && settings != null && settings.Goals.Count > 0 && ReadGoalsLocked(settings).All((GoalProgress goal) => goal.IsMet); } if (activeSession == null || !flag || State != ApConnectionState.Connected) { return; } Task.Run(delegate { try { activeSession.SetGoalAchieved(); Plugin.Log.LogInfo((object)"[SBG-AP] Goal reached; sent to the server."); } catch (Exception ex) { Plugin.Log.LogError((object)("[SBG-AP] Could not send the goal; it will be retried on the next connection. Cause: " + ex.Message)); } }); } private void FlushPendingLocations() { ArchipelagoSession activeSession = session; if (State != ApConnectionState.Connected || activeSession == null) { Plugin.Log.LogInfo((object)$"[SBG-AP] Not connected: {pendingLocations.Count} location check(s) saved until you connect."); return; } long[] toSend; lock (checkLock) { toSend = pendingLocations.Where((long id) => !inFlightLocations.Contains(id)).ToArray(); inFlightLocations.UnionWith(toSend); } if (toSend.Length != 0) { Task.Run(delegate { SendChecks(activeSession, toSend); }); } } private void SendChecks(ArchipelagoSession activeSession, long[] locationIds) { try { activeSession.Locations.CompleteLocationChecks(locationIds); lock (checkLock) { pendingLocations.RemoveAll((long id) => locationIds.Contains(id)); SavePendingLocations(); } Plugin.Log.LogInfo((object)("[SBG-AP] Sent location check(s): " + string.Join(", ", locationIds))); } catch (Exception ex) { Plugin.Log.LogError((object)("[SBG-AP] Could not send location check(s) " + string.Join(", ", locationIds) + "; they will be retried on the next connection. Cause: " + ex.Message)); } finally { lock (checkLock) { inFlightLocations.ExceptWith(locationIds); } } } internal void SendDeathLink(string cause) { DeathLinkService service = deathLinkService; if (service == null || State != ApConnectionState.Connected) { return; } Task.Run(delegate { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown try { service.SendDeathLink(new DeathLink(ownSlotName, cause)); Plugin.Log.LogInfo((object)("[SBG-AP] DeathLink sent: " + cause)); } catch (Exception ex) { Plugin.Log.LogWarning((object)("[SBG-AP] Could not send the DeathLink: " + ex.Message)); } }); } private void SavePendingLocations() { save.PendingLocations = pendingLocations.ToList(); PersistSave(); } private void PersistSave() { try { store.Save(save); } catch (Exception ex) { Plugin.Log.LogError((object)("[SBG-AP] Could not write the save file for slot " + save.Slot + ". Progress is still on the server. Cause: " + ex.Message)); } } private void ConnectAndLogin(string server, string slotName, string password) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown try { ArchipelagoSession val = ArchipelagoSessionFactory.CreateSession(server, 38281); val.Socket.SocketClosed += new SocketClosedHandler(OnSocketClosed); LoginResult val2 = val.TryConnectAndLogin("Super Battle Golf", slotName, (ItemsHandlingFlags)7, (Version)null, new string[1] { "AP" }, (string)null, string.IsNullOrEmpty(password) ? null : password, true); LoginSuccessful val3 = (LoginSuccessful)(object)((val2 is LoginSuccessful) ? val2 : null); if (val3 != null) { OnLoginSucceeded(val, slotName, val3); return; } LoginFailure val4 = (LoginFailure)val2; Fail("Login refused: " + string.Join("; ", val4.Errors)); } catch (Exception ex) { Fail("Could not connect to " + server + ": " + ex.Message); } } private void OnLoginSucceeded(ArchipelagoSession newSession, string slotName, LoginSuccessful success) { //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Expected O, but got Unknown //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Expected O, but got Unknown SlotSettings slotSettings; try { slotSettings = SlotSettings.Parse(success.SlotData); } catch (InvalidOperationException ex) { RejectLogin(newSession, ex.Message); return; } string text = WorldVersionCheck.Check(slotSettings.WorldVersion); if (text != null) { RejectLogin(newSession, text); return; } string seed = newSession.RoomState.Seed; ApSave apSave = store.Load(seed, slotName); ApSave apSave2 = apSave ?? new ApSave { Seed = seed, Slot = slotName }; apSave2.SlotData = new Dictionary<string, object>(success.SlotData); skipBacklogEffects = LateJoinPolicy.ShouldSkipBacklog(apSave != null, newSession.Locations.AllLocationsChecked.Count); if (skipBacklogEffects) { Plugin.Log.LogInfo((object)"[SBG-AP] Joining a game already in progress: items received so far will unlock things but not fire their one-off effects."); } lock (checkLock) { inFlightLocations.Clear(); } ownSlotName = slotName; lock (itemLock) { Unlocks = new UnlockState(); receivedItemNames.Clear(); itemPosition = 0; save = apSave2; Settings = slotSettings; } ResetForSave(apSave2, new HashSet<long>(newSession.Locations.AllLocationsChecked)); session = newSession; State = ApConnectionState.Connected; StatusDetail = $"Connected as slot {success.Slot} ({slotName}), apworld {slotSettings.WorldVersion}, " + $"score needed: {slotSettings.ScoreNeeded}."; Plugin.Log.LogInfo((object)("[SBG-AP] " + StatusDetail)); Plugin.Log.LogInfo((object)"[SBG-AP] Co-op: everyone in the same lobby should connect to this same slot."); newSession.MessageLog.OnMessageReceived += new MessageReceivedHandler(OnLogMessage); EnableDeathLinkIfRequested(newSession, slotSettings); newSession.Items.ItemReceived += new ItemReceivedHandler(OnItemReceived); ProcessReceivedItems(newSession.Items); skipBacklogEffects = false; this.UnlocksChanged?.Invoke(); lock (checkLock) { PersistSave(); } FlushPendingLocations(); SendGoalIfMet(); } private void EnableDeathLinkIfRequested(ArchipelagoSession newSession, SlotSettings settings)
Archipelago.MultiClient.Net.dll
Decompiled 17 hours 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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net.WebSockets; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using Archipelago.MultiClient.Net.Colors; using Archipelago.MultiClient.Net.ConcurrentCollection; using Archipelago.MultiClient.Net.Converters; using Archipelago.MultiClient.Net.DataPackage; using Archipelago.MultiClient.Net.Enums; using Archipelago.MultiClient.Net.Exceptions; using Archipelago.MultiClient.Net.Extensions; using Archipelago.MultiClient.Net.Helpers; using Archipelago.MultiClient.Net.MessageLog.Messages; using Archipelago.MultiClient.Net.MessageLog.Parts; using Archipelago.MultiClient.Net.Models; using Archipelago.MultiClient.Net.Packets; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: ComVisible(false)] [assembly: Guid("35a803ad-85ed-42e9-b1e3-c6b72096f0c1")] [assembly: InternalsVisibleTo("Archipelago.MultiClient.Net.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Jarno Westhof, Hussein Farran, Zach Parks")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyDescription("A client library for use with .NET based prog-langs for interfacing with Archipelago hosts.")] [assembly: AssemblyFileVersion("6.7.1.0")] [assembly: AssemblyInformationalVersion("6.7.1+0c57591db30f2497b0b4fef87164aa2bbe2e51b2")] [assembly: AssemblyProduct("Archipelago.MultiClient.Net")] [assembly: AssemblyTitle("Archipelago.MultiClient.Net")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ArchipelagoMW/Archipelago.MultiClient.Net")] [assembly: AssemblyVersion("6.7.1.0")] internal interface IConcurrentHashSet<T> { bool TryAdd(T item); bool Contains(T item); void UnionWith(T[] otherSet); T[] ToArray(); ReadOnlyCollection<T> AsToReadOnlyCollection(); ReadOnlyCollection<T> AsToReadOnlyCollectionExcept(IConcurrentHashSet<T> otherSet); } public class AttemptingStringEnumConverter : StringEnumConverter { public AttemptingStringEnumConverter() { } public AttemptingStringEnumConverter(Type namingStrategyType) : base(namingStrategyType) { } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { try { return ((StringEnumConverter)this).ReadJson(reader, objectType, existingValue, serializer); } catch (JsonSerializationException) { return objectType.IsValueType ? Activator.CreateInstance(objectType) : null; } } } namespace Archipelago.MultiClient.Net { [Serializable] public abstract class ArchipelagoPacketBase { [JsonIgnore] internal JObject jobject; [JsonProperty("cmd")] [JsonConverter(typeof(StringEnumConverter))] public abstract ArchipelagoPacketType PacketType { get; } public JObject ToJObject() { return jobject; } } public interface IArchipelagoSession : IArchipelagoSessionActions { IArchipelagoSocketHelper Socket { get; } IReceivedItemsHelper Items { get; } ILocationCheckHelper Locations { get; } IPlayerHelper Players { get; } IDataStorageHelper DataStorage { get; } IConnectionInfoProvider ConnectionInfo { get; } IRoomStateHelper RoomState { get; } IMessageLogHelper MessageLog { get; } IHintsHelper Hints { get; } Task<RoomInfoPacket> ConnectAsync(); Task<LoginResult> LoginAsync(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true); LoginResult TryConnectAndLogin(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true); } public class ArchipelagoSession : IArchipelagoSession, IArchipelagoSessionActions { private const int ArchipelagoConnectionTimeoutInSeconds = 4; private ConnectionInfoHelper connectionInfo; private TaskCompletionSource<LoginResult> loginResultTask = new TaskCompletionSource<LoginResult>(); private TaskCompletionSource<RoomInfoPacket> roomInfoPacketTask = new TaskCompletionSource<RoomInfoPacket>(); public IArchipelagoSocketHelper Socket { get; } public IReceivedItemsHelper Items { get; } public ILocationCheckHelper Locations { get; } public IPlayerHelper Players { get; } public IDataStorageHelper DataStorage { get; } public IConnectionInfoProvider ConnectionInfo => connectionInfo; public IRoomStateHelper RoomState { get; } public IMessageLogHelper MessageLog { get; } public IHintsHelper Hints { get; } internal ArchipelagoSession(IArchipelagoSocketHelper socket, IReceivedItemsHelper items, ILocationCheckHelper locations, IPlayerHelper players, IRoomStateHelper roomState, ConnectionInfoHelper connectionInfoHelper, IDataStorageHelper dataStorage, IMessageLogHelper messageLog, IHintsHelper createHints) { Socket = socket; Items = items; Locations = locations; Players = players; RoomState = roomState; connectionInfo = connectionInfoHelper; DataStorage = dataStorage; MessageLog = messageLog; Hints = createHints; socket.PacketReceived += Socket_PacketReceived; } private void Socket_PacketReceived(ArchipelagoPacketBase packet) { if (!(packet is ConnectedPacket) && !(packet is ConnectionRefusedPacket)) { if (packet is RoomInfoPacket result) { roomInfoPacketTask.TrySetResult(result); } } else { loginResultTask.TrySetResult(LoginResult.FromPacket(packet)); } } public Task<RoomInfoPacket> ConnectAsync() { roomInfoPacketTask = new TaskCompletionSource<RoomInfoPacket>(); Task.Factory.StartNew(delegate { try { Task task = Socket.ConnectAsync(); task.Wait(TimeSpan.FromSeconds(4.0)); if (!task.IsCompleted) { roomInfoPacketTask.TrySetCanceled(); } } catch (AggregateException) { roomInfoPacketTask.TrySetCanceled(); } }); return roomInfoPacketTask.Task; } public Task<LoginResult> LoginAsync(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true) { loginResultTask = new TaskCompletionSource<LoginResult>(); if (!roomInfoPacketTask.Task.IsCompleted) { loginResultTask.TrySetResult(new LoginFailure("You are not connected, run ConnectAsync() first")); return loginResultTask.Task; } connectionInfo.SetConnectionParameters(game, tags, itemsHandlingFlags, uuid); try { Socket.SendPacket(BuildConnectPacket(name, password, version, requestSlotData)); } catch (ArchipelagoSocketClosedException) { loginResultTask.TrySetResult(new LoginFailure("You are not connected, run ConnectAsync() first")); return loginResultTask.Task; } SetResultAfterTimeout(loginResultTask, 4, new LoginFailure("Connection timed out.")); return loginResultTask.Task; } private static void SetResultAfterTimeout<T>(TaskCompletionSource<T> task, int timeoutInSeconds, T result) { new CancellationTokenSource(TimeSpan.FromSeconds(timeoutInSeconds)).Token.Register(delegate { task.TrySetResult(result); }); } public LoginResult TryConnectAndLogin(string game, string name, ItemsHandlingFlags itemsHandlingFlags, Version version = null, string[] tags = null, string uuid = null, string password = null, bool requestSlotData = true) { Task<RoomInfoPacket> task = ConnectAsync(); try { task.Wait(TimeSpan.FromSeconds(4.0)); } catch (AggregateException ex) { if (ex.GetBaseException() is OperationCanceledException) { return new LoginFailure("Connection timed out."); } return new LoginFailure(ex.GetBaseException().Message); } if (!task.IsCompleted) { return new LoginFailure("Connection timed out."); } return LoginAsync(game, name, itemsHandlingFlags, version, tags, uuid, password, requestSlotData).Result; } private ConnectPacket BuildConnectPacket(string name, string password, Version version, bool requestSlotData) { return new ConnectPacket { Game = ConnectionInfo.Game, Name = name, Password = password, Tags = ConnectionInfo.Tags, Uuid = ConnectionInfo.Uuid, Version = ((version != null) ? new NetworkVersion(version) : new NetworkVersion(0, 6, 0)), ItemsHandling = ConnectionInfo.ItemsHandlingFlags, RequestSlotData = requestSlotData }; } public void Say(string message) { Socket.SendPacket(new SayPacket { Text = message }); } public void SetClientState(ArchipelagoClientState state) { Socket.SendPacket(new StatusUpdatePacket { Status = state }); } public void SetGoalAchieved() { SetClientState(ArchipelagoClientState.ClientGoal); } } public interface IArchipelagoSessionActions { void Say(string message); void SetClientState(ArchipelagoClientState state); void SetGoalAchieved(); } public static class ArchipelagoSessionFactory { public static ArchipelagoSession CreateSession(Uri uri) { ArchipelagoSocketHelper socket = new ArchipelagoSocketHelper(uri); DataPackageCache cache = new DataPackageCache(socket); ConnectionInfoHelper connectionInfoHelper = new ConnectionInfoHelper(socket); PlayerHelper playerHelper = new PlayerHelper(socket, connectionInfoHelper); ItemInfoResolver itemInfoResolver = new ItemInfoResolver(cache, connectionInfoHelper); LocationCheckHelper locationCheckHelper = new LocationCheckHelper(socket, itemInfoResolver, connectionInfoHelper, playerHelper); ReceivedItemsHelper items = new ReceivedItemsHelper(socket, locationCheckHelper, itemInfoResolver, connectionInfoHelper, playerHelper); RoomStateHelper roomStateHelper = new RoomStateHelper(socket, locationCheckHelper); DataStorageHelper dataStorageHelper = new DataStorageHelper(socket, connectionInfoHelper); MessageLogHelper messageLog = new MessageLogHelper(socket, itemInfoResolver, playerHelper, connectionInfoHelper); HintsHelper createHints = new HintsHelper(socket, playerHelper, locationCheckHelper, roomStateHelper, dataStorageHelper); return new ArchipelagoSession(socket, items, locationCheckHelper, playerHelper, roomStateHelper, connectionInfoHelper, dataStorageHelper, messageLog, createHints); } public static ArchipelagoSession CreateSession(string hostname, int port = 38281) { return CreateSession(ParseUri(hostname, port)); } internal static Uri ParseUri(string hostname, int port) { string text = hostname; if (!text.StartsWith("ws://") && !text.StartsWith("wss://")) { text = "unspecified://" + text; } if (!text.Substring(text.IndexOf("://", StringComparison.Ordinal) + 3).Contains(":")) { text += $":{port}"; } if (text.EndsWith(":")) { text += port; } return new Uri(text); } } public abstract class LoginResult { public abstract bool Successful { get; } public static LoginResult FromPacket(ArchipelagoPacketBase packet) { if (!(packet is ConnectedPacket connectedPacket)) { if (packet is ConnectionRefusedPacket connectionRefusedPacket) { return new LoginFailure(connectionRefusedPacket); } throw new ArgumentOutOfRangeException("packet", "packet is not a connection result packet"); } return new LoginSuccessful(connectedPacket); } } public class LoginSuccessful : LoginResult { public override bool Successful => true; public int Team { get; } public int Slot { get; } public Dictionary<string, object> SlotData { get; } public LoginSuccessful(ConnectedPacket connectedPacket) { Team = connectedPacket.Team; Slot = connectedPacket.Slot; SlotData = connectedPacket.SlotData; } } public class LoginFailure : LoginResult { public override bool Successful => false; public ConnectionRefusedError[] ErrorCodes { get; } public string[] Errors { get; } public LoginFailure(ConnectionRefusedPacket connectionRefusedPacket) { if (connectionRefusedPacket.Errors != null) { ErrorCodes = connectionRefusedPacket.Errors.ToArray(); Errors = ErrorCodes.Select(GetErrorMessage).ToArray(); } else { ErrorCodes = new ConnectionRefusedError[0]; Errors = new string[0]; } } public LoginFailure(string message) { ErrorCodes = new ConnectionRefusedError[0]; Errors = new string[1] { message }; } private static string GetErrorMessage(ConnectionRefusedError errorCode) { return errorCode switch { ConnectionRefusedError.InvalidSlot => "The slot name did not match any slot on the server.", ConnectionRefusedError.InvalidGame => "The slot is set to a different game on the server.", ConnectionRefusedError.SlotAlreadyTaken => "The slot already has a connection with a different uuid established.", ConnectionRefusedError.IncompatibleVersion => "The client and server version mismatch.", ConnectionRefusedError.InvalidPassword => "The password is invalid.", ConnectionRefusedError.InvalidItemsHandling => "The item handling flags provided are invalid.", _ => $"Unknown error: {errorCode}.", }; } } internal class TwoWayLookup<TA, TB> : IEnumerable<KeyValuePair<TB, TA>>, IEnumerable { private readonly Dictionary<TA, TB> aToB = new Dictionary<TA, TB>(); private readonly Dictionary<TB, TA> bToA = new Dictionary<TB, TA>(); public TA this[TB b] => bToA[b]; public TB this[TA a] => aToB[a]; public void Add(TA a, TB b) { aToB[a] = b; bToA[b] = a; } public void Add(TB b, TA a) { Add(a, b); } public bool TryGetValue(TA a, out TB b) { return aToB.TryGetValue(a, out b); } public bool TryGetValue(TB b, out TA a) { return bToA.TryGetValue(b, out a); } public IEnumerator<KeyValuePair<TB, TA>> GetEnumerator() { return bToA.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } namespace Archipelago.MultiClient.Net.Packets { public class BouncedPacket : BouncePacket { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Bounced; } public class BouncePacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Bounce; [JsonProperty("games")] public List<string> Games { get; set; } = new List<string>(); [JsonProperty("slots")] public List<int> Slots { get; set; } = new List<int>(); [JsonProperty("tags")] public List<string> Tags { get; set; } = new List<string>(); [JsonProperty("data")] public Dictionary<string, JToken> Data { get; set; } } public class ConnectedPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Connected; [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } [JsonProperty("players")] public NetworkPlayer[] Players { get; set; } [JsonProperty("missing_locations")] public long[] MissingChecks { get; set; } [JsonProperty("checked_locations")] public long[] LocationsChecked { get; set; } [JsonProperty("slot_data")] public Dictionary<string, object> SlotData { get; set; } [JsonProperty("slot_info")] public Dictionary<int, NetworkSlot> SlotInfo { get; set; } [JsonProperty("hint_points")] public int? HintPoints { get; set; } } public class ConnectionRefusedPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ConnectionRefused; [JsonProperty("errors", ItemConverterType = typeof(AttemptingStringEnumConverter))] public ConnectionRefusedError[] Errors { get; set; } } public class ConnectPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Connect; [JsonProperty("password")] public string Password { get; set; } [JsonProperty("game")] public string Game { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("uuid")] public string Uuid { get; set; } [JsonProperty("version")] public NetworkVersion Version { get; set; } [JsonProperty("tags")] public string[] Tags { get; set; } [JsonProperty("items_handling")] public ItemsHandlingFlags ItemsHandling { get; set; } [JsonProperty("slot_data")] public bool RequestSlotData { get; set; } } public class ConnectUpdatePacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ConnectUpdate; [JsonProperty("tags")] public string[] Tags { get; set; } [JsonProperty("items_handling")] public ItemsHandlingFlags? ItemsHandling { get; set; } } public class CreateHintsPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.CreateHints; [JsonProperty("locations")] public long[] Locations { get; set; } [JsonProperty("player")] public int Player { get; set; } [JsonProperty("status")] public HintStatus Status { get; set; } } public class DataPackagePacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.DataPackage; [JsonProperty("data")] public Archipelago.MultiClient.Net.Models.DataPackage DataPackage { get; set; } } public class GetDataPackagePacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.GetDataPackage; [JsonProperty("games")] public string[] Games { get; set; } } public class GetPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Get; [JsonProperty("keys")] public string[] Keys { get; set; } } public class InvalidPacketPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.InvalidPacket; [JsonProperty("type")] public InvalidPacketErrorType ErrorType { get; set; } [JsonProperty("text")] public string ErrorText { get; set; } [JsonProperty("original_cmd")] public ArchipelagoPacketType OriginalCmd { get; set; } } public class LocationChecksPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationChecks; [JsonProperty("locations")] public long[] Locations { get; set; } } public class LocationInfoPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationInfo; [JsonProperty("locations")] public NetworkItem[] Locations { get; set; } } public class LocationScoutsPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.LocationScouts; [JsonProperty("locations")] public long[] Locations { get; set; } [JsonProperty("create_as_hint")] public int CreateAsHint { get; set; } } public class PrintJsonPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.PrintJSON; [JsonProperty("data")] public JsonMessagePart[] Data { get; set; } [JsonProperty("type")] [JsonConverter(typeof(AttemptingStringEnumConverter))] public JsonMessageType? MessageType { get; set; } } public class ItemPrintJsonPacket : PrintJsonPacket { [JsonProperty("receiving")] public int ReceivingPlayer { get; set; } [JsonProperty("item")] public NetworkItem Item { get; set; } } public class ItemCheatPrintJsonPacket : PrintJsonPacket { [JsonProperty("receiving")] public int ReceivingPlayer { get; set; } [JsonProperty("item")] public NetworkItem Item { get; set; } [JsonProperty("team")] public int Team { get; set; } } public class HintPrintJsonPacket : PrintJsonPacket { [JsonProperty("receiving")] public int ReceivingPlayer { get; set; } [JsonProperty("item")] public NetworkItem Item { get; set; } [JsonProperty("found")] public bool? Found { get; set; } } public class JoinPrintJsonPacket : PrintJsonPacket { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } [JsonProperty("tags")] public string[] Tags { get; set; } } public class LeavePrintJsonPacket : PrintJsonPacket { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } } public class ChatPrintJsonPacket : PrintJsonPacket { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } [JsonProperty("message")] public string Message { get; set; } } public class ServerChatPrintJsonPacket : PrintJsonPacket { [JsonProperty("message")] public string Message { get; set; } } public class TutorialPrintJsonPacket : PrintJsonPacket { } public class TagsChangedPrintJsonPacket : PrintJsonPacket { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } [JsonProperty("tags")] public string[] Tags { get; set; } } public class CommandResultPrintJsonPacket : PrintJsonPacket { } public class AdminCommandResultPrintJsonPacket : PrintJsonPacket { } public class GoalPrintJsonPacket : PrintJsonPacket { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } } public class ReleasePrintJsonPacket : PrintJsonPacket { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } } public class CollectPrintJsonPacket : PrintJsonPacket { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } } public class CountdownPrintJsonPacket : PrintJsonPacket { [JsonProperty("countdown")] public int RemainingSeconds { get; set; } } public class ReceivedItemsPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.ReceivedItems; [JsonProperty("index")] public int Index { get; set; } [JsonProperty("items")] public NetworkItem[] Items { get; set; } } public class RetrievedPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Retrieved; [JsonProperty("keys")] public Dictionary<string, JToken> Data { get; set; } } public class RoomInfoPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.RoomInfo; [JsonProperty("version")] public NetworkVersion Version { get; set; } [JsonProperty("generator_version")] public NetworkVersion GeneratorVersion { get; set; } [JsonProperty("tags")] public string[] Tags { get; set; } [JsonProperty("password")] public bool Password { get; set; } [JsonProperty("permissions")] public Dictionary<string, Permissions> Permissions { get; set; } [JsonProperty("hint_cost")] public int HintCostPercentage { get; set; } [JsonProperty("location_check_points")] public int LocationCheckPoints { get; set; } [JsonProperty("players")] public NetworkPlayer[] Players { get; set; } [JsonProperty("games")] public string[] Games { get; set; } [JsonProperty("datapackage_checksums")] public Dictionary<string, string> DataPackageChecksums { get; set; } [JsonProperty("seed_name")] public string SeedName { get; set; } [JsonProperty("time")] public double Timestamp { get; set; } } public class RoomUpdatePacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.RoomUpdate; [JsonProperty("tags")] public string[] Tags { get; set; } [JsonProperty("password")] public bool? Password { get; set; } [JsonProperty("permissions")] public Dictionary<string, Permissions> Permissions { get; set; } = new Dictionary<string, Permissions>(); [JsonProperty("hint_cost")] public int? HintCostPercentage { get; set; } [JsonProperty("location_check_points")] public int? LocationCheckPoints { get; set; } [JsonProperty("players")] public NetworkPlayer[] Players { get; set; } [JsonProperty("hint_points")] public int? HintPoints { get; set; } [JsonProperty("checked_locations")] public long[] CheckedLocations { get; set; } } public class SayPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Say; [JsonProperty("text")] public string Text { get; set; } } public class SetNotifyPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.SetNotify; [JsonProperty("keys")] public string[] Keys { get; set; } } public class SetPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Set; [JsonProperty("key")] public string Key { get; set; } [JsonProperty("default")] public JToken DefaultValue { get; set; } [JsonProperty("operations")] public OperationSpecification[] Operations { get; set; } [JsonProperty("want_reply")] public bool WantReply { get; set; } [JsonExtensionData] public Dictionary<string, JToken> AdditionalArguments { get; set; } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { AdditionalArguments?.Remove("cmd"); } } public class SetReplyPacket : SetPacket { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.SetReply; [JsonProperty("value")] public JToken Value { get; set; } [JsonProperty("original_value")] public JToken OriginalValue { get; set; } } public class StatusUpdatePacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.StatusUpdate; [JsonProperty("status")] public ArchipelagoClientState Status { get; set; } } public class SyncPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Sync; } internal class UnknownPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.Unknown; } public class UpdateHintPacket : ArchipelagoPacketBase { public override ArchipelagoPacketType PacketType => ArchipelagoPacketType.UpdateHint; [JsonProperty("player")] public int Player { get; set; } [JsonProperty("location")] public long Location { get; set; } [JsonProperty("status")] public HintStatus Status { get; set; } } } namespace Archipelago.MultiClient.Net.Models { public struct Color : IEquatable<Color> { public static Color Red = new Color(byte.MaxValue, 0, 0); public static Color Green = new Color(0, 128, 0); public static Color Yellow = new Color(byte.MaxValue, byte.MaxValue, 0); public static Color Blue = new Color(0, 0, byte.MaxValue); public static Color Magenta = new Color(byte.MaxValue, 0, byte.MaxValue); public static Color Cyan = new Color(0, byte.MaxValue, byte.MaxValue); public static Color Black = new Color(0, 0, 0); public static Color White = new Color(byte.MaxValue, byte.MaxValue, byte.MaxValue); public static Color SlateBlue = new Color(106, 90, 205); public static Color Salmon = new Color(250, 128, 114); public static Color Plum = new Color(221, 160, 221); public byte R { get; set; } public byte G { get; set; } public byte B { get; set; } public Color(byte r, byte g, byte b) { R = r; G = g; B = b; } public override bool Equals(object obj) { if (obj is Color color && R == color.R && G == color.G) { return B == color.B; } return false; } public bool Equals(Color other) { if (R == other.R && G == other.G) { return B == other.B; } return false; } public override int GetHashCode() { return ((-1520100960 * -1521134295 + R.GetHashCode()) * -1521134295 + G.GetHashCode()) * -1521134295 + B.GetHashCode(); } public static bool operator ==(Color left, Color right) { return left.Equals(right); } public static bool operator !=(Color left, Color right) { return !(left == right); } } public class DataPackage { [JsonProperty("games")] public Dictionary<string, GameData> Games { get; set; } = new Dictionary<string, GameData>(); } public class DataStorageElement { internal DataStorageElementContext Context; internal List<OperationSpecification> Operations = new List<OperationSpecification>(0); internal DataStorageHelper.DataStorageUpdatedHandler Callbacks; internal Dictionary<string, JToken> AdditionalArguments = new Dictionary<string, JToken>(0); private JToken cachedValue; public event DataStorageHelper.DataStorageUpdatedHandler OnValueChanged { add { Context.AddHandler(Context.Key, value); } remove { Context.RemoveHandler(Context.Key, value); } } internal DataStorageElement(DataStorageElementContext context) { Context = context; } internal DataStorageElement(OperationType operationType, JToken value) { Operations = new List<OperationSpecification>(1) { new OperationSpecification { OperationType = operationType, Value = value } }; } internal DataStorageElement(DataStorageElement source, OperationType operationType, JToken value) : this(source.Context) { Operations = source.Operations.ToList(); Callbacks = source.Callbacks; AdditionalArguments = source.AdditionalArguments; Operations.Add(new OperationSpecification { OperationType = operationType, Value = value }); } internal DataStorageElement(DataStorageElement source, Callback callback) : this(source.Context) { Operations = source.Operations.ToList(); Callbacks = source.Callbacks; AdditionalArguments = source.AdditionalArguments; Callbacks = (DataStorageHelper.DataStorageUpdatedHandler)Delegate.Combine(Callbacks, callback.Method); } internal DataStorageElement(DataStorageElement source, AdditionalArgument additionalArgument) : this(source.Context) { Operations = source.Operations.ToList(); Callbacks = source.Callbacks; AdditionalArguments = source.AdditionalArguments; AdditionalArguments[additionalArgument.Key] = additionalArgument.Value; } public static DataStorageElement operator ++(DataStorageElement a) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(1)); } public static DataStorageElement operator --(DataStorageElement a) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(-1)); } public static DataStorageElement operator +(DataStorageElement a, int b) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b)); } public static DataStorageElement operator +(DataStorageElement a, long b) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b)); } public static DataStorageElement operator +(DataStorageElement a, float b) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b)); } public static DataStorageElement operator +(DataStorageElement a, double b) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b)); } public static DataStorageElement operator +(DataStorageElement a, decimal b) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b)); } public static DataStorageElement operator +(DataStorageElement a, string b) { return new DataStorageElement(a, OperationType.Add, JToken.op_Implicit(b)); } public static DataStorageElement operator +(DataStorageElement a, JToken b) { return new DataStorageElement(a, OperationType.Add, b); } public static DataStorageElement operator +(DataStorageElement a, IEnumerable b) { return new DataStorageElement(a, OperationType.Add, (JToken)(object)JArray.FromObject((object)b)); } public static DataStorageElement operator +(DataStorageElement a, OperationSpecification s) { return new DataStorageElement(a, s.OperationType, s.Value); } public static DataStorageElement operator +(DataStorageElement a, Callback c) { return new DataStorageElement(a, c); } public static DataStorageElement operator +(DataStorageElement a, AdditionalArgument arg) { return new DataStorageElement(a, arg); } public static DataStorageElement operator *(DataStorageElement a, int b) { return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b)); } public static DataStorageElement operator *(DataStorageElement a, long b) { return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b)); } public static DataStorageElement operator *(DataStorageElement a, float b) { return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b)); } public static DataStorageElement operator *(DataStorageElement a, double b) { return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b)); } public static DataStorageElement operator *(DataStorageElement a, decimal b) { return new DataStorageElement(a, OperationType.Mul, JToken.op_Implicit(b)); } public static DataStorageElement operator %(DataStorageElement a, int b) { return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b)); } public static DataStorageElement operator %(DataStorageElement a, long b) { return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b)); } public static DataStorageElement operator %(DataStorageElement a, float b) { return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b)); } public static DataStorageElement operator %(DataStorageElement a, double b) { return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b)); } public static DataStorageElement operator %(DataStorageElement a, decimal b) { return new DataStorageElement(a, OperationType.Mod, JToken.op_Implicit(b)); } public static DataStorageElement operator ^(DataStorageElement a, int b) { return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b)); } public static DataStorageElement operator ^(DataStorageElement a, long b) { return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b)); } public static DataStorageElement operator ^(DataStorageElement a, float b) { return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b)); } public static DataStorageElement operator ^(DataStorageElement a, double b) { return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b)); } public static DataStorageElement operator ^(DataStorageElement a, decimal b) { return new DataStorageElement(a, OperationType.Pow, JToken.op_Implicit(b)); } public static DataStorageElement operator -(DataStorageElement a, int b) { return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b))); } public static DataStorageElement operator -(DataStorageElement a, long b) { return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b))); } public static DataStorageElement operator -(DataStorageElement a, float b) { return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(0f - b))); } public static DataStorageElement operator -(DataStorageElement a, double b) { return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(0.0 - b))); } public static DataStorageElement operator -(DataStorageElement a, decimal b) { return new DataStorageElement(a, OperationType.Add, JToken.FromObject((object)(-b))); } public static DataStorageElement operator /(DataStorageElement a, int b) { return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / (decimal)b))); } public static DataStorageElement operator /(DataStorageElement a, long b) { return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / (decimal)b))); } public static DataStorageElement operator /(DataStorageElement a, float b) { return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1.0 / (double)b))); } public static DataStorageElement operator /(DataStorageElement a, double b) { return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1.0 / b))); } public static DataStorageElement operator /(DataStorageElement a, decimal b) { return new DataStorageElement(a, OperationType.Mul, JToken.FromObject((object)(1m / b))); } public static implicit operator DataStorageElement(bool b) { return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(b)); } public static implicit operator DataStorageElement(int i) { return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(i)); } public static implicit operator DataStorageElement(long l) { return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(l)); } public static implicit operator DataStorageElement(decimal m) { return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(m)); } public static implicit operator DataStorageElement(double d) { return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(d)); } public static implicit operator DataStorageElement(float f) { return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(f)); } public static implicit operator DataStorageElement(string s) { if (s != null) { return new DataStorageElement(OperationType.Replace, JToken.op_Implicit(s)); } return new DataStorageElement(OperationType.Replace, (JToken)(object)JValue.CreateNull()); } public static implicit operator DataStorageElement(JToken o) { return new DataStorageElement(OperationType.Replace, o); } public static implicit operator DataStorageElement(Array a) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)a)); } public static implicit operator DataStorageElement(List<bool> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator DataStorageElement(List<int> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator DataStorageElement(List<long> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator DataStorageElement(List<decimal> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator DataStorageElement(List<double> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator DataStorageElement(List<float> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator DataStorageElement(List<string> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator DataStorageElement(List<object> l) { return new DataStorageElement(OperationType.Replace, (JToken)(object)JArray.FromObject((object)l)); } public static implicit operator bool(DataStorageElement e) { return RetrieveAndReturnBoolValue<bool>(e); } public static implicit operator bool?(DataStorageElement e) { return RetrieveAndReturnBoolValue<bool?>(e); } public static implicit operator int(DataStorageElement e) { return RetrieveAndReturnDecimalValue<int>(e); } public static implicit operator int?(DataStorageElement e) { return RetrieveAndReturnDecimalValue<int?>(e); } public static implicit operator long(DataStorageElement e) { return RetrieveAndReturnDecimalValue<long>(e); } public static implicit operator long?(DataStorageElement e) { return RetrieveAndReturnDecimalValue<long?>(e); } public static implicit operator float(DataStorageElement e) { return RetrieveAndReturnDecimalValue<float>(e); } public static implicit operator float?(DataStorageElement e) { return RetrieveAndReturnDecimalValue<float?>(e); } public static implicit operator double(DataStorageElement e) { return RetrieveAndReturnDecimalValue<double>(e); } public static implicit operator double?(DataStorageElement e) { return RetrieveAndReturnDecimalValue<double?>(e); } public static implicit operator decimal(DataStorageElement e) { return RetrieveAndReturnDecimalValue<decimal>(e); } public static implicit operator decimal?(DataStorageElement e) { return RetrieveAndReturnDecimalValue<decimal?>(e); } public static implicit operator string(DataStorageElement e) { return RetrieveAndReturnStringValue(e); } public static implicit operator bool[](DataStorageElement e) { return RetrieveAndReturnArrayValue<bool[]>(e); } public static implicit operator int[](DataStorageElement e) { return RetrieveAndReturnArrayValue<int[]>(e); } public static implicit operator long[](DataStorageElement e) { return RetrieveAndReturnArrayValue<long[]>(e); } public static implicit operator decimal[](DataStorageElement e) { return RetrieveAndReturnArrayValue<decimal[]>(e); } public static implicit operator double[](DataStorageElement e) { return RetrieveAndReturnArrayValue<double[]>(e); } public static implicit operator float[](DataStorageElement e) { return RetrieveAndReturnArrayValue<float[]>(e); } public static implicit operator string[](DataStorageElement e) { return RetrieveAndReturnArrayValue<string[]>(e); } public static implicit operator object[](DataStorageElement e) { return RetrieveAndReturnArrayValue<object[]>(e); } public static implicit operator List<bool>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<bool>>(e); } public static implicit operator List<int>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<int>>(e); } public static implicit operator List<long>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<long>>(e); } public static implicit operator List<decimal>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<decimal>>(e); } public static implicit operator List<double>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<double>>(e); } public static implicit operator List<float>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<float>>(e); } public static implicit operator List<string>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<string>>(e); } public static implicit operator List<object>(DataStorageElement e) { return RetrieveAndReturnArrayValue<List<object>>(e); } public static implicit operator Array(DataStorageElement e) { return RetrieveAndReturnArrayValue<Array>(e); } public static implicit operator JArray(DataStorageElement e) { return RetrieveAndReturnArrayValue<JArray>(e); } public static implicit operator JToken(DataStorageElement e) { return e.Context.GetData(e.Context.Key); } public static DataStorageElement operator +(DataStorageElement a, BigInteger b) { return new DataStorageElement(a, OperationType.Add, JToken.Parse(b.ToString())); } public static DataStorageElement operator *(DataStorageElement a, BigInteger b) { return new DataStorageElement(a, OperationType.Mul, JToken.Parse(b.ToString())); } public static DataStorageElement operator %(DataStorageElement a, BigInteger b) { return new DataStorageElement(a, OperationType.Mod, JToken.Parse(b.ToString())); } public static DataStorageElement operator ^(DataStorageElement a, BigInteger b) { return new DataStorageElement(a, OperationType.Pow, JToken.Parse(b.ToString())); } public static DataStorageElement operator -(DataStorageElement a, BigInteger b) { return new DataStorageElement(a, OperationType.Add, JToken.Parse((-b).ToString())); } public static DataStorageElement operator /(DataStorageElement a, BigInteger b) { throw new InvalidOperationException("DataStorage[Key] / BigInterger is not supported, due to loss of precision when using integer division"); } public static implicit operator DataStorageElement(BigInteger bi) { return new DataStorageElement(OperationType.Replace, JToken.Parse(bi.ToString())); } public static implicit operator BigInteger(DataStorageElement e) { return RetrieveAndReturnBigIntegerValue<BigInteger>(e); } public static implicit operator BigInteger?(DataStorageElement e) { return RetrieveAndReturnBigIntegerValue<BigInteger?>(e); } private static T RetrieveAndReturnBigIntegerValue<T>(DataStorageElement e) { if (e.cachedValue != null) { if (!BigInteger.TryParse(((object)e.cachedValue).ToString(), out var result)) { return default(T); } return (T)Convert.ChangeType(result, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T)); } BigInteger result2; BigInteger? bigInteger = (BigInteger.TryParse(((object)e.Context.GetData(e.Context.Key)).ToString(), out result2) ? new BigInteger?(result2) : null); if (!bigInteger.HasValue && !IsNullable<T>()) { bigInteger = Activator.CreateInstance<BigInteger>(); } foreach (OperationSpecification operation in e.Operations) { if (operation.OperationType == OperationType.Floor || operation.OperationType == OperationType.Ceil) { continue; } if (!BigInteger.TryParse(((object)operation.Value).ToString(), NumberStyles.AllowLeadingSign, null, out var result3)) { throw new InvalidOperationException($"DataStorage[Key] cannot be converted to BigInterger as its value its not an integer number, value: {operation.Value}"); } switch (operation.OperationType) { case OperationType.Replace: bigInteger = result3; break; case OperationType.Add: bigInteger += result3; break; case OperationType.Mul: bigInteger *= result3; break; case OperationType.Mod: bigInteger %= result3; break; case OperationType.Pow: bigInteger = BigInteger.Pow(bigInteger.Value, (int)operation.Value); break; case OperationType.Max: { BigInteger value = result3; BigInteger? bigInteger2 = bigInteger; if (value > bigInteger2) { bigInteger = result3; } break; } case OperationType.Min: { BigInteger value = result3; BigInteger? bigInteger2 = bigInteger; if (value < bigInteger2) { bigInteger = result3; } break; } case OperationType.Xor: bigInteger ^= result3; break; case OperationType.Or: bigInteger |= result3; break; case OperationType.And: bigInteger &= result3; break; case OperationType.LeftShift: bigInteger <<= (int)operation.Value; break; case OperationType.RightShift: bigInteger >>= (int)operation.Value; break; } } e.cachedValue = JToken.Parse(bigInteger.ToString()); if (!bigInteger.HasValue) { return default(T); } return (T)Convert.ChangeType(bigInteger.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T)); } public void Initialize(JToken value) { Context.Initialize(Context.Key, value); } public void Initialize(IEnumerable value) { Context.Initialize(Context.Key, (JToken)(object)JArray.FromObject((object)value)); } public Task<T> GetAsync<T>() { return GetAsync().ContinueWith((Task<JToken> r) => r.Result.ToObject<T>()); } public Task<JToken> GetAsync() { return Context.GetAsync(Context.Key); } private static T RetrieveAndReturnArrayValue<T>(DataStorageElement e) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Invalid comparison between Unknown and I4 //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_00d8: Unknown result type (might be due to invalid IL or missing references) if (e.cachedValue != null) { return ((JToken)(JArray)e.cachedValue).ToObject<T>(); } JArray val = (JArray)(((object)e.Context.GetData(e.Context.Key).ToObject<JArray>()) ?? ((object)new JArray())); foreach (OperationSpecification operation in e.Operations) { switch (operation.OperationType) { case OperationType.Add: if ((int)operation.Value.Type != 2) { throw new InvalidOperationException($"Cannot perform operation {OperationType.Add} on Array value, with a non Array value: {operation.Value}"); } ((JContainer)val).Merge((object)operation.Value); break; case OperationType.Replace: if ((int)operation.Value.Type != 2) { throw new InvalidOperationException($"Cannot replace Array value, with a non Array value: {operation.Value}"); } val = (JArray)(((object)operation.Value.ToObject<JArray>()) ?? ((object)new JArray())); break; default: throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on Array value"); } } e.cachedValue = (JToken)(object)val; return ((JToken)val).ToObject<T>(); } private static string RetrieveAndReturnStringValue(DataStorageElement e) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Invalid comparison between Unknown and I4 //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Invalid comparison between Unknown and I4 if (e.cachedValue != null) { return (string)e.cachedValue; } JToken val = e.Context.GetData(e.Context.Key); string text = (((int)val.Type == 10) ? null : ((object)val).ToString()); foreach (OperationSpecification operation in e.Operations) { switch (operation.OperationType) { case OperationType.Add: text += (string)operation.Value; break; case OperationType.Mul: if ((int)operation.Value.Type != 6) { throw new InvalidOperationException($"Cannot perform operation {OperationType.Mul} on string value, with a non interger value: {operation.Value}"); } text = string.Concat(Enumerable.Repeat(text, (int)operation.Value)); break; case OperationType.Replace: text = (string)operation.Value; break; default: throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on string value"); } } if (text == null) { e.cachedValue = (JToken)(object)JValue.CreateNull(); } else { e.cachedValue = JToken.op_Implicit(text); } return (string)e.cachedValue; } private static T RetrieveAndReturnBoolValue<T>(DataStorageElement e) { if (e.cachedValue != null) { return e.cachedValue.ToObject<T>(); } bool? flag = e.Context.GetData(e.Context.Key).ToObject<bool?>() ?? ((bool?)Activator.CreateInstance(typeof(T))); foreach (OperationSpecification operation in e.Operations) { if (operation.OperationType == OperationType.Replace) { flag = (bool?)operation.Value; continue; } throw new InvalidOperationException($"Cannot perform operation {operation.OperationType} on boolean value"); } e.cachedValue = JToken.op_Implicit(flag); if (!flag.HasValue) { return default(T); } return (T)Convert.ChangeType(flag.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T)); } private static T RetrieveAndReturnDecimalValue<T>(DataStorageElement e) { if (e.cachedValue != null) { return e.cachedValue.ToObject<T>(); } decimal? num = e.Context.GetData(e.Context.Key).ToObject<decimal?>(); if (!num.HasValue && !IsNullable<T>()) { num = Activator.CreateInstance<decimal>(); } foreach (OperationSpecification operation in e.Operations) { switch (operation.OperationType) { case OperationType.Replace: num = (decimal)operation.Value; break; case OperationType.Add: num += (decimal?)(decimal)operation.Value; break; case OperationType.Mul: num *= (decimal?)(decimal)operation.Value; break; case OperationType.Mod: num %= (decimal?)(decimal)operation.Value; break; case OperationType.Pow: num = (decimal)Math.Pow((double)num.Value, (double)operation.Value); break; case OperationType.Max: num = Math.Max(num.Value, (decimal)operation.Value); break; case OperationType.Min: num = Math.Min(num.Value, (decimal)operation.Value); break; case OperationType.Xor: num = (long)num.Value ^ (long)operation.Value; break; case OperationType.Or: num = (long)num.Value | (long)operation.Value; break; case OperationType.And: num = (long)num.Value & (long)operation.Value; break; case OperationType.LeftShift: num = (long)num.Value << (int)operation.Value; break; case OperationType.RightShift: num = (long)num.Value >> (int)operation.Value; break; case OperationType.Floor: num = Math.Floor(num.Value); break; case OperationType.Ceil: num = Math.Ceiling(num.Value); break; } } e.cachedValue = JToken.op_Implicit(num); if (!num.HasValue) { return default(T); } return (T)Convert.ChangeType(num.Value, IsNullable<T>() ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T)); } private static bool IsNullable<T>() { if (typeof(T).IsGenericType) { return typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition(); } return false; } public T To<T>() { if (Operations.Count != 0) { throw new InvalidOperationException("DataStorageElement.To<T>() cannot be used together with other operations on the DataStorageElement"); } return Context.GetData(Context.Key).ToObject<T>(); } public override string ToString() { return (Context?.ToString() ?? "(null)") + ", (" + ListOperations() + ")"; } private string ListOperations() { if (Operations != null) { return string.Join(", ", Operations.Select((OperationSpecification o) => o.ToString()).ToArray()); } return "none"; } } internal class DataStorageElementContext { internal string Key { get; set; } internal Action<string, DataStorageHelper.DataStorageUpdatedHandler> AddHandler { get; set; } internal Action<string, DataStorageHelper.DataStorageUpdatedHandler> RemoveHandler { get; set; } internal Func<string, JToken> GetData { get; set; } internal Action<string, JToken> Initialize { get; set; } internal Func<string, Task<JToken>> GetAsync { get; set; } public override string ToString() { return "Key: " + Key; } } public class GameData { [JsonProperty("location_name_to_id")] public Dictionary<string, long> LocationLookup { get; set; } = new Dictionary<string, long>(); [JsonProperty("item_name_to_id")] public Dictionary<string, long> ItemLookup { get; set; } = new Dictionary<string, long>(); [Obsolete("use Checksum instead")] [JsonProperty("version")] public int Version { get; set; } [JsonProperty("checksum")] public string Checksum { get; set; } } public class Hint { [JsonProperty("receiving_player")] public int ReceivingPlayer { get; set; } [JsonProperty("finding_player")] public int FindingPlayer { get; set; } [JsonProperty("item")] public long ItemId { get; set; } [JsonProperty("location")] public long LocationId { get; set; } [JsonProperty("item_flags")] public ItemFlags ItemFlags { get; set; } [JsonProperty("found")] public bool Found { get; set; } [JsonProperty("entrance")] public string Entrance { get; set; } [JsonProperty("status")] public HintStatus Status { get; set; } } public class ItemInfo { private readonly IItemInfoResolver itemInfoResolver; public long ItemId { get; } public long LocationId { get; } public PlayerInfo Player { get; } public ItemFlags Flags { get; } public string ItemName => itemInfoResolver.GetItemName(ItemId, ItemGame); public string ItemDisplayName => ItemName ?? $"Item: {ItemId}"; public string LocationName => itemInfoResolver.GetLocationName(LocationId, LocationGame); public string LocationDisplayName => LocationName ?? $"Location: {LocationId}"; public string ItemGame { get; } public string LocationGame { get; } public ItemInfo(NetworkItem item, string receiverGame, string senderGame, IItemInfoResolver itemInfoResolver, PlayerInfo player) { this.itemInfoResolver = itemInfoResolver; ItemGame = receiverGame; LocationGame = senderGame; ItemId = item.Item; LocationId = item.Location; Flags = item.Flags; Player = player; } public SerializableItemInfo ToSerializable() { return new SerializableItemInfo { IsScout = (GetType() == typeof(ScoutedItemInfo)), ItemId = ItemId, LocationId = LocationId, PlayerSlot = Player, Player = Player, Flags = Flags, ItemGame = ItemGame, ItemName = ItemName, LocationGame = LocationGame, LocationName = LocationName }; } } public class ScoutedItemInfo : ItemInfo { public new PlayerInfo Player => base.Player; public bool IsReceiverRelatedToActivePlayer { get; } public ScoutedItemInfo(NetworkItem item, string receiverGame, string senderGame, IItemInfoResolver itemInfoResolver, IPlayerHelper players, PlayerInfo player) : base(item, receiverGame, senderGame, itemInfoResolver, player) { IsReceiverRelatedToActivePlayer = (players.ActivePlayer ?? new PlayerInfo()).IsRelatedTo(player); } } public class JsonMessagePart { [JsonProperty("type")] [JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })] public JsonMessagePartType? Type { get; set; } [JsonProperty("color")] [JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })] public JsonMessagePartColor? Color { get; set; } [JsonProperty("text")] public string Text { get; set; } [JsonProperty("player")] public int? Player { get; set; } [JsonProperty("flags")] public ItemFlags? Flags { get; set; } [JsonProperty("hint_status")] public HintStatus? HintStatus { get; set; } } public struct NetworkItem { [JsonProperty("item")] public long Item { get; set; } [JsonProperty("location")] public long Location { get; set; } [JsonProperty("player")] public int Player { get; set; } [JsonProperty("flags")] public ItemFlags Flags { get; set; } } public struct NetworkPlayer { [JsonProperty("team")] public int Team { get; set; } [JsonProperty("slot")] public int Slot { get; set; } [JsonProperty("alias")] public string Alias { get; set; } [JsonProperty("name")] public string Name { get; set; } } public struct NetworkSlot { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("game")] public string Game { get; set; } [JsonProperty("type")] public SlotType Type { get; set; } [JsonProperty("group_members")] public int[] GroupMembers { get; set; } } public class NetworkVersion { [JsonProperty("major")] public int Major { get; set; } [JsonProperty("minor")] public int Minor { get; set; } [JsonProperty("build")] public int Build { get; set; } [JsonProperty("class")] public string Class => "Version"; public NetworkVersion() { } public NetworkVersion(int major, int minor, int build) { Major = major; Minor = minor; Build = build; } public NetworkVersion(Version version) { Major = version.Major; Minor = version.Minor; Build = version.Build; } public Version ToVersion() { return new Version(Major, Minor, Build); } } public class OperationSpecification { [JsonProperty("operation")] [JsonConverter(typeof(AttemptingStringEnumConverter), new object[] { typeof(SnakeCaseNamingStrategy) })] public OperationType OperationType; [JsonProperty("value")] public JToken Value { get; set; } public override string ToString() { return $"{OperationType}: {Value}"; } } public static class Operation { public static OperationSpecification Min(int i) { return new OperationSpecification { OperationType = OperationType.Min, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Min(long i) { return new OperationSpecification { OperationType = OperationType.Min, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Min(float i) { return new OperationSpecification { OperationType = OperationType.Min, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Min(double i) { return new OperationSpecification { OperationType = OperationType.Min, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Min(decimal i) { return new OperationSpecification { OperationType = OperationType.Min, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Min(JToken i) { return new OperationSpecification { OperationType = OperationType.Min, Value = i }; } public static OperationSpecification Min(BigInteger i) { return new OperationSpecification { OperationType = OperationType.Min, Value = JToken.Parse(i.ToString()) }; } public static OperationSpecification Max(int i) { return new OperationSpecification { OperationType = OperationType.Max, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Max(long i) { return new OperationSpecification { OperationType = OperationType.Max, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Max(float i) { return new OperationSpecification { OperationType = OperationType.Max, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Max(double i) { return new OperationSpecification { OperationType = OperationType.Max, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Max(decimal i) { return new OperationSpecification { OperationType = OperationType.Max, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Max(JToken i) { return new OperationSpecification { OperationType = OperationType.Max, Value = i }; } public static OperationSpecification Max(BigInteger i) { return new OperationSpecification { OperationType = OperationType.Max, Value = JToken.Parse(i.ToString()) }; } public static OperationSpecification Remove(JToken value) { return new OperationSpecification { OperationType = OperationType.Remove, Value = value }; } public static OperationSpecification Pop(int value) { return new OperationSpecification { OperationType = OperationType.Pop, Value = JToken.op_Implicit(value) }; } public static OperationSpecification Pop(JToken value) { return new OperationSpecification { OperationType = OperationType.Pop, Value = value }; } public static OperationSpecification Update(IDictionary dictionary) { return new OperationSpecification { OperationType = OperationType.Update, Value = (JToken)(object)JObject.FromObject((object)dictionary) }; } public static OperationSpecification Floor() { return new OperationSpecification { OperationType = OperationType.Floor, Value = null }; } public static OperationSpecification Ceiling() { return new OperationSpecification { OperationType = OperationType.Ceil, Value = null }; } } public static class Bitwise { public static OperationSpecification Xor(long i) { return new OperationSpecification { OperationType = OperationType.Xor, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Xor(BigInteger i) { return new OperationSpecification { OperationType = OperationType.Xor, Value = JToken.Parse(i.ToString()) }; } public static OperationSpecification Or(long i) { return new OperationSpecification { OperationType = OperationType.Or, Value = JToken.op_Implicit(i) }; } public static OperationSpecification Or(BigInteger i) { return new OperationSpecification { OperationType = OperationType.Or, Value = JToken.Parse(i.ToString()) }; } public static OperationSpecification And(long i) { return new OperationSpecification { OperationType = OperationType.And, Value = JToken.op_Implicit(i) }; } public static OperationSpecification And(BigInteger i) { return new OperationSpecification { OperationType = OperationType.And, Value = JToken.Parse(i.ToString()) }; } public static OperationSpecification LeftShift(long i) { return new OperationSpecification { OperationType = OperationType.LeftShift, Value = JToken.op_Implicit(i) }; } public static OperationSpecification RightShift(long i) { return new OperationSpecification { OperationType = OperationType.RightShift, Value = JToken.op_Implicit(i) }; } } public class Callback { internal DataStorageHelper.DataStorageUpdatedHandler Method { get; set; } private Callback() { } public static Callback Add(DataStorageHelper.DataStorageUpdatedHandler callback) { return new Callback { Method = callback }; } } public class AdditionalArgument { internal string Key { get; set; } internal JToken Value { get; set; } private AdditionalArgument() { } public static AdditionalArgument Add(string name, JToken value) { return new AdditionalArgument { Key = name, Value = value }; } } public class MinimalSerializableItemInfo { public long ItemId { get; set; } public long LocationId { get; set; } public int PlayerSlot { get; set; } public ItemFlags Flags { get; set; } public string ItemGame { get; set; } public string LocationGame { get; set; } } public class SerializableItemInfo : MinimalSerializableItemInfo { public bool IsScout { get; set; } public PlayerInfo Player { get; set; } public string ItemName { get; set; } public string LocationName { get; set; } [JsonIgnore] public string ItemDisplayName => ItemName ?? $"Item: {base.ItemId}"; [JsonIgnore] public string LocationDisplayName => LocationName ?? $"Location: {base.LocationId}"; public string ToJson(bool full = false) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown MinimalSerializableItemInfo minimalSerializableItemInfo = this; if (!full) { minimalSerializableItemInfo = new MinimalSerializableItemInfo { ItemId = base.ItemId, LocationId = base.LocationId, PlayerSlot = base.PlayerSlot, Flags = base.Flags }; if (IsScout) { minimalSerializableItemInfo.ItemGame = base.ItemGame; } else { minimalSerializableItemInfo.LocationGame = base.LocationGame; } } JsonSerializerSettings val = new JsonSerializerSettings { NullValueHandling = (NullValueHandling)1, Formatting = (Formatting)0 }; return JsonConvert.SerializeObject((object)minimalSerializableItemInfo, val); } public static SerializableItemInfo FromJson(string json, IArchipelagoSession session = null) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown ItemInfoStreamingContext additional = ((session != null) ? new ItemInfoStreamingContext { Items = session.Items, Locations = session.Locations, PlayerHelper = session.Players, ConnectionInfo = session.ConnectionInfo } : null); JsonSerializerSettings val = new JsonSerializerSettings { Context = new StreamingContext(StreamingContextStates.Other, additional) }; return JsonConvert.DeserializeObject<SerializableItemInfo>(json, val); } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext streamingContext) { if (base.ItemGame == null && base.LocationGame != null) { IsScout = false; } else if (base.ItemGame != null && base.LocationGame == null) { IsScout = true; } if (streamingContext.Context is ItemInfoStreamingContext itemInfoStreamingContext) { if (IsScout && base.LocationGame == null) { base.LocationGame = itemInfoStreamingContext.ConnectionInfo.Game; } else if (!IsScout && base.ItemGame == null) { base.ItemGame = itemInfoStreamingContext.ConnectionInfo.Game; } if (ItemName == null) { ItemName = itemInfoStreamingContext.Items.GetItemName(base.ItemId, base.ItemGame); } if (LocationName == null) { LocationName = itemInfoStreamingContext.Locations.GetLocationNameFromId(base.LocationId, base.LocationGame); } if (Player == null) { Player = itemInfoStreamingContext.PlayerHelper.GetPlayerInfo(base.PlayerSlot); } } } } internal class ItemInfoStreamingContext { public IReceivedItemsHelper Items { get; set; } public ILocationCheckHelper Locations { get; set; } public IPlayerHelper PlayerHelper { get; set; } public IConnectionInfoProvider ConnectionInfo { get; set; } } } namespace Archipelago.MultiClient.Net.MessageLog.Parts { public class EntranceMessagePart : MessagePart { internal EntranceMessagePart(JsonMessagePart messagePart) : base(MessagePartType.Entrance, messagePart, Archipelago.MultiClient.Net.Colors.PaletteColor.Blue) { base.Text = messagePart.Text; } } public class HintStatusMessagePart : MessagePart { internal HintStatusMessagePart(JsonMessagePart messagePart) : base(MessagePartType.HintStatus, messagePart) { base.Text = messagePart.Text; if (messagePart.HintStatus.HasValue) { base.PaletteColor = ColorUtils.GetColor(messagePart.HintStatus.Value); } } } public class ItemMessagePart : MessagePart { public ItemFlags Flags { get; } public long ItemId { get; } public int Player { get; } internal ItemMessagePart(IPlayerHelper players, IItemInfoResolver items, JsonMessagePart part) : base(MessagePartType.Item, part) { Flags = part.Flags.GetValueOrDefault(); base.PaletteColor = ColorUtils.GetColor(Flags); Player = part.Player.GetValueOrDefault(); string game = (players.GetPlayerInfo(Player) ?? new PlayerInfo()).Game; JsonMessagePartType? type = part.Type; if (type.HasValue) { switch (type.GetValueOrDefault()) { case JsonMessagePartType.ItemId: ItemId = long.Parse(part.Text); base.Text = items.GetItemName(ItemId, game) ?? $"Item: {ItemId}"; break; case JsonMessagePartType.ItemName: ItemId = 0L; base.Text = part.Text; break; } } } } public class LocationMessagePart : MessagePart { public long LocationId { get; } public int Player { get; } internal LocationMessagePart(IPlayerHelper players, IItemInfoResolver itemInfoResolver, JsonMessagePart part) : base(MessagePartType.Location, part, Archipelago.MultiClient.Net.Colors.PaletteColor.Green) { Player = part.Player.GetValueOrDefault(); string game = (players.GetPlayerInfo(Player) ?? new PlayerInfo()).Game; JsonMessagePartType? type = part.Type; if (type.HasValue) { switch (type.GetValueOrDefault()) { case JsonMessagePartType.LocationId: LocationId = long.Parse(part.Text); base.Text = itemInfoResolver.GetLocationName(LocationId, game) ?? $"Location: {LocationId}"; break; case JsonMessagePartType.LocationName: LocationId = itemInfoResolver.GetLocationId(part.Text, game); base.Text = part.Text; break; } } } } public class MessagePart { public string Text { get; internal set; } public MessagePartType Type { get; internal set; } public Color Color => GetColor(BuiltInPalettes.Dark); public PaletteColor? PaletteColor { get; protected set; } public bool IsBackgroundColor { get; internal set; } internal MessagePart(MessagePartType type, JsonMessagePart messagePart, PaletteColor? color = null) { Type = type; Text = messagePart.Text; if (color.HasValue) { PaletteColor = color.Value; } else if (messagePart.Color.HasValue) { PaletteColor = ColorUtils.GetColor(messagePart.Color.Value); IsBackgroundColor = messagePart.Color.Value >= JsonMessagePartColor.BlackBg; } else { PaletteColor = null; } } public T GetColor<T>(Palette<T> palette) { return palette[PaletteColor]; } public override string ToString() { return Text; } } public enum MessagePartType { Text, Player, Item, Location, Entrance, HintStatus } public class PlayerMessagePart : MessagePart { public bool IsActivePlayer { get; } public int SlotId { get; } internal PlayerMessagePart(IPlayerHelper players, IConnectionInfoProvider connectionInfo, JsonMessagePart part) : base(MessagePartType.Player, part) { switch (part.Type) { case JsonMessagePartType.PlayerId: SlotId = int.Parse(part.Text); IsActivePlayer = SlotId == connectionInfo.Slot; base.Text = players.GetPlayerAlias(SlotId) ?? $"Player {SlotId}"; break; case JsonMessagePartType.PlayerName: SlotId = 0; IsActivePlayer = false; base.Text = part.Text; break; } base.PaletteColor = (IsActivePlayer ? Archipelago.MultiClient.Net.Colors.PaletteColor.Magenta : Archipelago.MultiClient.Net.Colors.PaletteColor.Yellow); } } } namespace Archipelago.MultiClient.Net.MessageLog.Messages { public class AdminCommandResultLogMessage : LogMessage { internal AdminCommandResultLogMessage(MessagePart[] parts) : base(parts) { } } public class ChatLogMessage : PlayerSpecificLogMessage { public string Message { get; } internal ChatLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string message) : base(parts, players, team, slot) { Message = message; } } public class CollectLogMessage : PlayerSpecificLogMessage { internal CollectLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot) : base(parts, players, team, slot) { } } public class CommandResultLogMessage : LogMessage { internal CommandResultLogMessage(MessagePart[] parts) : base(parts) { } } public class CountdownLogMessage : LogMessage { public int RemainingSeconds { get; } internal CountdownLogMessage(MessagePart[] parts, int remainingSeconds) : base(parts) { RemainingSeconds = remainingSeconds; } } public class GoalLogMessage : PlayerSpecificLogMessage { internal GoalLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot) : base(parts, players, team, slot) { } } public class HintItemSendLogMessage : ItemSendLogMessage { public bool IsFound { get; } internal HintItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, bool found, IItemInfoResolver itemInfoResolver) : base(parts, players, receiver, sender, item, itemInfoResolver) { IsFound = found; } } public class ItemCheatLogMessage : ItemSendLogMessage { internal ItemCheatLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, NetworkItem item, IItemInfoResolver itemInfoResolver) : base(parts, players, slot, 0, item, team, itemInfoResolver) { } } public class ItemSendLogMessage : LogMessage { private PlayerInfo ActivePlayer { get; } public PlayerInfo Receiver { get; } public PlayerInfo Sender { get; } public bool IsReceiverTheActivePlayer => Receiver == ActivePlayer; public bool IsSenderTheActivePlayer => Sender == ActivePlayer; public bool IsRelatedToActivePlayer { get { if (!ActivePlayer.IsRelatedTo(Receiver)) { return ActivePlayer.IsRelatedTo(Sender); } return true; } } public ItemInfo Item { get; } internal ItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, IItemInfoResolver itemInfoResolver) : this(parts, players, receiver, sender, item, players.ActivePlayer.Team, itemInfoResolver) { } internal ItemSendLogMessage(MessagePart[] parts, IPlayerHelper players, int receiver, int sender, NetworkItem item, int team, IItemInfoResolver itemInfoResolver) : base(parts) { ActivePlayer = players.ActivePlayer ?? new PlayerInfo(); Receiver = players.GetPlayerInfo(team, receiver) ?? new PlayerInfo(); Sender = players.GetPlayerInfo(team, sender) ?? new PlayerInfo(); PlayerInfo player = players.GetPlayerInfo(team, item.Player) ?? new PlayerInfo(); Item = new ItemInfo(item, Receiver.Game, Sender.Game, itemInfoResolver, player); } } public class JoinLogMessage : PlayerSpecificLogMessage { public string[] Tags { get; } internal JoinLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string[] tags) : base(parts, players, team, slot) { Tags = tags; } } public class LeaveLogMessage : PlayerSpecificLogMessage { internal LeaveLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot) : base(parts, players, team, slot) { } } public class LogMessage { public MessagePart[] Parts { get; } internal LogMessage(MessagePart[] parts) { Parts = parts; } public override string ToString() { if (Parts.Length == 1) { return Parts[0].Text; } StringBuilder stringBuilder = new StringBuilder(); MessagePart[] parts = Parts; foreach (MessagePart messagePart in parts) { stringBuilder.Append(messagePart.Text); } return stringBuilder.ToString(); } } public abstract class PlayerSpecificLogMessage : LogMessage { private PlayerInfo ActivePlayer { get; } public PlayerInfo Player { get; } public bool IsActivePlayer => Player == ActivePlayer; public bool IsRelatedToActivePlayer => ActivePlayer.IsRelatedTo(Player); internal PlayerSpecificLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot) : base(parts) { ActivePlayer = players.ActivePlayer ?? new PlayerInfo(); Player = players.GetPlayerInfo(team, slot) ?? new PlayerInfo(); } } public class ReleaseLogMessage : PlayerSpecificLogMessage { internal ReleaseLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot) : base(parts, players, team, slot) { } } public class ServerChatLogMessage : LogMessage { public string Message { get; } internal ServerChatLogMessage(MessagePart[] parts, string message) : base(parts) { Message = message; } } public class TagsChangedLogMessage : PlayerSpecificLogMessage { public string[] Tags { get; } internal TagsChangedLogMessage(MessagePart[] parts, IPlayerHelper players, int team, int slot, string[] tags) : base(parts, players, team, slot) { Tags = tags; } } public class TutorialLogMessage : LogMessage { internal TutorialLogMessage(MessagePart[] parts) : base(parts) { } } } namespace Archipelago.MultiClient.Net.Helpers { public class ArchipelagoSocketHelper : BaseArchipelagoSocketHelper<ClientWebSocket>, IArchipelagoSocketHelper { public Uri Uri { get; } internal ArchipelagoSocketHelper(Uri hostUri) : base(CreateWebSocket(), 1024) { Uri = hostUri; } private static ClientWebSocket CreateWebSocket() { return new ClientWebSocket(); } public async Task ConnectAsync() { await ConnectToProvidedUri(Uri); StartPolling(); } private async Task ConnectToProvidedUri(Uri uri) { if (uri.Scheme != "unspecified") { try { await Socket.ConnectAsync(uri, CancellationToken.None); return; } catch (Exception e) { OnError(e); throw; } } List<Exception> errors = new List<Exception>(0); try { await Socket.ConnectAsync(uri.AsWss(), CancellationToken.None); if (Socket.State == WebSocketState.Open) { return; } } catch (Exception item) { errors.Add(item); Socket = CreateWebSocket(); } try { await Socket.ConnectAsync(uri.AsWs(), CancellationToken.None); } catch (Exception item2) { errors.Add(item2); OnError(new AggregateException(errors)); throw; } } } public class BaseArchipelagoSocketHelper<T> where T : WebSocket { private static readonly ArchipelagoPacketConverter Converter = new ArchipelagoPacketConverter(); private readonly BlockingCollection<Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>> sendQueue = new BlockingCollection<Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>>(); internal T Socket; private readonly int bufferSize; public bool Connected { get { if (Socket.State != WebSocketState.Open) { return Socket.State == WebSocketState.CloseReceived; } return true; } } public event ArchipelagoSocketHelperDelagates.PacketReceivedHandler PacketReceived; public event ArchipelagoSocketHelperDelagates.PacketsSentHandler PacketsSent; public event ArchipelagoSocketHelperDelagates.ErrorReceivedHandler ErrorReceived; public event ArchipelagoSocketHelperDelagates.SocketClosedHandler SocketClosed; public event ArchipelagoSocketHelperDelagates.SocketOpenedHandler SocketOpened; internal BaseArchipelagoSocketHelper(T socket, int bufferSize = 1024) { Socket = socket; this.bufferSize = bufferSize; } internal void StartPolling() { if (this.SocketOpened != null) { this.SocketOpened(); } Task.Run((Func<Task?>)PollingLoop); Task.Run((Func<Task?>)SendLoop); } private async Task PollingLoop() { byte[] buffer = new byte[bufferSize]; while (Socket.State == WebSocketState.Open) { string message = null; try { message = await ReadMessageAsync(buffer); } catch (Exception e) { OnError(e); } OnMessageReceived(message); } } private async Task SendLoop() { while (Socket.State == WebSocketState.Open) { try { await HandleSendBuffer(); } catch (Exception e) { OnError(e); } await Task.Delay(20); } } private async Task<string> ReadMessageAsync(byte[] buffer) { using MemoryStream readStream = new MemoryStream(buffer.Length); WebSocketReceiveResult result; do { result = await Socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { try { await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } catch { } OnSocketClosed(); } else { readStream.Write(buffer, 0, result.Count); } } while (!result.EndOfMessage); return Encoding.UTF8.GetString(readStream.ToArray()); } public async Task DisconnectAsync() { await Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closure requested by client", CancellationToken.None); OnSocketClosed(); } public void SendPacket(ArchipelagoPacketBase packet) { SendMultiplePackets(new List<ArchipelagoPacketBase> { packet }); } public void SendMultiplePackets(List<ArchipelagoPacketBase> packets) { SendMultiplePackets(packets.ToArray()); } public void SendMultiplePackets(params ArchipelagoPacketBase[] packets) { SendMultiplePacketsAsync(packets).Wait(); } public Task SendPacketAsync(ArchipelagoPacketBase packet) { return SendMultiplePacketsAsync(new List<ArchipelagoPacketBase> { packet }); } public Task SendMultiplePacketsAsync(List<ArchipelagoPacketBase> packets) { return SendMultiplePacketsAsync(packets.ToArray()); } public Task SendMultiplePacketsAsync(params ArchipelagoPacketBase[] packets) { TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(); foreach (ArchipelagoPacketBase item in packets) { sendQueue.Add(new Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>>(item, taskCompletionSource)); } return taskCompletionSource.Task; } private async Task HandleSendBuffer() { List<ArchipelagoPacketBase> list = new List<ArchipelagoPacketBase>(); List<TaskCompletionSource<bool>> tasks = new List<TaskCompletionSource<bool>>(); Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>> tuple = sendQueue.Take(); list.Add(tuple.Item1); tasks.Add(tuple.Item2); Tuple<ArchipelagoPacketBase, TaskCompletionSource<bool>> item; while (sendQueue.TryTake(out item)) { list.Add(item.Item1); tasks.Add(item.Item2); } if (!list.Any()) { return; } if (Socket.State != WebSocketState.Open) { throw new ArchipelagoSocketClosedException(); } ArchipelagoPacketBase[] packets = list.ToArray(); string s = JsonConvert.SerializeObject((object)packets); byte[] messageBuffer = Encoding.UTF8.GetBytes(s); int messagesCount = (int)Math.Ceiling((double)messageBuffer.Length / (double)bufferSize); for (int i = 0; i < messagesCount; i++) { int num = bufferSize * i; int num2 = bufferSize; bool endOfMessage = i + 1 == messagesCount; if (num2 * (i + 1) > messageBuffer.Length) { num2 = messageBuffer.Length - num; } await Socket.SendAsync(new ArraySegment<byte>(messageBuffer, num, num2), WebSocketMessageType.Text, endOfMessage, CancellationToken.None); } foreach (TaskCompletionSource<bool> item2 in tasks) { item2.TrySetResult(result: true); } OnPacketSend(packets); } private void OnPacketSend(ArchipelagoPacketBase[] packets) { try { if (this.PacketsSent != null) { this.PacketsSent(packets); } } catch (Exception e) { OnError(e); } } private void OnSocketClosed() { try { if (this.SocketClosed != null) { this.SocketClosed(""); } } catch (Exception e) { OnError(e); } } private void OnMessageReceived(string message) { try { if (string.IsNullOrEmpty(message) || this.PacketReceived == null) { return; } List<ArchipelagoPacketBase> list = null; try { list = JsonConvert.DeserializeObject<List<ArchipelagoPacketBase>>(message, (JsonConverter[])(object)new JsonConverter[1] { Converter }); } catch (Exception e) { OnError(e); } if (list == null) { return; } foreach (ArchipelagoPacketBase item in list) { this.PacketReceived(item); } } catch (Exception e2) { OnError(e2); } } protected void OnError(Exception e) { try { if (this.ErrorReceived != null) { this.ErrorReceived(e, e.Message); } } catch (Exception ex) { Console.Out.WriteLine("Error occured during reporting of errorOuter Errror: " + e.Message + " " + e.StackTrace + "Inner Errror: " + ex.Message + " " + ex.StackTrace); } } } public interface IConnectionInfoProvider { string Game { get; } int Team { get; } int Slot { get; } string[] Tags { get; } ItemsHandlingFlags ItemsHandlingFlags { get; } string Uuid { get; } void UpdateConnectionOptions(string[] tags); void UpdateConnectionOptions(ItemsHandlingFlags itemsHandlingFlags); void UpdateConnectionOptions(string[] tags, ItemsHandlingFlags itemsHandlingFlags); } public class ConnectionInfoHelper : IConnectionInfoProvider { private readonly IArchipelagoSocketHelper socket; public string Game { get; private set; } public int Team { get; private set; } public int Slot { get; private set; } public string[] Tags { get; internal set; } public ItemsHandlingFlags ItemsHandlingFlags { get; internal set; } public string Uuid { get; private set; } internal ConnectionInfoHelper(IArchipelagoSocketHelper socket) { this.socket = socket; Reset(); socket.PacketReceived += PacketReceived; } private void PacketReceived(ArchipelagoPacketBase packet) { if (!(packet is ConnectedPacket connectedPacket)) { if (packet is ConnectionRefusedPacket) { Reset(); } return; } Team = connectedPacket.Team; Slot = connectedPacket.Slot; if (connectedPacket.SlotInfo != null && connectedPacket.SlotInfo.ContainsKey(Slot)) { Game = connectedPacket.SlotInfo[Slot].Game; } } internal void SetConnectionParameters(string game, string[] tags, ItemsHandlingFlags itemsHandlingFlags, string uuid) { Game = game; Tags = tags ?? new string[0]; ItemsHandlingFlags = itemsHandlingFlags; Uuid = uuid ?? Guid.NewGuid().ToString(); } private void Reset() { Game = null; Team = -1; Slot = -1; Tags = new string[0]; ItemsHandlingFlags = ItemsHandlingFlags.NoItems; Uuid = null; } public void UpdateConnectionOptions(string[] tags) { UpdateConnectionOptions(tags, ItemsHandlingFlags); } public void UpdateConnectionOptions(ItemsHandlingFlags itemsHandlingFlags) { UpdateConnectionOptions(Tags, itemsHandlingFlags); } public void UpdateConnectionOptions(string[] tags, ItemsHandlingFlags itemsHandlingFlags) { SetConnectionParameters(Game, tags, itemsHandlingFlags, Uuid); socket.SendPacket(new ConnectUpdatePacket { Tags = Tags, ItemsHandling = ItemsHandlingFlags }); } } public interface IDataStorageHelper : IDataStorageWrapper { DataStorageElement this[Scope scope, string key] { get; set; } DataStorageElement this[string key] { get; set; } } public class DataStorageHelper : IDataStorageHelper, IDataStorageWrapper { public delegate void DataStorageUpdatedHandler(JToken originalValue, JToken newValue, Dictionary<string, JToken> additionalArguments); private readonly Dictionary<string, DataStorageUpdatedHandler> onValueChangedEventHandlers = new Dictionary<string, DataStorageUpdatedHandler>(); private readonly Dictionary<Guid, DataStorageUpdatedHandler> operationSpecificCallbacks = new Dictionary<Guid, DataStorageUpdatedHandler>(); private readonly Dictionary<string, TaskCompletionSource<JToken>> asyncRetrievalTasks = new Dictionary<string, TaskCompletionSource<JToken>>(); private readonly IArchipelagoSocketHelper socket; private readonly IConnectionInfoProvider connectionInfoProvider; public DataStorageElement this[Scope scope, string key] { get { return this[AddScope(scope, key)]; } set { this[AddScope(scope, key)] = value; } } public DataStorageElement this[string key] { get { return new DataStorageElement(GetContextForKey(key)); } set { SetValue(key, value); } } internal DataStorageHelper(IArchipelagoSocketHelper socket, IConnectionInfoProvider connectionInfoProvider) { this.socket = socket; this.connectionInfoProvider = connectionInfoProvider; socket.PacketReceived += OnPacketReceived; } private void OnPacketReceived(ArchipelagoPacketBase packet) { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Invalid comparison between Unknown and I4 if (!(packet is RetrievedPacket retrievedPacket)) { if (packet is SetReplyPacket setReplyPacket) { if (setReplyPacket.AdditionalArguments != null && setReplyPacket.AdditionalArguments.ContainsKey("Reference") && (int)setReplyPacket.AdditionalArguments["Reference"].Type == 8 && ((string)setReplyPacket.AdditionalArguments["Reference"]).TryParseNGuid(out var g) && operationSpecificCallbacks.TryGetValue(g, out var value)) { value(setReplyPacket.OriginalValue, setReplyPacket.Value, setReplyPacket.AdditionalArguments); operationSpecificCallbacks.Remove(g); } if (onValueChangedEventHandlers.TryGetValue(setReplyPacket.Key, out var value2)) { value2(setReplyPacket.OriginalValue, setReplyPacket.Value, setReplyPacket.AdditionalArguments); } } return; } foreach (KeyValuePair<string, JToken> datum in retrievedPacket.Data) { if (asyncRetrievalTasks.TryGetValue(datum.Key, out var value3)) { value3.TrySetResult(datum.Value); asyncRetrievalTasks.Remove(datum.Key); } } } private Task<JToken> GetAsync(string key) { if (asyncRetrievalTasks.TryGetValue(key, out var value)) { return value.Task; } TaskCompletionSource<JToken> taskCompletionSource = new TaskCompletionSource<JToken>(); asyncRetrievalTasks[key] = taskCompletionSource; socket.SendPacketAsync(new GetPacket { Keys = new string[1] { key } }); return taskCompletionSource.Task; } private void Initialize(string key, JToken value) { socket.SendPacketAsync(new SetPacket { Key = key, DefaultValue = value, Operations = new OperationSpecification[1] { new OperationSpecification { OperationType = OperationType.Default } } }); } private JToken GetValue(string key) { Task<JToken> async = GetAsync(key); if (!async.Wait(TimeSpan.FromSeconds(2.0))) { throw new TimeoutException("Timed out retrieving data for key `" + key + "`. This may be due to an attempt to retrieve a value from the DataStorageHelper in a synchronous fashion from within a PacketReceived handler. When using the DataStorageHelper from within code which runs on the websocket thread then use the asynchronous getters. Ex: `DataStorageHelper[\"" + key + "\"].GetAsync().ContinueWith(x => {});`Be aware that DataStorageHelper calls tend to cause packet responses, so making a call from within a PacketReceived handler may cause an infinite loop."); } return async.Result; } private void SetValue(string key, DataStorageElement e) { if (key.StartsWith("_read_")) { throw new InvalidOperationException("DataStorage write operation on readonly key '" + key + "' is not allowed"); } if (e == null) { e = new DataStorageElement(OperationType.Replace, (JToken)(object)JValue.CreateNull()); } if (e.Context == null) { e.Context = GetContextForKey(key); } else if (e.Context.Key != key) { e.Operations.Insert(0, new OperationSpecification { OperationType = OperationType.Replace, Value = GetValue(e.Context.Key) }); } Dictionary<string, JToken> dictionary = e.AdditionalArguments ?? new Dictionary<string, JToken>(0); if (e.Callbacks != null) { Guid key2 = Guid.NewGuid(); operationSpecificCallbacks[key2] = e.Callbacks; dictionary["Reference"] = JToken.op_Implicit(key2.ToString("N")); socket.SendPacketAsync(new SetPacket { Key = key, Operations = e.Operations.ToArray(), WantReply = true, AdditionalArguments = dictionary }); } else { socket.SendPacketAsync(new SetPacket { Key = key, Operations = e.Operations.ToArray(), AdditionalArguments = dictionary }); } } private DataStorageElementContext GetContextForKey(string key) { return new DataStorageElementContext { Key = key, GetData = GetValue, GetAsync = GetAsync, Initialize = Initialize, AddHandler = AddHandler, RemoveHandler = RemoveHandler }; } private void AddHandler(string key, DataStorageUpdatedHandler handler) { if (onValueChangedEventHandlers.ContainsKey(key)) { Dictionary<string, DataStorageUpdatedHandler> dictionary = onValueChangedEventHandlers; dictionary[key] = (DataStorageUpdatedHandler)Delegate.Combine(dictionary[key], handler); } else { onValueChangedEventHandlers[key] = handler; } socket.SendPacketAsync(new SetNotifyPacket { Keys = new string[1] { key } }); } private void RemoveHandler(string key, DataStorageUpdatedHandler handler) { if (onValueChangedEventHandlers.ContainsKey(key)) { Dictionary<string, DataStorageUpdatedHandler> dictionary = onValueChangedEventHandlers; dictionary[key] = (DataStorageUpdatedHandler)Delegate.Remove(dictionary[key], handler); if (onValueChangedEventHandlers[key] == null) { onValueChangedEventHandlers.Remove(key); } } } private string AddScope(Scope scope, string key) { return scope switch { Scope.Global => key, Scope.Game => $"{scope}:{connectionInfoProvider.Game}:{key}", Scope.Team => $"{scope}:{connectionInfoProvider.Team}:{key}", Scope.Slot => $"{scope}:{connectionInfoProvider.Slot}:{key}", Scope.ReadOnly => "_read_" + key, _ => throw new ArgumentOutOfRangeException("scope", scope, "Invalid scope for key " + key), }; } private DataStorageElement GetHintsElement(int? slot = null, int? team = null) { return this[Scope.ReadOnly, $"hints_{team ?? connectionInfoProvider.Team}_{slot ?? connectionInfoProvider.Slot}"]; } private DataStorageElement GetSlotDataElement(int? slot = null) { return this[Scope.ReadOnly, $"slot_data_{slot ?? connectionInfoProvider.Slot}"]; } private DataStorageElement GetItemNameGroupsElement(string game = null) { return this[Scope.ReadOnly, "item_name_groups_" + (game ?? connectionInfoProvider.Game)]; } private DataStorageElement GetLocationNameGroupsElement(string game = null) { return this[Scope.ReadOnly, "location_name_groups_" + (game ?? connectionInfoProvider.Game)]; } private DataStorageElement GetClientStatusElement(int? slot = null, int? team = null) { return this[Scope.ReadOnly, $"client_status_{team ?? connectionInfoProvider.Team}_{slot ?? connectionInfoProvider.Slot}"]; } private DataStorageElement GetRaceModeElement() { return this[Scope.ReadOnly, "race_mode"]; } public Hint[] GetHints(int? slot = null, int? team = null) { return GetHintsElement(slot, team).To<Hint[]>(); } public Task<Hint[]> GetHintsAsync(int? slot = null, int? team = null) { return GetHintsElement(slot, team).GetAsync<Hint[]>(); } public void TrackHints(Action<Hint[]> onHintsUpdated, bool retrieveCurrentlyUnlockedHints = true, int? slot = null, int? team = null) { GetHintsElement(slot, team).OnValueChanged += delegate(JToken _, JToken newValue, Dictionary<string, JToken> x) { onHintsUpdated(newValue.ToObject<Hint[]>()); }; if (retrieveCurrentlyUnlockedHints) { GetHintsAsync(slot, team).ContinueWith(delegate(Task<Hint[]> t) { onHintsUpdated(t.Result); }); } } public Dictionary<string, object> GetSlotData(int? slot = null) { return GetSlotData<Dictionary<string, object>>(slot); } public T GetSlotData<T>(int? slot = null) where T : class { return GetSlotDataElement(slot).To<T>(); } public Task<Dictionary<string, object>> GetSlotDataAsync(int? slot = null) { return GetSlotDataAsync<Dictionary<string, object>>(slot); } public Task<T> GetSlotDataAsync<T>(int? slot = null) where T : class { return GetSlotDataElement(slot).GetAsync<T>(); } public Dictionary<string, string[]> GetItemNameGroups(string game = null) { return GetItemNameGroupsElement(game).To<Dictionary<string, string[]>>(); } public Task<Dictionary<string, string[]>> GetItemNameGroupsAsync(string game = null) { return GetItemNameGroupsElement(game).GetAsync<Dictionary<string, string[]>>(); } public Dictionary<string, string[]> GetLocationNameGroups(string game = null) { return GetLocationNameGroupsElement(game).To<Dictionary<string, string[]>>(); } public Task<Dictionary<string, string[]>> GetLocationNameGroupsAsync(string game = null) { return GetLocationNameGroupsElement(game).GetAsync<Dictionary<string, string[]>>(); } public ArchipelagoClientState GetClientStatus(int? slot = null, int? team = null) { return GetClientStatusElement(slot, team).To<ArchipelagoClientState?>().GetValueOrDefault(); } public Task<ArchipelagoClientState> GetClientStatusAsync(int? slot = null, int? team = null) { return GetClientStatusElement(slot, team).GetAsync<ArchipelagoClientState?>().ContinueWith((Task<ArchipelagoClientState?> r) => r.Result.GetValueOrDefault()); } public void TrackClientStatus(Action<ArchipelagoClientState> onStatusUpdated, bool retrieveCurrentClientStatus = true, int? slot = null, int? team = null) { GetClientStatusElement(slot, team).OnValueChanged += delegate(JToken _, JToken newValue, Dictionary<string, JToken> x) { onStatusUpdated(newValue.ToObject<ArchipelagoClientState>());