using System; using System.Buffers.Binary; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dissonance; using Dissonance.Audio.Playback; using DunGen; using GameNetcodeStuff; using HarmonyLib; using HarmonyLib.Tools; using LethalPerformance.API; using LethalPerformance.Caching; using LethalPerformance.Configuration; using LethalPerformance.Extensions; using LethalPerformance.Patcher; using LethalPerformance.Patcher.API; using LethalPerformance.Patcher.Patches; using LethalPerformance.Unity; using LethalPerformance.Utilities; using Microsoft.CodeAnalysis; using NAudio.Wave; using TMPro; using Unity.AI.Navigation; using Unity.Burst.LowLevel; using Unity.Mathematics; using Unity.Netcode; using Unity.Profiling; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.InputSystem; using UnityEngine.Pool; using UnityEngine.Profiling; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("DissonanceVoip")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalPerformance")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.2.5.0")] [assembly: AssemblyInformationalVersion("1.2.5+76a8596824241c3ab2931e3ae57f62e5eb8f97e7")] [assembly: AssemblyProduct("LethalPerformance")] [assembly: AssemblyTitle("LethalPerformance")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.5.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray : IEnumerable, ICollection, IList, IEnumerable, IReadOnlyCollection, IReadOnlyList, ICollection, IList { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection.Count => _items.Length; T IReadOnlyList.this[int index] => _items[index]; int ICollection.Count => _items.Length; bool ICollection.IsReadOnly => true; T IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.Add(T item) { throw new NotSupportedException(); } void ICollection.Clear() { throw new NotSupportedException(); } bool ICollection.Contains(T item) { return ((ICollection)_items).Contains(item); } void ICollection.CopyTo(T[] array, int arrayIndex) { ((ICollection)_items).CopyTo(array, arrayIndex); } bool ICollection.Remove(T item) { throw new NotSupportedException(); } int IList.IndexOf(T item) { return ((IList)_items).IndexOf(item); } void IList.Insert(int index, T item) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.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 LethalPerformance { internal static class Dependencies { public const string MoreCompany = "me.swipez.melonloader.morecompany"; public const string Loadstone = "com.adibtw.loadstone"; public const string MoreSuits = "x753.More_Suits"; public const string LethalCompanyVR = "io.daxcess.lcvr"; public const string LethalLevelLoader = "imabatby.lethallevelloader"; public const string LobbyControl = "mattymatty.LobbyControl"; public static bool IsModLoaded(string id) { if (!Chainloader.PluginInfos.ContainsKey(id)) { return Patch_Chainloader.IsModWillBeLoaded(id); } return true; } } [BepInPlugin("LethalPerformance", "LethalPerformance", "1.2.5")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class LethalPerformancePlugin : BaseUnityPlugin { public static LethalPerformancePlugin Instance { get; private set; } internal ManualLogSource Logger { get; private set; } internal string WorkingDirectory { get; private set; } internal ConfigManager Configuration { get; private set; } internal Harmony? Harmony { get; private set; } internal ES3SaverTask ES3SaverTask { get; } = new ES3SaverTask(); protected void Awake() { Instance = this; Logger = ((BaseUnityPlugin)this).Logger; WorkingDirectory = new FileInfo(((BaseUnityPlugin)this).Info.Location).DirectoryName; Configuration = new ConfigManager(((BaseUnityPlugin)this).Config); LoadGameBurstLib(); InitializeHarmony(); CallInitializeOnAwake(); InitializeSaveScheduler(); } private void InitializeSaveScheduler() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown GameObject val = new GameObject("Lethal Performance Configuration Scheduler", new Type[1] { typeof(SaveScheduleComponent) }); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); } private void InitializeHarmony() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) LogChannel channelFilter = Logger.ChannelFilter; if ((channelFilter & 4) == 0) { Logger.ChannelFilter = (LogChannel)0; } Harmony = new Harmony("LethalPerformance"); try { Harmony.PatchAll(typeof(LethalPerformancePlugin).Assembly); } catch (Exception ex) { Logger.LogError((object)ex); } Logger.ChannelFilter = channelFilter; } private void CallInitializeOnAwake() { foreach (MethodInfo item in from m in typeof(LethalPerformancePlugin).Assembly.GetTypes().SelectMany((Type t) => t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) where ((MemberInfo)m).GetCustomAttribute() != null select m) { item.Invoke(null, null); Logger.LogInfo((object)("Initialized " + GeneralExtensions.FullDescription((MethodBase)item))); } } private void LoadGameBurstLib() { string text = Path.Combine(WorkingDirectory, "lib_burst_generated.data"); if (!File.Exists(text)) { Logger.LogFatal((object)"Failed to find \"lib_burst_generated.data\""); } else if (!BurstCompilerService.LoadBurstLibrary(text)) { Logger.LogFatal((object)"Failed to load burst library. Probably machine architecture is not x64 or CPU doesn't support AVX2 and SSE2 instructions"); } } } internal sealed class SaveScheduleComponent : MonoBehaviour { public void LateUpdate() { LethalPerformancePatcher.ConfigSaverTask.ScheduleSave(); LethalPerformancePlugin.Instance.ES3SaverTask.SaveIfDirty(); } public void OnDisable() { LethalPerformancePatcher.ConfigSaverTask.Save(); LethalPerformancePlugin.Instance.ES3SaverTask.SaveIfDirty(); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LethalPerformance"; public const string PLUGIN_NAME = "LethalPerformance"; public const string PLUGIN_VERSION = "1.2.5"; } } namespace LethalPerformance.Validation { [HarmonyPatch(typeof(StartOfRound))] internal static class EntranceTeleportValidation { [HarmonyPatch("OnShipLandedMiscEvents")] [HarmonyPostfix] private static void ShowWarningTip() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) Scene lastLoadedScene = SceneUtilities.GetLastLoadedScene(); if (!((Scene)(ref lastLoadedScene)).IsValid()) { return; } List list = default(List); PooledObject> val = CollectionPool, GameObject>.Get(ref list); try { List list2 = default(List); PooledObject> val2 = CollectionPool, EntranceTeleport>.Get(ref list2); try { ((Scene)(ref lastLoadedScene)).GetRootGameObjects(list); bool flag = false; foreach (GameObject item in list) { list2.Clear(); item.GetComponentsInChildren(list2); foreach (EntranceTeleport item2 in list2) { if (!((NetworkBehaviour)item2).IsSpawned) { flag = true; goto end_IL_0089; } } continue; end_IL_0089: break; } if (flag) { HUDManager.Instance.DisplayTip("Lethal Performance", "Entrance teleport mismatch. Expect 'The entrance appears to be blocked'.", true, false, "LP_ETBAD"); } } finally { ((IDisposable)val2).Dispose(); } } finally { ((IDisposable)val).Dispose(); } } } } namespace LethalPerformance.Utilities { internal class ES3SaverTask { private readonly HashSet m_ChangedSaves = new HashSet(); public void ScheduleSaveFor(ES3File file) { m_ChangedSaves.Add(file); } public void SaveIfDirty() { //IL_004d: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown if (m_ChangedSaves.Count == 0) { return; } int num = 0; foreach (ES3File changedSafe in m_ChangedSaves) { if (!TryGetPath(changedSafe, out string path)) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)"Got unknown cached save"); continue; } num++; changedSafe.Sync(new ES3Settings(path, (ES3Settings)null) { encryptionType = (EncryptionType)1, _location = (Location)0 }); } LethalPerformancePlugin.Instance.Logger.LogInfo((object)$"Saved {num} save(s)"); m_ChangedSaves.Clear(); } private static bool TryGetPath(ES3File file, out string? path) { foreach (KeyValuePair cachedFile in ES3File.cachedFiles) { if (cachedFile.Value == file) { path = cachedFile.Key; return true; } } path = null; return false; } } internal static class HDRenderPipelineAssetOptimizer { [InitializeOnAwake] public static void Initialize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) HDRenderPipelineAsset val = (HDRenderPipelineAsset)GraphicsSettings.currentRenderPipeline; RenderPipelineSettings currentPlatformRenderPipelineSettings = val.currentPlatformRenderPipelineSettings; currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionProbeTexCacheSize = LethalPerformancePlugin.Instance.Configuration.ReflectionProbeCacheResolution.Value; currentPlatformRenderPipelineSettings.lightLoopSettings.cookieAtlasSize = (CookieAtlasResolution)LethalPerformancePlugin.Instance.Configuration.CookieAtlasResolution.Value; currentPlatformRenderPipelineSettings.hdShadowInitParams.cachedAreaLightShadowAtlas = 8192; currentPlatformRenderPipelineSettings.hdShadowInitParams.cachedPunctualLightShadowAtlas = 8192; currentPlatformRenderPipelineSettings.hdShadowInitParams.allowDirectionalMixedCachedShadows = true; bool flag = (currentPlatformRenderPipelineSettings.supportVolumetrics = SystemInfo.supportsRenderTargetArrayIndexFromVertexShader); val.currentPlatformRenderPipelineSettings = currentPlatformRenderPipelineSettings; HDRenderPipelineGlobalSettings instance = HDRenderPipelineGlobalSettings.instance; ref FrameSettings defaultFrameSettings = ref instance.GetDefaultFrameSettings((FrameSettingsRenderType)0); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)80, false); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)1, true); ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)22, false); LethalPerformancePlugin.Instance.Logger.LogInfo((object)"Disabled StopNan and enabled DepthPrepassWithDeferredRendering globally"); if (!flag) { ((FrameSettings)(ref defaultFrameSettings)).SetEnabled((FrameSettingsField)28, false); LethalPerformancePlugin.Instance.Logger.LogInfo((object)"Disabled volumetric fog as hardware system doesn't support it"); } } } internal static class NetworkManagerUtilities { public static void FindAllSpawnedNetworkBehaviour(List spawnedObjects) where T : Object { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || singleton.SpawnManager == null) { return; } foreach (NetworkObject spawnedObjects2 in singleton.SpawnManager.SpawnedObjectsList) { if ((Object)(object)spawnedObjects2 == (Object)null) { continue; } foreach (NetworkBehaviour childNetworkBehaviour in spawnedObjects2.ChildNetworkBehaviours) { T val = (T)(object)((childNetworkBehaviour is T) ? childNetworkBehaviour : null); if (val != null && childNetworkBehaviour.IsSpawned && !((Object)(object)childNetworkBehaviour.NetworkObject != (Object)(object)spawnedObjects2)) { spawnedObjects.Add(val); } } } } } internal class OpenLogsFolderKeybind { private static InputActionAsset? s_InputActions; [InitializeOnAwake] private static void Initialize() { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) InputActionAsset val = (s_InputActions = ScriptableObject.CreateInstance()); ((Object)val).name = "LethalPerformance Input Asset"; ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); InputActionMap val2 = InputActionSetupExtensions.AddActionMap(val, "LPActionMap"); InputAction val3 = InputActionSetupExtensions.AddAction(val2, "General", (InputActionType)1, (string)null, (string)null, (string)null, (string)null, (string)null); CompositeSyntax val4 = InputActionSetupExtensions.AddCompositeBinding(val3, "TwoModifiers", (string)null, (string)null); val4 = ((CompositeSyntax)(ref val4)).With("Binding", "/l", (string)null, (string)null); val4 = ((CompositeSyntax)(ref val4)).With("Modifier1", "/ctrl", (string)null, (string)null); ((CompositeSyntax)(ref val4)).With("Modifier2", "/shift", (string)null, (string)null); val3.performed += OnOpenLogsPressed; SceneManager.activeSceneChanged += SceneManager_activeSceneChanged; } private static void SceneManager_activeSceneChanged(Scene arg0, Scene arg1) { SceneManager.activeSceneChanged -= SceneManager_activeSceneChanged; if ((Object)(object)s_InputActions != (Object)null) { s_InputActions.Enable(); } } private static void OnOpenLogsPressed(CallbackContext obj) { if (!((Object)(object)GameNetworkManager.Instance != (Object)null) || !((Object)(object)GameNetworkManager.Instance.localPlayerController != (Object)null) || !GameNetworkManager.Instance.localPlayerController.isTypingChat) { Application.OpenURL("\"" + Application.persistentDataPath + "\""); } } } internal static class SceneUtilities { public static bool IsDontDestroyOnLoad(this Scene scene) { return ((Scene)(ref scene)).buildIndex == -1; } public static bool IsMainMenu(this Scene scene) { return ((Scene)(ref scene)).name == "MainMenu"; } public static bool IsSceneShip(this Scene scene) { return ((Scene)(ref scene)).name == "SampleSceneRelay"; } public static Scene GetLastLoadedScene() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) int sceneCount = SceneManager.sceneCount; if (sceneCount == 0) { return default(Scene); } return SceneManager.GetSceneAt(sceneCount - 1); } } } namespace LethalPerformance.Patches { [HarmonyPatch(typeof(CustomPassVolume))] internal static class Patch_CustomPassVolume { [HarmonyPatch("Cull")] [HarmonyPrefix] public static bool Cull(out CullingResults? __result) { __result = null; return false; } } [HarmonyPatch(typeof(FoliageDetailDistance))] internal static class Patch_FoliageDetailDistance { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("Update")] [HarmonyTranspiler] public static IEnumerable RemoveMaterialCheck(IEnumerable instructions) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); FieldInfo field = typeof(FoliageDetailDistance).GetField("allBushRenderers", AccessTools.all); CodeMatch[] matches = (CodeMatch[])(object)new CodeMatch[10] { new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, "start"), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)field, (string)null), new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldarg_0, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Brfalse, (object)null, (string)null) }; val.MatchForward(false, matches).Repeat((Action)delegate(CodeMatcher match) { match.RemoveInstructions(matches.Length); CodeInstructionExtensions.MoveLabelsTo(match.NamedMatch("start"), match.Instruction); }, (Action)null); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(HangarShipDoor))] internal static class Patch_HangarShipDoor { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("Update")] [HarmonyTranspiler] public static IEnumerable FixFormatAllocation(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Box, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null) }).SetInstructionAndAdvance(new CodeInstruction(OpCodes.Conv_R4, (object)null)).RemoveInstruction() .Set(OpCodes.Call, (object)typeof(TMP_Text).GetMethod("SetText", new Type[2] { typeof(string), typeof(float) })); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(HDAdditionalCameraData))] internal static class Patch_HDAdditionalCameraData { [HarmonyPatch("RegisterDebug")] [HarmonyPrefix] public static bool DisableRegisteringDebugData() { return false; } } [HarmonyPatch(typeof(HDCamera))] internal static class Patch_HDCamera { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrepare] public static bool ShouldPatch() { return !Dependencies.IsModLoaded("io.daxcess.lcvr"); } [HarmonyPrefix] [HarmonyPatch("UpdateShaderVariablesXRCB")] public unsafe static bool Prefix(HDCamera __instance, ref ShaderVariablesXR cb) { fixed (ShaderVariablesXR* ptr = &cb) { void* ptr2 = ptr; fixed (ViewConstants* ptr3 = __instance.m_XRViewConstants) { void* ptr4 = ptr3; ReadableViewConstants* ptr5 = (ReadableViewConstants*)ptr4; int viewCount = __instance.viewCount; CameraBurst.UpdateShaderVariablesXRCB(ref ptr5, ref viewCount, (ReadableShaderVariablesXR*)ptr2); return false; } } } [HarmonyPrefix] [HarmonyPatch(/*Could not decode attribute arguments.*/)] public unsafe static bool UpdateShaderVariablesGlobalCB(HDCamera __instance, ref ShaderVariablesGlobal cb, int frameCount) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) fixed (ShaderVariablesGlobal* ptr = &cb) { void* ptr2 = ptr; fixed (ViewConstants* ptr3 = &__instance.mainViewConstants) { void* ptr4 = ptr3; fixed (Vector4* ptr5 = __instance.frustumPlaneEquations) { void* ptr6 = ptr5; float4x4 val = default(float4x4); ((float4x4)(ref val))..ctor(float4.op_Implicit(__instance.screenSize), float4.op_Implicit(__instance.postProcessScreenSize), float4.op_Implicit(RTHandles.rtHandleProperties.rtHandleScale), float4.op_Implicit(__instance.m_HistoryRTSystem.rtHandleProperties.rtHandleScale)); float4x4 val2 = default(float4x4); ((float4x4)(ref val2))..ctor(float4.op_Implicit(__instance.m_PostProcessRTScales), float4.op_Implicit(__instance.m_PostProcessRTScalesHistory), new float4((float)__instance.actualWidth, ((Rect)(ref __instance.finalViewport)).width, (float)__instance.actualHeight, ((Rect)(ref __instance.finalViewport)).height), float4.op_Implicit(__instance.zBufferParams)); float4x4 val3 = default(float4x4); ((float4x4)(ref val3))..ctor(float4.op_Implicit(__instance.projectionParams), float4.op_Implicit(__instance.unity_OrthoParams), float4.op_Implicit(__instance.screenParams), float4.op_Implicit(__instance.taaJitter)); bool flag = (Object)(object)__instance.m_AdditionalCameraData == (Object)null; float num = (flag ? 1f : __instance.m_AdditionalCameraData.deExposureMultiplier); float4 val4 = (float4)(flag ? new float4(1f, 1f, 0f, 0f) : float4.op_Implicit(__instance.m_AdditionalCameraData.screenCoordScaleBias)); float4 val5 = (flag ? float4.zero : float4.op_Implicit(__instance.m_AdditionalCameraData.screenSizeOverride)); FrameSettings frameSettings = __instance.frameSettings; AntialiasingMode antialiasing = __instance.antialiasing; CameraType cameraType = __instance.camera.cameraType; ReadableViewConstants* ptr7 = (ReadableViewConstants*)ptr4; float4* ptr8 = (float4*)ptr6; ref float taaSharpenStrength = ref __instance.taaSharpenStrength; ref int taaFrameIndex = ref __instance.taaFrameIndex; ref int colorPyramidHistoryMipCount = ref __instance.colorPyramidHistoryMipCount; float globalMipBias = __instance.globalMipBias; ref float time = ref __instance.time; ref float lastTime = ref __instance.lastTime; int viewCount = __instance.viewCount; float probeRangeCompressionFactor = __instance.probeRangeCompressionFactor; bool flag2 = !flag; CameraBurst.UpdateShaderVariablesGlobalCB((ReadableShaderVariablesGlobal*)ptr2, ref frameSettings, ref antialiasing, ref cameraType, ref ptr7, ref val, ref val2, ref val3, ref ptr8, ref taaSharpenStrength, ref taaFrameIndex, ref colorPyramidHistoryMipCount, ref globalMipBias, ref time, ref lastTime, ref frameCount, ref viewCount, ref probeRangeCompressionFactor, ref num, ref val4, ref flag2, ref val5); return false; } } } } } [HarmonyPatch(typeof(PlayerControllerB))] internal static class Patch_PlayerControllerB { private static Vector3[] s_Normals; [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrefix] [HarmonyPatch("ShowNameBillboard")] public static bool FixLocalBillBoardIsEnabling(PlayerControllerB __instance, bool __runOriginal) { if (!__runOriginal) { return __runOriginal; } bool flag = (Object)(object)__instance == (Object)(object)StartOfRound.Instance.localPlayerController; return !flag; } [HarmonyPatch("CalculateGroundNormal")] [HarmonyTranspiler] private static IEnumerable UseStaticField(IEnumerable instructions) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown List list = instructions.ToList(); short value = OpCodes.Ldc_I4_0.Value; OpCode opcode = list[0].opcode; int num = opcode.Value - value; if (num < 0 || num >= OpCodes.Ldc_I4_8.Value) { return list; } s_Normals = (Vector3[])(object)new Vector3[num + 1]; list.RemoveRange(0, 2); FieldInfo field = typeof(Patch_PlayerControllerB).GetField("s_Normals", AccessTools.all); list.Insert(0, new CodeInstruction(OpCodes.Ldsfld, (object)field)); return list; } } [HarmonyPatch(typeof(StartOfRound))] internal static class Patch_StartOfRound { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("SetPlayerSafeInShip")] [HarmonyTranspiler] public static IEnumerable ReplaceFindOfObjectOfType(IEnumerable instructions, ILGenerator generator) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Expected O, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Expected O, but got Unknown //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Expected O, but got Unknown //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Expected O, but got Unknown //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); LocalBuilder countLocal = generator.DeclareLocal(typeof(int), pinned: false); MethodInfo findObjectOfTypeMethod = typeof(Object).GetMethod("FindObjectsOfType", 1, AccessTools.all, null, CallingConventions.Any, Array.Empty(), Array.Empty()).MakeGenericMethod(typeof(EnemyAI)); MethodInfo getMethod = typeof(RoundManager).GetProperty("Instance", AccessTools.all).GetGetMethod(); FieldInfo field = typeof(RoundManager).GetField("SpawnedEnemies", AccessTools.all); FieldInfo field2 = typeof(List).GetField("_items", AccessTools.all); MethodInfo getMethod2 = typeof(List).GetProperty("Count", AccessTools.all).GetGetMethod(); val.SearchForward((Func)((CodeInstruction c) => CodeInstructionExtensions.Calls(c, findObjectOfTypeMethod))).Set(OpCodes.Call, (object)getMethod).Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldfld, (object)field), new CodeInstruction(OpCodes.Ldfld, (object)field2) }) .Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[4] { new CodeInstruction(OpCodes.Call, (object)getMethod), new CodeInstruction(OpCodes.Ldfld, (object)field), new CodeInstruction(OpCodes.Callvirt, (object)getMethod2), new CodeInstruction(OpCodes.Stloc, (object)countLocal) }); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[2] { new CodeMatch((OpCode?)OpCodes.Ldloc_1, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldlen, (object)null, (string)null) }).Repeat((Action)delegate(CodeMatcher m) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown m.RemoveInstructions(2).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldloc, (object)countLocal) }); }, (Action)null); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(TimeOfDay))] [HarmonyPriority(0)] internal static class Patch_TimeOfDay { [HarmonyPatch("Start")] [HarmonyPostfix] public static void FixParticleSubEmitters(TimeOfDay __instance) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) WeatherEffect[] effects = __instance.effects; foreach (WeatherEffect val in effects) { if (val == null || (Object)(object)val.effectObject == (Object)null) { continue; } ParticleSystem componentInChildren = val.effectObject.GetComponentInChildren(); if ((Object)(object)componentInChildren == (Object)null) { continue; } SubEmittersModule subEmitters = componentInChildren.subEmitters; if (((SubEmittersModule)(ref subEmitters)).enabled) { int subEmittersCount = ((SubEmittersModule)(ref subEmitters)).subEmittersCount; for (int j = 0; j < subEmittersCount; j++) { ParticleSystem subEmitterSystem = ((SubEmittersModule)(ref subEmitters)).GetSubEmitterSystem(j); MainModule main = subEmitterSystem.main; ((MainModule)(ref main)).stopAction = (ParticleSystemStopAction)0; } } } } } [HarmonyPatch(typeof(VehicleController))] internal static class Patch_VehicleController { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("FixedUpdate")] [HarmonyTranspiler] internal static IEnumerable NotSearchDropshipAfterDelivery(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldfld, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Brtrue, (object)null, "branch") }); object operand = val.NamedMatch("branch").operand; FieldInfo field = typeof(VehicleController).GetField("hasBeenSpawned", AccessTools.all); val.Advance(1).Insert((CodeInstruction[])(object)new CodeInstruction[3] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldfld, (object)field), new CodeInstruction(OpCodes.Brtrue, operand) }); return val.Instructions(); } } [HarmonyPatch(typeof(VolumeComponent))] internal static class Patch_VolumeComponent { private struct CodeInstruction { public OpCode opCode; public FieldInfo? field; public readonly void Emit(ILGenerator il) { if (field == null) { il.Emit(opCode); } else { il.Emit(opCode, field); } } } private static readonly MethodInfo s_ListAdd = typeof(List).GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); private static readonly Dictionary>?> s_FindParametersDelegates = new Dictionary>>(); [HarmonyPatch("FindParameters")] [HarmonyPrefix] private static bool FindParametersFast(object o, List parameters) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown VolumeComponent arg = (VolumeComponent)o; Type type = o.GetType(); if (!s_FindParametersDelegates.TryGetValue(type, out Action> value)) { value = CreateFindParameters(type); s_FindParametersDelegates[type] = value; } if (value == null) { return true; } value(arg, parameters); return false; } public static Action>? CreateFindParameters(Type type) { DynamicMethod dynamicMethod = new DynamicMethod("FindParametersFast", null, new Type[2] { typeof(VolumeComponent), typeof(List) }, type, skipVisibility: true); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); List codeInstructions = new List { new CodeInstruction { opCode = OpCodes.Ldarg_0 } }; EmitAddItem(type, iLGenerator, codeInstructions); iLGenerator.Emit(OpCodes.Ret); try { return (Action>)dynamicMethod.CreateDelegate(typeof(Action>)); } catch (Exception ex) { LethalPerformancePlugin.Instance.Logger.LogError((object)ex); } return null; } private static void EmitAddItem(Type type, ILGenerator il, List codeInstructions) { Label? label = null; if (codeInstructions.Count > 1) { foreach (CodeInstruction codeInstruction in codeInstructions) { codeInstruction.Emit(il); } label = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, label.Value); } foreach (FieldInfo item in from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) orderby f.MetadataToken select f) { Type fieldType = item.FieldType; if (fieldType.IsSubclassOf(typeof(VolumeParameter))) { il.Emit(OpCodes.Ldarg_1); foreach (CodeInstruction codeInstruction2 in codeInstructions) { codeInstruction2.Emit(il); } il.Emit(OpCodes.Ldfld, item); il.Emit(OpCodes.Callvirt, s_ListAdd); } else { if (fieldType.IsArray || !fieldType.IsClass || typeof(ICollection).IsAssignableFrom(fieldType)) { continue; } codeInstructions.Add(new CodeInstruction { opCode = OpCodes.Ldfld, field = item }); if (codeInstructions.Count > 30) { codeInstructions.ForEach(delegate(CodeInstruction c) { Console.WriteLine(c.field?.DeclaringType.Name + " " + c.field?.Name); }); } EmitAddItem(fieldType, il, codeInstructions); codeInstructions.RemoveAt(codeInstructions.Count - 1); } } if (label.HasValue) { il.Emit(OpCodes.Nop); il.MarkLabel(label.Value); } } } [HarmonyPatch] internal static class Patch_WaveFileWriter { private static readonly byte[] s_RIFF = "RIFF"u8.ToArray(); private static readonly byte[] s_WAVE = "WAVE"u8.ToArray(); private static readonly byte[] s_Fmt = "fmt "u8.ToArray(); private static readonly byte[] s_Data = "data"u8.ToArray(); private static readonly byte[] s_Fact = "fact"u8.ToArray(); private static readonly Dictionary s_StringToFieldMapping = new Dictionary { ["RIFF"] = typeof(Patch_WaveFileWriter).GetField("s_RIFF", AccessTools.all), ["WAVE"] = typeof(Patch_WaveFileWriter).GetField("s_WAVE", AccessTools.all), ["fmt "] = typeof(Patch_WaveFileWriter).GetField("s_Fmt", AccessTools.all), ["data"] = typeof(Patch_WaveFileWriter).GetField("s_Data", AccessTools.all), ["fact"] = typeof(Patch_WaveFileWriter).GetField("s_Fact", AccessTools.all) }; [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPatch(typeof(WaveFileWriter), "WriteDataChunkHeader")] [HarmonyPatch(typeof(WaveFileWriter), "CreateFactChunk")] [HarmonyTranspiler] private static IEnumerable ReplaceASCIICallToStaticField(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Call, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldstr, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Callvirt, (object)null, (string)null) }).Repeat((Action)delegate(CodeMatcher m) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown string key = (string)m.InstructionAt(1).operand; FieldInfo fieldInfo = s_StringToFieldMapping[key]; m.RemoveInstructions(3).Insert((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo) }); }, (Action)null); return val.InstructionEnumeration(); } [HarmonyPatch(typeof(WaveFileWriter), "WriteSamples")] [HarmonyTranspiler] private static IEnumerable FixWriterFloatAllocation(IEnumerable _) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown return new <>z__ReadOnlyArray((CodeInstruction[])(object)new CodeInstruction[6] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Ldarg_2, (object)null), new CodeInstruction(OpCodes.Ldarg_3, (object)null), CodeInstruction.Call((LambdaExpression)(Expression>>)(() => WriteSamples)), new CodeInstruction(OpCodes.Ret, (object)null) }); } private static void WriteSamples(WaveFileWriter waveFileWriter, float[] samples, int offset, int count) { Span span = stackalloc byte[4]; for (int i = 0; i < count; i++) { BinaryPrimitivesExtension.WriteSingleLittleEndian(span, samples[offset + i]); waveFileWriter._outStream.Write(span); waveFileWriter._dataChunkSize += 4; } } } } namespace LethalPerformance.Patches.ReferenceHolder { internal static class MoonCachingPatch { [HarmonyPatch(typeof(NavMeshSurface))] private static class Patch_NavMeshSurface { [HarmonyPatch("OnEnable")] [HarmonyPostfix] public static void OnEnable() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) Scene lastLoadedScene = SceneUtilities.GetLastLoadedScene(); if (!((Scene)(ref lastLoadedScene)).IsValid()) { return; } int handle = ((Scene)(ref lastLoadedScene)).handle; if (handle != s_LastCalledSceneId) { if (((Scene)(ref lastLoadedScene)).rootCount == 0) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("New scene loading triggered navmesh, but no roots on the scene! Mod initializing navmesh early?\n" + Environment.StackTrace)); } else if (!FindDropship(lastLoadedScene) || !FindDungeon(lastLoadedScene)) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("New scene loading triggered navmesh, but nothing found! Mod initializing navmesh early?\n" + Environment.StackTrace)); } else { s_LastCalledSceneId = handle; } } } private static bool FindDungeon(Scene scene) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/Systems/LevelGeneration/DungeonGenerator"); RuntimeDungeon instance = default(RuntimeDungeon); if ((Object)(object)val != (Object)null && val.TryGetComponent(ref instance)) { s_RuntimeDungeon.SetInstance(instance); return true; } List list = default(List); PooledObject> val2 = CollectionPool, GameObject>.Get(ref list); try { ((Scene)(ref scene)).GetRootGameObjects(list); foreach (GameObject item in list) { instance = item.GetComponentInChildren(false); if (!((Object)(object)instance == (Object)null)) { s_RuntimeDungeon.SetInstance(instance); return true; } } return false; } finally { ((IDisposable)val2).Dispose(); } } private static bool FindDropship(Scene scene) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/Systems/ItemShipAnimContainer/ItemShip"); ItemDropship instance = default(ItemDropship); if ((Object)(object)val != (Object)null && val.TryGetComponent(ref instance)) { s_ItemDropship.SetInstance(instance); return true; } List list = default(List); PooledObject> val2 = CollectionPool, GameObject>.Get(ref list); try { ((Scene)(ref scene)).GetRootGameObjects(list); foreach (GameObject item in list) { instance = item.GetComponentInChildren(false); if (!((Object)(object)instance == (Object)null)) { s_ItemDropship.SetInstance(instance); return true; } } return false; } finally { ((IDisposable)val2).Dispose(); } } } [HarmonyPatch(typeof(ElevatorAnimationEvents))] private static class Patch_ElevatorAnimationEvents { [HarmonyPatch("ElevatorFullyRunning")] [HarmonyPrefix] private static void ElevatorFullyRunning() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) Scene lastLoadedScene = SceneUtilities.GetLastLoadedScene(); if (((Scene)(ref lastLoadedScene)).IsValid()) { int handle = ((Scene)(ref lastLoadedScene)).handle; if (handle == s_LastCalledSceneId) { s_LastCalledSceneId = -1; s_ItemDropship.SetInstance(null); s_RuntimeDungeon.SetInstance(null); } } } } private static readonly UnsafeCachedInstance s_ItemDropship = UnsafeCacheManager.AddReferenceToMap((UnsafeCachedInstance)new ManualCachedInstance()); private static readonly UnsafeCachedInstance s_RuntimeDungeon = UnsafeCacheManager.AddReferenceToMap((UnsafeCachedInstance)new ManualCachedInstance()); private static int s_LastCalledSceneId = -1; } [HarmonyPatch(typeof(EventSystem))] internal static class Patch_EventSystem { private static readonly string[] s_CameraPaths = new string[3] { "/Systems/GameSystems/ItemSystems/MapCamera", "/Environment/HangarShip/Cameras/FrontDoorSecurityCam/SecurityCamera", "/Environment/HangarShip/Cameras/ShipCamera" }; [HarmonyPatch("OnEnable")] [HarmonyPrefix] public static void FindReferences(EventSystem __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Scene scene = ((Component)__instance).gameObject.scene; if (!scene.IsSceneShip()) { return; } try { UnsafeCacheManager.CacheInstances(); DeleteUnusedStuff(); } catch (Exception arg) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)$"Failed to get references. Probably other mod destroyed object.\n{arg}"); } } private static void DeleteUnusedStuff() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/PlayersContainer"); if ((Object)(object)val == (Object)null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)"Failed to find Player container"); return; } List list = default(List); PooledObject> val2 = ListPool.Get(ref list); try { val.GetComponentsInChildren(list); CanvasScaler val3 = default(CanvasScaler); GraphicRaycaster val4 = default(GraphicRaycaster); foreach (PlayerControllerB item in list) { if (((Component)item.usernameCanvas).TryGetComponent(ref val3)) { Object.Destroy((Object)(object)val3); } if (((Component)item.usernameCanvas).TryGetComponent(ref val4)) { Object.Destroy((Object)(object)val4); } } val = GameObject.Find("/Systems/GameSystems/ItemSystems/MapScreenUIWorldSpace"); if ((Object)(object)val != (Object)null) { GraphicRaycaster val5 = default(GraphicRaycaster); if (val.TryGetComponent(ref val5)) { Object.Destroy((Object)(object)val5); } CanvasScaler val6 = default(CanvasScaler); if (val.TryGetComponent(ref val6)) { Object.Destroy((Object)(object)val6); } } val = GameObject.Find("/Environment/HangarShip/ShipModels2b/MonitorWall/Cube/Canvas (1)"); if ((Object)(object)val != (Object)null) { GraphicRaycaster val7 = default(GraphicRaycaster); if (val.TryGetComponent(ref val7)) { Object.Destroy((Object)(object)val7); } CanvasScaler val8 = default(CanvasScaler); if (val.TryGetComponent(ref val8)) { Object.Destroy((Object)(object)val8); } } ChangeUICameraSettings(); RemoveAudioSpecializerPlugin(); DisableCameraCleanup(); } finally { ((IDisposable)val2).Dispose(); } } private static void DisableCameraCleanup() { string[] array = s_CameraPaths; HDAdditionalCameraData val2 = default(HDAdditionalCameraData); foreach (string text in array) { GameObject val = GameObject.Find(text); if (!((Object)(object)val == (Object)null) && val.TryGetComponent(ref val2)) { val2.hasPersistentHistory = true; } } } private static void RemoveAudioSpecializerPlugin() { if (!Dependencies.IsModLoaded("imabatby.lethallevelloader") && !Dependencies.IsModLoaded("mattymatty.LobbyControl")) { AudioSource[] array = Resources.FindObjectsOfTypeAll(); AudioSource[] array2 = array; foreach (AudioSource val in array2) { val.spatialize = false; } LethalPerformancePlugin.Instance.Logger.LogInfo((object)$"Disabled spatialize for {array.Length} audio sources"); } } private static void ChangeUICameraSettings() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) if (!Dependencies.IsModLoaded("io.daxcess.lcvr")) { GameObject val = GameObject.Find("/Systems/UI/UICamera"); HDAdditionalCameraData val2 = default(HDAdditionalCameraData); if (!((Object)(object)val == (Object)null) && val.TryGetComponent(ref val2)) { ref FrameSettingsOverrideMask renderingPathCustomFrameSettingsOverrideMask = ref val2.renderingPathCustomFrameSettingsOverrideMask; ref FrameSettings renderingPathCustomFrameSettings = ref val2.renderingPathCustomFrameSettings; ((BitArray128)(ref renderingPathCustomFrameSettingsOverrideMask.mask))[127u] = true; ((BitArray128)(ref renderingPathCustomFrameSettings.bitDatas))[127u] = false; ((BitArray128)(ref renderingPathCustomFrameSettingsOverrideMask.mask))[79u] = true; ((BitArray128)(ref renderingPathCustomFrameSettings.bitDatas))[79u] = false; val2.probeLayerMask = LayerMask.op_Implicit(0); } } } } } namespace LethalPerformance.Patches.Mods { [HarmonyPatch] internal static class Patch_MoreSuits { private static readonly MethodInfo? s_MethodToPatch; static Patch_MoreSuits() { if (Chainloader.PluginInfos.TryGetValue("x753.More_Suits", out var value)) { Type type = AccessTools.Inner(((object)value.Instance).GetType(), "StartOfRoundPatch"); if (type != null) { s_MethodToPatch = type.GetMethod("StartPatch", AccessTools.all); } if (s_MethodToPatch == null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)"Failed to find MoreSuits method to patch"); } } } [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPrepare] public static bool ShouldPatch() { return s_MethodToPatch != null; } [HarmonyTargetMethod] public static MethodBase GetTargetMethod() { return s_MethodToPatch; } [HarmonyTranspiler] public static IEnumerable OptimizeSuitsTextures(IEnumerable codeInstructions) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(codeInstructions, (ILGenerator)null); ConstructorInfo textureConstructor = typeof(Texture2D).GetConstructor(new Type[4] { typeof(int), typeof(int), typeof(TextureFormat), typeof(bool) }); val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Ldc_I4_2, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Ldc_I4_2, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Newobj, (object)null, (string)null) }).Repeat((Action)delegate(CodeMatcher m) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown m.SetOpcodeAndAdvance(OpCodes.Ldc_I4_4).SetOpcodeAndAdvance(OpCodes.Ldc_I4_4).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldc_I4, (object)12), new CodeInstruction(OpCodes.Ldc_I4_1, (object)null) }) .SetOperandAndAdvance((object)textureConstructor); }, (Action)null); return val.InstructionEnumeration(); } } } namespace LethalPerformance.Metrics { [HarmonyPatch(typeof(ProfilingSampler))] [IgnoredByDeepProfiler] internal static class Patch_ProfilingSampler { [HarmonyPrepare] public static bool ShouldPatch() { return Debug.isDebugBuild; } [HarmonyPatch("Begin")] [HarmonyPostfix] public static void Begin(ProfilingSampler __instance) { CustomSampler inlineSampler = __instance.inlineSampler; if (inlineSampler != null) { inlineSampler.Begin(); } } [HarmonyPatch("End")] [HarmonyPostfix] public static void End(ProfilingSampler __instance) { CustomSampler inlineSampler = __instance.inlineSampler; if (inlineSampler != null) { inlineSampler.End(); } } } [HarmonyPatch(typeof(ProfilingScope))] [IgnoredByDeepProfiler] internal static class Patch_ProfilingScope { private sealed class ProfilingScopeData { public CommandBuffer m_CommandBuffer; public ProfilingSampler? m_Sampler; } private static readonly Stack s_ProfilingScopeDatas = new Stack(); [HarmonyPrepare] public static bool ShouldPatch() { return Debug.isDebugBuild; } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPrefix] public static void StartProfiler(CommandBuffer cmd, ProfilingSampler? sampler) { ProfilingScopeData profilingScopeData = UnsafeGenericPool.Get(); profilingScopeData.m_Sampler = sampler; profilingScopeData.m_CommandBuffer = cmd; s_ProfilingScopeDatas.Push(profilingScopeData); if (sampler != null) { sampler.Begin(cmd); } } [HarmonyPatch("Dispose")] [HarmonyPrefix] public static void StopProfiler() { if (s_ProfilingScopeDatas.TryPop(out ProfilingScopeData result)) { ProfilingSampler? sampler = result.m_Sampler; if (sampler != null) { sampler.End(result.m_CommandBuffer); } result.m_Sampler = null; result.m_CommandBuffer = null; UnsafeGenericPool.Release(result); } } } } namespace LethalPerformance.Extensions { internal static class BinaryPrimitivesExtension { public static void WriteSingleLittleEndian(Span destination, float value) { if (BitConverter.IsLittleEndian) { MemoryMarshal.Write(destination, ref value); return; } int value2 = BinaryPrimitives.ReverseEndianness(BitConverter.SingleToInt32Bits(value)); MemoryMarshal.Write(destination, ref value2); } } internal static class CodeMatcherExtensions { public static CodeMatcher GetOperand(this CodeMatcher matcher, out object operand) { operand = matcher.Operand; return matcher; } } internal static class TransformExtensions { public static string GetScenePath(this Transform transform) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('/').Append(((Object)transform).name); Transform parent; while (Object.op_Implicit((Object)(object)(parent = transform.parent))) { stringBuilder.Insert(0, ((Object)parent).name).Insert(0, '/'); transform = parent; } return stringBuilder.ToString(); } } } namespace LethalPerformance.EasySave3 { internal static class ES3Utilities { public static void ForceToCache(ES3Settings settings) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) Location location = settings._location; if (((int)location == 0 || (int)location == 4) ? true : false) { settings._location = (Location)4; } } public static void LoadFileToCache(ES3Settings settings) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) if ((int)settings.encryptionType != 0) { settings.encryptionType = (EncryptionType)0; } if (ES3File.cachedFiles.ContainsKey(settings.path)) { return; } ES3Settings val = (ES3Settings)settings.Clone(); val._location = (Location)0; Location location = settings._location; settings._location = (Location)0; string fullPath = settings.FullPath; settings._location = location; if (!File.Exists(fullPath)) { ES3File val2 = new ES3File(val, false); val2.syncWithFile = true; ES3File.cachedFiles[settings.path] = val2; return; } ES3Settings val3 = (ES3Settings)settings.Clone(); val3._location = (Location)0; if (CheckFileEncrypted(fullPath)) { val3.encryptionType = (EncryptionType)1; } ES3File.cachedFiles[settings.path] = new ES3File(ES3.LoadRawBytes(val3), val); } private static bool CheckFileEncrypted(string path) { using FileStream fileStream = File.OpenRead(path); ReadOnlySpan other = "{\""u8; Span span = stackalloc byte[2]; int num = fileStream.Read(span); return num != 2 || !span.SequenceEqual(other); } } [HarmonyPatch(typeof(ES3))] internal static class Patch_ES3 { [HarmonyPatch("DeleteFile", new Type[] { typeof(ES3Settings) })] [HarmonyPostfix] internal static void DeleteCachedFile(ES3Settings settings) { ES3File.cachedFiles.Remove(settings.path); } [HarmonyPatch("RenameFile", new Type[] { typeof(ES3Settings), typeof(ES3Settings) })] [HarmonyPostfix] internal static void RenameCachedFile(ES3Settings oldSettings, ES3Settings newSettings) { if (ES3File.cachedFiles.Remove(oldSettings.path, out var value)) { ES3File.cachedFiles[newSettings.path] = value; } } [HarmonyPatch("GetKeys", new Type[] { typeof(ES3Settings) })] [HarmonyPatch("KeyExists", new Type[] { typeof(string), typeof(ES3Settings) })] [HarmonyPatch("DeleteKey", new Type[] { typeof(string), typeof(ES3Settings) })] [HarmonyPatch("LethalPerformance_Load")] [HarmonyPatch("LethalPerformance_Save")] [HarmonyPrefix] internal static void UseCache(ES3Settings settings) { ES3Utilities.ForceToCache(settings); ES3Utilities.LoadFileToCache(settings); } } [HarmonyPatch(typeof(ES3File))] internal static class Patch_ES3File { [HarmonyPatch("KeyExists", new Type[] { typeof(string), typeof(ES3Settings) })] [HarmonyPrefix] public static void KeyExists(ES3Settings settings) { ES3Utilities.ForceToCache(settings); ES3Utilities.LoadFileToCache(settings); } [HarmonyPatch("LethalPerformance_Save")] [HarmonyPrefix] public static void ScheduleSave(ES3File __instance) { LethalPerformancePlugin.Instance.ES3SaverTask.ScheduleSaveFor(__instance); } } } namespace LethalPerformance.Configuration { internal class AcceptableValueEnum : AcceptableValueBase where T : struct { private static readonly string[] s_EnumValues = Enum.GetNames(typeof(T)); public AcceptableValueEnum() : base(typeof(T)) { if (s_EnumValues.Length == 0) { throw new ArgumentException("Enum should have any value"); } } public override object Clamp(object value) { if (((AcceptableValueBase)this).IsValid(value)) { return value; } return Enum.Parse(s_EnumValues[0]); } public override bool IsValid(object value) { return Enum.IsDefined(typeof(T), value); } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", s_EnumValues); } } internal class ConfigManager { private readonly ConfigFile m_Config; public ConfigEntry CookieAtlasResolution { get; private set; } public ConfigEntry ReflectionProbeCacheResolution { get; private set; } public ConfigManager(ConfigFile config) { m_Config = config; BindConfig(); } private void BindConfig() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown CookieAtlasResolution = BindRenderingConfig("Rendering", "Cookie atlas texture resolution", CookieAtlasResolutionLimited.CookieResolution1024, new ConfigDescription("Sets cookie light atlas texture resolution. By default 1024 is enough for vanilla, but some mods can use custom cookie texture, causing this log spam:\n\"No more space in the 2D Cookie Texture Atlas. To solve this issue, increase the resolution of the cookie atlas in the HDRP settings\".\n\nTo fix it just increase the resolution of texture atlas.", (AcceptableValueBase)(object)new AcceptableValueEnum(), Array.Empty())); ReflectionProbeCacheResolution = BindRenderingConfig("Rendering", "Reflection probe atlas texture resolution", (ReflectionProbeTextureCacheResolution)134218752, new ConfigDescription("Sets reflection probe cache resolution. By default it's 16384x8192 causing high RAM usage (~1GB) even if vanilla game doesn't use them at all. But some mods may use, so it may cause this log spam:\n\"No more space in Reflection Probe Atlas. To solve this issue, increase the size of the Reflection Probe Atlas in the HDRP settings\".\n\nTo fix it just increase the resolution of texture atlas.", (AcceptableValueBase)(object)new AcceptableValueEnum(), Array.Empty())); } private ConfigEntry BindRenderingConfig(string section, string key, T defaultValue, ConfigDescription? description) { ConfigEntry val = m_Config.Bind(section, key, defaultValue, description); val.SettingChanged += UpdateRenderingAsset; return val; } private ConfigEntry BindHarmonyConfig(string section, string key, T defaultValue, string? description) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) ConfigDescription val = ((description == null) ? ((ConfigDescription)null) : new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty())); ConfigEntry val2 = m_Config.Bind(section, key, defaultValue, val); val2.SettingChanged += RepatchHarmony; return val2; } private static void UpdateRenderingAsset(object _, EventArgs __) { HDRenderPipelineAssetOptimizer.Initialize(); } private static void RepatchHarmony(object _, EventArgs __) { LethalPerformancePlugin.Instance.Logger.LogInfo((object)"Config option of Harmony got changed, repatching..."); Harmony harmony = LethalPerformancePlugin.Instance.Harmony; if (harmony == null) { return; } try { harmony.UnpatchSelf(); harmony.PatchAll(typeof(ConfigManager).Assembly); } catch (Exception ex) { LethalPerformancePlugin.Instance.Logger.LogError((object)("Failed to repatch with Harmony\n" + ex)); } } } internal enum CookieAtlasResolutionLimited { CookieResolution1024 = 0x400, CookieResolution2048 = 0x800, CookieResolution4096 = 0x1000, CookieResolution8192 = 0x2000, CookieResolution16384 = 0x4000 } } namespace LethalPerformance.Caching { internal class AutoUnsafeCachedInstance : UnsafeCachedInstance, IAutoInstance where T : Behaviour { private readonly string m_HierarchyPath; public AutoUnsafeCachedInstance(string hierarchyPath) { m_HierarchyPath = hierarchyPath; } public void SaveInstance() { if ((Object)(object)base.Instance != (Object)null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)(typeof(T).Name + " instance is already cached")); } GameObject val = GameObject.Find(m_HierarchyPath); if ((Object)(object)val != (Object)null) { T instance = default(T); if (val.TryGetComponent(ref instance)) { base.Instance = instance; } else { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("Failed to cache instance of " + typeof(T).Name)); } } else { LethalPerformancePlugin.Instance.Logger.LogWarning((object)("Failed to find gameobject of " + typeof(T).Name)); } } } public interface IAutoInstance { void SaveInstance(); } internal struct InstanceResult { public bool isFound; public Behaviour? instance; public InstanceResult(bool isFound, Behaviour? instance) { this.isFound = isFound; this.instance = instance; } public static InstanceResult Found(Behaviour? instance) { InstanceResult result = default(InstanceResult); result.instance = instance; result.isFound = true; return result; } public static InstanceResult NotFound(Behaviour? instance) { InstanceResult result = default(InstanceResult); result.instance = instance; result.isFound = false; return result; } public readonly void Deconstruct(out bool isFound, out Behaviour? instance) { isFound = this.isFound; instance = this.instance; } } internal struct InstancesResult { public bool isFound; public Behaviour[]? instances; public InstancesResult(bool isFound, Behaviour[]? instances) { this.isFound = isFound; this.instances = instances; } public static InstancesResult Found(Behaviour[]? instances) { InstancesResult result = default(InstancesResult); result.instances = instances; result.isFound = true; return result; } public static InstancesResult NotFound(Behaviour[]? instances) { InstancesResult result = default(InstancesResult); result.instances = instances; result.isFound = false; return result; } public readonly void Deconstruct(out bool isFound, out Behaviour[]? instances) { isFound = this.isFound; instances = this.instances; } } internal class ManualCachedInstance : UnsafeCachedInstance where T : Behaviour { public override InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 if ((Object)(object)base.Instance == (Object)null) { return InstanceResult.Found(null); } if ((int)findObjectsInactive == 1) { return InstanceResult.Found((Behaviour?)(object)base.Instance); } if (((Behaviour)base.Instance).enabled && ((Component)(object)base.Instance).gameObject.activeInHierarchy) { return InstanceResult.Found((Behaviour?)(object)base.Instance); } return InstanceResult.Found(null); } } internal abstract class UnsafeCachedInstance { public static List UnsafeCachedInstances { get; private set; } = new List(); public abstract InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive); public abstract void Cleanup(); public static T AddSelfToMap(T unsafeInstance) where T : UnsafeCachedInstance where B : Behaviour { return (T)UnsafeCacheManager.AddReferenceToMap(unsafeInstance); } } internal class UnsafeCachedInstance : UnsafeCachedInstance where T : Behaviour { public T? Instance { get; protected set; } protected UnsafeCachedInstance() { Instance = default(T); UnsafeCachedInstance.UnsafeCachedInstances.Add(this); } public void SetInstance(T? instance) { if ((Object)(object)instance != (Object)null && (Object)(object)Instance != (Object)null) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)(typeof(T).Name + " is requested caching, while cached instance is still alive")); } Instance = instance; } public override InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Invalid comparison between Unknown and I4 if ((Object)(object)Instance == (Object)null) { return InstanceResult.NotFound(null); } if ((int)findObjectsInactive == 1) { return InstanceResult.Found((Behaviour?)(object)Instance); } if (((Behaviour)Instance).enabled && ((Component)(object)Instance).gameObject.activeInHierarchy) { return InstanceResult.Found((Behaviour?)(object)Instance); } return InstanceResult.Found(null); } public override void Cleanup() { Instance = default(T); } } internal static class UnsafeCacheManager { public delegate InstanceResult TryGetInstance(FindObjectsInactive findObjectsInactive); public delegate InstancesResult TryGetInstances(FindObjectsInactive findObjectsInactive); private static readonly Dictionary s_MapGettingInstance; private static readonly Dictionary s_MapGettingInstances; static UnsafeCacheManager() { s_MapGettingInstance = new Dictionary { [typeof(StartOfRound)] = (FindObjectsInactive _) => new InstanceResult(Object.op_Implicit((Object)(object)StartOfRound.Instance), (Behaviour?)(object)StartOfRound.Instance), [typeof(GameNetworkManager)] = (FindObjectsInactive _) => InstanceResult.Found((Behaviour?)(object)GameNetworkManager.Instance), [typeof(HUDManager)] = (FindObjectsInactive _) => new InstanceResult(Object.op_Implicit((Object)(object)HUDManager.Instance), (Behaviour?)(object)HUDManager.Instance), [typeof(GlobalEffects)] = (FindObjectsInactive _) => new InstanceResult(Object.op_Implicit((Object)(object)GlobalEffects.Instance), (Behaviour?)(object)GlobalEffects.Instance), [typeof(IngamePlayerSettings)] = (FindObjectsInactive _) => InstanceResult.Found((Behaviour?)(object)IngamePlayerSettings.Instance), [typeof(SteamManager)] = (FindObjectsInactive _) => InstanceResult.Found((Behaviour?)(object)SteamManager.Instance) }; s_MapGettingInstances = new Dictionary { [typeof(PlayerVoiceIngameSettings)] = delegate(FindObjectsInactive inactive) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Invalid comparison between Unknown and I4 if (!TryGetCachedBehaviour(inactive, out DissonanceComms result)) { return InstancesResult.NotFound(null); } List players = result._players._players; Stack items = result._playbackPool._pool._items; List list = default(List); PooledObject> val = CollectionPool, PlayerVoiceIngameSettings>.Get(ref list); try { PlayerVoiceIngameSettings item = default(PlayerVoiceIngameSettings); for (int i = 0; i < players.Count; i++) { IVoicePlayback playback = result._players._players[i].Playback; MonoBehaviour val2 = (MonoBehaviour)(object)((playback is MonoBehaviour) ? playback : null); if (val2 != null && (Object)(object)val2 != (Object)null && ((Component)val2).TryGetComponent(ref item)) { list.Add(item); } } if ((int)inactive == 1) { PlayerVoiceIngameSettings item2 = default(PlayerVoiceIngameSettings); foreach (VoicePlayback item3 in items) { if (((Component)item3).TryGetComponent(ref item2)) { list.Add(item2); } } } Behaviour[] instances = (Behaviour[])(object)list.ToArray(); return InstancesResult.Found(instances); } finally { ((IDisposable)val).Dispose(); } } }; AddReference("/Systems/DissonanceSetup"); AddReference("/Systems/GameSystems/RoundManager"); AddReference("/Systems/GameSystems/QuickMenuManager"); AddReference("/Systems/GameSystems/TimeAndWeather"); AddReference("/Systems/GameSystems/SoundManager"); AddReference("/Systems/GameSystems/ShipBuildMode"); AddReference("/Systems/GameSystems/Misc/MoldSpreadManager"); AddReference("/Systems/GameSystems/TimeAndWeather/Stormy"); AddReference("/Systems/UI/Canvas/IngamePlayerHUD/BeltBagUI"); AddReference("/Systems/Audios/PlayerAudioListener"); AddReference("/Environment/HangarShip/Terminal/TerminalTrigger/TerminalScript"); AddReference("/Environment/HangarShip/StartGameLever"); AddReference("/Environment/HangarShip/AnimatedShipDoor"); static void AddReference(string hierarchyPath) where T : notnull, Behaviour { AutoUnsafeCachedInstance autoUnsafeCachedInstance = new AutoUnsafeCachedInstance(hierarchyPath); s_MapGettingInstance[typeof(T)] = autoUnsafeCachedInstance.TryGetInstance; } } public static UnsafeCachedInstance AddReferenceToMap(UnsafeCachedInstance unsafeInstance) where T : Behaviour { s_MapGettingInstance[typeof(T)] = unsafeInstance.TryGetInstance; return unsafeInstance; } public static void AddActionToMap(Type type, TryGetInstances action) { s_MapGettingInstances[type] = action; } public static bool RemoveActionToMap(Type type) { return s_MapGettingInstances.Remove(type); } public static void CacheInstances() { foreach (UnsafeCachedInstance unsafeCachedInstance in UnsafeCachedInstance.UnsafeCachedInstances) { if (unsafeCachedInstance is IAutoInstance autoInstance) { autoInstance.SaveInstance(); } } } public static bool TryGetCachedReference(Type type, FindObjectsInactive findObjectsInactive, out Object? cache) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) bool isFound; if (s_MapGettingInstance.TryGetValue(type, out TryGetInstance value)) { value(findObjectsInactive).Deconstruct(out isFound, out Behaviour instance); bool flag = isFound; Behaviour val = instance; if (flag) { cache = (Object?)(object)val; return true; } } if (s_MapGettingInstances.TryGetValue(type, out TryGetInstances value2)) { value2(findObjectsInactive).Deconstruct(out isFound, out Behaviour[] instances); bool flag2 = isFound; Behaviour[] array = instances; if (flag2 && array.Length != 0) { cache = (Object?)(object)array[0]; } else { cache = null; } return true; } cache = null; return false; } public static bool TryGetCachedReferences(Type type, FindObjectsInactive findObjectsInactive, out Object[]? cache) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) bool isFound; if (s_MapGettingInstances.TryGetValue(type, out TryGetInstances value)) { value(findObjectsInactive).Deconstruct(out isFound, out Behaviour[] instances); bool flag = isFound; Behaviour[] array = instances; if (flag) { Object[] array2 = (Object[])(object)array; cache = array2; return true; } } if (s_MapGettingInstance.TryGetValue(type, out TryGetInstance value2)) { value2(findObjectsInactive).Deconstruct(out isFound, out Behaviour instance); bool flag2 = isFound; Behaviour val = instance; if (flag2 && (Object)(object)val != (Object)null) { cache = (Object[]?)(object)new Object[1] { (Object)val }; } else { cache = Array.Empty(); } return true; } cache = null; return false; } public static void CleanupCache() { foreach (UnsafeCachedInstance unsafeCachedInstance in UnsafeCachedInstance.UnsafeCachedInstances) { unsafeCachedInstance.Cleanup(); } } private static bool TryGetCachedBehaviour(FindObjectsInactive findObjectsInactive, [NotNullWhen(true)] out T? result) where T : Behaviour { //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (TryGetCachedReference(typeof(T), findObjectsInactive, out Object cache)) { result = (T)(object)cache; return true; } result = default(T); return false; } } } namespace LethalPerformance.Caching.References { internal static class NetworkBehaviourCaching { private static readonly HashSet s_TypesToCache = new HashSet { typeof(VehicleController), typeof(GrabbableObject), typeof(DepositItemsDesk), typeof(ShipTeleporter), typeof(BreakerBox), typeof(MineshaftElevatorController), typeof(ShipLights), typeof(TVScript), typeof(EnemyVent), typeof(TerminalAccessibleObject), typeof(DoorLock), typeof(UnlockableSuit), typeof(Landmine), typeof(Turret), typeof(SpikeRoofTrap), typeof(StoryLog), typeof(EntranceTeleport) }; private static readonly MethodInfo s_FindWithSpawnedBehaviours = typeof(NetworkBehaviourCaching).GetMethod("FindWithSpawnedBehaviours", AccessTools.all); [InitializeOnAwake] internal static void Initialize() { foreach (Type item in s_TypesToCache) { AddActionToMap(item); } } private static void AddActionToMap(Type type) { MethodInfo method = s_FindWithSpawnedBehaviours.MakeGenericMethod(type); UnsafeCacheManager.TryGetInstances action = (UnsafeCacheManager.TryGetInstances)Delegate.CreateDelegate(typeof(UnsafeCacheManager.TryGetInstances), method); UnsafeCacheManager.AddActionToMap(type, action); } private static InstancesResult FindWithSpawnedBehaviours(FindObjectsInactive inactive) where T : Object { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if ((int)inactive == 1) { LethalPerformancePlugin.Instance.Logger.LogWarning((object)(typeof(T).Name + " search called with inactive objects, probably will cause incompatibility!")); } List list = default(List); PooledObject> val = CollectionPool, T>.Get(ref list); try { NetworkManagerUtilities.FindAllSpawnedNetworkBehaviour(list); return InstancesResult.Found(list.ToArray() as Behaviour[]); } finally { ((IDisposable)val).Dispose(); } } } [HarmonyPatch(typeof(AudioReverbPresets))] internal static class Patch_AudioReverbPresets { private static readonly UnsafeCachedInstance s_Instance = UnsafeCacheManager.AddReferenceToMap((UnsafeCachedInstance)new ManualCachedInstance()); [HarmonyPrepare] public static void Prepare() { } [HarmonyPatch("Awake")] [HarmonyPrefix] public static void Awake(AudioReverbPresets __instance) { s_Instance.SetInstance(__instance); } } } namespace LethalPerformance.Caching.FindingObjectOptimization { [HarmonyPatch(typeof(Object))] internal static class NativeFindObjectOfTypePatch { [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [HarmonyPatch("FindAnyObjectByType", new Type[] { typeof(Type), typeof(FindObjectsInactive) })] [HarmonyPatch("FindFirstObjectByType", new Type[] { typeof(Type), typeof(FindObjectsInactive) })] [HarmonyPrefix] public static bool FindObjectFast(Type type, FindObjectsInactive findObjectsInactive, bool __runOriginal, ref Object? __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!__runOriginal) { return false; } return !TryFindObjectFast(type, findObjectsInactive, out __result); } [HarmonyPatch("FindObjectOfType", new Type[] { typeof(Type), typeof(bool) })] [HarmonyPrefix] public static bool FindObjectFast(Type type, bool includeInactive, bool __runOriginal, ref Object? __result) { if (!__runOriginal) { return false; } return !TryFindObjectFast(type, (FindObjectsInactive)(includeInactive ? 1 : 0), out __result); } [HarmonyPatch("FindObjectsOfType", new Type[] { typeof(Type), typeof(bool) })] [HarmonyPrefix] public static bool FindObjectsFast(Type type, bool includeInactive, bool __runOriginal, ref Object[]? __result) { if (!__runOriginal) { return false; } return !TryFindObjectsFast(type, (FindObjectsInactive)(includeInactive ? 1 : 0), out __result); } [HarmonyPatch("FindObjectsByType", new Type[] { typeof(Type), typeof(FindObjectsInactive), typeof(FindObjectsSortMode) })] [HarmonyPrefix] public static bool FindObjectsFast(Type type, FindObjectsInactive findObjectsInactive, bool __runOriginal, ref Object[]? __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!__runOriginal) { return false; } return !TryFindObjectsFast(type, findObjectsInactive, out __result); } [Conditional("ENABLE_PROFILER")] private static void ShowInProfilerType(Type type, bool findAllObjects) { string text = "DiFFoZ.Find." + type.Name; if (findAllObjects) { text += " (all objects)"; } LethalPerformancePlugin.Instance.Logger.LogInfo((object)("[Cache] " + text)); } public static bool TryFindObjectFast(Type type, FindObjectsInactive findObjectsInactive, out Object? result) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (UnsafeCacheManager.TryGetCachedReference(type, findObjectsInactive, out result)) { return true; } result = null; return false; } public static bool TryFindObjectsFast(Type type, FindObjectsInactive findObjectsInactive, out Object[]? result) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (UnsafeCacheManager.TryGetCachedReferences(type, findObjectsInactive, out result)) { return true; } result = null; return false; } } internal static class ReplaceFindObjectOfTypePatch { [CompilerGenerated] private sealed class d__5 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private MethodInfo <>2__current; private int <>l__initialThreadId; private Type 5__2; MethodInfo IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__5(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = typeof(BreakerBox); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 1; return true; case 1: <>1__state = -1; <>2__current = 5__2.GetMethod("SetSwitchesOff", AccessTools.all); <>1__state = 2; return true; case 2: <>1__state = -1; 5__2 = typeof(FoliageDetailDistance); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 3; return true; case 3: <>1__state = -1; 5__2 = typeof(animatedSun); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 4; return true; case 4: <>1__state = -1; 5__2 = typeof(BoomboxItem); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 5; return true; case 5: <>1__state = -1; 5__2 = typeof(TimeOfDay); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 6; return true; case 6: <>1__state = -1; <>2__current = 5__2.GetMethod("SyncNewProfitQuotaClientRpc", AccessTools.all); <>1__state = 7; return true; case 7: <>1__state = -1; 5__2 = typeof(Terminal); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 8; return true; case 8: <>1__state = -1; <>2__current = 5__2.GetMethod("ParsePlayerSentence", AccessTools.all); <>1__state = 9; return true; case 9: <>1__state = -1; <>2__current = 5__2.GetMethod("LoadNewNodeIfAffordable", AccessTools.all); <>1__state = 10; return true; case 10: <>1__state = -1; <>2__current = AccessTools.EnumeratorMoveNext((MethodBase)5__2.GetMethod("displayReimbursedTipDelay", AccessTools.all)); <>1__state = 11; return true; case 11: <>1__state = -1; 5__2 = typeof(StartOfRound); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 12; return true; case 12: <>1__state = -1; <>2__current = 5__2.GetMethod("SetMapScreenInfoToCurrentLevel", AccessTools.all); <>1__state = 13; return true; case 13: <>1__state = -1; <>2__current = 5__2.GetMethod("ChangePlanet", AccessTools.all); <>1__state = 14; return true; case 14: <>1__state = -1; <>2__current = 5__2.GetMethod("ArriveAtLevel", AccessTools.all); <>1__state = 15; return true; case 15: <>1__state = -1; <>2__current = 5__2.GetMethod("SwitchMapMonitorPurpose", AccessTools.all); <>1__state = 16; return true; case 16: <>1__state = -1; <>2__current = 5__2.GetMethod("StartGameServerRpc", AccessTools.all); <>1__state = 17; return true; case 17: <>1__state = -1; <>2__current = 5__2.GetMethod("StartGame", AccessTools.all); <>1__state = 18; return true; case 18: <>1__state = -1; <>2__current = 5__2.GetMethod("ShipHasLeft", AccessTools.all); <>1__state = 19; return true; case 19: <>1__state = -1; <>2__current = 5__2.GetMethod("SetTimeAndPlanetToSavedSettings", AccessTools.all); <>1__state = 20; return true; case 20: <>1__state = -1; <>2__current = 5__2.GetMethod("SetShipReadyToLand", AccessTools.all); <>1__state = 21; return true; case 21: <>1__state = -1; <>2__current = 5__2.GetMethod("SetShipDoorsOverheatClientRpc", AccessTools.all); <>1__state = 22; return true; case 22: <>1__state = -1; <>2__current = 5__2.GetMethod("ResetShip", AccessTools.all); <>1__state = 23; return true; case 23: <>1__state = -1; <>2__current = 5__2.GetMethod("ResetPlayersLoadedValueClientRpc", AccessTools.all); <>1__state = 24; return true; case 24: <>1__state = -1; <>2__current = 5__2.GetMethod("ResetMoldStates", AccessTools.all); <>1__state = 25; return true; case 25: <>1__state = -1; <>2__current = 5__2.GetMethod("PowerSurgeShip", AccessTools.all); <>1__state = 26; return true; case 26: <>1__state = -1; <>2__current = 5__2.GetMethod("PassTimeToNextDay", AccessTools.all); <>1__state = 27; return true; case 27: <>1__state = -1; <>2__current = 5__2.GetMethod("GetBodiesInShip", AccessTools.all); <>1__state = 28; return true; case 28: <>1__state = -1; <>2__current = AccessTools.EnumeratorMoveNext((MethodBase)5__2.GetMethod("TravelToLevelEffects", AccessTools.all)); <>1__state = 29; return true; case 29: <>1__state = -1; 5__2 = typeof(Shovel); <>2__current = 5__2.GetMethod("HitShovel", AccessTools.all); <>1__state = 30; return true; case 30: <>1__state = -1; 5__2 = typeof(RoundManager); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 31; return true; case 31: <>1__state = -1; <>2__current = AccessTools.EnumeratorMoveNext((MethodBase)5__2.GetMethod("turnOnLights", AccessTools.all)); <>1__state = 32; return true; case 32: <>1__state = -1; 5__2 = typeof(OutOfBoundsTrigger); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 33; return true; case 33: <>1__state = -1; 5__2 = typeof(MouthDogAI); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 34; return true; case 34: <>1__state = -1; 5__2 = typeof(LungProp); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 35; return true; case 35: <>1__state = -1; 5__2 = typeof(LevelGenerationManager); <>2__current = 5__2.GetMethod("Awake", AccessTools.all); <>1__state = 36; return true; case 36: <>1__state = -1; 5__2 = typeof(Landmine); <>2__current = AccessTools.EnumeratorMoveNext((MethodBase)5__2.GetMethod("StartIdleAnimation", AccessTools.all)); <>1__state = 37; return true; case 37: <>1__state = -1; 5__2 = typeof(KnifeItem); <>2__current = 5__2.GetMethod("HitKnife", AccessTools.all); <>1__state = 38; return true; case 38: <>1__state = -1; 5__2 = typeof(ItemDropship); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 39; return true; case 39: <>1__state = -1; 5__2 = typeof(InteractTrigger); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 40; return true; case 40: <>1__state = -1; 5__2 = typeof(HUDManager); <>2__current = 5__2.GetMethod("Awake", AccessTools.all); <>1__state = 41; return true; case 41: <>1__state = -1; 5__2 = typeof(HangarShipDoor); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 42; return true; case 42: <>1__state = -1; 5__2 = typeof(GlobalEffects); <>2__current = 5__2.GetMethod("Awake", AccessTools.all); <>1__state = 43; return true; case 43: <>1__state = -1; 5__2 = typeof(GameNetworkManager); <>2__current = 5__2.GetMethod("SaveGameValues", AccessTools.all); <>1__state = 44; return true; case 44: <>1__state = -1; <>2__current = 5__2.GetMethod("ResetSavedGameValues", AccessTools.all); <>1__state = 45; return true; case 45: <>1__state = -1; 5__2 = typeof(PlayerControllerB); <>2__current = 5__2.GetMethod("SetSpectatedPlayerEffects", AccessTools.all); <>1__state = 46; return true; case 46: <>1__state = -1; 5__2 = typeof(EntranceTeleport); <>2__current = 5__2.GetMethod("Awake", AccessTools.all); <>1__state = 47; return true; case 47: <>1__state = -1; 5__2 = typeof(EnemyVent); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 48; return true; case 48: <>1__state = -1; 5__2 = typeof(Anomaly); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 49; return true; case 49: <>1__state = -1; 5__2 = typeof(PlayerVoiceIngameSettings); <>2__current = 5__2.GetMethod("InitializeComponents", AccessTools.all); <>1__state = 50; return true; case 50: <>1__state = -1; 5__2 = typeof(StunGrenadeItem); <>2__current = 5__2.GetMethod("ExplodeStunGrenade", AccessTools.all); <>1__state = 51; return true; case 51: <>1__state = -1; 5__2 = typeof(StoryLog); <>2__current = 5__2.GetMethod("Start", AccessTools.all); <>1__state = 52; return true; case 52: <>1__state = -1; <>2__current = 5__2.GetMethod("CollectLog", AccessTools.all); <>1__state = 53; return true; case 53: <>1__state = -1; 5__2 = typeof(AudioReverbTrigger); <>2__current = 5__2.GetMethod("OnTriggerStay", AccessTools.all); <>1__state = 54; return true; case 54: <>1__state = -1; return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; return this; } return new d__5(0); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private static readonly Dictionary s_MapGettingInstance = new Dictionary { { typeof(StartOfRound), AccessTools.PropertyGetter(typeof(StartOfRound), "Instance") }, { typeof(TimeOfDay), AccessTools.PropertyGetter(typeof(TimeOfDay), "Instance") }, { typeof(GameNetworkManager), AccessTools.PropertyGetter(typeof(GameNetworkManager), "Instance") }, { typeof(HUDManager), AccessTools.PropertyGetter(typeof(HUDManager), "Instance") }, { typeof(GlobalEffects), AccessTools.PropertyGetter(typeof(GlobalEffects), "Instance") }, { typeof(IngamePlayerSettings), AccessTools.PropertyGetter(typeof(IngamePlayerSettings), "Instance") }, { typeof(RoundManager), AccessTools.PropertyGetter(typeof(RoundManager), "Instance") }, { typeof(ShipBuildModeManager), AccessTools.PropertyGetter(typeof(ShipBuildModeManager), "Instance") }, { typeof(SoundManager), AccessTools.PropertyGetter(typeof(SoundManager), "Instance") }, { typeof(SteamManager), AccessTools.PropertyGetter(typeof(SteamManager), "Instance") } }; private static readonly HashSet s_ExcludedTypes = new HashSet(); private static readonly MethodInfo s_FindObjectByTypeNonOrdered = typeof(ObjectExtensions).GetMethod("FindObjectByTypeNonOrdered", AccessTools.all); private static readonly MethodInfo s_FindObjectByTypeNonOrderedInActive = typeof(ObjectExtensions).GetMethod("FindObjectByTypeNonOrderedInActive", AccessTools.all); [HarmonyCleanup] public static Exception? Cleanup(Exception exception) { return HarmonyExceptionHandler.ReportException(exception); } [IteratorStateMachine(typeof(d__5))] [HarmonyTargetMethods] private static IEnumerable GetTargetMethods() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__5(-2); } [HarmonyTranspiler] public static IEnumerable ReplaceFindObjectOfTypeTranspiler(IEnumerable codeInstructions) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown CodeMatcher matcher = new CodeMatcher(codeInstructions, (ILGenerator)null); matcher.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((Func)CallsFindObjectOfType, (string)null) }).Repeat((Action)delegate(CodeMatcher m) { MethodInfo methodInfo = (MethodInfo)matcher.Operand; Type type = methodInfo.GetGenericArguments()[0]; ParameterInfo[] parameters = methodInfo.GetParameters(); if (s_MapGettingInstance.TryGetValue(type, out MethodInfo value)) { if (parameters.Length != 0 && parameters[0].ParameterType == typeof(bool)) { m.Advance(-1).RemoveInstruction(); } matcher.Operand = value; } else { value = ((parameters.Length == 0 || !(parameters[0].ParameterType == typeof(bool))) ? s_FindObjectByTypeNonOrdered.MakeGenericMethod(type) : s_FindObjectByTypeNonOrderedInActive.MakeGenericMethod(type)); matcher.Operand = value; } }, (Action)null); return matcher.InstructionEnumeration(); } private static bool CallsFindObjectOfType(CodeInstruction instruction) { if (!(instruction.operand is MethodInfo methodInfo) || !methodInfo.IsGenericMethod || methodInfo.DeclaringType != typeof(Object) || !methodInfo.Name.Equals("FindObjectOfType")) { return false; } Type item = methodInfo.GetGenericArguments()[0]; if (s_ExcludedTypes.Contains(item)) { return false; } return true; } } } namespace LethalPerformance.API { internal static class ObjectExtensions { public static T? FindObjectByTypeNonOrdered() where T : Object { if (UnsafeCacheManager.TryGetCachedReference(typeof(T), (FindObjectsInactive)0, out Object cache)) { return (T)(object)cache; } Object[] array = Object.FindObjectsByType(typeof(T), (FindObjectsInactive)0, (FindObjectsSortMode)0); Object val = ((array.Length != 0) ? array[0] : null); return (T)(object)((val is T) ? val : null); } public static T? FindObjectByTypeNonOrderedInActive(bool includeInactive) where T : Object { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (UnsafeCacheManager.TryGetCachedReference(typeof(T), (FindObjectsInactive)1, out Object cache)) { return (T)(object)cache; } FindObjectsInactive val = (FindObjectsInactive)(includeInactive ? 1 : 0); Object[] array = Object.FindObjectsByType(typeof(T), val, (FindObjectsSortMode)0); Object val2 = ((array.Length != 0) ? array[0] : null); return (T)(object)((val2 is T) ? val2 : null); } public static bool ComparePlayerRagdollTag(GameObject gameObject) { if (!gameObject.CompareTag("PlayerRagdoll") && !gameObject.CompareTag("PlayerRagdoll1") && !gameObject.CompareTag("PlayerRagdoll2")) { return gameObject.CompareTag("PlayerRagdoll3"); } return true; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }