Decompiled source of DRGSMultiplayer v0.2.1
plugins/DRGSMultiplayer.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Assets.Scripts; using Assets.Scripts.Data; using Assets.Scripts.EnemyBehaviours; using Assets.Scripts.LevelGeneration; using Assets.Scripts.LevelObjectives.Handlers; using Assets.Scripts.SkillSystem; using Assets.Scripts.VFXSystem; using BepInEx; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Cysharp.Threading.Tasks; using DRGSMultiplayer.Game; using DRGSMultiplayer.Net; using DRGSMultiplayer.Patches; using DRGSMultiplayer.UI; using DRS.UI; using FundayFactory.UI; using FundayGames.LocalPrefs; using FundayGames.PlatformService; using FundayGames.PlatformService.Steam; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using Il2CppSystem.Reflection; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.AI; using UnityEngine.AddressableAssets; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine.VFX; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("DRGSMultiplayer")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+b6d5e3275ae5dac2c0a0cf72c444fbcdf50ce9cf")] [assembly: AssemblyProduct("DRGSMultiplayer")] [assembly: AssemblyTitle("DRGSMultiplayer")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.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 DRGSMultiplayer { [BepInPlugin("drgs.multiplayer", "DRGS Multiplayer", "0.2.1")] public class Plugin : BasePlugin { public const string Guid = "drgs.multiplayer"; public const string Name = "DRGS Multiplayer"; public const string Version = "0.2.1"; internal static ManualLogSource Log; internal static Harmony Harmony; internal static string ToggleKeyName = "F8"; internal static string HostKeyName = "F9"; internal static string LeaveKeyName = "F10"; private ConfigEntry<string> _toggleKey; private ConfigEntry<string> _hostKey; private ConfigEntry<string> _leaveKey; private ConfigEntry<bool> _showAtStart; private ConfigEntry<float> _timeout; private ConfigEntry<float> _heartbeat; private ConfigEntry<int> _maxPlayers; private ConfigEntry<int> _localPort; private ConfigEntry<bool> _autoLocal; internal static int InstanceIndex = 1; private static Mutex _instanceMutex; private static int DetectInstance() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown bool flag = default(bool); for (int i = 1; i <= 8; i++) { try { bool createdNew; Mutex mutex = new Mutex(initiallyOwned: true, $"Global\\DRGSMP_Instance{i}", out createdNew); if (createdNew) { _instanceMutex = mutex; return i; } mutex.Dispose(); } catch (UnauthorizedAccessException) { } catch (Exception ex2) { ManualLogSource log = Log; BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(19, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[instance] mutex "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(i); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex2.Message); } log.LogWarning(val); return i; } } return 9; } public override void Load() { //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Expected O, but got Unknown //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Expected O, but got Unknown //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Expected O, but got Unknown //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Expected O, but got Unknown Log = ((BasePlugin)this).Log; _toggleKey = ((BasePlugin)this).Config.Bind<string>("UI", "ToggleKey", "F8", "UnityEngine.KeyCode / InputSystem Key name that toggles the multiplayer overlay (F1..F12, Backslash, ...)."); _hostKey = ((BasePlugin)this).Config.Bind<string>("UI", "HostKey", "F9", "Fallback hotkey to host a lobby (only active if IMGUI is unusable)."); _leaveKey = ((BasePlugin)this).Config.Bind<string>("UI", "LeaveKey", "F10", "Fallback hotkey to leave the lobby (only active if IMGUI is unusable)."); _showAtStart = ((BasePlugin)this).Config.Bind<bool>("UI", "ShowAtStart", false, "Show the overlay when the game starts."); _timeout = ((BasePlugin)this).Config.Bind<float>("Net", "TimeoutSeconds", 5f, "Seconds without packets from a peer before it is considered disconnected."); _heartbeat = ((BasePlugin)this).Config.Bind<float>("Net", "HeartbeatSeconds", 1f, "Heartbeat interval."); _maxPlayers = ((BasePlugin)this).Config.Bind<int>("Lobby", "MaxPlayers", 4, new ConfigDescription("Max lobby size (host included).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 4), Array.Empty<object>())); ToggleKeyName = _toggleKey.Value; HostKeyName = _hostKey.Value; LeaveKeyName = _leaveKey.Value; NetManager.TimeoutSeconds = _timeout.Value; NetManager.HeartbeatInterval = _heartbeat.Value; LobbyManager.MaxMembers = _maxPlayers.Value; Overlay.Visible = _showAtStart.Value; _localPort = ((BasePlugin)this).Config.Bind<int>("Net", "LocalPort", 27777, new ConfigDescription("UDP port the loopback (same-PC test) host binds on 127.0.0.1.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1024, 65000), Array.Empty<object>())); _autoLocal = ((BasePlugin)this).Config.Bind<bool>("Net", "AutoLocal", false, "Loopback test: instance 1 auto-hosts, instance 2 auto-joins on startup (env DRGSMP_AUTOLOCAL=1 or a BepInEx/DRGSMP_AUTOLOCAL marker file also enables it)."); NetManager.LocalPort = _localPort.Value; NetManager.AutoLocal = _autoLocal.Value || Environment.GetEnvironmentVariable("DRGSMP_AUTOLOCAL") == "1" || File.Exists(Path.Combine(Paths.BepInExRootPath, "DRGSMP_AUTOLOCAL")); Smoke.Init(); if (Smoke.Enabled) { NetManager.AutoLocal = true; } InstanceIndex = DetectInstance(); Log.LogInfo((object)($"[instance] this is instance {InstanceIndex}" + (NetManager.AutoLocal ? " (AutoLocal)" : ""))); Harmony = new Harmony("drgs.multiplayer"); ApplyPatches(); if (InstanceIndex >= 2) { SaveGuard.Apply(Harmony); } GroundZonePatches.Apply(Harmony); WeaponSpawnPatches.Apply(Harmony); if (Smoke.Enabled) { SmokePatches.Apply(Harmony); } UnityLogTap.Install(); NetDriver.Create(); ManualLogSource log = Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(24, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("DRGS Multiplayer"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("0.2.1"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded (overlay key: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ToggleKeyName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(")"); } log.LogInfo(val); } private static void ApplyPatches() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Expected O, but got Unknown int num = 0; int num2 = 0; Type[] types = typeof(Plugin).Assembly.GetTypes(); bool flag = default(bool); foreach (Type type in types) { if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length == 0 || type.DeclaringType == typeof(SaveGuard)) { continue; } try { Harmony.CreateClassProcessor(type).Patch(); num++; } catch (Exception ex) { num2++; ManualLogSource log = Log; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(17, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[patch] "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(type.Name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" failed: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetBaseException().Message); } log.LogError(val); } } ManualLogSource log2 = Log; BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(39, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[patch] applied "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" patch classes, "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num2); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" failed"); } log2.LogInfo(val2); } } } namespace DRGSMultiplayer.UI { internal static class Clipboard { private const uint CF_UNICODETEXT = 13u; private const uint GMEM_MOVEABLE = 2u; [DllImport("user32.dll", SetLastError = true)] private static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll", SetLastError = true)] private static extern bool CloseClipboard(); [DllImport("user32.dll", SetLastError = true)] private static extern bool EmptyClipboard(); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr GetClipboardData(uint uFormat); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GlobalLock(IntPtr hMem); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GlobalUnlock(IntPtr hMem); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GlobalFree(IntPtr hMem); public static string Get() { if (!OpenClipboard(IntPtr.Zero)) { return null; } try { IntPtr clipboardData = GetClipboardData(13u); if (clipboardData == IntPtr.Zero) { return null; } IntPtr intPtr = GlobalLock(clipboardData); if (intPtr == IntPtr.Zero) { return null; } try { return Marshal.PtrToStringUni(intPtr); } finally { GlobalUnlock(clipboardData); } } finally { CloseClipboard(); } } public static bool Set(string text) { if (!OpenClipboard(IntPtr.Zero)) { return false; } try { EmptyClipboard(); int num = (text.Length + 1) * 2; IntPtr intPtr = GlobalAlloc(2u, (UIntPtr)(ulong)num); if (intPtr == IntPtr.Zero) { return false; } IntPtr intPtr2 = GlobalLock(intPtr); if (intPtr2 == IntPtr.Zero) { GlobalFree(intPtr); return false; } try { Marshal.Copy(text.ToCharArray(), 0, intPtr2, text.Length); Marshal.WriteInt16(intPtr2, text.Length * 2, 0); } finally { GlobalUnlock(intPtr); } if (SetClipboardData(13u, intPtr) == IntPtr.Zero) { GlobalFree(intPtr); return false; } return true; } finally { CloseClipboard(); } } } internal static class Overlay { public static bool Visible; public static bool Broken; private static string _lobbyInput = ""; private static float _contentHeight = 300f; private static int _errors; private const float W = 460f; private const float Pad = 10f; private const float Row = 24f; private static float _x; private static float _y; public static void Draw() { if (!Visible || Broken) { return; } try { DrawInner(); } catch (Exception ex) { if (++_errors >= 3) { Broken = true; Plugin.Log.LogError((object)("[ui] IMGUI unusable, disabling overlay (hotkeys fallback active): " + ex)); } else { Plugin.Log.LogWarning((object)("[ui] IMGUI error: " + ex.Message)); } } } private static void DrawInner() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0537: Unknown result type (might be due to invalid IL or missing references) //IL_08a0: Unknown result type (might be due to invalid IL or missing references) //IL_07b6: Unknown result type (might be due to invalid IL or missing references) //IL_091a: Unknown result type (might be due to invalid IL or missing references) //IL_0921: Expected O, but got Unknown float num = Mathf.Max(1f, (float)Screen.height / 900f); GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f)); NetManager instance = NetManager.Instance; LobbyManager lobby = instance.Lobby; GUI.Box(new Rect(10f, 10f, 460f, _contentHeight + 20f), "DRGS Multiplayer 0.2.1 [inst " + NetManager.InstanceIndex + " | " + instance.TransportName + "] (toggle: " + Plugin.ToggleKeyName + ")"); _x = 20f; _y = 36f; bool steamReady = instance.SteamReady; if (!steamReady) { Label("Steam not ready: " + (instance.SteamError ?? "waiting...")); } Label($"You: {instance.LocalName} ({instance.LocalId})"); Label($"State: {instance.State} | {(instance.IsLoopback ? instance.LoopbackStatus : lobby.Status)}"); if (!string.IsNullOrEmpty(instance.LastError)) { Label("Last error: " + instance.LastError); } if (!string.IsNullOrEmpty(lobby.LastError) && lobby.LastError != instance.LastError) { Label("Lobby: " + lobby.LastError); } if (instance.IsConnected) { EGameState state = GameRefs.State; Label($"Co-op: {state} stage {GameRefs.StageIndex} seed {Session.RunSeed}" + ((PauseState.Suppressed > 0) ? " [pause suppressed]" : "")); if (!string.IsNullOrEmpty(Session.Status)) { Label(Session.Status); } Label(SessionFlow.StatusLine); Label(WeaponFx.StatusLine); Label(ObjectiveSync.StatusLine); Label(MissionLayout.StatusLine); Label(WorldObjectSync.StatusLine); if (instance.IsClient) { Label("Client: the host starts runs (pick your dwarf, then wait in the menu)."); } } float num2 = 216f; bool flag = instance.State == NetState.Offline; if (Button("Host (friends only)", _x, num2, flag && steamReady)) { instance.Host(); } if (Button("Leave", _x + num2 + 8f, num2, !flag)) { instance.Leave(); } _y += 30f; Label($"Local test (127.0.0.1:{NetManager.LocalPort}, instance {NetManager.InstanceIndex}{(NetManager.AutoLocal ? ", auto" : "")})"); if (Button("Local Host", _x, num2, flag)) { instance.HostLocal(); } if (Button("Local Join", _x + num2 + 8f, num2, flag)) { instance.JoinLocal(); } _y += 30f; if (instance.IsLoopback) { Label($"Peers ({instance.Peers.Count}):"); foreach (KeyValuePair<ulong, Peer> peer in instance.Peers) { Label($" {peer.Value.Name} ({peer.Key})" + (peer.Value.Direct ? $" hb {peer.Value.Age:0.0}s" : " (relayed)")); } } if (lobby.InLobby) { GUI.Label(new Rect(_x, _y, 370f, 24f), "Lobby ID: " + lobby.LobbyId); if (Button("Copy", _x + 460f - 20f - 64f, 64f, enabled: true)) { Clipboard.Set(lobby.LobbyId.ToString()); } _y += 28f; Label($"Members ({lobby.Members.Count}/{LobbyManager.MaxMembers}):"); foreach (ulong member in lobby.Members) { string text = " " + SteamCtx.NameOf(member); if (member == lobby.OwnerId) { text += " [host]"; } Peer value; if (member == instance.LocalId) { text += " (you)"; } else if (instance.Peers.TryGetValue(member, out value)) { text += (value.Direct ? $" hb {value.Age:0.0}s" : " (relayed)"); } else if (instance.IsConnected) { text += " (not connected)"; } Label(text); } } if (flag && steamReady) { _y += 4f; Label("Friends in a lobby:"); if (lobby.FriendLobbies.Count == 0) { Label(" (none found)"); } int num3 = 0; foreach (FriendLobby friendLobby in lobby.FriendLobbies) { if (num3++ >= 6) { break; } string value2 = (string.IsNullOrEmpty(friendLobby.ModVersion) ? "no mod/unknown" : ("v" + friendLobby.ModVersion)); bool flag2 = friendLobby.ModVersion == "0.2.1"; GUI.Label(new Rect(_x, _y, 370f, 24f), $" {friendLobby.FriendName} [{value2}]"); if (Button("Join", _x + 460f - 20f - 64f, 64f, flag2 && !lobby.Busy)) { instance.Join(friendLobby.LobbyId); } _y += 24f; } _y += 4f; GUI.Label(new Rect(_x, _y, 300f, 24f), "Join by lobby ID (clipboard)"); if (Button("Paste+Join", _x + 460f - 20f - 134f, 134f, !lobby.Busy)) { _lobbyInput = (Clipboard.Get() ?? "").Trim(); if (ulong.TryParse(_lobbyInput, out var result)) { instance.Join(result); } else { ManualLogSource log = Plugin.Log; bool flag3 = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(36, 1, ref flag3); if (flag3) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[ui] clipboard is not a lobby ID: '"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(_lobbyInput); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("'"); } log.LogWarning(val); } } _y += 24f; } Finish(); } private static void Finish() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 float num = _y - 10f; if (Event.current != null && (int)Event.current.type == 7) { _contentHeight = Mathf.Max(60f, num - 10f); } } private static void Label(string s) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) GUI.Label(new Rect(_x, _y, 440f, 24f), s); _y += 22f; } private static bool Button(string text, float x, float width, bool enabled) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) bool enabled2 = GUI.enabled; GUI.enabled = enabled; bool num = GUI.Button(new Rect(x, _y, width, 24f), text); GUI.enabled = enabled2; return num && enabled; } } } namespace DRGSMultiplayer.Patches { [HarmonyPatch(typeof(EnemySpawner), "Update")] internal static class EnemySync_Spawner_Update { private static bool Prefix(EnemySpawner __instance) { try { if (!EnemySync.ClientActive) { EnemySync.ClientIdle(); return true; } EnemySync.EnsureHooked(); EnemySync.ClientTick(__instance); return false; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] EnemySpawner.Update (client): " + ex)); return false; } } private static void Postfix(EnemySpawner __instance) { try { if (NetManager.Instance.IsHost) { EnemySync.EnsureHooked(); EnemySync.HostTick(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] EnemySpawner.Update (host): " + ex)); } } } [HarmonyPatch(typeof(EnemySpawner), "Spawn", new Type[] { typeof(Enemy), typeof(int), typeof(bool), typeof(EEnemyScaleMode), typeof(int) })] internal static class EnemySync_Spawner_SpawnSwarm { private static bool _began; private static bool Prefix(EnemySpawner __instance, ref List<Enemy> __result) { try { if (EnemySync.ClientActive) { __result = new List<Enemy>(); return false; } if (EnemySync.HostActive) { _began = true; EnemySync.HostSwarmSpawnBegin(__instance); } return true; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] EnemySpawner.Spawn prefix: " + ex)); return true; } } private static void Postfix(EnemySpawner __instance) { if (!_began) { return; } _began = false; try { EnemySync.HostSwarmSpawnEnd(__instance); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] EnemySpawner.Spawn postfix: " + ex)); } } } internal static class SpawnAtGate { internal static bool Prefix(Func<int> type, ref Enemy result, out bool began) { began = false; try { if (EnemySync.ClientActive) { if (EnemySync.ClientAllowSpawnAt(type())) { return true; } result = null; return false; } if (EnemySync.HostActive) { began = true; EnemySync.HostSpawnAtBegin(); } return true; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] EnemySpawner.SpawnAt prefix: " + ex)); return true; } } internal static void Postfix(bool began) { if (began) { EnemySync.HostSpawnAtEnd(); } } } [HarmonyPatch(typeof(EnemySpawner), "SpawnAt", new Type[] { typeof(EEnemy), typeof(Vector3), typeof(EEnemyScaleMode) })] internal static class EnemySync_Spawner_SpawnAtId { private static bool Prefix(EEnemy __0, ref Enemy __result, out bool __state) { //IL_0006: 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) return SpawnAtGate.Prefix(() => (int)__0, ref __result, out __state); } private static void Postfix(bool __state) { SpawnAtGate.Postfix(__state); } } [HarmonyPatch(typeof(EnemySpawner), "SpawnAt", new Type[] { typeof(Enemy), typeof(Vector3), typeof(EEnemyScaleMode) })] internal static class EnemySync_Spawner_SpawnAtPrefab { private static bool Prefix(Enemy __0, ref Enemy __result, out bool __state) { return SpawnAtGate.Prefix(() => ((Object)(object)__0 != (Object)null) ? ((int)__0.ID) : (-1), ref __result, out __state); } private static void Postfix(bool __state) { SpawnAtGate.Postfix(__state); } } [HarmonyPatch(typeof(CoreGameEvents), "TriggerStageBossSpawned")] internal static class EnemySync_TriggerStageBossSpawned { private static bool Prefix() { try { return !EnemySync.ClientActive || EnemySync.ClientAllowBossSpawned(); } catch { return true; } } private static void Postfix(StageBossSpawnArgs __0) { try { if (EnemySync.HostActive) { EnemySync.HostOnBossSpawned(__0); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TriggerStageBossSpawned: " + ex)); } } } [HarmonyPatch(typeof(EliminationMissionHandler), "OnCoreLevelBegin")] internal static class EnemySync_Elimination_OnCoreLevelBegin { private static bool Prefix() { return !EnemySync.ClientActive; } } [HarmonyPatch(typeof(EggHuntMissionHandler), "SpawnBoss")] internal static class EnemySync_EggHunt_SpawnBoss { private static bool Prefix() { return !EnemySync.ClientActive; } } [HarmonyPatch(typeof(SpawnHuuliArtifactData), "Apply")] internal static class EnemySync_SpawnHuuliArtifactData_Apply { private static bool Prefix(SpawnHuuliArtifactData __instance, RunSettingsManager __1) { if (!EnemySync.ClientActive) { return true; } try { EnemySync.ClientRequestHuuli(__instance, __1); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] SpawnHuuliArtifactData.Apply: " + ex)); } return false; } } [HarmonyPatch(typeof(CoreGameEvents), "TriggerLootBugSpawned")] internal static class EnemySync_TriggerLootBugSpawned { private static bool Prefix() { try { return !EnemySync.ClientActive || EnemySync.ClientAllowLootBugSpawned(); } catch { return true; } } private static void Postfix(LootBugSpawnArgs __0) { try { if (EnemySync.HostActive) { EnemySync.HostOnLootBugSpawned(__0); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TriggerLootBugSpawned: " + ex)); } } } [HarmonyPatch(typeof(CoreGameEvents), "TriggerPreHealthTransferEvent")] internal static class EnemySync_TriggerPreHealthTransfer { private static bool Prefix() { try { return !EnemySync.ClientActive || EnemySync.ClientAllowHealTransfer(); } catch { return true; } } private static void Postfix(HealthTransferEventArgs __0) { try { if (EnemySync.HostActive) { EnemySync.HostOnHealTransfer(__0); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TriggerPreHealthTransferEvent: " + ex)); } } } [HarmonyPatch(typeof(SpawnHuuliArtifact), "Do")] internal static class EnemySync_SpawnHuuliArtifact_Do { private static bool Prefix() { return !EnemySync.ClientActive; } } [HarmonyPatch(typeof(Enemy), "OnSpawn")] internal static class EnemySync_Enemy_OnSpawn { private static void Postfix(Enemy __instance, EEnemyScaleMode __3) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) try { if (EnemySync.HostActive) { EnemySync.HostOnSpawn(__instance, __3); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] Enemy.OnSpawn: " + ex)); } } } [HarmonyPatch(typeof(Enemy), "Die")] internal static class EnemySync_Enemy_Die { private static bool Prefix(Enemy __instance) { try { if (EnemySync.HostActive) { EnemySync.HostBeforeDeath(__instance); return true; } return !EnemySync.ClientActive || !EnemySync.IsPuppet(__instance); } catch { return true; } } private static void Postfix(Enemy __instance, EDamageType __0) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) try { if (EnemySync.HostActive) { EnemySync.HostOnDeath(__instance, __0); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] Enemy.Die: " + ex)); } } } [HarmonyPatch(typeof(Enemy), "DeSpawn")] internal static class EnemySync_Enemy_DeSpawn { private static void Postfix(Enemy __instance) { try { if (EnemySync.HostActive) { EnemySync.HostOnRemoved(__instance); } else if (EnemySync.ClientActive) { EnemySync.ClientOnRemoved(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] Enemy.DeSpawn: " + ex)); } } } [HarmonyPatch(typeof(Enemy), "Recall")] internal static class EnemySync_Enemy_Recall { private static void Postfix(Enemy __instance) { try { if (EnemySync.HostActive) { EnemySync.HostOnRemoved(__instance); } else if (EnemySync.ClientActive) { EnemySync.ClientOnRemoved(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] Enemy.Recall: " + ex)); } } } [HarmonyPatch(typeof(Enemy), "TakeDamage")] internal static class EnemySync_Enemy_TakeDamage { [HarmonyPriority(0)] private static bool Prefix(Enemy __instance, long __0, bool __1, EDamageType __2, EDamageSource __4, Entity __5, bool __runOriginal, ref bool __result) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) try { if (EnemySync.HostActive) { EnemySync.HostBeforeDamage(__instance); } else if (__runOriginal && EnemySync.ClientActive) { if (EnemySync.ClientSuppressAoeHit(__instance)) { __result = false; return false; } EnemySync.ClientOnLocalHit(__instance, __0, __1, __2, __4, __5); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] Enemy.TakeDamage prefix: " + ex)); } return true; } private static void Postfix(Enemy __instance) { try { if (EnemySync.HostActive) { EnemySync.HostMarkHp(__instance); } } catch { } } } [HarmonyPatch(typeof(Enemy), "Knockback", new Type[] { typeof(Vector3), typeof(float), typeof(float), typeof(float) })] internal static class EnemySync_Enemy_Knockback { private static bool Prefix(Enemy __instance, Vector3 __0, float __1, float __2, float __3) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) try { return !EnemySync.ClientActive || EnemySync.ClientOnKnockback(__instance, __0, __1, __2, __3); } catch { return true; } } } [HarmonyPatch(typeof(EnemyAnimator), "BeginAttackAnimation")] internal static class EnemySync_EnemyAnimator_BeginAttack { private static void Postfix(EnemyAnimator __instance) { try { if (EnemySync.HostActive) { EnemySync.HostOnAttackAnim(((Il2CppObjectBase)__instance).Pointer); } } catch { } } } [HarmonyPatch(typeof(AIProjectileHandler), "ActivateWeapon")] internal static class EnemySync_AIProjectileHandler_ActivateWeapon { private static bool _began; private static bool Prefix(AIProjectileHandler __instance) { try { if (EnemySync.ClientActive) { return EnemySync.ClientAllowFire((AIWeaponHandler)(object)__instance); } if (EnemySync.HostActive) { _began = EnemySync.HostOnFire((AIWeaponHandler)(object)__instance, 1); } return true; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] AIProjectileHandler.ActivateWeapon: " + ex.Message)); return true; } } private static void Postfix() { if (_began) { _began = false; EnemySync.HostFireEnd(); } } } [HarmonyPatch(typeof(MeleeWeaponSkillHandler), "ActivateWeapon")] internal static class EnemySync_MeleeWeaponSkillHandler_ActivateWeapon { private static bool _began; private static bool Prefix(MeleeWeaponSkillHandler __instance) { try { if (EnemySync.ClientActive) { return EnemySync.ClientAllowFire((AIWeaponHandler)(object)__instance); } if (EnemySync.HostActive) { _began = EnemySync.HostOnFire((AIWeaponHandler)(object)__instance, 2); } return true; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] MeleeWeaponSkillHandler.ActivateWeapon: " + ex.Message)); return true; } } private static void Postfix() { if (_began) { _began = false; EnemySync.HostFireEnd(); } } } [HarmonyPatch(typeof(MeleeWeaponSkillHandler), "OnAttackFrame")] internal static class EnemySync_MeleeWeaponSkillHandler_OnAttackFrame { private static bool Prefix(MeleeWeaponSkillHandler __instance) { try { return !EnemySync.ClientActive || EnemySync.ClientAllowAttackFrame((AIWeaponHandler)(object)__instance); } catch { return true; } } } [HarmonyPatch(typeof(_IEDelayedFriendlyFire_d__10), "MoveNext")] internal static class EnemySync_FriendlyFire_MoveNext { private static bool Prefix(_IEDelayedFriendlyFire_d__10 __instance, ref bool __result) { try { if (!EnemySync.ClientActive || EnemySync.ClientAllowFriendlyFire(__instance.enemy)) { return true; } __result = false; return false; } catch { return true; } } } [HarmonyPatch(typeof(AIFireballFanSkill), "Activate")] internal static class EnemySync_FireballFan_Activate { private static bool Prefix(AIFireballFanSkill __instance) { try { return !EnemySync.ClientActive || EnemySync.ClientAllowSkill((AISkill)(object)__instance); } catch { return true; } } private static void Postfix(AIFireballFanSkill __instance) { try { if (EnemySync.HostActive) { EnemySync.HostOnSkill((AISkill)(object)__instance, 1); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] AIFireballFanSkill.Activate: " + ex.Message)); } } } [HarmonyPatch(typeof(AIGroundSpikeSkill), "Activate")] internal static class EnemySync_GroundSpikeSkill_Activate { private static bool Prefix(AIGroundSpikeSkill __instance) { try { return !EnemySync.ClientActive || EnemySync.ClientAllowSkill((AISkill)(object)__instance); } catch { return true; } } private static void Postfix(AIGroundSpikeSkill __instance) { try { if (EnemySync.HostActive) { EnemySync.HostOnSkill((AISkill)(object)__instance, 2); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] AIGroundSpikeSkill.Activate: " + ex.Message)); } } } [HarmonyPatch(typeof(AIFireballFanSkill), "OnProjectileHit")] internal static class EnemySync_FireballFan_OnProjectileHit { private static void Prefix(AIFireballFanSkill __instance, out bool __state) { __state = false; try { if (EnemySync.ClientActive) { Enemy owner = ((AISkill)__instance).owner; if (!((Object)(object)owner == (Object)null) && EnemySync.IsPuppet(owner)) { EnemySync.ClientAoeBegin(); __state = true; } } } catch { } } private static void Postfix(bool __state) { if (__state) { EnemySync.ClientAoeEnd(); } } } [HarmonyPatch(typeof(GroundSpike), "OnSpawn", new Type[] { typeof(Vector3), typeof(float), typeof(float), typeof(float) })] internal static class EnemySync_GroundSpike_OnSpawn { private static void Prefix(out bool __state) { __state = false; try { if (EnemySync.ClientActive) { EnemySync.ClientAoeBegin(); __state = true; } } catch { } } private static void Postfix(bool __state) { if (__state) { EnemySync.ClientAoeEnd(); } } } internal static class LootGoblinPuppetGuard { internal static bool Allow(BaseEnemyBehaviour b) { try { return !EnemySync.ClientActive || b == null || (Object)(object)b.owner == (Object)null || !EnemySync.IsPuppet(b.owner); } catch { return true; } } } [HarmonyPatch(typeof(EnemyBehaviourLootGoblin), "TriggerStartState")] internal static class EnemySync_LootGoblin_TriggerStartState { private static bool Prefix(EnemyBehaviourLootGoblin __instance) { return LootGoblinPuppetGuard.Allow((BaseEnemyBehaviour)(object)__instance); } } [HarmonyPatch(typeof(EnemyBehaviourLootGoblin), "TriggerFlee")] internal static class EnemySync_LootGoblin_TriggerFlee { private static bool Prefix(EnemyBehaviourLootGoblin __instance) { return LootGoblinPuppetGuard.Allow((BaseEnemyBehaviour)(object)__instance); } } [HarmonyPatch(typeof(EnemyBehaviourLootGoblin), "SetState")] internal static class EnemySync_LootGoblin_SetState { private static bool Prefix(EnemyBehaviourLootGoblin __instance) { return LootGoblinPuppetGuard.Allow((BaseEnemyBehaviour)(object)__instance); } } [HarmonyPatch(typeof(Enemy), "OnCreated")] internal static class EnemySync_Enemy_OnCreated { private static void Prefix(ref Player __1) { try { if ((Object)(object)__1 != (Object)null && EnemySync.IsDummy(((Il2CppObjectBase)__1).Pointer) && (Object)(object)GameRefs.Player != (Object)null) { __1 = GameRefs.Player; } } catch { } } } [HarmonyPatch(typeof(Player), "TakeDamage")] internal static class EnemySync_Player_TakeDamage_DummyGuard { [HarmonyPriority(800)] private static bool Prefix(Player __instance, ref bool __result) { try { if (!EnemySync.IsDummy(((Il2CppObjectBase)__instance).Pointer)) { return true; } __result = false; return false; } catch { return true; } } } [HarmonyPatch(typeof(MapGenerator), "CreateMap")] internal static class EnemySync_CreateMap { private static void Prefix() { try { if (NetManager.Instance.IsConnected) { EnemySync.OnNewMap(); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] EnemySync CreateMap: " + ex.Message)); } } } internal static class EnemyTerrainGuard { internal static bool Allow(Enemy enemy, ref bool result) { try { if (!EnemySync.ClientActive) { return true; } if (!EnemySync.ClientInPuppetAoe && (!((Object)(object)enemy != (Object)null) || !EnemySync.IsHostEnemyOnClient(enemy))) { return true; } result = false; return false; } catch { return true; } } } [HarmonyPatch(typeof(RockBlock), "TakeDamage")] internal static class EnemySync_RockBlock_TakeDamage { private static bool Prefix(Enemy __4, ref bool __result) { return EnemyTerrainGuard.Allow(__4, ref __result); } } [HarmonyPatch(typeof(MaterialBlock), "TakeDamage")] internal static class EnemySync_MaterialBlock_TakeDamage { private static bool Prefix(Enemy __4, ref bool __result) { return EnemyTerrainGuard.Allow(__4, ref __result); } } [HarmonyPatch(typeof(RegeneratingRockBlock), "TakeDamage")] internal static class EnemySync_RegenRockBlock_TakeDamage { private static bool Prefix(Enemy __4, ref bool __result) { return EnemyTerrainGuard.Allow(__4, ref __result); } } [HarmonyPatch(typeof(StatusEffectHandler), "Apply")] internal static class EnemySync_StatusEffect_Apply { private static void Postfix(StatusEffectHandler __instance, EStatusEffect __0, int __1) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) try { if (NetManager.Instance.IsConnected) { EnemySync.OnStatusApplied(__instance, __0, __1); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] StatusEffectHandler.Apply: " + ex.Message)); } } } [HarmonyPatch(typeof(GameController), "Inject")] internal static class GameController_Inject { private static void Postfix(GameController __instance, UIManager __0, MapGenerator __7, Player __8, RunSettingsManager __10, RunStateManager __15) { try { GameRefs.Capture(__instance, __0, __7, __8, __10, __15); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] GameController.Inject: " + ex)); } } } [HarmonyPatch(typeof(GameController), "OnDestroy")] internal static class GameController_OnDestroy { private static void Postfix(GameController __instance) { try { if (!((Object)(object)GameRefs.GC != (Object)null) || !(((Il2CppObjectBase)GameRefs.GC).Pointer != ((Il2CppObjectBase)__instance).Pointer)) { ProxyManager.Clear(); PauseState.Reset(); GameRefs.Clear(); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] GameController.OnDestroy: " + ex)); } } } [HarmonyPatch(typeof(UIManager), "OnStartGameButton")] internal static class UIManager_OnStartGameButton { private static bool Prefix() { try { if (NetManager.Instance.State == NetState.Offline) { return true; } return Session.OnStartGamePrefix(); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnStartGameButton: " + ex)); return true; } } } [HarmonyPatch(typeof(MapGenerator), "CreateMap")] internal static class MapGenerator_CreateMap { private static void Prefix() { try { if (Session.SeedActive) { Session.Reseed(GameRefs.StageIndex, "CreateMap"); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] CreateMap: " + ex)); } } } [HarmonyPatch(typeof(RunStateManager), "GetFirstStage")] internal static class RunStateManager_GetFirstStage { private static void Prefix() { try { if (Session.SeedActive) { Session.Reseed(1000, "GetFirstStage"); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] GetFirstStage: " + ex)); } } } [HarmonyPatch(typeof(RunStateManager), "ProgressStage")] internal static class RunStateManager_ProgressStage { private static void Prefix(RunStateManager __instance) { try { if (Session.SeedActive) { Session.Reseed(2000 + __instance.CurrentStageIndex + 1, "ProgressStage"); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] ProgressStage: " + ex)); } } } [HarmonyPatch(typeof(RunStateManager), "SetupSecondaryObjectives")] internal static class RunStateManager_SetupSecondaryObjectives { private static void Prefix(int __0) { try { if (Session.SeedActive) { Session.Reseed(3000 + __0, "SetupSecondaryObjectives"); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] SetupSecondaryObjectives: " + ex)); } } } [HarmonyPatch(typeof(GameController), "PauseCore")] internal static class GameController_PauseCore { private static bool Prefix(Action __0) { try { if (!Session.Active || Session.RunSeed == 0) { return true; } PauseState.Suppressed++; Plugin.Log.LogInfo((object)("[pause] PauseCore suppressed (co-op), depth " + PauseState.Suppressed)); if (__0 != null) { __0.Invoke(); } return false; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] PauseCore: " + ex)); return false; } } } [HarmonyPatch(typeof(GameController), "UnpauseCore")] internal static class GameController_UnpauseCore { private static bool Prefix() { try { if (PauseState.Suppressed <= 0) { return true; } PauseState.Suppressed--; Plugin.Log.LogInfo((object)("[pause] UnpauseCore swallowed, depth " + PauseState.Suppressed)); return false; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] UnpauseCore: " + ex)); return true; } } } [HarmonyPatch(typeof(Player), "TakeDamage")] internal static class Player_TakeDamage { private static bool Prefix(Player __instance, ref bool __result) { try { if (!PauseState.LocalInvulnerable) { return true; } Player player = GameRefs.Player; if ((Object)(object)player == (Object)null || ((Il2CppObjectBase)player).Pointer != ((Il2CppObjectBase)__instance).Pointer) { return true; } __result = false; return false; } catch { return true; } } } [HarmonyPatch(typeof(GameController), "OnStageEnd")] internal static class GameController_OnStageEnd { private static void Postfix() { try { if (Session.Active) { Session.SendStageEvent(StageEventKind.StageEnd, GameRefs.StageIndex, ""); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnStageEnd: " + ex)); } } } [HarmonyPatch(typeof(GameController), "OnShopExit")] internal static class GameController_OnShopExit { private static void Prefix() { try { if (Session.Active) { Session.SendStageEvent(StageEventKind.ShopExit, GameRefs.StageIndex, ""); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnShopExit: " + ex)); } } } [HarmonyPatch(typeof(GameController), "OnCoreRunEnd")] internal static class GameController_OnCoreRunEnd { private static void Postfix() { try { if (Session.RunSeed != 0 || PauseState.Suppressed != 0) { Session.OnRunEnd(); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnCoreRunEnd: " + ex)); } } } [HarmonyPatch(typeof(SteamFeatureLobby), "Initialize")] internal static class SteamFeatureLobby_Initialize { private static void Postfix(SteamFeatureLobby __instance) { try { Plugin.Log.LogInfo((object)"[lobbyfix] SteamFeatureLobby.Initialize observed"); SteamLobbyFix.Install(__instance); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] SteamFeatureLobby.Initialize: " + ex)); } } } internal static class MissionSeed { internal const int RunStartSalt = 3999; internal const int KCycle = 1; internal const int KCocoons = 2; internal static void Enter(int salt, string where, out State? state) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) state = null; if (Session.SeedActive) { state = Random.state; Session.Reseed(salt, where); } } internal static int StageSalt(int k) { return 4000 + GameRefs.StageIndex * 16 + k; } internal static Exception Exit(Exception ex, State? state, string where) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) try { if (state.HasValue) { Random.state = state.Value; } } catch (Exception ex2) { Plugin.Log.LogError((object)("[patch] " + where + " seed restore: " + ex2.Message)); } return ex; } } [HarmonyPatch(typeof(RunStateManager), "OnCoreRunStarted")] internal static class MissionSeed_OnCoreRunStarted { private static void Prefix(out State? __state) { __state = null; try { MissionSeed.Enter(3999, "RunStateManager.OnCoreRunStarted", out __state); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] RunStateManager.OnCoreRunStarted seed: " + ex.Message)); } } private static Exception Finalizer(Exception __exception, State? __state) { return MissionSeed.Exit(__exception, __state, "RunStateManager.OnCoreRunStarted"); } } [HarmonyPatch(typeof(RunStateManager), "OnNewCycleSetup")] internal static class MissionSeed_OnNewCycleSetup { private static void Prefix(out State? __state) { __state = null; try { MissionSeed.Enter(MissionSeed.StageSalt(1), "RunStateManager.OnNewCycleSetup", out __state); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] RunStateManager.OnNewCycleSetup seed: " + ex.Message)); } } private static Exception Finalizer(Exception __exception, State? __state) { return MissionSeed.Exit(__exception, __state, "RunStateManager.OnNewCycleSetup"); } } [HarmonyPatch(typeof(MHandlerSpawnCocoons), "OnStageBegin")] internal static class MissionSeed_SpawnCocoons { private static void Prefix(out State? __state) { __state = null; try { MissionSeed.Enter(MissionSeed.StageSalt(2), "MHandlerSpawnCocoons.OnStageBegin", out __state); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] MHandlerSpawnCocoons.OnStageBegin seed: " + ex.Message)); } } private static Exception Finalizer(Exception __exception, State? __state) { return MissionSeed.Exit(__exception, __state, "MHandlerSpawnCocoons.OnStageBegin"); } } [HarmonyPatch(typeof(GameController), "OnObjectiveComplete")] internal static class GameController_OnObjectiveComplete_Seed { private static void Prefix(GameController __instance, ObjectiveProgress __0, out State? __state) { //IL_006c: Unknown result type (might be due to invalid IL or missing references) __state = null; try { if (!Session.SeedActive) { return; } int num = -1; List<ObjectiveProgress> val = (((Object)(object)__instance.objectiveTracker != (Object)null) ? __instance.objectiveTracker.Objectives : null); if (val != null && __0 != null) { for (int i = 0; i < val.Count; i++) { ObjectiveProgress val2 = val[i]; if (val2 != null && ((Il2CppObjectBase)val2).Pointer == ((Il2CppObjectBase)__0).Pointer) { num = i; break; } } } __state = Random.state; Session.Reseed(5000 + GameRefs.StageIndex * 16 + num, "OnObjectiveComplete #" + num); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnObjectiveComplete seed: " + ex.Message)); } } private static Exception Finalizer(Exception __exception, State? __state) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) try { if (__state.HasValue) { Random.state = __state.Value; } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnObjectiveComplete seed restore: " + ex.Message)); } return __exception; } } [HarmonyPatch(typeof(ObjectiveProgress), "AddProgress")] internal static class ObjectiveSync_AddProgress { private static bool Prefix(ObjectiveProgress __instance, int __0, ref bool __result) { try { return !EnemySync.ClientActive || ObjectiveSync.ClientAllowAdd(__instance, __0, ref __result); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] ObjectiveProgress.AddProgress: " + ex.Message)); return true; } } private static void Postfix(ObjectiveProgress __instance, bool __runOriginal) { try { if (__runOriginal && EnemySync.HostActive) { ObjectiveSync.HostOnProgress(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] ObjectiveProgress.AddProgress postfix: " + ex.Message)); } } } [HarmonyPatch(typeof(ObjectiveProgress), "SetProgress")] internal static class ObjectiveSync_SetProgress { private static bool Prefix(ObjectiveProgress __instance, ref bool __result) { try { if (!EnemySync.ClientActive) { return true; } __result = __instance.isComplete; return false; } catch { return true; } } private static void Postfix(ObjectiveProgress __instance, bool __runOriginal) { try { if (__runOriginal && EnemySync.HostActive) { ObjectiveSync.HostOnProgress(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] ObjectiveProgress.SetProgress postfix: " + ex.Message)); } } } internal static class PerPlayerScope { internal static void Enter(out bool entered) { entered = EnemySync.ClientActive; if (entered) { ObjectiveSync.PerPlayerDepth++; } } internal static void Exit(bool entered) { if (entered && ObjectiveSync.PerPlayerDepth > 0) { ObjectiveSync.PerPlayerDepth--; } } } [HarmonyPatch(typeof(LevelObjectiveTracker), "OnCurrencyCollected")] internal static class ObjectiveSync_OnCurrencyCollected { private static void Prefix(out bool __state) { PerPlayerScope.Enter(out __state); } private static void Postfix(bool __state) { PerPlayerScope.Exit(__state); } } [HarmonyPatch(typeof(LevelObjectiveTracker), "OnEggCollected")] internal static class ObjectiveSync_OnEggCollected { private static void Prefix(out bool __state) { PerPlayerScope.Enter(out __state); } private static void Postfix(bool __state) { PerPlayerScope.Exit(__state); } } [HarmonyPatch(typeof(LevelObjectiveTracker), "OnLevelPickupCollected")] internal static class ObjectiveSync_OnLevelPickupCollected { private static void Prefix(out bool __state) { PerPlayerScope.Enter(out __state); } private static void Postfix(bool __state) { PerPlayerScope.Exit(__state); } } [HarmonyPatch(typeof(LevelObjectiveTracker), "OnTNTArmed")] internal static class ObjectiveSync_OnTNTArmed { private static void Prefix(out bool __state) { PerPlayerScope.Enter(out __state); } private static void Postfix(bool __state) { PerPlayerScope.Exit(__state); } } [HarmonyPatch(typeof(PointExtractionHandler), "OnAquarkDelivered")] internal static class ObjectiveSync_OnAquarkDelivered { private static void Prefix(out bool __state) { PerPlayerScope.Enter(out __state); } private static void Postfix(bool __state) { PerPlayerScope.Exit(__state); } } [HarmonyPatch(typeof(DropPod), "AnimateIn", new Type[] { typeof(float) })] internal static class ObjectiveSync_DropPod_AnimateIn { private static bool Prefix() { try { if (!EnemySync.ClientActive) { return true; } Plugin.Log.LogInfo((object)"[objective] client: own drop pod skipped (waiting for the host's)"); return false; } catch { return true; } } private static void Postfix(DropPod __instance, bool __runOriginal) { try { if (__runOriginal && EnemySync.HostActive) { ObjectiveSync.HostOnPodIn(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] DropPod.AnimateIn: " + ex)); } } } [HarmonyPatch(typeof(GameController), "_OnObjectiveComplete_b__76_1")] internal static class ObjectiveSync_PodCancelCondition { private static bool Prefix(ref bool __result) { try { if (!EnemySync.HostActive) { return true; } __result = false; return false; } catch { return true; } } } internal static class SaveGuard { [HarmonyPatch(typeof(PCSaveFileManager), "PerformSave")] internal static class PerformSave { private static bool Prefix(ref bool __result) { Note("PerformSave"); __result = true; return false; } } [HarmonyPatch(typeof(PCSaveFileManager), "RotateSaveFile")] internal static class RotateSaveFile { private static bool Prefix() { Note("RotateSaveFile"); return false; } } [HarmonyPatch(typeof(PCSaveFileManager), "DeleteSaveSlot")] internal static class DeleteSaveSlot { private static bool Prefix() { Note("DeleteSaveSlot"); return false; } } [HarmonyPatch(typeof(PCSaveFileManager), "WriteToDisk")] internal static class WriteToDisk { private static bool Prefix(ref bool __result) { Note("WriteToDisk"); __result = true; return false; } } [HarmonyPatch(typeof(PCMidRunSaveManager), "TryWriteSaveToDisk")] internal static class TryWriteSaveToDisk { private static bool Prefix(ref bool __result) { Note("TryWriteSaveToDisk"); __result = true; return false; } } [HarmonyPatch(typeof(PCMidRunSaveManager), "DeleteSave")] internal static class MidRunDeleteSave { private static bool Prefix(ref UniTask __result) { Note("MidRun.DeleteSave"); __result = Completed(); return false; } } [HarmonyPatch(typeof(PCMidRunSaveManager), "DeleteSaveForCurrentSlot")] internal static class MidRunDeleteSaveForCurrentSlot { private static bool Prefix(ref UniTask __result) { Note("MidRun.DeleteSaveForCurrentSlot"); __result = Completed(); return false; } } [HarmonyPatch(typeof(LocalPrefs), "Save")] internal static class LocalPrefsSave { private static bool Prefix() { Note("LocalPrefs.Save"); return false; } } private static bool _logged; public static void Apply(Harmony harmony) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown int num = 0; int num2 = 0; Type[] nestedTypes = typeof(SaveGuard).GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic); bool flag = default(bool); foreach (Type type in nestedTypes) { if (type.GetCustomAttributes(typeof(HarmonyPatch), inherit: false).Length == 0) { continue; } try { harmony.CreateClassProcessor(type).Patch(); num++; } catch (Exception ex) { num2++; ManualLogSource log = Plugin.Log; BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(21, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[saveguard] "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(type.Name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" failed: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetBaseException().Message); } log.LogError(val); } } ManualLogSource log2 = Plugin.Log; BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(61, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[saveguard] instance "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(Plugin.InstanceIndex); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(": save writes disabled ("); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" hooks, "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num2); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" failed)"); } log2.LogInfo(val2); } private static void Note(string what) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown if (!_logged) { _logged = true; ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(72, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[saveguard] instance "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(Plugin.InstanceIndex); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": blocked first write ("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(what); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("); further blocks not logged"); } log.LogInfo(val); } } private static UniTask Completed() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown try { return new UniTask(); } catch { return null; } } } [HarmonyPatch(typeof(GameController), "OnPlayerDropPodEscape")] internal static class SessionFlow_OnPlayerDropPodEscape { private static bool Prefix(GameController __instance) { try { if (SessionFlow.BypassGate || !SessionFlow.CoOpRun) { return true; } GameController gc = __instance; return !SessionFlow.BeginGate(GateKind.StageEnd, GameRefs.StageIndex, delegate { gc.OnPlayerDropPodEscape(); }, missed: false); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnPlayerDropPodEscape: " + ex)); return true; } } } [HarmonyPatch(typeof(GameController), "OnPlayerMissedDropPod")] internal static class SessionFlow_OnPlayerMissedDropPod { private static bool Prefix(GameController __instance) { try { if (SessionFlow.BypassGate || !SessionFlow.CoOpRun) { return true; } GameController gc = __instance; return !SessionFlow.BeginGate(GateKind.StageEnd, GameRefs.StageIndex, delegate { SessionFlow.EscapeWithoutPod(gc); }, missed: true); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnPlayerMissedDropPod: " + ex)); return true; } } } [HarmonyPatch(typeof(UIShopScreen), "OnPlayButton")] internal static class SessionFlow_ShopPlay { private static bool Prefix(UIShopScreen __instance) { try { if (SessionFlow.BypassGate || !SessionFlow.CoOpRun) { return true; } UIShopScreen shop = __instance; return !SessionFlow.BeginGate(GateKind.ShopExit, GameRefs.StageIndex, delegate { shop.OnPlayButton(); }, missed: false); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] UIShopScreen.OnPlayButton: " + ex)); return true; } } } [HarmonyPatch(typeof(GameController), "OnPlayerDeath")] internal static class SessionFlow_OnPlayerDeath { private static bool Prefix() { try { if (SessionFlow.BypassDeath || !SessionFlow.CoOpRun) { return true; } return !Revive.OnLocalDeath(); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnPlayerDeath: " + ex)); return true; } } } [HarmonyPatch(typeof(Player), "Move")] internal static class SessionFlow_PlayerMove { private static bool Prefix(Player __instance) { try { if (!Revive.LocalDowned && !SessionFlow.WaitingMissed) { return true; } Player player = GameRefs.Player; return (Object)(object)player == (Object)null || ((Il2CppObjectBase)player).Pointer != ((Il2CppObjectBase)__instance).Pointer; } catch { return true; } } } [HarmonyPatch(typeof(Player), "TakeDamage")] internal static class SessionFlow_PlayerTakeDamage { private static bool Prefix(Player __instance, ref bool __result) { try { if (!Revive.LocalDowned && !SessionFlow.Waiting) { return true; } Player player = GameRefs.Player; if ((Object)(object)player == (Object)null || ((Il2CppObjectBase)player).Pointer != ((Il2CppObjectBase)__instance).Pointer) { return true; } __result = false; return false; } catch { return true; } } } [HarmonyPatch(typeof(Player), "Heal")] internal static class SessionFlow_PlayerHeal { private static bool Prefix(Player __instance) { try { if (!Revive.LocalDowned || Revive.AllowHeal) { return true; } Player player = GameRefs.Player; return (Object)(object)player == (Object)null || ((Il2CppObjectBase)player).Pointer != ((Il2CppObjectBase)__instance).Pointer; } catch { return true; } } } [HarmonyPatch(typeof(GameController), "OnCoreRunEnd")] internal static class SessionFlow_OnCoreRunEnd { private static void Postfix() { try { SessionFlow.OnLocalRunEnd(); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] OnCoreRunEnd (flow): " + ex)); } } } internal static class SessionFlowSaveGuard { [HarmonyPatch(typeof(PCMidRunSaveManager), "SaveToCurrentSlot")] internal static class SaveToCurrentSlot { private static bool Prefix(ref UniTask<bool> __result) { try { if (!Active) { return true; } Note("SaveToCurrentSlot"); return !TryCompleted(ref __result); } catch { return true; } } } [HarmonyPatch(typeof(PCMidRunSaveManager), "Save")] internal static class Save { private static bool Prefix(ref UniTask<bool> __result) { try { if (!Active) { return true; } Note("Save"); return !TryCompleted(ref __result); } catch { return true; } } } [HarmonyPatch(typeof(PCMidRunSaveManager), "TryWriteSaveToDisk")] internal static class TryWriteSaveToDisk { private static bool Prefix(ref bool __result) { try { if (!Active) { return true; } Note("TryWriteSaveToDisk"); __result = true; return false; } catch { return true; } } } private static bool _logged; internal static bool Active { get { try { return Session.SeedActive; } catch { return false; } } } internal static void Note(string what) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown if (!_logged) { _logged = true; ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(79, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[coopsave] co-op run active: mid-run save blocked ("); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(what); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("); further blocks not logged"); } log.LogInfo(val); } } private static bool TryCompleted(ref UniTask<bool> result) { try { result = new UniTask<bool>(true); return result != null; } catch { return false; } } } internal static class SmokePatches { public static void Apply(Harmony harmony) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown try { MethodInfo methodInfo = AccessTools.Method(typeof(Player), "Move", (Type[])null, (Type[])null); MethodInfo method = typeof(SmokePatches).GetMethod("MovePrefix", BindingFlags.Static | BindingFlags.NonPublic); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Log.LogInfo((object)"[smoke] patched Player.Move (bot movement)"); if (Smoke.God) { MethodInfo methodInfo2 = AccessTools.Method(typeof(Player), "TakeDamage", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(SmokePatches).GetMethod("GodPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Log.LogInfo((object)"[smoke] god mode: local dwarf takes no damage"); } } catch (Exception ex) { ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(34, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[patch] SmokePatches.Move failed: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.GetBaseException().Message); } log.LogError(val); } } private static bool GodPrefix(Player __instance, ref bool __result) { try { Player player = GameRefs.Player; if ((Object)(object)player == (Object)null || ((Il2CppObjectBase)player).Pointer != ((Il2CppObjectBase)__instance).Pointer) { return true; } __result = false; return false; } catch { return true; } } private static void MovePrefix(Player __instance) { try { if (Smoke.Enabled) { SmokeBot.ApplyMove(__instance); } } catch (Exception e) { Smoke.Warn("move prefix", e); } } } internal static class TerrainHooks { internal static bool IsSynced(MineableBlock b) { if (!((Object)(object)((Il2CppObjectBase)b).TryCast<RockBlock>() != (Object)null)) { return (Object)(object)((Il2CppObjectBase)b).TryCast<MaterialBlock>() != (Object)null; } return true; } } [HarmonyPatch(typeof(MineableBlock), "Setup")] internal static class TerrainSync_BlockSetup { private static void Postfix(MineableBlock __instance, int __2, int __3) { try { if (NetManager.Instance.IsConnected && TerrainHooks.IsSynced(__instance)) { TerrainSync.Register(__instance, __2, __3); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TerrainSync Setup: " + ex.Message)); } } } [HarmonyPatch(typeof(MapGenerator), "CreateMap")] internal static class TerrainSync_CreateMap { private static void Prefix() { try { if (NetManager.Instance.IsConnected) { TerrainSync.ResetForNewMap(); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TerrainSync CreateMap: " + ex.Message)); } } } [HarmonyPatch(typeof(MapGenerator), "BlockDestroyed")] internal static class TerrainSync_BlockDestroyed { private static void Postfix(MineableBlock __0) { try { if (NetManager.Instance.IsConnected && !TerrainSync.Applying && !((Object)(object)__0 == (Object)null) && TerrainSync.TryGetTracked(__0, out var key, out var _) && TerrainSync.RegenDepth <= 0) { TerrainSync.QueueDestroy(key); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TerrainSync BlockDestroyed: " + ex.Message)); } } } [HarmonyPatch(typeof(RegeneratingRockBlock), "RegenLayerDie")] internal static class TerrainSync_RegenLayerDie { private static void Prefix() { try { if (NetManager.Instance.IsConnected && !TerrainSync.Applying) { TerrainSync.RegenDepth++; } } catch { } } private static void Postfix(RegeneratingRockBlock __instance) { try { if (NetManager.Instance.IsConnected && !TerrainSync.Applying) { if (TerrainSync.RegenDepth > 0) { TerrainSync.RegenDepth--; } if (TerrainSync.TryGetTracked((MineableBlock)(object)__instance, out var key, out var _)) { TerrainSync.QueueRegenLayer(key); } } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TerrainSync RegenLayerDie: " + ex.Message)); } } } [HarmonyPatch(typeof(MineableBlock), "TakeDamage")] internal static class TerrainSync_TakeDamage { private static void Postfix(MineableBlock __instance) { try { if (NetManager.Instance.IsConnected && !TerrainSync.Applying && TerrainSync.TryGetTracked(__instance, out var key, out var tracked)) { TerrainSync.QueueDamage(key, tracked); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] TerrainSync TakeDamage: " + ex.Message)); } } } [HarmonyPatch(typeof(PickupSpawner), "SpawnMaterial")] internal static class TerrainSync_NoMaterial { private static bool Prefix() { return !TerrainSync.Applying; } } [HarmonyPatch(typeof(PickupSpawner), "SpawnXP")] internal static class TerrainSync_NoXP { private static bool Prefix() { return !TerrainSync.Applying; } } [HarmonyPatch(typeof(PickupSpawner), "SpawnAlienEgg")] internal static class TerrainSync_NoEgg { private static bool Prefix() { return !TerrainSync.Applying; } } internal static class FxHooks { internal static bool IsLocalPlayerProjectile(Projectile p) { if (p.isEnemy || (Object)(object)p.aiWeaponHandler != (Object)null) { return false; } WeaponHandler weaponHandler = p.weaponHandler; if ((Object)(object)weaponHandler != (Object)null && (Object)(object)weaponHandler.enemyOwner != (Object)null) { return false; } Entity owner = p.owner; if ((Object)(object)owner != (Object)null && (Object)(object)((Il2CppObjectBase)owner).TryCast<Player>() == (Object)null) { return false; } return true; } internal static bool IsLocalPlayerWeapon(WeaponHandler wh) { if ((Object)(object)wh != (Object)null && (Object)(object)wh.enemyOwner == (Object)null) { return (Object)(object)wh.owner != (Object)null; } return false; } } [HarmonyPatch(typeof(Projectile), "SetInitialState")] internal static class WeaponFx_ProjectileLaunch { private static void Postfix(Projectile __instance, Vector3 __0, Vector3 __1) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) try { if (NetManager.Instance.IsConnected && WeaponFx.CanSend && FxHooks.IsLocalPlayerProjectile(__instance)) { WeaponFx.OnProjectile(__instance, __0, __1); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx SetInitialState: " + ex.Message)); } } } [HarmonyPatch(typeof(ExplosionHandler), "Explode")] internal static class WeaponFx_Explode { private static void Postfix(WeaponHandler __0, Vector3 __1, float __2, EDamageType __3, VFXAssetGeneric __5, bool __7) { //IL_0023: 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) try { if (NetManager.Instance.IsConnected && WeaponFx.CanSend && __7 && FxHooks.IsLocalPlayerWeapon(__0)) { WeaponFx.OnExplosion(__1, __2, __3, __5); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx Explode: " + ex.Message)); } } } [HarmonyPatch(typeof(ExplosionHandler), "ExplodeShrapnel")] internal static class WeaponFx_Shrapnel { private static void Postfix(WeaponHandler __0, Vector3 __1, float __2) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) try { if (NetManager.Instance.IsConnected && WeaponFx.CanSend && FxHooks.IsLocalPlayerWeapon(__0)) { WeaponFx.OnShrapnel(__1, __2); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx Shrapnel: " + ex.Message)); } } } [HarmonyPatch(typeof(BeamWeaponHandler), "BaseLogicTick")] internal static class WeaponFx_BeamTick { private static void Postfix(BeamWeaponHandler __instance) { try { if (NetManager.Instance.IsConnected && WeaponFx.CanSend && FxHooks.IsLocalPlayerWeapon((WeaponHandler)(object)__instance)) { WeaponFx.OnBeamTick(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx BeamTick: " + ex.Message)); } } } [HarmonyPatch(typeof(BeamWeaponHandler), "StopBeaming")] internal static class WeaponFx_BeamStop { private static void Postfix(BeamWeaponHandler __instance) { try { if (NetManager.Instance.IsConnected) { WeaponFx.OnBeamStop(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx BeamStop: " + ex.Message)); } } } [HarmonyPatch(typeof(Drone), "StartDrone")] internal static class WeaponFx_DroneStart { private static void Postfix(Drone __instance) { try { if (NetManager.Instance.IsConnected && WeaponFx.CanSend) { Player player = GameRefs.Player; Player owner = __instance.owner; if (!((Object)(object)player == (Object)null) && !((Object)(object)owner == (Object)null) && !(((Il2CppObjectBase)owner).Pointer != ((Il2CppObjectBase)player).Pointer)) { WeaponFx.OnDroneStart(__instance); } } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx DroneStart: " + ex.Message)); } } } [HarmonyPatch(typeof(Drone), "StopDrone")] internal static class WeaponFx_DroneStop { private static void Postfix(Drone __instance) { try { WeaponFx.OnDroneStop(__instance); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx DroneStop: " + ex.Message)); } } } [HarmonyPatch(typeof(Drone), "ForceStop")] internal static class WeaponFx_DroneForceStop { private static void Postfix(Drone __instance) { try { WeaponFx.OnDroneStop(__instance); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx DroneForceStop: " + ex.Message)); } } } [HarmonyPatch(typeof(Projectile), "ProjectileHit")] internal static class WeaponFx_ProjectileHit { private static void Prefix(Projectile __instance) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) try { if (NetManager.Instance.IsConnected && WeaponFx.CanSend && FxHooks.IsLocalPlayerProjectile(__instance)) { WeaponFx.OnImpact(__instance, ((Component)__instance).transform.position); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponFx ProjectileHit: " + ex.Message)); } } } internal static class GroundZonePatches { private static int _logged; public static void Apply(Harmony harmony) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Expected O, but got Unknown int num = 0; try { HarmonyMethod val = new HarmonyMethod(typeof(GroundZonePatches).GetMethod("Postfix", BindingFlags.Static | BindingFlags.NonPublic)); MethodInfo[] methods = typeof(GroundZone).GetMethods(BindingFlags.Instance | BindingFlags.Public); bool flag = default(bool); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name != "Init" || methodInfo.IsGenericMethod) { continue; } try { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); num++; } catch (Exception ex) { ManualLogSource log = Plugin.Log; BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(32, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("[patch] GroundZone.Init("); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(methodInfo.GetParameters().Length); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" args): "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message); } log.LogWarning(val2); } } ManualLogSource log2 = Plugin.Log; BepInExInfoLogInterpolatedStringHandler val3 = new BepInExInfoLogInterpolatedStringHandler(43, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("[patch] GroundZone.Init overloads patched: "); ((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<int>(num); } log2.LogInfo(val3); if (num == 0) { Plugin.Log.LogError((object)"[patch] GroundZonePatches failed: no GroundZone.Init overload found"); } } catch (Exception ex2) { Plugin.Log.LogError((object)("[patch] GroundZonePatches failed: " + ex2.GetBaseException().Message)); } } private static void Postfix(GroundZone __instance) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown try { if (!NetManager.Instance.IsConnected || !WeaponFx.CanSend) { return; } Player player = GameRefs.Player; if ((Object)(object)player == (Object)null) { return; } if (_logged < 5) { _logged++; string text = "none"; try { if ((Object)(object)__instance.player != (Object)null) { text = "player"; } else if ((Object)(object)__instance.handler != (Object)null && (Object)(object)((WeaponHandler)__instance.handler).owner != (Object)null) { text = "handler"; } else if ((Object)(object)__instance.baseWeaponHandler != (Object)null && (Object)(object)__instance.baseWeaponHandler.owner != (Object)null) { text = "baseHandler"; } } catch { text = "?"; } ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(37, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[fx] ground zone init: '"); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Object)((Component)__instance).gameObject).name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' owner="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" vfx="); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>((Object)(object)__instance.vfx != (Object)null); } log.LogInfo(val); } Player val2 = null; try { val2 = __instance.player; } catch { } if ((Object)(object)val2 == (Object)null) { try { GroundzoneGrenadeWeaponHandler handler = __instance.handler; if ((Object)(object)handler != (Object)null) { val2 = ((WeaponHandler)handler).owner; } } catch { } } if ((Object)(object)val2 == (Object)null) { try { WeaponHandler baseWeaponHandler = __instance.baseWeaponHandler; if ((Object)(object)baseWeaponHandler != (Object)null) { val2 = baseWeaponHandler.owner; } } catch { } } if (!((Object)(object)val2 == (Object)null) && !(((Il2CppObjectBase)val2).Pointer != ((Il2CppObjectBase)player).Pointer)) { WeaponFx.OnZone(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] GroundZone.Init postfix: " + ex.Message)); } } } internal static class WeaponSpawnPatches { public static void Apply(Harmony harmony) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown Type[] obj = new Type[3] { typeof(WeaponSpawn), typeof(WeaponSpawnTurret), typeof(WeaponSpawnThumperTurret) }; HarmonyMethod post = new HarmonyMethod(typeof(WeaponSpawnPatches).GetMethod("SpawnPostfix", BindingFlags.Static | BindingFlags.NonPublic)); HarmonyMethod post2 = new HarmonyMethod(typeof(WeaponSpawnPatches).GetMethod("DeSpawnPostfix", BindingFlags.Static | BindingFlags.NonPublic)); int num = 0; Type[] array = obj; foreach (Type t in array) { num += TryPatch(harmony, t, "OnSpawn", post); num += TryPatch(harmony, t, "DeSpawn", post2); } ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(41, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[patch] WeaponSpawn spawn/despawn hooks: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num); } log.LogInfo(val); if (num == 0) { Plugin.Log.LogError((object)"[patch] WeaponSpawnPatches failed: no OnSpawn/DeSpawn found"); } } private static int TryPatch(Harmony harmony, Type t, string name, HarmonyMethod post) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown try { MethodInfo methodInfo = AccessTools.DeclaredMethod(t, name, (Type[])null, (Type[])null); if (methodInfo == null) { return 0; } harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, post, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); return 1; } catch (Exception ex) { ManualLogSource log = Plugin.Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(11, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[patch] "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(t.Name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("."); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } log.LogWarning(val); return 0; } } private static void SpawnPostfix(WeaponSpawn __instance) { try { if (NetManager.Instance.IsConnected && WeaponFx.CanSend) { Player player = GameRefs.Player; Player val = null; try { val = __instance.owner; } catch { } if (!((Object)(object)player == (Object)null) && !((Object)(object)val == (Object)null) && !(((Il2CppObjectBase)val).Pointer != ((Il2CppObjectBase)player).Pointer)) { WeaponFx.OnSpawnObject(__instance); } } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponSpawn.OnSpawn: " + ex.Message)); } } private static void DeSpawnPostfix(WeaponSpawn __instance) { try { WeaponFx.OnSpawnObjectStop(__instance); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] WeaponSpawn.DeSpawn: " + ex.Message)); } } } [HarmonyPatch(typeof(MapGenerator), "PlaceActivationZone")] internal static class WorldSync_PlaceActivationZone { private static bool Prefix(ref ActivationZone __result) { try { if (WorldObjectSync.AllowPlaceZone()) { return true; } __result = null; return false; } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] PlaceActivationZone: " + ex.Message)); return true; } } private static void Postfix(ActivationZone __result, ERewardType __3, bool __runOriginal) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) try { if (__runOriginal && EnemySync.HostActive) { WorldObjectSync.HostOnZonePlaced(__result, __3); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] PlaceActivationZone postfix: " + ex)); } } } [HarmonyPatch(typeof(CoreGameEvents), "TriggerActivationZoneAdded")] internal static class WorldSync_TriggerActivationZoneAdded { private static bool Prefix() { try { return WorldObjectSync.AllowZoneAddedEvent(); } catch { return true; } } } [HarmonyPatch(typeof(ActivationZone), "OnZoneActivated")] internal static class WorldSync_OnZoneActivated { private static bool Prefix(ActivationZone __instance) { try { if (!EnemySync.HostActive && !EnemySync.ClientActive) { return true; } return WorldObjectSync.OnZoneActivatedPrefix(__instance); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] ActivationZone.OnZoneActivated: " + ex)); return true; } } private static void Postfix(ActivationZone __instance, bool __runOriginal) { try { if (__runOriginal && EnemySync.HostActive) { WorldObjectSync.HostOnZoneActivated(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] ActivationZone.OnZoneActivated postfix: " + ex)); } } } [HarmonyPatch(typeof(SupplyPod), "SummonAt")] internal static class WorldSync_SupplyPod_SummonAt { private static void Prefix(SupplyPod __instance, ref Vector3 __0) { try { if (EnemySync.HostActive || EnemySync.ClientActive) { WorldObjectSync.OnSummonAt(__instance, ref __0); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] SupplyPod.SummonAt: " + ex)); } } } [HarmonyPatch(typeof(SupplyPod), "Update")] internal static class WorldSync_SupplyPod_Update { private static void Prefix(SupplyPod __instance, out bool __state) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 __state = false; try { __state = (EnemySync.HostActive || EnemySync.ClientActive) && (int)__instance.state == 3; } catch { } } private static void Postfix(SupplyPod __instance, bool __state) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 try { if (__state && (int)__instance.state == 4) { WorldObjectSync.OnLocalPodAccess(__instance); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] SupplyPod.Update postfix: " + ex)); } } } [HarmonyPatch(typeof(SupplyPod), "OnSupplyPodExit")] internal static class WorldSync_SupplyPod_OnSupplyPodExit { private static bool Prefix(SupplyPod __instance) { try { if (!EnemySync.HostActive && !EnemySync.ClientActive) { return true; } return WorldObjectSync.AllowPodExit(__instance); } catch { return true; } } } [HarmonyPatch(typeof(SupplyPod), "HandleLanding")] internal static class WorldSync_SupplyPod_HandleLanding { private static void Prefix(out bool __state) { __state = EnemySync.ClientActive; if (__state) { WorldObjectSync.LandingDepth++; } } private static void Postfix(bool __state) { if (__state && WorldObjectSync.LandingDepth > 0) { WorldObjectSync.LandingDepth--; } } } [HarmonyPatch(typeof(Enemy), "TakeDamage")] internal static class WorldSync_Enemy_TakeDamage_Landing { [HarmonyPriority(800)] private static bool Prefix(Enemy __instance, ref bool __result) { try { if (WorldObjectSync.LandingDepth <= 0 || !EnemySync.ClientActive || !EnemySync.IsPuppet(__instance)) { return true; } __result = false; return false; } catch { return true; } } } [HarmonyPatch(typeof(LevelPickup), "OnTriggerEnter")] internal static class WorldSync_LevelPickup_OnTriggerEnter { private static bool Prefix(LevelPickup __instance, Collider __0, out bool __state) { __state = false; try { if (!EnemySync.HostActive && !EnemySync.ClientActive) { return true; } return WorldObjectSync.PickupPrefix(__instance, __0, fromTrigger: true, out __state); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] LevelPickup.OnTriggerEnter: " + ex)); return true; } } private static void Postfix(LevelPickup __instance, bool __state, bool __runOriginal) { try { if (__runOriginal && EnemySync.HostActive) { WorldObjectSync.HostPickupPostfix(__instance, __state); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] LevelPickup.OnTriggerEnter postfix: " + ex)); } } } [HarmonyPatch(typeof(LevelPickup), "DoPickup")] internal static class WorldSync_LevelPickup_DoPickup { private static bool Prefix(LevelPickup __instance, out bool __state) { __state = false; try { if (!EnemySync.HostActive && !EnemySync.ClientActive) { return true; } return WorldObjectSync.PickupPrefix(__instance, null, fromTrigger: false, out __state); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] LevelPickup.DoPickup: " + ex)); return true; } } private static void Postfix(LevelPickup __instance, bool __state, bool __runOriginal) { try { if (__runOriginal && EnemySync.HostActive) { WorldObjectSync.HostPickupPostfix(__instance, __state); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] LevelPickup.DoPickup postfix: " + ex)); } } } [HarmonyPatch(typeof(MapEggSack), "OnTriggerEnter")] internal static class WorldSync_MapEggSack_OnTriggerEnter { private static bool Prefix(MapEggSack __instance, out bool __state) { __state = true; try { if (!EnemySync.HostActive && !EnemySync.ClientActive) { return true; } return WorldObjectSync.SackTriggerPrefix(__instance, out __state); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] MapEggSack.OnTriggerEnter: " + ex)); return true; } } private static void Postfix(MapEggSack __instance, bool __state, bool __runOriginal) { try { if (__runOriginal && EnemySync.HostActive) { WorldObjectSync.HostSackTriggered(__instance, __state); } } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] MapEggSack.OnTriggerEnter postfix: " + ex)); } } } [HarmonyPatch(typeof(MapEggSack), "DoPop")] internal static class WorldSync_MapEggSack_DoPop { private static bool Prefix(MapEggSack __instance) { try { if (!EnemySync.HostActive && !EnemySync.ClientActive) { return true; } return WorldObjectSync.SackPopPrefix(__instance); } catch (Exception ex) { Plugin.Log.LogError((object)("[patch] MapEggSack.DoPop: " + ex)); return true; } } } [HarmonyPatch(typeof(MapEggSack), "OnDespawn")] internal static class WorldSync_MapEggSack_OnDespawn { private static void Postfix(MapEggSack __instance) { try { if (EnemySync.HostActive || EnemySync.ClientActive) { WorldObjectSync.OnSackDespawn(__instance); } } catch { } } } } namespace DRGSMultiplayer.Net { internal interface ITransport { string Name { get; } bool Send(ulong peer, byte[] data, bool reliable, out string error); void Pump(Action<ulong, byte[]> sink); void ClosePeer(ulong peer); void Close(); } public sealed class FriendLobby { public ulong FriendId; public string FriendName; public ulong LobbyId; public string ModVersion; } public sealed class LobbyManager { private enum Pending { None, Create, Join } public const string DataKey = "drgsmp"; public static int MaxMembers = 4; public readonly List<ulong> Members = new List<ulong>(); public readonly List<FriendLobby> FriendLobbies = new List<FriendLobby>(); private Pending _pending; private ulong _call; private ulong _joinTarget; private double _nextMemberPoll; private double _nextFriendPoll; private readonly HashSet<ulong> _requestedData = new HashSet<ulong>(); public ulong LobbyId { get; private set; } public ulong OwnerId { get; private set; } public string Status { get; private set; } = "Not in a lobby"; public string LastError { get; private set; } public bool InLobby => LobbyId != 0; public bool Busy => _pending != Pending.None; public bool IsOwner { get { if (InLobby) { return OwnerId == SteamCtx.LocalId; } return false; } } public event Action MembersRefreshed; public event Action<bool> Entered; public event Action<string> Failed; public void Host() { if (SteamCtx.Ready && !Busy && !InLobby) { LastError = null; _call = SteamNative.SteamAPI_ISteamMatchmaking_CreateLobby(SteamCtx.Matchmaking, 1, MaxMembers); _pending = Pending.Create; Status = "Creating lobby..."; Plugin.Log.LogInfo((object)("[lobby] CreateLobby call " + _call)); } } public void Join(ulong lobbyId) { if (SteamCtx.Ready && !Busy && lobbyId != 0L) { if (InLobby) { Leave(); } LastError = null; _joinTarget = lobbyId; _call = SteamNative.SteamAPI_ISteamMatchmaking_JoinLobby(SteamCtx.Matchmaking, lobbyId); _pending = Pending.Join; Status = "Joining lobby " + lobbyId + "..."; Plugin.Log.LogInfo((object)("[lobby] JoinLobby " + lobbyId + " call " + _call)); } } public void Leave() { if (SteamCtx.Ready && LobbyId != 0L) { try { SteamNative.SteamAPI_ISteamMatchmaking_LeaveLobby(SteamCtx.Matchmaking, LobbyId); } catch { } } LobbyId = 0uL; OwnerId = 0uL; Members.Clear(); _pending = Pending.None; _call = 0uL; Status = "Not in a lobby"; } public bool IsMember(ulong id) { if (LobbyId == 0L || !SteamCtx.Ready) { return false; } int num = SteamNative.SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(SteamCtx.Matchmaking, LobbyId); for (int i = 0; i < num; i++) { if (SteamNative.SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex(SteamCtx.Matchmaking, LobbyId, i) == id) { return true; } } return false; } public string GetData(ulong lobby, string key) { return SteamNative.Str(SteamNative.SteamAPI_ISteamMatchmaking_GetLobbyData(SteamCtx.Matchmaking, lobby, key)); } public void Poll(double now) { if (SteamCtx.Ready) { if (_pending != Pending.None) { PollPending(); } if (LobbyId != 0L && now >= _nextMemberPoll) { _nextMemberPoll = now + 1.0; RefreshMembers(); } if (now >= _nextFriendPoll) { _nextFriendPoll = now + 2.0; RefreshFriendLobbies(); } } } private unsafe void PollPending() { if (!SteamNative.SteamAPI_ISteamUtils_IsAPICallCompleted(SteamCtx.Utils, _call, out var failed)) { return; } Pending pending = _pending; _pending = Pending.None; if (failed) { int value = SteamNative.SteamAPI_ISteamUtils_GetAPICallFailureReason(SteamCtx.Utils, _call); Fail($"{pending} call failed (reason {value})"); return; } byte* ptr = stackalloc byte[64]; for (int i = 0; i < 64; i++) { ptr[i] = 0; } int iCallbackExpected = ((pending == Pending.Create) ? 513 : 504); int cubCallback = ((pending == Pending.Create) ? 16 : 24); bool flag = SteamNative.SteamAPI_ISteamUtils_GetAPICallResult(SteamCtx.Utils, _call, ptr, cubCallback, iCallbackExpected, out failed); if (!flag) { flag = SteamNative.SteamAPI_ISteamUtils_GetAPICallResult(SteamCtx.Utils, _call, ptr, 64, iCallbackExpected, out failed); } if (!flag || failed) { Fail($"{pending}: GetAPICallResult failed"); return; } if (pending == Pending.Create) { int num = *(int*)ptr; ulong num2 = ((ulong*)ptr)[1]; if (num != 1 || num2 == 0L) { Fail($"CreateLobby failed (EResult {num})"); return; } LobbyId = num2; SteamNative.SteamAPI_ISteamMatchmaking_SetLobbyData(SteamCtx.Matchmaking, num2, "drgsmp", "0.2.1"); SteamNative.SteamAPI_ISteamMatchmaking_SetLobbyData(SteamCtx.Matchmaking, num2, "host_name", SteamCtx.LocalName); SteamNative.SteamAPI_ISteamMatchmaking_SetLobbyJoinable(SteamCtx.Matchmaking, num2, joinable: true); Status = "Hosting lobby " + num2; Plugin.Log.LogInfo((object)("[lobby] created " + num2)); RefreshMembers(); this.Entered?.Invoke(obj: true); return; } ulong num3 = *(ulong*)ptr; uint num4 = ((uint*)ptr)[4]; if (num4 != 1 || num3 == 0L) { Fail($"JoinLobby failed (EChatRoomEnterResponse {num4}: {EnterResponseText(num4)})"); return; } LobbyId = num3; string data = GetData(num3, "drgsmp"); if (data != "0.2.1") { string msg = (string.IsNullOrEmpty(data) ? "That lobby is not a DRGS Multiplayer lobby" : $"Mod version mismatch (host {data}, you {"0.2.1"})"); Leave(); Fail(msg); } else { Status = "In lobby " + num3; Plugin.Log.LogInfo((object)("[lobby] joined " + num3)); RefreshMembers(); this.Entered?.Invoke(obj: false); } } private static string EnterResponseText(uint r) { return r switch { 2u => "doesn't exist", 3u => "not allowed", 4u => "full", 5u => "error", 6u => "banned", 7u => "limited user", 8u => "clan disabled", 9u => "community ban", 10u => "member blocked you", 11u => "you blocked a member", _ => "unknown", }; } private void Fail(string msg) { _pending = Pending.None; LastError = msg; Status = (InLobby ? Status : "Not in a lobby"); Plugin.Log.LogWarning((object)("[lobby] " + msg)); this.Failed?.Invoke(msg); } private void RefreshMembers() { if (LobbyId != 0L) { Members.Clear(); int num = SteamNative.SteamAPI_ISteamMatchmaking_GetNumLobbyMembers(SteamCtx.Matchmaking, LobbyId); for (int i = 0; i < num; i++) { Members.Add(SteamNative.SteamAPI_ISteamMatchmaking_GetLobbyMemberByIndex(SteamCtx.Matchmaking, LobbyId, i)); } OwnerId = SteamNative.SteamAPI_ISteamMatchmaking_GetLobbyOwner(SteamCtx.Matchmaking, LobbyId); this.MembersRefreshed?.Invoke(); } } private unsafe void RefreshFriendLobbies() { FriendLobbies.Clear(); int num = SteamNative.SteamAPI_ISteamFriends_GetFriendCount(SteamCtx.Friends, 4); byte* ptr = stackalloc byte[48]; for (int i = 0; i < num; i++) { ulong num2 = SteamNative.SteamAPI_ISteamFriends_GetFriendByIndex(SteamCtx.Friends, i, 4); for (int j = 0; j < 48; j++) { ptr[j] = 0; } if (!SteamNative.SteamAPI_ISteamFriends_GetFriendGamePlayed(SteamCtx.Friends, num2, ptr)) { continue; } long num3 = *(long*)ptr; ulong num4 = ((ulong*)ptr)[2]; if ((uint)(num3 & 0xFFFFFF) == SteamCtx.AppId && num4 != 0L && num4 != LobbyId) { if (_requestedData.Add(num4)) { Steam
patchers/DRGSMultiplayer.Bootstrap.dll
Decompiled 3 weeks agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Preloader.Core.Patching; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("DRGSMultiplayer.Bootstrap")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.2.1.0")] [assembly: AssemblyInformationalVersion("0.2.1+b6d5e3275ae5dac2c0a0cf72c444fbcdf50ce9cf")] [assembly: AssemblyProduct("DRGSMultiplayer.Bootstrap")] [assembly: AssemblyTitle("DRGSMultiplayer.Bootstrap")] [assembly: AssemblyVersion("0.2.1.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace DRGSMultiplayer.Bootstrap { [PatcherPluginInfo("drgs.multiplayer.bootstrap", "DRGS Multiplayer Bootstrap", "0.2.1")] public class BootstrapPatcher : BasePatcher { internal enum Outcome { NoGenerator, AlreadyFixed, Replaced, ReplacedNeedsRestart, RebuildNeedsRestart } public const string Guid = "drgs.multiplayer.bootstrap"; public const string Version = "0.2.1"; private const string GeneratorName = "Il2CppInterop.Generator.dll"; private const string PayloadResource = "DRGSMultiplayer.Bootstrap.Il2CppInterop.Generator.dll"; private const string PayloadVersion = "1.5.3-ci.1121"; private const int FixedCiBuild = 1121; private static readonly Version FixedRelease = new Version(1, 5, 3); private const string InteropSentinel = "UnityEngine.CoreModule.dll"; private const string ProvenanceFile = "drgs-generator.txt"; private const uint MbOk = 0u; private const uint MbIconWarning = 48u; private const uint MbSetForeground = 65536u; public override void Initialize() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown try { Outcome outcome = Run(); if (outcome == Outcome.ReplacedNeedsRestart || outcome == Outcome.RebuildNeedsRestart) { ((BasePatcher)this).Log.LogMessage((object)"BepInEx will rebuild its interop assemblies on the next launch"); if (Notify(outcome)) { Environment.Exit(0); } } } catch (Exception ex) { ManualLogSource log = ((BasePatcher)this).Log; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(20, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("could not replace "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Il2CppInterop.Generator.dll"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } log.LogError(val); ((BasePatcher)this).Log.LogError((object)"Fix it by hand: put Il2CppInterop.Generator 1.5.3-ci.1121 in BepInEx/core/Il2CppInterop.Generator.dll and delete BepInEx/interop/assembly-hash.txt."); } } internal Outcome Run() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown string text = Path.Combine(Paths.BepInExAssemblyDirectory, "Il2CppInterop.Generator.dll"); bool flag = default(bool); if (!File.Exists(text)) { ManualLogSource log = ((BasePatcher)this).Log; BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(38, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" does not exist, leaving BepInEx alone"); } log.LogWarning(val); return Outcome.NoGenerator; } string interop = InteropAssemblyPath(); string productVersion = FileVersionInfo.GetVersionInfo(text).ProductVersion; if (HasDuplicateTypeFix(productVersion)) { ManualLogSource log2 = ((BasePatcher)this).Log; BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(31, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>("Il2CppInterop.Generator.dll"); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(productVersion); ((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" already has the Unity 6.4 fix"); } log2.LogInfo(val2); if (GeneratedThisLaunch(interop)) { Stamp(interop, productVersion); return Outcome.AlreadyFixed; } if (Vouched(interop)) { return Outcome.AlreadyFixed; } ((BasePatcher)this).Log.LogWarning((object)"interop assemblies were built by a generator without the Unity 6.4 fix and have to be rebuilt"); DropHash(interop); return Outcome.RebuildNeedsRestart; } bool num = Vouched(interop); Replace(text); ManualLogSource log3 = ((BasePatcher)this).Log; BepInExMessageLogInterpolatedStringHandler val3 = new BepInExMessageLogInterpolatedStringHandler(47, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("replaced "); ((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>("Il2CppInterop.Generator.dll"); ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" "); ((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(productVersion); ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" with "); ((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>("1.5.3-ci.1121"); ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" (Unity 6.4 duplicate-type fix)"); } log3.LogMessage(val3); if (num) { ((BasePatcher)this).Log.LogMessage((object)"interop assemblies came from a fixed generator, no regeneration needed"); return Outcome.Replaced; } DropHash(interop); return Outcome.ReplacedNeedsRestart; } private bool GeneratedThisLaunch(string interop) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown string path = Path.Combine(interop, "UnityEngine.CoreModule.dll"); if (!File.Exists(path)) { return false; } try { using Process process = Process.GetCurrentProcess(); return File.GetLastWriteTimeUtc(path) >= process.StartTime.ToUniversalTime(); } catch (Exception ex) { ManualLogSource log = ((BasePatcher)this).Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(34, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("could not tell when "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("UnityEngine.CoreModule.dll"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" was written: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } log.LogWarning(val); return false; } } private bool Vouched(string interop) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown if (!File.Exists(Path.Combine(interop, "UnityEngine.CoreModule.dll"))) { return false; } string text = Path.Combine(interop, "drgs-generator.txt"); if (!File.Exists(text)) { return false; } try { return HasDuplicateTypeFix(File.ReadAllText(text).Trim()); } catch (Exception ex) { ManualLogSource log = ((BasePatcher)this).Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(17, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("could not read "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } log.LogWarning(val); return false; } } private void Stamp(string interop, string generatorVersion) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown try { if (Directory.Exists(interop)) { string path = Path.Combine(interop, "drgs-generator.txt"); if (!File.Exists(path) || !(File.ReadAllText(path).Trim() == generatorVersion)) { File.WriteAllText(path, generatorVersion); } } } catch (Exception ex) { ManualLogSource log = ((BasePatcher)this).Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(63, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("could not record which generator built the interop assemblies: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } log.LogWarning(val); } } private static void DropHash(string interop) { string path = Path.Combine(interop, "assembly-hash.txt"); if (File.Exists(path)) { File.Delete(path); } } private static bool HasDuplicateTypeFix(string informationalVersion) { if (string.IsNullOrEmpty(informationalVersion)) { return false; } string[] array = informationalVersion.Split('+')[0].Split(new char[1] { '-' }, 2); if (!System.Version.TryParse(array[0], out Version result)) { return false; } if (result > FixedRelease) { return true; } if (result < FixedRelease) { return false; } if (array.Length == 1) { return false; } string text = array[1]; if (text.StartsWith("ci.", StringComparison.Ordinal) && int.TryParse(text.Substring(3), out var result2)) { return result2 >= 1121; } return false; } private static void Replace(string generator) { string text = generator + ".new"; using (Stream stream = typeof(BootstrapPatcher).Assembly.GetManifestResourceStream("DRGSMultiplayer.Bootstrap.Il2CppInterop.Generator.dll")) { if (stream == null) { throw new InvalidOperationException("DRGSMultiplayer.Bootstrap.Il2CppInterop.Generator.dll is missing from the patcher assembly"); } using FileStream destination = File.Create(text); stream.CopyTo(destination); } string text2 = FreeBackupPath(generator); File.Move(generator, text2); try { File.Move(text, generator); } catch { File.Move(text2, generator); throw; } } private static string FreeBackupPath(string generator) { string text = generator + ".stock"; for (int i = 0; i < 10; i++) { if (!File.Exists(text)) { return text; } try { File.Delete(text); return text; } catch (Exception) { text = $"{generator}.stock.{i + 1}"; } } return $"{generator}.stock.{DateTime.UtcNow:yyyyMMddHHmmss}"; } private static string InteropAssemblyPath() { string text = Utility.GetCommandLineArgValue("--unhollowed-path"); if (string.IsNullOrEmpty(text)) { ConfigEntry<string> val = default(ConfigEntry<string>); text = (ConfigFile.CoreConfig.TryGetEntry<string>("IL2CPP", "IL2CPPInteropAssembliesPath", ref val) ? val.Value : "{BepInEx}"); } return Path.Combine(text.Replace("{BepInEx}", Paths.BepInExRootPath).Replace("{ProcessName}", Paths.ProcessName), "interop"); } [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int MessageBoxW(IntPtr hWnd, string text, string caption, uint type); private bool Notify(Outcome outcome) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown string text = ((outcome == Outcome.RebuildNeedsRestart) ? "DRGS Multiplayer has to rebuild the files BepInEx generated for this version of the game." : "DRGS Multiplayer updated BepInEx for this version of the game.") + "\n\nStart the game once more to finish. That launch takes a few minutes with no window at all while BepInEx rebuilds its interop assemblies - that is normal, so give it time and don't kill it. It only happens once."; try { return MessageBoxW(IntPtr.Zero, text, "DRGS Multiplayer", 65584u) != 0; } catch (Exception ex) { ManualLogSource log = ((BasePatcher)this).Log; bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(35, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("could not show the restart prompt: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message); } log.LogWarning(val); return false; } } } }