Decompiled source of CEO TWEAK PACK v1.1.2
BepInEx/plugins/3rdPerson.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using MoreCompany.Cosmetics; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Rendering; using _3rdPerson.Helper; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("3rdPerson")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("3rdPerson")] [assembly: AssemblyTitle("3rdPerson")] [assembly: AssemblyVersion("1.0.0.0")] 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; } } } namespace _3rdPerson { [BepInPlugin("verity.3rdperson", "3rd Person", "1.1.0")] public class Plugin : BaseUnityPlugin { public static readonly Harmony Harmony = new Harmony("verity.3rdperson"); public static ManualLogSource LogSource = null; public static ConfigEntry<string> KeybindEntry = null; public static ConfigEntry<string> OrbitKeybindEntry = null; public static ConfigEntry<float> OrbitSpeedEntry = null; public static ConfigEntry<float> Distance = null; public static ConfigEntry<float> RightOffset = null; public static ConfigEntry<float> UpOffset = null; public static ConfigEntry<bool> MoreCompanyCosmetics = null; private void Awake() { //IL_0005: 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown GameObject val = new GameObject("3rdPerson"); val.AddComponent<PluginLoader>(); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)val); LogSource = ((BaseUnityPlugin)this).Logger; LogSource.LogInfo((object)"3rd Person Mod Loaded."); KeybindEntry = ((BaseUnityPlugin)this).Config.Bind<string>("Camera Settings", "Keybind", "c", "The keybind used to toggle third person."); Distance = ((BaseUnityPlugin)this).Config.Bind<float>("Camera Settings", "Distance", 2f, "Distance of the camera from the player."); RightOffset = ((BaseUnityPlugin)this).Config.Bind<float>("Camera Settings", "Right-Offset", 0.6f, "Offset of the camera to the right from the player."); UpOffset = ((BaseUnityPlugin)this).Config.Bind<float>("Camera Settings", "Up-Offset", 0.1f, "Offset of the camera upwards from the player."); OrbitKeybindEntry = ((BaseUnityPlugin)this).Config.Bind<string>("Orbit Settings", "Keybind", "<Mouse>/middleButton", "The keybind used to 'orbit' around the player."); OrbitSpeedEntry = ((BaseUnityPlugin)this).Config.Bind<float>("Orbit Settings", "Orbit-Speed", 75f, "The speed/sensitivity of the orbiting."); MoreCompanyCosmetics = ((BaseUnityPlugin)this).Config.Bind<bool>("Mod Support", "MoreCompany-Cosmetic-Support", false, "Displays MoreCompany Cosmetics in third person, this can mess with first person visibility if you have glasses on."); } } public class PluginLoader : MonoBehaviour { private void Start() { LocalPlayer localPlayer = ((Component)this).gameObject.AddComponent<LocalPlayer>(); ((Object)localPlayer).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)localPlayer); Keybinding keybinding = ((Component)this).gameObject.AddComponent<Keybinding>(); ((Object)keybinding).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)keybinding); ThirdPersonCamera thirdPersonCamera = ((Component)this).gameObject.AddComponent<ThirdPersonCamera>(); ((Object)thirdPersonCamera).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)thirdPersonCamera); Hooks.Init(); } } } namespace _3rdPerson.Helper { public static class Hooks { private class HarmonyHooks { private static bool _previousState; public static void MenuOpenedHook() { _previousState = ThirdPersonCamera.ViewState; if (LocalPlayer.IsActive() && ThirdPersonCamera.ViewState) { LocalPlayer.GetController().quickMenuManager.isMenuOpen = false; ThirdPersonCamera.Toggle(); } } public static void MenuClosedHook() { if (LocalPlayer.IsActive() && _previousState) { LocalPlayer.GetController().inTerminalMenu = false; ThirdPersonCamera.Toggle(); } } public static void MoreCompanyHook() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) CosmeticApplication val = Object.FindObjectOfType<CosmeticApplication>(); if (CosmeticRegistry.locallySelectedCosmetics.Count <= 0 || val.spawnedCosmetics.Count > 0) { return; } foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics) { val.ApplyCosmetic(locallySelectedCosmetic, true); } foreach (CosmeticInstance spawnedCosmetic in val.spawnedCosmetics) { Transform transform = ((Component)spawnedCosmetic).transform; transform.localScale *= 0.38f; SetAllChildrenLayer(((Component)spawnedCosmetic).transform, 29); } } private static void SetAllChildrenLayer(Transform transform, int layer) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown ((Component)transform).gameObject.layer = layer; foreach (Transform item in transform) { SetAllChildrenLayer(item, layer); } } public static bool PlayerInputHook() { if (ThirdPersonCamera.ViewState) { return !Keybinding.orbitAction.IsPressed(); } return true; } public static void KillPlayerHook() { if (ThirdPersonCamera.ViewState) { ThirdPersonCamera.Toggle(); } } } public static void Init() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Expected O, but got Unknown //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Expected O, but got Unknown //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Expected O, but got Unknown //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Expected O, but got Unknown MethodInfo method = typeof(QuickMenuManager).GetMethod("OpenQuickMenu"); MethodInfo method2 = typeof(HarmonyHooks).GetMethod("MenuOpenedHook"); Plugin.Harmony.Patch((MethodBase)method, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.LogSource.LogInfo((object)"Open Menu Hooked."); MethodInfo method3 = typeof(QuickMenuManager).GetMethod("CloseQuickMenu"); MethodInfo method4 = typeof(HarmonyHooks).GetMethod("MenuClosedHook"); Plugin.Harmony.Patch((MethodBase)method3, new HarmonyMethod(method4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.LogSource.LogInfo((object)"Close Menu Hooked."); MethodInfo method5 = typeof(Terminal).GetMethod("BeginUsingTerminal"); MethodInfo method6 = typeof(HarmonyHooks).GetMethod("MenuOpenedHook"); Plugin.Harmony.Patch((MethodBase)method5, new HarmonyMethod(method6), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.LogSource.LogInfo((object)"Open Terminal Hooked."); MethodInfo method7 = typeof(Terminal).GetMethod("QuitTerminal"); MethodInfo method8 = typeof(HarmonyHooks).GetMethod("MenuClosedHook"); Plugin.Harmony.Patch((MethodBase)method7, new HarmonyMethod(method8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.LogSource.LogInfo((object)"Close Terminal Hooked."); MethodInfo method9 = typeof(PlayerControllerB).GetMethod("PlayerLookInput", BindingFlags.Instance | BindingFlags.NonPublic); MethodInfo method10 = typeof(HarmonyHooks).GetMethod("PlayerInputHook"); Plugin.Harmony.Patch((MethodBase)method9, new HarmonyMethod(method10), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.LogSource.LogInfo((object)"Player Look Input Hooked."); MethodInfo method11 = typeof(PlayerControllerB).GetMethod("KillPlayer"); MethodInfo method12 = typeof(HarmonyHooks).GetMethod("KillPlayerHook"); Plugin.Harmony.Patch((MethodBase)method11, new HarmonyMethod(method12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.LogSource.LogInfo((object)"Player Killed Hooked."); if (Chainloader.PluginInfos.ContainsKey("me.swipez.melonloader.morecompany") && Plugin.MoreCompanyCosmetics.Value) { MethodInfo method13 = typeof(HUDManager).GetMethod("AddPlayerChatMessageClientRpc", BindingFlags.Instance | BindingFlags.NonPublic); MethodInfo method14 = typeof(HarmonyHooks).GetMethod("MoreCompanyHook"); Plugin.Harmony.Patch((MethodBase)method13, (HarmonyMethod)null, new HarmonyMethod(method14), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.LogSource.LogInfo((object)"MoreCompany Cosmetics Added."); } Plugin.LogSource.LogInfo((object)"Hooks Initialized."); } } public class Keybinding : MonoBehaviour { public static InputAction orbitAction; private void Awake() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown InputAction val = new InputAction((string)null, (InputActionType)0, "<Keyboard>/" + Plugin.KeybindEntry.Value, (string)null, (string)null, (string)null); val.performed += KeyPressed; val.Enable(); orbitAction = new InputAction("MouseLeftClick", (InputActionType)0, Plugin.OrbitKeybindEntry.Value ?? "", (string)null, (string)null, (string)null); orbitAction.Enable(); } private void KeyPressed(CallbackContext obj) { ThirdPersonCamera.Toggle(); } private void OnEnable() { Plugin.LogSource.LogInfo((object)("Keybinding Initialized, Current Keybind " + Plugin.KeybindEntry.Value + ".")); } } public class LocalPlayer : MonoBehaviour { private static PlayerControllerB? _playerController; public void OnEnable() { Plugin.LogSource.LogInfo((object)"Local Player Caching Initialized."); } private void Update() { if (GameNetworkManager.Instance != null) { _playerController = GameNetworkManager.Instance.localPlayerController; } } public static bool IsActive() { if ((Object)(object)_playerController != (Object)null) { return !_playerController.isPlayerDead; } return false; } public static PlayerControllerB GetController() { return _playerController; } } public class ThirdPersonCamera : MonoBehaviour { private static Camera _camera; public static bool ViewState; public static Camera GetCamera => _camera; private void Awake() { _camera = ((Component)this).gameObject.AddComponent<Camera>(); ((Object)_camera).hideFlags = (HideFlags)61; _camera.fieldOfView = 66f; _camera.nearClipPlane = 0.1f; _camera.cullingMask = 557520895; if (Chainloader.PluginInfos.ContainsKey("quackandcheese.mirrordecor")) { _camera.cullingMask = 557520887; } ((Behaviour)_camera).enabled = false; Object.DontDestroyOnLoad((Object)(object)_camera); } private void OnEnable() { Plugin.LogSource.LogInfo((object)"Third Person Camera Initialized."); } private void Update() { if (!LocalPlayer.IsActive() || LocalPlayer.GetController().quickMenuManager.isMenuOpen || LocalPlayer.GetController().inTerminalMenu || LocalPlayer.GetController().isPlayerDead) { return; } if (Object.FindObjectsOfType<CentipedeAI>().Any((CentipedeAI centipede) => (Object)(object)centipede.clingingToPlayer != (Object)null && centipede.clingingToPlayer.playerClientId == NetworkManager.Singleton.LocalClientId)) { Plugin.LogSource.LogInfo((object)"Centipede On Player!"); if (ViewState) { Toggle(); } } else if (!Keybinding.orbitAction.IsPressed()) { ThirdPersonUpdate(); } else { ThirdPersonOrbitUpdate(); } } private void ThirdPersonUpdate() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: 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_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) Camera gameplayCamera = LocalPlayer.GetController().gameplayCamera; Vector3 val = ((Component)gameplayCamera).transform.forward * -1f; Vector3 val2 = ((Component)gameplayCamera).transform.TransformDirection(Vector3.right) * Plugin.RightOffset.Value; Vector3 val3 = Vector3.up * Plugin.UpOffset.Value; float value = Plugin.Distance.Value; ((Component)_camera).transform.position = ((Component)gameplayCamera).transform.position + val * value + val2 + val3; ((Component)_camera).transform.rotation = Quaternion.LookRotation(((Component)gameplayCamera).transform.forward); } private void ThirdPersonOrbitUpdate() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: 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_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) MovementActions movement = LocalPlayer.GetController().playerActions.Movement; Vector2 val = ((MovementActions)(ref movement)).Look.ReadValue<Vector2>() * (0.008f * (float)IngamePlayerSettings.Instance.settings.lookSensitivity); if (IngamePlayerSettings.Instance.settings.invertYAxis) { val.y *= -1f; } ((Component)_camera).transform.Rotate(Vector3.right, val.y * Plugin.OrbitSpeedEntry.Value * Time.deltaTime); ((Component)_camera).transform.RotateAround(((Component)LocalPlayer.GetController().gameplayCamera).transform.position, Vector3.up, val.x * Plugin.OrbitSpeedEntry.Value * Time.deltaTime); float value = Plugin.Distance.Value; ((Component)_camera).transform.position = ((Component)LocalPlayer.GetController().gameplayCamera).transform.position - ((Component)_camera).transform.forward * value; } public static void Toggle() { if (!LocalPlayer.IsActive() || LocalPlayer.GetController().isTypingChat || LocalPlayer.GetController().quickMenuManager.isMenuOpen || LocalPlayer.GetController().inTerminalMenu || LocalPlayer.GetController().isPlayerDead) { return; } ViewState = !ViewState; GameObject val = GameObject.Find("Systems/UI/Canvas/Panel/"); Canvas component = GameObject.Find("Systems/UI/Canvas/").GetComponent<Canvas>(); if (ViewState) { if (!Chainloader.PluginInfos.ContainsKey("quackandcheese.mirrordecor")) { ((Renderer)LocalPlayer.GetController().thisPlayerModel).shadowCastingMode = (ShadowCastingMode)1; } val.SetActive(false); component.worldCamera = _camera; component.renderMode = (RenderMode)0; GameObject.Find("Systems/Rendering/PlayerHUDHelmetModel/").SetActive(false); ((Renderer)LocalPlayer.GetController().thisPlayerModelArms).enabled = false; ((Behaviour)LocalPlayer.GetController().gameplayCamera).enabled = false; ((Behaviour)_camera).enabled = true; } else { if (!Chainloader.PluginInfos.ContainsKey("quackandcheese.mirrordecor")) { ((Renderer)LocalPlayer.GetController().thisPlayerModel).shadowCastingMode = (ShadowCastingMode)3; } val.SetActive(true); component.worldCamera = GameObject.Find("UICamera").GetComponent<Camera>(); component.renderMode = (RenderMode)1; GameObject.Find("Systems/Rendering/PlayerHUDHelmetModel/").SetActive(true); ((Renderer)LocalPlayer.GetController().thisPlayerModelArms).enabled = true; ((Behaviour)LocalPlayer.GetController().gameplayCamera).enabled = true; ((Behaviour)_camera).enabled = false; } } } }
BepInEx/plugins/aeioucompany/AEIOUCompany.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("AEIOUCompany")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Jogn Maden")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("AEIOUCompany")] [assembly: AssemblyTitle("AEIOUCompany")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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; } } } public class Speak { public string ChatMessage; public int PlayerId; public Speak(string chatMessage, int playerId) { ChatMessage = chatMessage; PlayerId = playerId; } } namespace AEIOU_Company { [HarmonyPatch] public class Patches { private static int NEW_CHAT_SIZE = Plugin.ChatSize; private static TMP_InputField chatTextField = null; private static string lastChatMessage = ""; private static readonly float[] emptySamples = new float[TTS.IN_BUFFER_SIZE]; private static List<Speak> _speaks = new List<Speak>(); private static bool _isProcessing = false; [HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")] [HarmonyPostfix] public static void AddPlayerChatMessageClientRpcPostfix(HUDManager __instance, string chatMessage, int playerId) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) if (lastChatMessage == chatMessage) { return; } lastChatMessage = chatMessage; if (playerId > HUDManager.Instance.playersManager.allPlayerScripts.Length) { return; } bool flag = GameNetworkManager.Instance.localPlayerController.holdingWalkieTalkie && StartOfRound.Instance.allPlayerScripts[playerId].holdingWalkieTalkie; float num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)HUDManager.Instance.playersManager.allPlayerScripts[playerId]).transform.position); if (num > 25f && !flag && GameNetworkManager.Instance.localPlayerController.isPlayerDead) { MethodInfo methodInfo = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); methodInfo.Invoke(HUDManager.Instance, new object[2] { chatMessage, HUDManager.Instance.playersManager.allPlayerScripts[playerId].playerUsername }); } Plugin.Log($"AddTextToChatOnServer: {chatMessage} {playerId}"); QueueSpeak(__instance, chatMessage, playerId); if (_isProcessing) { return; } _isProcessing = true; Task.Run(delegate { while (_speaks.Count > 0) { try { Speak(__instance, _speaks[0].ChatMessage, _speaks[0].PlayerId); _speaks.RemoveAt(0); } catch (Exception data) { Plugin.Log(data); _speaks.Clear(); _isProcessing = false; return; } } _isProcessing = false; }); } public static void Speak(HUDManager __instance, string chatMessage, int playerId) { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) Plugin.Log("Speak"); PlayerControllerB val = null; for (int i = 0; i < __instance.playersManager.allPlayerScripts.Length; i++) { if (Object.op_Implicit((Object)(object)__instance.playersManager.allPlayerScripts[playerId])) { val = __instance.playersManager.allPlayerScripts[playerId]; } } if ((Object)(object)val == (Object)null) { Plugin.Log("couldnt find player"); return; } Plugin.Log("Found player"); Transform obj = ((Component)val).gameObject.transform.Find("AEIOUSpeakObject"); GameObject val2 = ((obj != null) ? ((Component)obj).gameObject : null); if ((Object)(object)val2 == (Object)null) { val2 = new GameObject("AEIOUSpeakObject"); val2.transform.parent = ((Component)val).transform; val2.transform.localPosition = Vector3.zero; val2.AddComponent<AudioSource>(); val2.AddComponent<AudioHighPassFilter>(); val2.AddComponent<AudioLowPassFilter>(); } Plugin.Log("Found AEIOUSpeakObject"); AudioSource component = val2.GetComponent<AudioSource>(); if ((Object)(object)component == (Object)null) { Plugin.LogError("Couldn't speak, AudioSource was null"); return; } string message = chatMessage.Replace("\r", "").Replace("\n", ""); float[] array = TTS.SpeakToMemory(message, 7.5f); if ((Object)(object)component.clip == (Object)null) { component.clip = AudioClip.Create("AEIOUCLIP", TTS.IN_BUFFER_SIZE, 1, 11025, false); } Plugin.Log("Setting up clip"); component.clip.SetData(emptySamples, 0); component.clip.SetData(array, 0); component.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val.playerClientId]; component.rolloffMode = (AudioRolloffMode)2; component.minDistance = 1f; component.maxDistance = 40f; component.dopplerLevel = Plugin.TTSDopperLevel; component.pitch = 1f; component.spatialize = true; component.spatialBlend = (val.isPlayerDead ? 0f : 1f); bool flag = !val.isPlayerDead || StartOfRound.Instance.localPlayerController.isPlayerDead; component.volume = (flag ? Plugin.TTSVolume : 0f); AudioHighPassFilter component2 = val2.GetComponent<AudioHighPassFilter>(); if ((Object)(object)component2 != (Object)null) { ((Behaviour)component2).enabled = false; } AudioLowPassFilter component3 = val2.GetComponent<AudioLowPassFilter>(); if ((Object)(object)component3 != (Object)null) { component3.lowpassResonanceQ = 1f; component3.cutoffFrequency = 5000f; } if (component.isPlaying) { component.Stop(true); } Plugin.Log("Playing audio: " + ((object)component).ToString() + component.volume); if (val.holdingWalkieTalkie) { GrabbableObject currentlyHeldObjectServer = val.currentlyHeldObjectServer; WalkieTalkie val3 = (WalkieTalkie)(object)((currentlyHeldObjectServer is WalkieTalkie) ? currentlyHeldObjectServer : null); if (val3 != null) { Plugin.Log("WalkieTalkie"); bool flag2 = false; for (int j = 0; j < WalkieTalkie.allWalkieTalkies.Count; j++) { if ((Object)(object)((GrabbableObject)WalkieTalkie.allWalkieTalkies[j]).playerHeldBy == (Object)(object)StartOfRound.Instance.localPlayerController && ((GrabbableObject)WalkieTalkie.allWalkieTalkies[j]).isBeingUsed) { flag2 = true; } } if ((Object)(object)val3 != (Object)null && ((GrabbableObject)val3).isBeingUsed && flag2) { component.volume = Plugin.TTSVolume; if ((Object)(object)val == (Object)(object)StartOfRound.Instance.localPlayerController) { Plugin.Log("Pushing walkie button"); val.playerBodyAnimator.SetBool("walkieTalkie", true); ((MonoBehaviour)val3).StartCoroutine(WaitAndStopUsingWalkieTalkie(component.clip, val)); } else { ((Behaviour)component2).enabled = true; component3.lowpassResonanceQ = 3f; component3.cutoffFrequency = 4000f; component.spatialBlend = 0f; } } } } component.PlayOneShot(component.clip, 1f); RoundManager.Instance.PlayAudibleNoise(val2.transform.position, 25f, 0.7f, 0, false, 0); } public static void QueueSpeak(HUDManager __instance, string chatMessage, int playerId) { Plugin.Log("Queueing speak"); _speaks.Add(new Speak(chatMessage, playerId)); } public static IEnumerator WaitAndStopUsingWalkieTalkie(AudioClip clip, PlayerControllerB player) { Plugin.Log($"WalkieButton Length {TTS.CurrentAudioLengthInSeconds}"); yield return (object)new WaitForSeconds(TTS.CurrentAudioLengthInSeconds); Plugin.Log("WalkieButton end"); player.playerBodyAnimator.SetBool("walkieTalkie", false); } [HarmonyPatch(typeof(HUDManager), "EnableChat_performed")] [HarmonyPostfix] public static void EnableChat_performedPostfix(ref TMP_InputField ___chatTextField, HUDManager __instance) { ___chatTextField.characterLimit = NEW_CHAT_SIZE; chatTextField = ___chatTextField; Plugin.Log("Enable Chat"); } [HarmonyPatch(typeof(PlayerControllerB), "KillPlayer")] [HarmonyPostfix] public static void KillPlayerPostfix(PlayerControllerB __instance) { HUDManager.Instance.HideHUD(false); HUDManager.Instance.UpdateHealthUI(100, false); Plugin.Log("Player died, re-enabling UI"); } [HarmonyPatch(typeof(HUDManager), "EnableChat_performed")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> EnableChat_performedTranspiler(IEnumerable<CodeInstruction> oldInstructions) { List<CodeInstruction> list = new List<CodeInstruction>(oldInstructions); for (int i = 0; i < list.Count - 3; i++) { if (list[i].opcode == OpCodes.Ldarg_0 && CodeInstructionExtensions.Is(list[i + 1], OpCodes.Ldfld, (MemberInfo)AccessTools.Field(typeof(HUDManager), "localPlayer")) && CodeInstructionExtensions.Is(list[i + 2], OpCodes.Ldfld, (MemberInfo)AccessTools.Field(typeof(PlayerControllerB), "isPlayerDead")) && list[i + 3].opcode == OpCodes.Brfalse) { Plugin.Log("Patching dead chat in EnableChat_performed"); list[i].opcode = OpCodes.Br; list[i].operand = list[i + 3].operand; break; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> SubmitChat_performedTranspiler(IEnumerable<CodeInstruction> oldInstructions) { List<CodeInstruction> list = new List<CodeInstruction>(oldInstructions); patchMaxChatSize(list); patchDeadChat(list); return list.AsEnumerable(); static void patchDeadChat(List<CodeInstruction> newInstructions) { for (int i = 0; i < newInstructions.Count - 3; i++) { if (newInstructions[i].opcode == OpCodes.Ldarg_0 && CodeInstructionExtensions.Is(newInstructions[i + 1], OpCodes.Ldfld, (MemberInfo)AccessTools.Field(typeof(HUDManager), "localPlayer")) && CodeInstructionExtensions.Is(newInstructions[i + 2], OpCodes.Ldfld, (MemberInfo)AccessTools.Field(typeof(PlayerControllerB), "isPlayerDead")) && newInstructions[i + 3].opcode == OpCodes.Brfalse) { Plugin.Log("Patching dead chat in SubmitChat_performed"); newInstructions[i].opcode = OpCodes.Br; newInstructions[i].operand = newInstructions[i + 3].operand; break; } } } static void patchMaxChatSize(List<CodeInstruction> newInstructions) { CodeInstruction val = null; bool flag = false; foreach (CodeInstruction newInstruction in newInstructions) { if (CodeInstructionExtensions.Is(newInstruction, OpCodes.Ldc_I4_S, (object)50)) { flag = true; val = newInstruction; } else { if (newInstruction.opcode == OpCodes.Bge && flag) { val.opcode = OpCodes.Ldc_I4; val.operand = NEW_CHAT_SIZE + 1; Plugin.Log("Patched max chat length"); break; } if (flag) { flag = false; val = null; } } } } } [HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> AddPlayerChatMessageServerRpcTranspiler(IEnumerable<CodeInstruction> oldInstructions) { List<CodeInstruction> list = new List<CodeInstruction>(oldInstructions); foreach (CodeInstruction item in list) { if (CodeInstructionExtensions.Is(item, OpCodes.Ldc_I4_S, (object)50)) { item.opcode = OpCodes.Ldc_I4; item.operand = NEW_CHAT_SIZE; Plugin.Log("Patched server max chat length"); break; } } return list.AsEnumerable(); } } public class LCModUtils { private static Harmony _harmony; private static bool _shouldHost; private static bool _shouldJoin; public LCModUtils(Harmony harmony) { _harmony = harmony; } public void DisableFullscreen() { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(IngamePlayerSettings), "SetFullscreenMode", (Type[])null, (Type[])null); if (methodInfo == null) { Plugin.LogError("Couldn't find method SetFullscreenMode"); } MethodInfo methodInfo2 = SymbolExtensions.GetMethodInfo((Expression<Action>)(() => SetFullScreenModePrefix())); _harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Plugin.Log("Disabled Fullscreen"); } public void BootToLANMenu() { Plugin.Log("Attempting to load lan scene"); SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.LoadScene("InitSceneLANMode"); } public void StartLANHost() { BootToLANMenu(); _shouldHost = true; } public void StartLANClient() { BootToLANMenu(); _shouldJoin = true; } private static bool SetFullScreenModePrefix() { return false; } private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) { //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Expected O, but got Unknown MenuManager val = Object.FindObjectOfType<MenuManager>(); if (!(((Scene)(ref scene)).name == "MainMenu")) { return; } Plugin.Log("MainMenuLoaded"); GameObject lanWarningContainer = val.lanWarningContainer; if (Object.op_Implicit((Object)(object)lanWarningContainer)) { Plugin.Log("Destroy LAN Warning"); Object.Destroy((Object)(object)lanWarningContainer); } else { Plugin.Log("LANWarning Null"); } if (_shouldHost || _shouldJoin) { MethodInfo methodInfo = AccessTools.Method(typeof(MenuManager), "Start", (Type[])null, (Type[])null); if (methodInfo == null) { Plugin.LogError("Couldn't find method \"Start\" in MenuManager"); } MethodInfo methodInfo2 = SymbolExtensions.GetMethodInfo((Expression<Action>)(() => HostOrJoin())); _harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } SceneManager.sceneLoaded -= OnSceneLoaded; } private static void HostOrJoin() { MenuManager val = Object.FindObjectOfType<MenuManager>(); if (_shouldHost) { if (val != null) { val.ClickHostButton(); } if (val != null) { val.ConfirmHostButton(); } } else if (_shouldJoin) { AccessTools.Method(typeof(MenuManager), "ClickJoinButton", (Type[])null, (Type[])null)?.Invoke(val, null); } } } [BepInPlugin("AEIOUCompany", "AEIOUCompany", "1.0.0")] public class Plugin : BaseUnityPlugin { public static Harmony Harmony; protected static ManualLogSource Logger; public static bool PlayStartingUpMessage; public static float TTSVolume; public static float TTSDopperLevel; public static int ChatSize; public static void Log(object data) { ManualLogSource logger = Logger; if (logger != null) { logger.LogInfo(data); } } public static void LogError(object data) { ManualLogSource logger = Logger; if (logger != null) { logger.LogError(data); } } public void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown Harmony harmony = new Harmony("AEIOUCompany"); Harmony = harmony; Logger = ((BaseUnityPlugin)this).Logger; PlayStartingUpMessage = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "StartingUpMessage", true, "Enables \"starting up\" sound effect.").Value; TTSVolume = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Volume", 1f, "Volume scale of text-to-speech-voice. Values range from 0 to 1").Value; TTSDopperLevel = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Doppler Effect Level", 1f, "Values range from 0 to 1").Value; ChatSize = ((BaseUnityPlugin)this).Config.Bind<int>("Advanced", "Chat Character Limit", 1024, "WARNING: Everybody must have the same value set for this!").Value; TTS.Init(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin AEIOUCompany is loaded!"); Harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin total patches appled: {Harmony.GetPatchedMethods().Count()}"); } public void OnDestroy() { if (PlayStartingUpMessage) { TTS.Speak("Starting Up"); } } private void EnableTestMode() { LCModUtils lCModUtils = new LCModUtils(Harmony); lCModUtils.DisableFullscreen(); lCModUtils.BootToLANMenu(); } } public static class TTS { private static readonly int OUT_BUFFER_SIZE = 8192; public static readonly int IN_BUFFER_SIZE = 8388608; public static float CurrentAudioLengthInSeconds = 0f; private static float[] floatBuffer = new float[IN_BUFFER_SIZE]; private static NamedPipeClientStream _namedPipeClientStream; private static StreamWriter _streamWriter; private static BinaryWriter _binaryWriter; private static BinaryReader _binaryReader; private static bool _initialized = false; public static void Init() { StartSpeakServer(); try { _namedPipeClientStream = new NamedPipeClientStream("AEIOUCOMPANYMOD"); _streamWriter = new StreamWriter(_namedPipeClientStream, Encoding.UTF8, OUT_BUFFER_SIZE, leaveOpen: true); _binaryWriter = new BinaryWriter(_namedPipeClientStream, Encoding.UTF8, leaveOpen: true); _binaryReader = new BinaryReader(_namedPipeClientStream, Encoding.UTF8, leaveOpen: true); } catch (IOException data) { Plugin.LogError(data); } ConnectToSpeakServer(); _initialized = true; } public static void Speak(string message) { if (!_initialized) { Plugin.LogError("Tried to speak before initializing TTS!"); return; } try { SendMsg(message, "msgA"); } catch (IOException ex) { Plugin.LogError("Speak" + ex); } } public static float[] SpeakToMemory(string message, float volumeScale = 1f) { if (!_initialized) { Plugin.LogError("Tried to speak before initializing TTS!"); return null; } SendMsg(message, "msg"); ClearSamplesBuffer(); int num = _binaryReader.ReadInt32(); byte[] value = _binaryReader.ReadBytes(num); for (int i = 0; i < num - 1; i += 2) { int num2 = i / 2; float num3 = volumeScale * ((float)BitConverter.ToInt16(value, i) / 32767f); if (i < floatBuffer.Length) { floatBuffer[num2] = num3; } } int num4 = 0; for (int num5 = floatBuffer.Length - 1; num5 > 0; num5--) { if ((double)floatBuffer[num5] != 0.0) { num4 = num5; break; } } CurrentAudioLengthInSeconds = (float)num4 / 11025f; Plugin.Log("END"); return floatBuffer; } private static void SendMsg(string message, string prefix) { Plugin.Log("Sending: " + prefix + "=" + message + "]"); try { _streamWriter.WriteLine(); _streamWriter.Flush(); } catch (IOException ex) { if (ex.Message.Contains("Pipe is broken")) { StartSpeakServer(); ConnectToSpeakServer(); } else { Plugin.LogError(ex); } } catch (Exception data) { Plugin.LogError(data); } _streamWriter.WriteLine(prefix + "=[:np]" + message + "]"); _streamWriter.Flush(); } private static void ConnectToSpeakServer() { Plugin.Log("ConnectingToPipe"); try { _namedPipeClientStream.Connect(7500); } catch (TimeoutException) { Plugin.LogError("Unable to connect to SpeakServer after timeout"); } catch (IOException) { Plugin.LogError("IOException while trying to ConnectToSpeakServer"); } } private static void ClearSamplesBuffer() { for (int i = 0; i < floatBuffer.Length; i++) { floatBuffer[i] = 0f; } } private static void StartSpeakServer() { if (CheckForAEIOUSPEAKProcess()) { Process[] processesByName = Process.GetProcessesByName("AEIOUSpeak"); Process[] array = processesByName; foreach (Process process in array) { process.Close(); } } string text = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath.Replace("AEIOUCompany.dll", ""); Plugin.Log(text + "AEIOUSpeak.exe"); Process process2 = Process.Start(text + "AEIOUSpeak.exe"); Plugin.Log("Started Speak Server"); if (process2 == null) { Plugin.LogError("Failed to start Speak Server"); } } private static bool CheckForAEIOUSPEAKProcess() { Process[] processesByName = Process.GetProcessesByName("AEIOUSpeak"); if (processesByName.Length != 0) { return true; } return false; } } public static class PluginInfo { public const string PLUGIN_GUID = "AEIOUCompany"; public const string PLUGIN_NAME = "AEIOUCompany"; public const string PLUGIN_VERSION = "1.0.0"; } }
BepInEx/plugins/aeioucompany/SharpTalk.dll
Decompiled a year agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("SharpTalk")] [assembly: AssemblyDescription("A .NET wrapper for the DECtalk TTS engine.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpTalk")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("a8dbd00f-6cfd-4d00-a4d6-b0059b2eb887")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.8726.31713")] [module: UnverifiableCode] namespace SharpTalk; public class FonixTalkEngine : IDisposable { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void DtCallbackRoutine(int lParam1, int lParam2, uint drCallbackParameter, uint uiMsg); private struct PhonemeMark { public byte ThisPhoneme; public byte NextPhoneme; public ushort Duration; } [StructLayout(LayoutKind.Explicit)] private struct PhonemeTag { [FieldOffset(0)] public PhonemeMark PMData; [FieldOffset(0)] public int DWData; } private struct InMemoryRaiiHelper : IDisposable { private readonly FonixTalkEngine _engine; public InMemoryRaiiHelper(FonixTalkEngine engine) { _engine = engine; } public void Dispose() { _engine.CloseInMemory(); } } private struct BufferRaiiHelper : IDisposable { private readonly FonixTalkEngine _engine; public BufferRaiiHelper(FonixTalkEngine engine) { _engine = engine; } public void Dispose() { _engine.FreeBuffer(); } } public const uint DefaultRate = 200u; public const TtsVoice DefaultSpeaker = TtsVoice.Paul; private const uint WaveFormat_1M16 = 4u; private const uint TtsNotSupported = 32767u; private const uint TtsNotAvailable = 32766u; private const uint TtsLangError = 16384u; private static readonly uint UiIndexMsg = RegisterWindowMessage("DECtalkIndexMessage"); private static readonly uint UiErrorMsg = RegisterWindowMessage("DECtalkErrorMessage"); private static readonly uint UiBufferMsg = RegisterWindowMessage("DECtalkBufferMessage"); private static readonly uint UiPhonemeMsg = RegisterWindowMessage("DECtalkVisualMessage"); private IntPtr _handle; private IntPtr _speakerParamsPtr; private IntPtr _dummy1; private IntPtr _dummy2; private IntPtr _dummy3; private DtCallbackRoutine _callback; private TtsBufferManaged _buffer; private Stream _bufferStream; public TtsVoice Voice { get { Check(TextToSpeechGetSpeaker(_handle, out var speaker)); return speaker; } set { Check(TextToSpeechSetSpeaker(_handle, value)); } } public uint Rate { get { Check(TextToSpeechGetRate(_handle, out var rate)); return rate; } set { Check(TextToSpeechSetRate(_handle, value)); } } public SpeakerParams SpeakerParams { get { Check(TextToSpeechGetSpeakerParams(_handle, 0u, out _speakerParamsPtr, out _dummy1, out _dummy2, out _dummy3)); return (SpeakerParams)Marshal.PtrToStructure(_speakerParamsPtr, typeof(SpeakerParams)); } set { Check(TextToSpeechGetSpeakerParams(_handle, 0u, out _speakerParamsPtr, out _dummy1, out _dummy2, out _dummy3)); Marshal.StructureToPtr(value, _speakerParamsPtr, fDeleteOld: false); Check(TextToSpeechSetSpeakerParams(_handle, _speakerParamsPtr)); } } public event EventHandler<PhonemeEventArgs> Phoneme; [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechStartupEx(out IntPtr handle, uint uiDeviceNumber, uint dwDeviceOptions, DtCallbackRoutine callback, ref IntPtr dwCallbackParameter); [DllImport("FonixTalk.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool TextToSpeechSelectLang(IntPtr handle, uint lang); [DllImport("FonixTalk.dll")] private static extern uint TextToSpeechStartLang([MarshalAs(UnmanagedType.LPStr)] string lang); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechSetSpeaker(IntPtr handle, TtsVoice speaker); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechGetSpeaker(IntPtr handle, out TtsVoice speaker); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechGetRate(IntPtr handle, out uint rate); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechSetRate(IntPtr handle, uint rate); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechSpeakA(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string msg, uint flags); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechShutdown(IntPtr handle); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechPause(IntPtr handle); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechResume(IntPtr handle); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechReset(IntPtr handle, [MarshalAs(UnmanagedType.Bool)] bool bReset); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechSync(IntPtr handle); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechSetSpeakerParams(IntPtr handle, IntPtr spDefs); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechGetSpeakerParams(IntPtr handle, uint uiIndex, out IntPtr ppspCur, out IntPtr ppspLoLimit, out IntPtr ppspHiLimit, out IntPtr ppspDefault); [DllImport("FonixTalk.dll")] private unsafe static extern MMRESULT TextToSpeechAddBuffer(IntPtr handle, TtsBufferManaged.TTS_BUFFER_T* buffer); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechOpenInMemory(IntPtr handle, uint format); [DllImport("FonixTalk.dll")] private static extern MMRESULT TextToSpeechCloseInMemory(IntPtr handle); [DllImport("user32.dll")] private static extern uint RegisterWindowMessage([MarshalAs(UnmanagedType.LPStr)] string lpString); [DllImport("kernel32.dll")] private static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); public FonixTalkEngine(string language) { Init(language); } public FonixTalkEngine() { Init("US"); } public FonixTalkEngine(string language, uint rate, TtsVoice speaker) { Init(language); Voice = speaker; Rate = rate; } public FonixTalkEngine(uint rate, TtsVoice speaker) { Init("US"); Voice = speaker; Rate = rate; } private void Init(string lang) { _callback = TtsCallback; _buffer = null; _bufferStream = null; if (lang != "XX") { uint num = TextToSpeechStartLang(lang); if ((num & 0x4000u) != 0) { switch (num) { case 32767u: throw new FonixTalkException("This version of DECtalk does not support multiple languages."); case 32766u: throw new FonixTalkException("The specified language was not found."); } } if (!TextToSpeechSelectLang(IntPtr.Zero, num)) { throw new FonixTalkException("The specified language failed to load."); } } Check(TextToSpeechStartupEx(out _handle, uint.MaxValue, 0u, _callback, ref _handle)); Speak("[:phone on]"); } private unsafe void TtsCallback(int lParam1, int lParam2, uint drCallbackParameter, uint uiMsg) { if (uiMsg == UiPhonemeMsg && this.Phoneme != null) { PhonemeTag phonemeTag = default(PhonemeTag); phonemeTag.DWData = lParam2; PhonemeTag phonemeTag2 = phonemeTag; this.Phoneme(this, new PhonemeEventArgs((char)phonemeTag2.PMData.ThisPhoneme, phonemeTag2.PMData.Duration)); } else if (uiMsg == UiBufferMsg) { _bufferStream.Write(_buffer.GetBufferBytes(), 0, (int)_buffer.Length); _ = _buffer.Full; _buffer.Reset(); Check(TextToSpeechAddBuffer(_handle, _buffer.ValuePointer)); } else if (uiMsg != UiErrorMsg) { _ = UiIndexMsg; } } public byte[] SpeakToMemory(string input) { using (_bufferStream = new MemoryStream()) { using (OpenInMemory(4u)) { using (ReadyBuffer()) { Speak(input); Sync(); TextToSpeechReset(_handle, bReset: false); } } return ((MemoryStream)_bufferStream).ToArray(); } } public void SpeakToStream(Stream stream, string input) { _bufferStream = stream; using (OpenInMemory(4u)) { using (ReadyBuffer()) { Speak(input); Sync(); TextToSpeechReset(_handle, bReset: false); } } _bufferStream = null; } public void SpeakToWavFile(string path, string input) { using MemoryStream memoryStream = new MemoryStream(); SpeakToStream(memoryStream, input); int num = (int)memoryStream.Length; using BinaryWriter binaryWriter = new BinaryWriter(File.Create(path), Encoding.ASCII); binaryWriter.Write("RIFF".ToCharArray()); binaryWriter.Write(num + 44 - 8); binaryWriter.Write("WAVE".ToCharArray()); binaryWriter.Write("fmt ".ToCharArray()); binaryWriter.Write(16); binaryWriter.Write((short)1); binaryWriter.Write((short)1); binaryWriter.Write(11025); binaryWriter.Write(22050); binaryWriter.Write((short)2); binaryWriter.Write((short)16); binaryWriter.Write("data".ToCharArray()); binaryWriter.Write(num); memoryStream.Position = 0L; memoryStream.CopyTo(binaryWriter.BaseStream); } public void Pause() { Check(TextToSpeechPause(_handle)); } public void Resume() { Check(TextToSpeechResume(_handle)); } public void Reset() { Check(TextToSpeechReset(_handle, bReset: false)); } public void Sync() { Check(TextToSpeechSync(_handle)); } public void Speak(string msg) { Check(TextToSpeechSpeakA(_handle, msg, 1u)); } private static void Check(MMRESULT code) { if (code != 0) { throw new FonixTalkException(code); } } private InMemoryRaiiHelper OpenInMemory(uint format) { Check(TextToSpeechOpenInMemory(_handle, format)); return new InMemoryRaiiHelper(this); } private void CloseInMemory() { Check(TextToSpeechCloseInMemory(_handle)); } private unsafe BufferRaiiHelper ReadyBuffer() { if (_buffer != null) { throw new InvalidOperationException("Buffer already exists."); } _buffer = new TtsBufferManaged(); Check(TextToSpeechAddBuffer(_handle, _buffer.ValuePointer)); return new BufferRaiiHelper(this); } private void FreeBuffer() { _buffer.Dispose(); _buffer = null; } ~FonixTalkEngine() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); } private void Dispose(bool disposing) { TextToSpeechShutdown(_handle); if (_buffer != null) { _buffer.Dispose(); } if (disposing) { GC.SuppressFinalize(this); } } } public sealed class FonixTalkException : Exception { internal FonixTalkException(MMRESULT code) : base(GetMessage(code)) { } internal FonixTalkException(string message) : base(message) { } private static string GetMessage(MMRESULT code) { return code switch { MMRESULT.MMSYSERR_INVALPARAM => "An invalid parameter was passed to the function.", MMRESULT.MMSYSERR_INVALHANDLE => "The associated handle is invalid. Did you dispose it?", MMRESULT.MMSYSERR_ERROR => "The function returned a generic error. Please check that you are using the functions correctly.", MMRESULT.MMSYSERR_NOERROR => "The function did not throw an error. If you are seeing this, Berkin was obviously high while coding.", MMRESULT.MMSYSERR_NOMEM => "There was insufficnent memory available to allocate the requested resources.", MMRESULT.MMSYSERR_ALLOCATED => "The requested resources are already in use somewhere else.", MMRESULT.WAVERR_BADFORMAT => "Wave output device does not support request format.", MMRESULT.MMSYSERR_BADDEVICEID => "Device ID out of range.", MMRESULT.MMSYSERR_NODRIVER => "No wave output device present.", _ => code.ToString(), }; } } [Flags] internal enum DeviceOptions : uint { OwnAudioDevice = 1u, ReportOpenError = 2u, UseSapi5AudioDevice = 0x40000000u, DoNotUseAudioDevice = 0x80000000u } public static class LanguageCode { public const string EnglishUS = "US"; public const string EnglishUK = "UK"; public const string SpanishCastilian = "SP"; public const string SpanishLatinAmerican = "LA"; public const string German = "GR"; public const string French = "FR"; public const string None = "XX"; } internal enum MMRESULT : uint { MMSYSERR_NOERROR = 0u, MMSYSERR_ERROR = 1u, MMSYSERR_BADDEVICEID = 2u, MMSYSERR_NOTENABLED = 3u, MMSYSERR_ALLOCATED = 4u, MMSYSERR_INVALHANDLE = 5u, MMSYSERR_NODRIVER = 6u, MMSYSERR_NOMEM = 7u, MMSYSERR_NOTSUPPORTED = 8u, MMSYSERR_BADERRNUM = 9u, MMSYSERR_INVALFLAG = 10u, MMSYSERR_INVALPARAM = 11u, MMSYSERR_HANDLEBUSY = 12u, MMSYSERR_INVALIDALIAS = 13u, MMSYSERR_BADDB = 14u, MMSYSERR_KEYNOTFOUND = 15u, MMSYSERR_READERROR = 16u, MMSYSERR_WRITEERROR = 17u, MMSYSERR_DELETEERROR = 18u, MMSYSERR_VALNOTFOUND = 19u, MMSYSERR_NODRIVERCB = 20u, WAVERR_BADFORMAT = 32u, WAVERR_STILLPLAYING = 33u, WAVERR_UNPREPARED = 34u } public class PhonemeEventArgs : EventArgs { public readonly char Phoneme; public readonly uint Duration; internal PhonemeEventArgs(char phoneme, uint duration) { Phoneme = phoneme; Duration = duration; } } public enum TtsVoice : uint { Paul, Betty, Harry, Frank, Dennis, Kit, Ursula, Rita, Wendy } public struct SpeakerParams { [MarshalAs(UnmanagedType.I2)] public Sex Sex; public short Smoothness; public short Assertiveness; public short AveragePitch; public short Breathiness; public short Richness; public short NumFixedSampOG; public short Laryngealization; public short HeadSize; public short Formant4ResFreq; public short Formant4Bandwidth; public short Formant5ResFreq; public short Formant5Bandwidth; public short Parallel4Freq; public short Parallel5Freq; public short GainFrication; public short GainAspiration; public short GainVoicing; public short GainNasalization; public short GainCFR1; public short GainCFR2; public short GainCFR3; public short GainCFR4; public short Loudness; public short SpectralTilt; public short BaselineFall; public short LaxBreathiness; public short Quickness; public short HatRise; public short StressRise; public short GlottalSpeed; public short OutputGainMultiplier; } public enum Sex : short { Female, Male } [Flags] internal enum SpeakFlags : uint { Normal = 0u, Force = 1u } internal enum TTSMessageType : uint { Buffer, IndexMarker, Status, Visual } [StructLayout(LayoutKind.Sequential)] internal class TtsBufferManaged : IDisposable { public struct TTS_BUFFER_T { public const int BufferSize = 16384; public IntPtr DataPtr; public unsafe TTS_PHONEME_T* PhonemeArrayPtr; public unsafe TTS_INDEX_T* IndexArrayPtr; public uint MaxBufferLength; public uint MaxPhonemeChanges; public uint MaxIndexMarks; public uint BufferLength; public uint PhonemeChangeCount; public uint IndexMarkCount; public uint _reserved; } private TTS_BUFFER_T _value; private GCHandle _pinHandle; public bool Full => _value.BufferLength == _value.MaxBufferLength; public uint Length => _value.BufferLength; public unsafe TTS_BUFFER_T* ValuePointer { get { fixed (TTS_BUFFER_T* result = &_value) { return result; } } } public TtsBufferManaged() { _value = default(TTS_BUFFER_T); _pinHandle = GCHandle.Alloc(this, GCHandleType.Pinned); _value.MaxBufferLength = 16384u; _value.DataPtr = Marshal.AllocHGlobal(16384); } public byte[] GetBufferBytes() { byte[] array = new byte[_value.BufferLength]; Marshal.Copy(_value.DataPtr, array, 0, (int)_value.BufferLength); return array; } public void Reset() { _value.BufferLength = 0u; _value.PhonemeChangeCount = 0u; _value.IndexMarkCount = 0u; } public void Dispose() { Marshal.FreeHGlobal(_value.DataPtr); _pinHandle.Free(); GC.SuppressFinalize(this); } } internal struct TTS_INDEX_T { public uint IndexValue; public uint SampleNumber; private readonly uint _reserved; } internal struct TTS_PHONEME_T { public uint Phoneme; public uint PhonemeSampleNumber; public uint PhonemeDuration; private readonly uint _reserved; }
BepInEx/plugins/AlwaysHearWalkie.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LCAlwaysHearWalkieMod.Patches; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("AlwaysHearWalkie")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.4.3.0")] [assembly: AssemblyInformationalVersion("1.4.3+b44d9dd67954bb9cf96dd2ba0e84393e7774a6a0")] [assembly: AssemblyProduct("Always Hear Active Walkies")] [assembly: AssemblyTitle("AlwaysHearWalkie")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.4.3.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 BepInEx5.PluginTemplate { [BepInPlugin("suskitech.LCAlwaysHearActiveWalkie", "LC Always Hear Active Walkies", "1.4.3")] public class LCAlwaysHearWalkieMod : BaseUnityPlugin { public static ManualLogSource Log; private const string modGUID = "suskitech.LCAlwaysHearActiveWalkie"; private const string modName = "LC Always Hear Active Walkies"; private const string modVersion = "1.4.3"; private readonly Harmony harmony = new Harmony("suskitech.LCAlwaysHearActiveWalkie"); private static LCAlwaysHearWalkieMod Instance; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } Log = Logger.CreateLogSource("suskitech.LCAlwaysHearActiveWalkie"); Log.LogInfo((object)"\\ /"); Log.LogInfo((object)"/|\\"); Log.LogInfo((object)" |----|"); Log.LogInfo((object)" |[__]| Always Hear Active Walkies"); Log.LogInfo((object)" |. .| Version 1.4.3 Loaded"); Log.LogInfo((object)" |____|"); harmony.PatchAll(typeof(LCAlwaysHearWalkieMod)); harmony.PatchAll(typeof(PlayerControllerBPatch)); harmony.PatchAll(typeof(WalkieTalkiePatch)); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "AlwaysHearWalkie"; public const string PLUGIN_NAME = "Always Hear Active Walkies"; public const string PLUGIN_VERSION = "1.4.3"; } } namespace LCAlwaysHearWalkieMod.Patches { [HarmonyPatch(typeof(PlayerControllerB))] internal class PlayerControllerBPatch { private static float AudibleDistance = 20f; private static float throttleInterval = 0.35f; private static float throttle = 0f; private static float AverageDistanceToHeldWalkie = 2f; private static float WalkieRecordingRange = 20f; private static float PlayerToPlayerSpatialHearingRange = 20f; [HarmonyPatch("Update")] [HarmonyPostfix] private static void alwaysHearWalkieTalkiesPatch(ref bool ___holdingWalkieTalkie, ref PlayerControllerB __instance) { //IL_00d5: 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_0293: Unknown result type (might be due to invalid IL or missing references) //IL_029f: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Unknown result type (might be due to invalid IL or missing references) throttle += Time.deltaTime; if (throttle < throttleInterval) { return; } throttle = 0f; if ((Object)(object)__instance == (Object)null || (Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)__instance != (Object)(object)GameNetworkManager.Instance.localPlayerController || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null) { return; } if (!GameNetworkManager.Instance.localPlayerController.isPlayerDead) { List<WalkieTalkie> list = new List<WalkieTalkie>(); List<WalkieTalkie> list2 = new List<WalkieTalkie>(); for (int i = 0; i < WalkieTalkie.allWalkieTalkies.Count; i++) { float num = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[i]).transform.position, ((Component)__instance).transform.position); if (num <= AudibleDistance) { if (((GrabbableObject)WalkieTalkie.allWalkieTalkies[i]).isBeingUsed) { list.Add(WalkieTalkie.allWalkieTalkies[i]); } } else { list2.Add(WalkieTalkie.allWalkieTalkies[i]); } } bool flag = list.Count > 0; if (flag != __instance.holdingWalkieTalkie) { ___holdingWalkieTalkie = flag; for (int j = 0; j < list2.Count; j++) { if (j < list.Count) { list2[j].thisAudio.Stop(); } } } if (!flag) { return; } } PlayerControllerB val = ((!GameNetworkManager.Instance.localPlayerController.isPlayerDead || !((Object)(object)GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript != (Object)null)) ? GameNetworkManager.Instance.localPlayerController : GameNetworkManager.Instance.localPlayerController.spectatedPlayerScript); for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++) { PlayerControllerB val2 = StartOfRound.Instance.allPlayerScripts[k]; if ((!val2.isPlayerControlled && !val2.isPlayerDead) || (Object)(object)val2 == (Object)(object)GameNetworkManager.Instance.localPlayerController || val2.isPlayerDead || !val2.holdingWalkieTalkie) { continue; } float num2 = Vector3.Distance(((Component)val).transform.position, ((Component)val2).transform.position); float num3 = float.MaxValue; float num4 = float.MaxValue; for (int l = 0; l < WalkieTalkie.allWalkieTalkies.Count; l++) { if (!((GrabbableObject)WalkieTalkie.allWalkieTalkies[l]).isBeingUsed) { continue; } float num5 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l].target).transform.position, ((Component)val).transform.position); if (num5 < num4) { num4 = num5; } if (!WalkieTalkie.allWalkieTalkies[l].speakingIntoWalkieTalkie) { float num6 = Vector3.Distance(((Component)WalkieTalkie.allWalkieTalkies[l]).transform.position, ((Component)val2).transform.position); if (num6 < num3) { num3 = num6; } } } float num7 = Mathf.Min(1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num3), 1f - Mathf.InverseLerp(AverageDistanceToHeldWalkie, WalkieRecordingRange, num4)); float num8 = 1f - Mathf.InverseLerp(0f, PlayerToPlayerSpatialHearingRange, num2); val2.voicePlayerState.Volume = Mathf.Max(num7, num8); if (val2.speakingToWalkieTalkie && num7 > num8) { makePlayerSoundWalkieTalkie(val2); } else { makePlayerSoundSpatial(val2); } } } private static void makePlayerSoundWalkieTalkie(PlayerControllerB playerController) { AudioSource currentVoiceChatAudioSource = playerController.currentVoiceChatAudioSource; AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>(); AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>(); OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>(); ((Behaviour)component2).enabled = true; ((Behaviour)component).enabled = true; component3.overridingLowPass = true; currentVoiceChatAudioSource.spatialBlend = 0f; playerController.currentVoiceChatIngameSettings.set2D = true; currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId]; currentVoiceChatAudioSource.bypassListenerEffects = false; currentVoiceChatAudioSource.bypassEffects = false; currentVoiceChatAudioSource.panStereo = (GameNetworkManager.Instance.localPlayerController.isPlayerDead ? 0f : 0.4f); component3.lowPassOverride = 4000f; component.lowpassResonanceQ = 3f; } private static void makePlayerSoundSpatial(PlayerControllerB playerController) { AudioSource currentVoiceChatAudioSource = playerController.currentVoiceChatAudioSource; AudioLowPassFilter component = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>(); AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>(); OccludeAudio component3 = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>(); ((Behaviour)component2).enabled = false; ((Behaviour)component).enabled = true; component3.overridingLowPass = playerController.voiceMuffledByEnemy; currentVoiceChatAudioSource.spatialBlend = 1f; playerController.currentVoiceChatIngameSettings.set2D = false; currentVoiceChatAudioSource.bypassListenerEffects = false; currentVoiceChatAudioSource.bypassEffects = false; currentVoiceChatAudioSource.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[playerController.playerClientId]; component.lowpassResonanceQ = 1f; } } [HarmonyPatch(typeof(WalkieTalkie))] internal class WalkieTalkiePatch { [HarmonyPatch("EnableWalkieTalkieListening")] [HarmonyPrefix] private static bool alwaysHearWalkieTalkiesEnableWalkieTalkieListeningPatch(bool enable) { if (!enable) { return false; } return true; } } }
BepInEx/plugins/BetterStamina.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BetterStamina.Config; using GameNetcodeStuff; using HarmonyLib; using Unity.Collections; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("BetterStamina")] [assembly: AssemblyDescription("Mod made by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BetterStamina")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("1c42022e-b386-4342-baf0-67de1b7529e2")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace BetterStamina { [BepInPlugin("FlipMods.BetterStamina", "BetterStamina", "1.3.2")] public class Plugin : BaseUnityPlugin { private Harmony _harmony; public static Plugin instance; private void Awake() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown instance = this; ConfigSettings.BindConfigSettings(); _harmony = new Harmony("BetterStamina"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"BetterStamina loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } public static void LogError(string message) { ((BaseUnityPlugin)instance).Logger.LogError((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.BetterStamina"; public const string PLUGIN_NAME = "BetterStamina"; public const string PLUGIN_VERSION = "1.3.2"; } } namespace BetterStamina.Patches { [HarmonyPatch] public class PlayerPatcher { private static float currentSprintMeter; [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPrefix] public static void UpdateStaminaPrefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { currentSprintMeter = __instance.sprintMeter; } } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void UpdateStaminaPostfix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { float num = __instance.sprintMeter - currentSprintMeter; if (num < 0f) { __instance.sprintMeter = Mathf.Max(currentSprintMeter + num * ConfigSync.instance.staminaConsumptionMultiplier, 0f); } else if (num > 0f) { __instance.sprintMeter = Mathf.Min(currentSprintMeter + num * ConfigSync.instance.staminaRegenMultiplier, 1f); } } } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyPrefix] public static void LateUpdatePrefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { currentSprintMeter = __instance.sprintMeter; } } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyPostfix] public static void LateUpdateStaminaPostfix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { float num = __instance.sprintMeter - currentSprintMeter; if (num < 0f) { __instance.sprintMeter = Mathf.Max(currentSprintMeter + num * ConfigSync.instance.staminaConsumptionMultiplier, 0f); } else if (num > 0f) { __instance.sprintMeter = Mathf.Min(currentSprintMeter + num * ConfigSync.instance.staminaRegenMultiplier, 1f); } } } [HarmonyPatch(typeof(PlayerControllerB), "Jump_performed")] [HarmonyPrefix] public static void JumpPerformedPrefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { currentSprintMeter = __instance.sprintMeter; } } [HarmonyPatch(typeof(PlayerControllerB), "Jump_performed")] [HarmonyPostfix] public static void JumpPerformedPostfix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { float num = __instance.sprintMeter - currentSprintMeter; if (num < 0f) { __instance.sprintMeter = Mathf.Max(new float[1] { currentSprintMeter + num * ConfigSync.instance.jumpStaminaConsumptionMultiplier }); } } } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> SpoofWeightValuesUpdate(IEnumerable<CodeInstruction> instructions) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(instructions); FieldInfo field = typeof(PlayerControllerB).GetField("carryWeight", BindingFlags.Instance | BindingFlags.Public); MethodInfo method = typeof(PlayerPatcher).GetMethod("GetAdjustedWeight", BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldfld && (FieldInfo)list[i].operand == field) { list[i] = new CodeInstruction(OpCodes.Call, (object)method); list.RemoveAt(i - 1); } } return list.AsEnumerable(); } [HarmonyPatch(typeof(PlayerControllerB), "LateUpdate")] [HarmonyTranspiler] public static IEnumerable<CodeInstruction> SpoofWeightValuesLateUpdate(IEnumerable<CodeInstruction> instructions) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(instructions); FieldInfo field = typeof(PlayerControllerB).GetField("carryWeight", BindingFlags.Instance | BindingFlags.Public); MethodInfo method = typeof(PlayerPatcher).GetMethod("GetAdjustedWeight", BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldfld && (FieldInfo)list[i].operand == field) { list[i] = new CodeInstruction(OpCodes.Call, (object)method); list.RemoveAt(i - 1); } } return list.AsEnumerable(); } public static float GetAdjustedWeight() { return Mathf.Max(((Object)(object)StartOfRound.Instance.localPlayerController != (Object)null) ? (StartOfRound.Instance.localPlayerController.carryWeight * ConfigSync.instance.carryWeightPenaltyMultiplier) : 1f, 1f); } } } namespace BetterStamina.Config { [Serializable] public static class ConfigSettings { public static ConfigEntry<float> staminaRegenMultiplierConfig; public static ConfigEntry<float> staminaConsumptionMultiplierConfig; public static ConfigEntry<float> jumpStaminaConsumptionMultiplierConfig; public static ConfigEntry<float> carryWeightPenaltyMultiplierConfig; public static ConfigEntry<float> movementSpeedMultiplierConfig; public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); staminaRegenMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "StaminaRegenMultiplier", 1.5f, "Multiplier for how fast your stamina regens."); staminaConsumptionMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "StaminaConsumptionMultiplier", 0.75f, "Multiplier for how much stamina drains while sprinting."); jumpStaminaConsumptionMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "JumpStaminaConsumptionMultiplier", 0.75f, "Multiplier for how much stamina jumping consumes."); carryWeightPenaltyMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "CarryWeightPenaltyMultiplier", 0.5f, "Multiplier for how much your speed/stamina consumption are affected by weight."); movementSpeedMultiplierConfig = ((BaseUnityPlugin)Plugin.instance).Config.Bind<float>("BetterStamina", "MovementSpeedMultiplier", 1f, "Player movement speed multiplier."); } } [Serializable] [HarmonyPatch] public class ConfigSync { public static ConfigSync defaultConfig; public static ConfigSync instance; public static PlayerControllerB localPlayerController; public static bool isSynced = false; private static float defaultMovementSpeed = 4.6f; public float staminaRegenMultiplier = 1f; public float staminaConsumptionMultiplier = 1f; public float jumpStaminaConsumptionMultiplier = 1f; public float carryWeightPenaltyMultiplier = 1f; public float movementSpeedMultiplier = 1f; public static void BuildDefaultConfigSync() { instance = new ConfigSync(); } public static void BuildServerConfigSync() { if (defaultConfig == null) { defaultConfig = new ConfigSync(); defaultConfig.staminaRegenMultiplier = ConfigSettings.staminaRegenMultiplierConfig.Value; defaultConfig.staminaConsumptionMultiplier = ConfigSettings.staminaConsumptionMultiplierConfig.Value; defaultConfig.jumpStaminaConsumptionMultiplier = ConfigSettings.jumpStaminaConsumptionMultiplierConfig.Value; defaultConfig.carryWeightPenaltyMultiplier = ConfigSettings.carryWeightPenaltyMultiplierConfig.Value; defaultConfig.movementSpeedMultiplier = ConfigSettings.movementSpeedMultiplierConfig.Value; instance = defaultConfig; } } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] [HarmonyPostfix] public static void InitializeLocalPlayer(PlayerControllerB __instance) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown localPlayerController = __instance; if (NetworkManager.Singleton.IsServer) { BuildServerConfigSync(); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("BetterStamina-OnRequestConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSyncRequest)); OnLocalClientConfigSync(); } else { isSynced = false; BuildDefaultConfigSync(); NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("BetterStamina-OnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveConfigSync)); RequestConfigSync(); } } public static void RequestConfigSync() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsClient) { Plugin.Log("Sending config sync request to server."); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(4, (Allocator)2, -1); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BetterStamina-OnRequestConfigSync", 0uL, val, (NetworkDelivery)3); } else { Plugin.LogError("Failed to send config sync request."); } } public static void OnReceiveConfigSyncRequest(ulong clientId, FastBufferReader reader) { //IL_0053: 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_007c: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer) { Plugin.Log("Receiving config sync request from client with id: " + clientId + ". Sending config sync to client."); byte[] array = SerializeConfigToByteArray(instance); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(array.Length + 4, (Allocator)2, -1); int num = array.Length; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("BetterStamina-OnReceiveConfigSync", clientId, val, (NetworkDelivery)3); } } public static void OnReceiveConfigSync(ulong clientId, FastBufferReader reader) { //IL_0014: 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) if (((FastBufferReader)(ref reader)).TryBeginRead(4)) { int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (((FastBufferReader)(ref reader)).TryBeginRead(num)) { Plugin.Log("Receiving config sync from server."); byte[] data = new byte[num]; ((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0); instance = DeserializeFromByteArray(data); OnLocalClientConfigSync(); } else { Plugin.LogError("Error receiving sync from server."); } } else { Plugin.LogError("Error receiving bytes length."); } } public static void OnLocalClientConfigSync() { localPlayerController.movementSpeed = defaultMovementSpeed * instance.movementSpeedMultiplier; isSynced = true; } public static byte[] SerializeConfigToByteArray(ConfigSync config) { BinaryFormatter binaryFormatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(); binaryFormatter.Serialize(memoryStream, config); return memoryStream.ToArray(); } public static ConfigSync DeserializeFromByteArray(byte[] data) { MemoryStream serializationStream = new MemoryStream(data); BinaryFormatter binaryFormatter = new BinaryFormatter(); return (ConfigSync)binaryFormatter.Deserialize(serializationStream); } } }
BepInEx/plugins/BoomBoxNoPower.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using BoomBoxNoPower.Patches; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("BoomBoxNoPower")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BoomBoxNoPower")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("bd269fc6-abd7-4d33-b4d7-77be24732c49")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace BoomBoxNoPower { [BepInPlugin("BoomBox.BoomBoxNoPower", "Boombox No Power", "1.0.0.0")] public class BoomBoxModBase : BaseUnityPlugin { private const string modGUID = "BoomBox.BoomBoxNoPower"; private const string modName = "Boombox No Power"; private const string modVersion = "1.0.0.0"; private static BoomBoxModBase instance; private readonly Harmony harmony = new Harmony("BoomBox.BoomBoxNoPower"); internal ManualLogSource logger; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown if ((Object)instance != (Object)null) { instance = this; } logger = Logger.CreateLogSource("BoomBox.BoomBoxNoPower"); logger.LogInfo((object)"Boombox No Power has awoken"); harmony.PatchAll(typeof(BoomBoxModBase)); harmony.PatchAll(typeof(BoomBoxPatch)); } } } namespace BoomBoxNoPower.Patches { [HarmonyPatch(typeof(BoomboxItem))] internal class BoomBoxPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void PatchBattery(ref Item ___itemProperties) { ___itemProperties.requiresBattery = false; } } }
BepInEx/plugins/com.spycibot.cozyimprovements.dll
Decompiled a year agousing System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using SpyciBot.LC.CozyImprovements.Improvements; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("com.spycibot.cozyimprovements")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("\r\n\t\tEnhance the experience inside the ship to create a more immersive, cozy, and accessible environment.\r\n\t")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: AssemblyInformationalVersion("1.2.0")] [assembly: AssemblyProduct("Cozy Improvements")] [assembly: AssemblyTitle("com.spycibot.cozyimprovements")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.0.0")] [module: UnverifiableCode] namespace SpyciBot.LC.CozyImprovements { public class Config { public ConfigEntry<bool> configStorageLights; public ConfigEntry<bool> configLightSwitchGlow; public ConfigEntry<bool> configTerminalGlow; public ConfigEntry<bool> configTerminalMonitorAlwaysOn; public ConfigEntry<bool> configChargeStationGlow; public ConfigEntry<bool> configBigDoorButtons; public ConfigEntry<bool> configEasyLaunchLever; public ConfigEntry<bool> configBigTeleporterButtons; public ConfigEntry<bool> configBigMonitorButtons; public Config(ConfigFile cfg) { configStorageLights = cfg.Bind<bool>("General", "StorageLightsEnabled", true, "Makes the LightSwitch glow in the dark"); configLightSwitchGlow = cfg.Bind<bool>("General", "LightSwitchGlowEnabled", true, "Makes the LightSwitch glow in the dark"); configTerminalGlow = cfg.Bind<bool>("General", "TerminalGlowEnabled", true, "Makes the Terminal glow active all the time"); configTerminalMonitorAlwaysOn = cfg.Bind<bool>("General", "TerminalMonitorAlwaysOn", true, "Makes the Terminal screen active all the time; Will show the screen you left it on"); configChargeStationGlow = cfg.Bind<bool>("General", "ChargeStationGlowEnabled", true, "Makes the Charging Station glow with a yellow light"); configBigDoorButtons = cfg.Bind<bool>("General.Accessibility", "BigDoorButtonsEnabled", false, "Enlarges the door buttons so they're easier to press"); configEasyLaunchLever = cfg.Bind<bool>("General.Accessibility", "EasyLaunchLeverEnabled", true, "Enlarges the hitbox for the Launch Lever to cover more of the table so it's easier to pull"); configBigTeleporterButtons = cfg.Bind<bool>("General.Accessibility", "BigTeleporterButtonsEnabled", false, "Enlarges the teleporter buttons so they're easier to press"); configBigMonitorButtons = cfg.Bind<bool>("General.Accessibility", "BigMonitorButtonsEnabled", false, "Enlarges the Monitor buttons so they're easier to press"); } } [BepInPlugin("com.spycibot.cozyimprovements", "Cozy Improvements", "1.2.0")] [HarmonyPatch] public class CozyImprovements : BaseUnityPlugin { private static GameObject gameObject; private static Terminal TermInst; public static Config CozyConfig { get; internal set; } private void Awake() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Cozy Improvements - com.spycibot.cozyimprovements - 1.2.0 is loaded!"); Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null); CozyConfig = new Config(((BaseUnityPlugin)this).Config); } [HarmonyPatch(typeof(Terminal), "waitUntilFrameEndToSetActive")] [HarmonyPrefix] private static void PrefixWaitUntilFrameEndToSetActive(Terminal __instance, ref bool active) { TermInst = __instance; if (CozyConfig.configTerminalMonitorAlwaysOn.Value) { active = true; } } [HarmonyPatch(typeof(Terminal), "SetTerminalInUseClientRpc")] [HarmonyPostfix] private static void PostfixSetTerminalInUseClientRpc(Terminal __instance, bool inUse) { if (CozyConfig.configTerminalGlow.Value) { ((Behaviour)TermInst.terminalLight).enabled = true; } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")] [HarmonyPostfix] private static void PostfixOnPlayerConnectedClientRpc(StartOfRound __instance, ulong clientId, int connectedPlayers, ulong[] connectedPlayerIdsOrdered, int assignedPlayerObjectId, int serverMoneyAmount, int levelID, int profitQuota, int timeUntilDeadline, int quotaFulfilled, int randomSeed) { if (clientId == NetworkManager.Singleton.LocalClientId) { DoAllTheThings(); } } [HarmonyPatch(typeof(StartOfRound), "LoadUnlockables")] [HarmonyPostfix] private static void PostfixLoadUnlockables(StartOfRound __instance) { DoAllTheThings(); } private static void DoAllTheThings() { manageInteractables(); manageStorageCupboard(); } private static void manageInteractables() { //IL_0056: 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_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) _ = GameNetworkManager.Instance.localPlayerController; GameObject[] array = GameObject.FindGameObjectsWithTag("InteractTrigger"); for (int i = 0; i < array.Length; i++) { if (((Object)array[i]).name == "LightSwitch" && CozyConfig.configLightSwitchGlow.Value) { makeEmissive(array[i], new Color32((byte)182, (byte)240, (byte)150, (byte)102)); makeEmissive(((Component)array[i].transform.GetChild(0)).gameObject, new Color32((byte)241, (byte)80, (byte)80, (byte)10), 0.15f); } if (((Object)array[i]).name == "TerminalScript") { if (CozyConfig.configTerminalMonitorAlwaysOn.Value) { TermInst.LoadNewNode(TermInst.terminalNodes.specialNodes[1]); } if (CozyConfig.configTerminalGlow.Value) { ((Behaviour)TermInst.terminalLight).enabled = true; } } if (((Object)array[i]).name == "Trigger" && CozyConfig.configChargeStationGlow.Value) { GameObject val = ((Component)array[i].transform.parent.parent).gameObject; GameObject val2 = new GameObject("ChargeStationLight"); Light obj = val2.AddComponent<Light>(); obj.type = (LightType)2; obj.color = Color32.op_Implicit(new Color32((byte)240, (byte)240, (byte)140, byte.MaxValue)); obj.intensity = 0.05f; obj.range = 0.3f; obj.shadows = (LightShadows)2; val2.layer = LayerMask.NameToLayer("Room"); val2.transform.localPosition = new Vector3(0.5f, 0f, 0f); val2.transform.SetParent(val.transform, false); } if (((Object)array[i]).name == "Cube (2)" && ((Object)((Component)array[i].transform.parent).gameObject).name.StartsWith("CameraMonitor") && CozyConfig.configBigMonitorButtons.Value) { Accessibility.adjustMonitorButtons(array[i].gameObject); } } } private static void makeEmissive(GameObject gameObject, Color32 glowColor, float brightness = 0.02f) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: 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) MeshRenderer component = gameObject.GetComponent<MeshRenderer>(); Material material = ((Renderer)component).material; material.SetColor("_EmissiveColor", Color32.op_Implicit(glowColor) * brightness); ((Renderer)component).material = material; } private static void manageStorageCupboard() { PlaceableShipObject[] array = Object.FindObjectsOfType<PlaceableShipObject>(); for (int i = 0; i < array.Length; i++) { UnlockableItem obj = StartOfRound.Instance.unlockablesList.unlockables[array[i].unlockableID]; _ = obj.unlockableType; if (obj.unlockableName == "Cupboard") { gameObject = ((Component)array[i].parentObject).gameObject; break; } } if (!((Object)(object)gameObject == (Object)null) && CozyConfig.configStorageLights.Value) { spawnStorageLights(gameObject); } } private static void spawnStorageLights(GameObject storageCloset) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0158: 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) float num = -1.1175f; List<float> obj = new List<float> { 2.804f, 2.163f, 1.48f, 0.999f }; float num2 = 0.55f; float num3 = obj[0]; AttachLightToStorageCloset(storageCloset, new Vector3(num - num2, 0.4f, num3)); AttachLightToStorageCloset(storageCloset, new Vector3(num, 0.4f, num3)); AttachLightToStorageCloset(storageCloset, new Vector3(num + num2, 0.4f, num3)); num3 = obj[1]; AttachLightToStorageCloset(storageCloset, new Vector3(num - num2, 0.4f, num3)); AttachLightToStorageCloset(storageCloset, new Vector3(num, 0.4f, num3)); AttachLightToStorageCloset(storageCloset, new Vector3(num + num2, 0.4f, num3)); num3 = obj[2]; AttachLightToStorageCloset(storageCloset, new Vector3(num - num2, 0.4f, num3), 2f); AttachLightToStorageCloset(storageCloset, new Vector3(num, 0.4f, num3), 2f); AttachLightToStorageCloset(storageCloset, new Vector3(num + num2, 0.4f, num3), 2f); num3 = obj[3]; AttachLightToStorageCloset(storageCloset, new Vector3(num - num2, 0.4f, num3)); AttachLightToStorageCloset(storageCloset, new Vector3(num, 0.4f, num3)); AttachLightToStorageCloset(storageCloset, new Vector3(num + num2, 0.4f, num3)); } private static void AttachLightToStorageCloset(GameObject storageCloset, Vector3 lightPositionOffset, float intensity = 3f) { //IL_0005: 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_0011: 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: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0077: 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_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: 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_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("StorageClosetLight"); MeshFilter val2 = val.AddComponent<MeshFilter>(); MeshRenderer obj = val.AddComponent<MeshRenderer>(); GameObject val3 = GameObject.CreatePrimitive((PrimitiveType)0); val2.mesh = val3.GetComponent<MeshFilter>().mesh; Material val4 = new Material(Shader.Find("HDRP/Lit")); Color val5 = Color32.op_Implicit(new Color32((byte)249, (byte)240, (byte)202, byte.MaxValue)); val4.SetColor("_BaseColor", val5); float num = 1f; val4.SetColor("_EmissiveColor", val5 * num); ((Renderer)obj).material = val4; Object.DestroyImmediate((Object)(object)val3); Light obj2 = val.AddComponent<Light>(); obj2.type = (LightType)0; obj2.color = val5; obj2.intensity = intensity; obj2.range = 1.05f; obj2.spotAngle = 125f; obj2.shadows = (LightShadows)2; val.layer = LayerMask.NameToLayer("Room"); val.transform.localScale = new Vector3(0.125f, 0.125f, 0.04f); val.transform.localPosition = lightPositionOffset; val.transform.rotation = Quaternion.Euler(170f, 0f, 0f); val.transform.SetParent(storageCloset.transform, false); } private static string padString(string baseStr, char padChar, int width) { int totalWidth = (width - (baseStr.Length + 8)) / 2 + (baseStr.Length + 8); return (" " + baseStr + " ").PadLeft(totalWidth, padChar).PadRight(width, padChar); } private static void obviousDebug(string baseStr) { Debug.Log((object)"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Debug.Log((object)"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Debug.Log((object)"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Debug.Log((object)padString(baseStr ?? "", '~', 65)); Debug.Log((object)"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Debug.Log((object)"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Debug.Log((object)"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } } public static class PluginInfo { public const string PLUGIN_GUID = "com.spycibot.cozyimprovements"; public const string PLUGIN_NAME = "Cozy Improvements"; public const string PLUGIN_VERSION = "1.2.0"; } } namespace SpyciBot.LC.CozyImprovements.Improvements { [HarmonyPatch] public static class Accessibility { private static HangarShipDoor hangarShipDoor; [HarmonyPatch(typeof(StartMatchLever), "Start")] [HarmonyPostfix] private static void Postfix_StartMatchLever_Start(StartMatchLever __instance) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) if (CozyImprovements.CozyConfig.configEasyLaunchLever.Value) { ((Component)__instance).transform.localScale = new Vector3(1.139f, 0.339f, 1.539f); ((Component)__instance).transform.localPosition = new Vector3(8.7938f, 1.479f, -7.0767f); ((Component)__instance).transform.GetChild(0).position = new Vector3(8.8353f, 0.2931f, -14.5767f); } } [HarmonyPatch(typeof(HangarShipDoor), "Start")] [HarmonyPostfix] private static void Postfix_HangarShipDoor_Start(HangarShipDoor __instance) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0107: 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_0150: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) if (!CozyImprovements.CozyConfig.configBigDoorButtons.Value) { return; } hangarShipDoor = __instance; GameObject gameObject = ((Component)__instance.hydraulicsDisplay.transform.parent).gameObject; gameObject.transform.localScale = new Vector3(-2f, -2f, -2f); gameObject.transform.localPosition = new Vector3(-5.2085f, 1.8882f, -8.823f); GameObject gameObject2 = ((Component)gameObject.transform.Find("StartButton")).gameObject; GameObject gameObject3 = ((Component)gameObject.transform.Find("StopButton")).gameObject; gameObject3.transform.localScale = new Vector3(-1.1986f, -0.1986f, -1.1986f); gameObject2.transform.localScale = gameObject3.transform.localScale; gameObject2.transform.GetChild(0).localPosition = gameObject3.transform.GetChild(0).localPosition; gameObject2.transform.GetChild(0).localScale = gameObject3.transform.GetChild(0).localScale; Material[] materials = ((Renderer)gameObject2.GetComponent<MeshRenderer>()).materials; for (int i = 0; i < materials.Length; i++) { if (((Object)materials[i]).name == "GreenButton (Instance)") { materials[i].SetColor("_EmissiveColor", Color32.op_Implicit(new Color32((byte)39, (byte)51, (byte)39, byte.MaxValue))); } if (((Object)materials[i]).name == "ButtonWhite (Instance)") { materials[i].SetColor("_EmissiveColor", Color32.op_Implicit(new Color32((byte)179, (byte)179, (byte)179, byte.MaxValue))); } } ((Renderer)gameObject2.GetComponent<MeshRenderer>()).materials = materials; Material[] materials2 = ((Renderer)gameObject3.GetComponent<MeshRenderer>()).materials; for (int j = 0; j < materials2.Length; j++) { if (((Object)materials2[j]).name == "RedButton (Instance)") { materials2[j].SetColor("_EmissiveColor", Color32.op_Implicit(new Color32((byte)64, (byte)24, (byte)24, byte.MaxValue))); } if (((Object)materials2[j]).name == "ButtonWhite (Instance)") { materials2[j].SetColor("_EmissiveColor", Color32.op_Implicit(new Color32((byte)179, (byte)179, (byte)179, byte.MaxValue))); } } ((Renderer)gameObject3.GetComponent<MeshRenderer>()).materials = materials2; Transform child = gameObject.transform.Find("StartButton").GetChild(0); Transform child2 = gameObject.transform.Find("StopButton").GetChild(0); ((Renderer)((Component)child).GetComponent<MeshRenderer>()).material.color = Color32.op_Implicit(new Color32((byte)39, byte.MaxValue, (byte)39, byte.MaxValue)); ((Renderer)((Component)child2).GetComponent<MeshRenderer>()).material.color = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)24, (byte)24, byte.MaxValue)); Vector3 position = default(Vector3); ((Vector3)(ref position))..ctor(-3.7205f, 2.0504f, -16.3018f); Vector3 localScale = default(Vector3); ((Vector3)(ref localScale))..ctor(0.7393f, 0.4526f, 0.6202f); Vector3 localScale2 = default(Vector3); ((Vector3)(ref localScale2))..ctor(0.003493f, 0.000526f, 0.002202f); child.position = position; child.localScale = localScale; child2.position = position; child2.localScale = localScale2; } [HarmonyPatch(typeof(StartOfRound), "SetShipDoorsClosed")] [HarmonyPostfix] private static void Postfix_StartOfRound_SetShipDoorsClosed(StartOfRound __instance, bool closed) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) if (CozyImprovements.CozyConfig.configBigDoorButtons.Value) { GameObject gameObject = ((Component)hangarShipDoor.hydraulicsDisplay.transform.parent).gameObject; Transform child = gameObject.transform.Find("StartButton").GetChild(0); Transform child2 = gameObject.transform.Find("StopButton").GetChild(0); Vector3 localScale = default(Vector3); ((Vector3)(ref localScale))..ctor(0.7393f, 0.4526f, 0.6202f); Vector3 localScale2 = default(Vector3); ((Vector3)(ref localScale2))..ctor(0.003493f, 0.000526f, 0.002202f); child.localScale = localScale; child2.localScale = localScale; if (closed) { child.localScale = localScale; child2.localScale = localScale2; } else { child2.localScale = localScale; child.localScale = localScale2; } } } [HarmonyPatch(typeof(ShipTeleporter), "Awake")] [HarmonyPostfix] private static void Postfix_ShipTeleporter_Awake(ShipTeleporter __instance) { //IL_0031: 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) if (CozyImprovements.CozyConfig.configBigTeleporterButtons.Value) { ((Component)((Component)__instance.buttonTrigger).gameObject.transform.parent).gameObject.transform.localScale = Vector3.one * 3f; } } public static void adjustMonitorButtons(GameObject ButtonCube) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) if (CozyImprovements.CozyConfig.configBigMonitorButtons.Value) { GameObject gameObject = ((Component)ButtonCube.transform.parent).gameObject; gameObject.transform.localScale = new Vector3(1.852f, 1.8475f, 1.852f); if (((Object)gameObject).name == "CameraMonitorSwitchButton") { gameObject.transform.localPosition = new Vector3(-0.28f, -1.807f, -0.29f); } } } } }
BepInEx/plugins/CompanyExecutive.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Microsoft.CodeAnalysis; using TerminalApi; using TerminalApi.Events; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("SoulWIthMae")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+baa4b8edc3a25a899520149443b1032fbd9a9b6f")] [assembly: AssemblyProduct("CompanyExecutive")] [assembly: AssemblyTitle("CompanyExecutive")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 CompanyExecutive { [BepInPlugin("SoulWithMae.CompanyExecutive", "CompanyExecutive", "3.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public static ConfigEntry<bool> Enabled; public static ConfigEntry<int> MoneyToGive; public static ConfigEntry<bool> ConsistentGive; public static ConfigEntry<bool> OverrideMoney; private readonly Harmony _harmony = new Harmony("CompanyExecutive"); private void Awake() { Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "If the mod is enabled or not"); MoneyToGive = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MoneyToGive", 1000000, "The amount of money to give."); ConsistentGive = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ConsistentGive", true, "Whether to give more money on each day or not."); OverrideMoney = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "OverrideMoney", true, "Whether to override the starting money or just add to it."); _harmony.PatchAll(typeof(TerminalPatch)); TerminalConfig.Init(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin CompanyExecutive is loaded!"); } } [HarmonyPatch(typeof(Terminal))] internal class TerminalPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void Thingy(Terminal __instance, ref int ___groupCredits) { if (!Plugin.Enabled.Value) { return; } if (!Plugin.ConsistentGive.Value) { if (TimeOfDay.Instance.daysUntilDeadline == 3 && TimeOfDay.Instance.profitQuota == 130) { if (Plugin.OverrideMoney.Value) { ___groupCredits = Plugin.MoneyToGive.Value; } else { ___groupCredits += Plugin.MoneyToGive.Value; } } } else if (Plugin.OverrideMoney.Value) { ___groupCredits = Plugin.MoneyToGive.Value; } else { ___groupCredits += Plugin.MoneyToGive.Value; } } } public static class TerminalConfig { [CompilerGenerated] private static class <>O { public static TerminalParseSentenceEventHandler <0>__OnCommandSent; } public static void Init() { //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_005f: Expected O, but got Unknown TerminalApi.AddCommand("executive toggle", "Toggled pref.\n", (string)null, true); TerminalApi.AddCommand("executive consistent", "Toggled pref.\n", (string)null, true); TerminalApi.AddCommand("executive override", "Toggled pref.\n", (string)null, true); TerminalApi.AddCommand("executive give", "Added money to account.\n", (string)null, true); object obj = <>O.<0>__OnCommandSent; if (obj == null) { TerminalParseSentenceEventHandler val = OnCommandSent; <>O.<0>__OnCommandSent = val; obj = (object)val; } Events.TerminalParsedSentence += (TerminalParseSentenceEventHandler)obj; } private static void OnCommandSent(object sender, TerminalParseSentenceEventArgs e) { Terminal val = Object.FindObjectOfType<Terminal>(); if (e.SubmittedText.Contains("executive toggle")) { Plugin.Enabled.Value = !Plugin.Enabled.Value; } if (e.SubmittedText.Contains("executive consistent")) { Plugin.ConsistentGive.Value = !Plugin.ConsistentGive.Value; } if (e.SubmittedText.Contains("executive override")) { Plugin.OverrideMoney.Value = !Plugin.OverrideMoney.Value; } if (e.SubmittedText.Contains("executive give")) { if (Plugin.OverrideMoney.Value) { val.groupCredits = Plugin.MoneyToGive.Value; } else { val.groupCredits += Plugin.MoneyToGive.Value; } } } } public static class PluginInfo { public const string PLUGIN_GUID = "CompanyExecutive"; public const string PLUGIN_NAME = "CompanyExecutive"; public const string PLUGIN_VERSION = "1.0.0"; } }
BepInEx/plugins/Coroner/Coroner.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Xml.Linq; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Coroner.LCAPI; using GameNetcodeStuff; using HarmonyLib; using LC_API.ServerAPI; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("EliteMasterEric")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Rework the Performance Report with new info, including cause of death.")] [assembly: AssemblyFileVersion("1.5.3.0")] [assembly: AssemblyInformationalVersion("1.5.3+3f9dc5379bdbfe1ac1cf1b0df31bb040630db71f")] [assembly: AssemblyProduct("Coroner")] [assembly: AssemblyTitle("Coroner")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.5.3.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 Coroner { public class AdvancedDeathTracker { public const int PLAYER_CAUSE_OF_DEATH_DROPSHIP = 300; private static readonly Dictionary<int, AdvancedCauseOfDeath> PlayerCauseOfDeath = new Dictionary<int, AdvancedCauseOfDeath>(); public static void ClearDeathTracker() { PlayerCauseOfDeath.Clear(); } public static void SetCauseOfDeath(int playerIndex, AdvancedCauseOfDeath causeOfDeath, bool broadcast = true) { PlayerCauseOfDeath[playerIndex] = causeOfDeath; if (broadcast) { DeathBroadcaster.BroadcastCauseOfDeath(playerIndex, causeOfDeath); } } public static void SetCauseOfDeath(int playerIndex, CauseOfDeath causeOfDeath, bool broadcast = true) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) SetCauseOfDeath(playerIndex, ConvertCauseOfDeath(causeOfDeath), broadcast); } public static void SetCauseOfDeath(PlayerControllerB playerController, CauseOfDeath causeOfDeath, bool broadcast = true) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) SetCauseOfDeath((int)playerController.playerClientId, ConvertCauseOfDeath(causeOfDeath), broadcast); } public static void SetCauseOfDeath(PlayerControllerB playerController, AdvancedCauseOfDeath causeOfDeath, bool broadcast = true) { SetCauseOfDeath((int)playerController.playerClientId, causeOfDeath, broadcast); } public static AdvancedCauseOfDeath GetCauseOfDeath(int playerIndex) { PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerIndex]; return GetCauseOfDeath(playerController); } public static AdvancedCauseOfDeath GetCauseOfDeath(PlayerControllerB playerController) { if (!PlayerCauseOfDeath.ContainsKey((int)playerController.playerClientId)) { Plugin.Instance.PluginLogger.LogDebug($"Player {playerController.playerClientId} has no custom cause of death stored! Using fallback..."); return GuessCauseOfDeath(playerController); } Plugin.Instance.PluginLogger.LogDebug($"Player {playerController.playerClientId} has custom cause of death stored! {PlayerCauseOfDeath[(int)playerController.playerClientId]}"); return PlayerCauseOfDeath[(int)playerController.playerClientId]; } public static AdvancedCauseOfDeath GuessCauseOfDeath(PlayerControllerB playerController) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Invalid comparison between Unknown and I4 if (playerController.isPlayerDead) { if (IsHoldingJetpack(playerController)) { if ((int)playerController.causeOfDeath == 2) { return AdvancedCauseOfDeath.Player_Jetpack_Gravity; } if ((int)playerController.causeOfDeath == 3) { return AdvancedCauseOfDeath.Player_Jetpack_Blast; } } return ConvertCauseOfDeath(playerController.causeOfDeath); } return AdvancedCauseOfDeath.Unknown; } public static bool IsHoldingJetpack(PlayerControllerB playerController) { GrabbableObject currentlyHeldObjectServer = playerController.currentlyHeldObjectServer; if ((Object)(object)currentlyHeldObjectServer == (Object)null) { return false; } GameObject gameObject = ((Component)currentlyHeldObjectServer).gameObject; if ((Object)(object)gameObject == (Object)null) { return false; } GrabbableObject component = gameObject.GetComponent<GrabbableObject>(); if ((Object)(object)component == (Object)null) { return false; } if (component is JetpackItem) { return true; } return false; } public static AdvancedCauseOfDeath ConvertCauseOfDeath(CauseOfDeath causeOfDeath) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0004: 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_003b: Expected I4, but got Unknown return (int)causeOfDeath switch { 0 => AdvancedCauseOfDeath.Unknown, 1 => AdvancedCauseOfDeath.Bludgeoning, 2 => AdvancedCauseOfDeath.Gravity, 3 => AdvancedCauseOfDeath.Blast, 4 => AdvancedCauseOfDeath.Strangulation, 5 => AdvancedCauseOfDeath.Suffocation, 6 => AdvancedCauseOfDeath.Mauling, 7 => AdvancedCauseOfDeath.Gunshots, 8 => AdvancedCauseOfDeath.Crushing, 9 => AdvancedCauseOfDeath.Drowning, 10 => AdvancedCauseOfDeath.Abandoned, 11 => AdvancedCauseOfDeath.Electrocution, _ => AdvancedCauseOfDeath.Unknown, }; } public static string StringifyCauseOfDeath(CauseOfDeath causeOfDeath) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return StringifyCauseOfDeath(ConvertCauseOfDeath(causeOfDeath), Plugin.RANDOM); } public static string StringifyCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath) { return StringifyCauseOfDeath(causeOfDeath, Plugin.RANDOM); } public static string StringifyCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath, Random random) { string[] array = SelectCauseOfDeath(causeOfDeath); if (array.Length > 1 && (!causeOfDeath.HasValue || !Plugin.Instance.PluginConfig.ShouldUseSeriousDeathMessages())) { return array[random.Next(array.Length)]; } return array[0]; } public static string[] SelectCauseOfDeath(AdvancedCauseOfDeath? causeOfDeath) { if (!causeOfDeath.HasValue) { return LanguageHandler.GetValuesByTag("FunnyNote"); } return causeOfDeath switch { AdvancedCauseOfDeath.Bludgeoning => LanguageHandler.GetValuesByTag("DeathBludgeoning"), AdvancedCauseOfDeath.Gravity => LanguageHandler.GetValuesByTag("DeathGravity"), AdvancedCauseOfDeath.Blast => LanguageHandler.GetValuesByTag("DeathBlast"), AdvancedCauseOfDeath.Strangulation => LanguageHandler.GetValuesByTag("DeathStrangulation"), AdvancedCauseOfDeath.Suffocation => LanguageHandler.GetValuesByTag("DeathSuffocation"), AdvancedCauseOfDeath.Mauling => LanguageHandler.GetValuesByTag("DeathMauling"), AdvancedCauseOfDeath.Gunshots => LanguageHandler.GetValuesByTag("DeathGunshots"), AdvancedCauseOfDeath.Crushing => LanguageHandler.GetValuesByTag("DeathCrushing"), AdvancedCauseOfDeath.Drowning => LanguageHandler.GetValuesByTag("DeathDrowning"), AdvancedCauseOfDeath.Abandoned => LanguageHandler.GetValuesByTag("DeathAbandoned"), AdvancedCauseOfDeath.Electrocution => LanguageHandler.GetValuesByTag("DeathElectrocution"), AdvancedCauseOfDeath.Kicking => LanguageHandler.GetValuesByTag("DeathKicking"), AdvancedCauseOfDeath.Enemy_Bracken => LanguageHandler.GetValuesByTag("DeathEnemyBracken"), AdvancedCauseOfDeath.Enemy_EyelessDog => LanguageHandler.GetValuesByTag("DeathEnemyEyelessDog"), AdvancedCauseOfDeath.Enemy_ForestGiant => LanguageHandler.GetValuesByTag("DeathEnemyForestGiant"), AdvancedCauseOfDeath.Enemy_CircuitBees => LanguageHandler.GetValuesByTag("DeathEnemyCircuitBees"), AdvancedCauseOfDeath.Enemy_GhostGirl => LanguageHandler.GetValuesByTag("DeathEnemyGhostGirl"), AdvancedCauseOfDeath.Enemy_EarthLeviathan => LanguageHandler.GetValuesByTag("DeathEnemyEarthLeviathan"), AdvancedCauseOfDeath.Enemy_BaboonHawk => LanguageHandler.GetValuesByTag("DeathEnemyBaboonHawk"), AdvancedCauseOfDeath.Enemy_Jester => LanguageHandler.GetValuesByTag("DeathEnemyJester"), AdvancedCauseOfDeath.Enemy_CoilHead => LanguageHandler.GetValuesByTag("DeathEnemyCoilHead"), AdvancedCauseOfDeath.Enemy_SnareFlea => LanguageHandler.GetValuesByTag("DeathEnemySnareFlea"), AdvancedCauseOfDeath.Enemy_Hygrodere => LanguageHandler.GetValuesByTag("DeathEnemyHygrodere"), AdvancedCauseOfDeath.Enemy_HoarderBug => LanguageHandler.GetValuesByTag("DeathEnemyHoarderBug"), AdvancedCauseOfDeath.Enemy_SporeLizard => LanguageHandler.GetValuesByTag("DeathEnemySporeLizard"), AdvancedCauseOfDeath.Enemy_BunkerSpider => LanguageHandler.GetValuesByTag("DeathEnemyBunkerSpider"), AdvancedCauseOfDeath.Enemy_Thumper => LanguageHandler.GetValuesByTag("DeathEnemyThumper"), AdvancedCauseOfDeath.Enemy_MaskedPlayer_Wear => LanguageHandler.GetValuesByTag("DeathEnemyMaskedPlayerWear"), AdvancedCauseOfDeath.Enemy_MaskedPlayer_Victim => LanguageHandler.GetValuesByTag("DeathEnemyMaskedPlayerVictim"), AdvancedCauseOfDeath.Enemy_Nutcracker_Kicked => LanguageHandler.GetValuesByTag("DeathEnemyNutcrackerKicked"), AdvancedCauseOfDeath.Enemy_Nutcracker_Shot => LanguageHandler.GetValuesByTag("DeathEnemyNutcrackerShot"), AdvancedCauseOfDeath.Player_Jetpack_Gravity => LanguageHandler.GetValuesByTag("DeathPlayerJetpackGravity"), AdvancedCauseOfDeath.Player_Jetpack_Blast => LanguageHandler.GetValuesByTag("DeathPlayerJetpackBlast"), AdvancedCauseOfDeath.Player_Murder_Melee => LanguageHandler.GetValuesByTag("DeathPlayerMurderMelee"), AdvancedCauseOfDeath.Player_Murder_Shotgun => LanguageHandler.GetValuesByTag("DeathPlayerMurderShotgun"), AdvancedCauseOfDeath.Player_Quicksand => LanguageHandler.GetValuesByTag("DeathPlayerQuicksand"), AdvancedCauseOfDeath.Player_StunGrenade => LanguageHandler.GetValuesByTag("DeathPlayerStunGrenade"), AdvancedCauseOfDeath.Other_DepositItemsDesk => LanguageHandler.GetValuesByTag("DeathOtherDepositItemsDesk"), AdvancedCauseOfDeath.Other_Dropship => LanguageHandler.GetValuesByTag("DeathOtherItemDropship"), AdvancedCauseOfDeath.Other_Landmine => LanguageHandler.GetValuesByTag("DeathOtherLandmine"), AdvancedCauseOfDeath.Other_Turret => LanguageHandler.GetValuesByTag("DeathOtherTurret"), AdvancedCauseOfDeath.Other_Lightning => LanguageHandler.GetValuesByTag("DeathOtherLightning"), _ => LanguageHandler.GetValuesByTag("DeathUnknown"), }; } internal static void SetCauseOfDeath(PlayerControllerB playerControllerB, object enemy_BaboonHawk) { throw new NotImplementedException(); } } public enum AdvancedCauseOfDeath { Unknown, Bludgeoning, Gravity, Blast, Strangulation, Suffocation, Mauling, Gunshots, Crushing, Drowning, Abandoned, Electrocution, Kicking, Enemy_BaboonHawk, Enemy_Bracken, Enemy_CircuitBees, Enemy_CoilHead, Enemy_EarthLeviathan, Enemy_EyelessDog, Enemy_ForestGiant, Enemy_GhostGirl, Enemy_Hygrodere, Enemy_Jester, Enemy_SnareFlea, Enemy_SporeLizard, Enemy_HoarderBug, Enemy_Thumper, Enemy_BunkerSpider, Enemy_MaskedPlayer_Wear, Enemy_MaskedPlayer_Victim, Enemy_Nutcracker_Kicked, Enemy_Nutcracker_Shot, Player_Jetpack_Gravity, Player_Jetpack_Blast, Player_Quicksand, Player_Murder_Melee, Player_Murder_Shotgun, Player_StunGrenade, Other_Landmine, Other_Turret, Other_Lightning, Other_DepositItemsDesk, Other_Dropship } internal class DeathBroadcaster { private const string SIGNATURE_DEATH = "com.elitemastereric.coroner.death"; public static void Initialize() { if (Plugin.Instance.IsLCAPIPresent) { DeathBroadcasterLCAPI.Initialize(); } else { Plugin.Instance.PluginLogger.LogInfo("LC_API is not present! Skipping registration..."); } } public static void BroadcastCauseOfDeath(int playerId, AdvancedCauseOfDeath causeOfDeath) { AttemptBroadcast(BuildDataCauseOfDeath(playerId, causeOfDeath), "com.elitemastereric.coroner.death"); } private static string BuildDataCauseOfDeath(int playerId, AdvancedCauseOfDeath causeOfDeath) { string text = playerId.ToString(); int num = (int)causeOfDeath; return text + "|" + num; } private static void AttemptBroadcast(string data, string signature) { if (Plugin.Instance.IsLCAPIPresent) { DeathBroadcasterLCAPI.AttemptBroadcast(data, signature); } else { Plugin.Instance.PluginLogger.LogInfo("LC_API is not present! Skipping broadcast..."); } } } internal class LanguageHandler { public const string DEFAULT_LANGUAGE = "en"; public static readonly string[] AVAILABLE_LANGUAGES = new string[4] { "en", "ru", "nl", "fr" }; public const string TAG_FUNNY_NOTES = "FunnyNote"; public const string TAG_UI_NOTES = "UINotes"; public const string TAG_UI_DEATH = "UICauseOfDeath"; public const string TAG_DEATH_GENERIC_BLUDGEONING = "DeathBludgeoning"; public const string TAG_DEATH_GENERIC_GRAVITY = "DeathGravity"; public const string TAG_DEATH_GENERIC_BLAST = "DeathBlast"; public const string TAG_DEATH_GENERIC_STRANGULATION = "DeathStrangulation"; public const string TAG_DEATH_GENERIC_SUFFOCATION = "DeathSuffocation"; public const string TAG_DEATH_GENERIC_MAULING = "DeathMauling"; public const string TAG_DEATH_GENERIC_GUNSHOTS = "DeathGunshots"; public const string TAG_DEATH_GENERIC_CRUSHING = "DeathCrushing"; public const string TAG_DEATH_GENERIC_DROWNING = "DeathDrowning"; public const string TAG_DEATH_GENERIC_ABANDONED = "DeathAbandoned"; public const string TAG_DEATH_GENERIC_ELECTROCUTION = "DeathElectrocution"; public const string TAG_DEATH_GENERIC_KICKING = "DeathKicking"; public const string TAG_DEATH_ENEMY_BRACKEN = "DeathEnemyBracken"; public const string TAG_DEATH_ENEMY_EYELESS_DOG = "DeathEnemyEyelessDog"; public const string TAG_DEATH_ENEMY_FOREST_GIANT = "DeathEnemyForestGiant"; public const string TAG_DEATH_ENEMY_CIRCUIT_BEES = "DeathEnemyCircuitBees"; public const string TAG_DEATH_ENEMY_GHOST_GIRL = "DeathEnemyGhostGirl"; public const string TAG_DEATH_ENEMY_EARTH_LEVIATHAN = "DeathEnemyEarthLeviathan"; public const string TAG_DEATH_ENEMY_BABOON_HAWK = "DeathEnemyBaboonHawk"; public const string TAG_DEATH_ENEMY_JESTER = "DeathEnemyJester"; public const string TAG_DEATH_ENEMY_COILHEAD = "DeathEnemyCoilHead"; public const string TAG_DEATH_ENEMY_SNARE_FLEA = "DeathEnemySnareFlea"; public const string TAG_DEATH_ENEMY_HYGRODERE = "DeathEnemyHygrodere"; public const string TAG_DEATH_ENEMY_HOARDER_BUG = "DeathEnemyHoarderBug"; public const string TAG_DEATH_ENEMY_SPORE_LIZARD = "DeathEnemySporeLizard"; public const string TAG_DEATH_ENEMY_BUNKER_SPIDER = "DeathEnemyBunkerSpider"; public const string TAG_DEATH_ENEMY_THUMPER = "DeathEnemyThumper"; public const string TAG_DEATH_ENEMY_MASKED_PLAYER_WEAR = "DeathEnemyMaskedPlayerWear"; public const string TAG_DEATH_ENEMY_MASKED_PLAYER_VICTIM = "DeathEnemyMaskedPlayerVictim"; public const string TAG_DEATH_ENEMY_NUTCRACKER_KICKED = "DeathEnemyNutcrackerKicked"; public const string TAG_DEATH_ENEMY_NUTCRACKER_SHOT = "DeathEnemyNutcrackerShot"; public const string TAG_DEATH_PLAYER_JETPACK_GRAVITY = "DeathPlayerJetpackGravity"; public const string TAG_DEATH_PLAYER_JETPACK_BLAST = "DeathPlayerJetpackBlast"; public const string TAG_DEATH_PLAYER_MURDER_MELEE = "DeathPlayerMurderMelee"; public const string TAG_DEATH_PLAYER_MURDER_SHOTGUN = "DeathPlayerMurderShotgun"; public const string TAG_DEATH_PLAYER_QUICKSAND = "DeathPlayerQuicksand"; public const string TAG_DEATH_PLAYER_STUN_GRENADE = "DeathPlayerStunGrenade"; public const string TAG_DEATH_OTHER_DEPOSIT_ITEMS_DESK = "DeathOtherDepositItemsDesk"; public const string TAG_DEATH_OTHER_ITEM_DROPSHIP = "DeathOtherItemDropship"; public const string TAG_DEATH_OTHER_LANDMINE = "DeathOtherLandmine"; public const string TAG_DEATH_OTHER_TURRET = "DeathOtherTurret"; public const string TAG_DEATH_OTHER_LIGHTNING = "DeathOtherLightning"; public const string TAG_DEATH_UNKNOWN = "DeathUnknown"; private static XDocument languageData; public static void Initialize() { Plugin.Instance.PluginLogger.LogInfo("Coroner Language Support: " + Plugin.Instance.PluginConfig.GetSelectedLanguage()); ValidateLanguage(Plugin.Instance.PluginConfig.GetSelectedLanguage()); LoadLanguageData(Plugin.Instance.PluginConfig.GetSelectedLanguage()); } private static void ValidateLanguage(string languageCode) { if (!AVAILABLE_LANGUAGES.Contains(languageCode)) { Plugin.Instance.PluginLogger.LogWarning("Coroner Unknown language code: " + languageCode); Plugin.Instance.PluginLogger.LogWarning("Coroner There may be issues loading language data."); } } private static void LoadLanguageData(string languageCode) { try { languageData = XDocument.Load(Plugin.AssemblyDirectory + "/Strings_" + languageCode + ".xml"); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Coroner Error loading language data: " + ex.Message); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); if (languageCode != "en") { LoadLanguageData("en"); } } } public static string GetLanguageList() { return "(" + string.Join(", ", AVAILABLE_LANGUAGES) + ")"; } public static string GetValueByTag(string tag) { return languageData.Descendants(tag).FirstOrDefault()?.Attribute("text")?.Value; } public static string[] GetValuesByTag(string tag) { IEnumerable<XElement> source = languageData.Descendants(tag); IEnumerable<string> source2 = source.Select((XElement item) => item.Attribute("text")?.Value); IEnumerable<string> source3 = source2.Where((string item) => item != null); return source3.ToArray(); } } public static class PluginInfo { public const string PLUGIN_ID = "Coroner"; public const string PLUGIN_NAME = "Coroner"; public const string PLUGIN_AUTHOR = "EliteMasterEric"; public const string PLUGIN_VERSION = "1.5.3"; public const string PLUGIN_GUID = "com.elitemastereric.coroner"; } [BepInPlugin("com.elitemastereric.coroner", "Coroner", "1.5.3")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public static readonly Random RANDOM = new Random(); public PluginLogger PluginLogger; public PluginConfig PluginConfig; public bool IsLCAPIPresent = false; public static Plugin Instance { get; private set; } public static string AssemblyDirectory { get { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uriBuilder = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uriBuilder.Path); return Path.GetDirectoryName(path); } } private void Awake() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown Instance = this; PluginLogger = new PluginLogger(((BaseUnityPlugin)this).Logger, (LogLevel)16); Harmony val = new Harmony("com.elitemastereric.coroner"); val.PatchAll(); PluginLogger.LogInfo("Plugin Coroner (com.elitemastereric.coroner) is loaded!"); LoadConfig(); LanguageHandler.Initialize(); QueryLCAPI(); DeathBroadcaster.Initialize(); } private void QueryLCAPI() { PluginLogger.LogInfo("Checking for LC_API..."); if (Chainloader.PluginInfos.ContainsKey("LC_API")) { Chainloader.PluginInfos.TryGetValue("LC_API", out var value); if (value == null) { PluginLogger.LogError("Detected LC_API, but could not get plugin info!"); IsLCAPIPresent = false; } else { PluginLogger.LogInfo("LCAPI is present! " + value.Metadata.GUID + ":" + value.Metadata.Version); IsLCAPIPresent = true; } } else { PluginLogger.LogInfo("LCAPI is not present."); IsLCAPIPresent = false; } } private void LoadConfig() { PluginConfig = new PluginConfig(); PluginConfig.BindConfig(((BaseUnityPlugin)this).Config); } } public class PluginLogger { private ManualLogSource manualLogSource; private LogLevel logLevel; public PluginLogger(ManualLogSource manualLogSource, LogLevel logLevel = 16) { //IL_0010: 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) this.manualLogSource = manualLogSource; this.logLevel = logLevel; } public void LogFatal(object data) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)logLevel >= 1) { manualLogSource.LogFatal(data); } } public void LogError(object data) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)logLevel >= 2) { manualLogSource.LogError(data); } } public void LogWarning(object data) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)logLevel >= 4) { manualLogSource.LogWarning(data); } } public void LogMessage(object data) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)logLevel >= 8) { manualLogSource.LogMessage(data); } } public void LogInfo(object data) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 if ((int)logLevel >= 16) { manualLogSource.LogInfo(data); } } public void LogDebug(object data) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 if ((int)logLevel >= 32) { manualLogSource.LogDebug(data); } } } public class PluginConfig { private ConfigEntry<bool> DisplayCauseOfDeath; private ConfigEntry<bool> SeriousDeathMessages; private ConfigEntry<bool> DisplayFunnyNotes; private ConfigEntry<bool> DeathReplacesNotes; private ConfigEntry<string> LanguagePicker; public void BindConfig(ConfigFile _config) { DisplayCauseOfDeath = _config.Bind<bool>("General", "DisplayCauseOfDeath", true, "Display the cause of death in the player notes."); SeriousDeathMessages = _config.Bind<bool>("General", "SeriousDeathMessages", false, "Cause of death messages are more to-the-point."); DisplayFunnyNotes = _config.Bind<bool>("General", "DisplayFunnyNotes", true, "Display a random note when the player has no notes."); DeathReplacesNotes = _config.Bind<bool>("General", "DeathReplacesNotes", true, "True to replace notes when the player dies, false to append."); LanguagePicker = _config.Bind<string>("Language", "LanguagePicker", "en", "Select a language to use " + LanguageHandler.GetLanguageList()); } public bool ShouldDisplayCauseOfDeath() { return DisplayCauseOfDeath.Value; } public bool ShouldUseSeriousDeathMessages() { return SeriousDeathMessages.Value; } public bool ShouldDisplayFunnyNotes() { return DisplayFunnyNotes.Value; } public bool ShouldDeathReplaceNotes() { return DeathReplacesNotes.Value; } public string GetSelectedLanguage() { return LanguagePicker.Value; } } } namespace Coroner.Patch { [HarmonyPatch(typeof(PlayerControllerB))] [HarmonyPatch("KillPlayer")] internal class PlayerControllerBKillPlayerPatch { public static void Prefix(PlayerControllerB __instance, ref CauseOfDeath causeOfDeath) { try { if ((int)causeOfDeath == 300) { Plugin.Instance.PluginLogger.LogDebug("Player died from item dropship! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Other_Dropship); causeOfDeath = (CauseOfDeath)8; } else if (__instance.isSinking && (int)causeOfDeath == 5) { Plugin.Instance.PluginLogger.LogDebug("Player died of suffociation while sinking in quicksand! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Quicksand); } else if ((int)causeOfDeath != 3) { Plugin.Instance.PluginLogger.LogDebug("Player is dying! No cause of death registered in hook..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in PlayerControllerBKillPlayerPatch.Prefix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(DepositItemsDesk))] [HarmonyPatch("AnimationGrabPlayer")] internal class DepositItemsDeskAnimationGrabPlayerPatch { public static void Postfix(int playerID) { try { Plugin.Instance.PluginLogger.LogDebug("Accessing state after tentacle devouring..."); PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerID]; Plugin.Instance.PluginLogger.LogDebug("Player is dying! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(playerController, AdvancedCauseOfDeath.Other_DepositItemsDesk); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in DepositItemsDeskAnimationGrabPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(JesterAI))] [HarmonyPatch("killPlayerAnimation")] internal class JesterAIKillPlayerAnimationPatch { public static void Postfix(int playerId) { try { Plugin.Instance.PluginLogger.LogDebug("Accessing state after Jester mauling..."); PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId]; if ((Object)(object)val == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); return; } Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_Jester); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in JesterAIKillPlayerAnimationPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(SandWormAI))] [HarmonyPatch("EatPlayer")] internal class SandWormAIEatPlayerPatch { public static void Postfix(PlayerControllerB playerScript) { try { Plugin.Instance.PluginLogger.LogDebug("Accessing state after Sand Worm devouring..."); if ((Object)(object)playerScript == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); return; } Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(playerScript, AdvancedCauseOfDeath.Enemy_EarthLeviathan); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in SandWormAIEatPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(RedLocustBees))] [HarmonyPatch("BeeKillPlayerOnLocalClient")] internal class RedLocustBeesBeeKillPlayerOnLocalClientPatch { public static void Postfix(int playerId) { try { Plugin.Instance.PluginLogger.LogDebug("Accessing state after Circuit Bee electrocution..."); PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId]; if ((Object)(object)val == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (val.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_CircuitBees); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in RedLocustBeesBeeKillPlayerOnLocalClientPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(DressGirlAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class DressGirlAIOnCollideWithPlayerPatch { public static void Postfix(DressGirlAI __instance) { try { Plugin.Instance.PluginLogger.LogDebug("Processing Ghost Girl player collision..."); if ((Object)(object)__instance.hauntingPlayer == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after collision!"); } else if (__instance.hauntingPlayer.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(__instance.hauntingPlayer, AdvancedCauseOfDeath.Enemy_GhostGirl); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in DressGirlAIOnCollideWithPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(FlowermanAI))] [HarmonyPatch("killAnimation")] internal class FlowermanAIKillAnimationPatch { public static void Postfix(FlowermanAI __instance) { try { Plugin.Instance.PluginLogger.LogDebug("Accessing state after Bracken snapping neck..."); if ((Object)(object)((EnemyAI)__instance).inSpecialAnimationWithPlayer == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after snapping neck!"); return; } Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(((EnemyAI)__instance).inSpecialAnimationWithPlayer, AdvancedCauseOfDeath.Enemy_Bracken); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in FlowermanAIKillAnimationPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(ForestGiantAI))] [HarmonyPatch("EatPlayerAnimation")] internal class ForestGiantAIEatPlayerAnimationPatch { public static void Postfix(PlayerControllerB playerBeingEaten) { try { Plugin.Instance.PluginLogger.LogDebug("Accessing state after Forest Giant devouring..."); if ((Object)(object)playerBeingEaten == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); return; } Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(playerBeingEaten, AdvancedCauseOfDeath.Enemy_ForestGiant); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in ForestGiantAIEatPlayerAnimationPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(MouthDogAI))] [HarmonyPatch("KillPlayer")] internal class MouthDogAIKillPlayerPatch { public static void Postfix(int playerId) { try { Plugin.Instance.PluginLogger.LogDebug("Accessing state after dog devouring..."); PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerId]; if ((Object)(object)val == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); return; } Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_EyelessDog); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in MouthDogAIKillPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(CentipedeAI))] [HarmonyPatch("DamagePlayerOnIntervals")] internal class CentipedeAIDamagePlayerOnIntervalsPatch { public static void Postfix(CentipedeAI __instance) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Invalid comparison between Unknown and I4 try { Plugin.Instance.PluginLogger.LogDebug("Handling Snare Flea damage..."); if ((Object)(object)__instance.clingingToPlayer == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player being clung to!"); } else if (__instance.clingingToPlayer.isPlayerDead && (int)__instance.clingingToPlayer.causeOfDeath == 5) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(__instance.clingingToPlayer, AdvancedCauseOfDeath.Enemy_SnareFlea); } else if (__instance.clingingToPlayer.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player somehow died while attacked by Snare Flea! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in CentipedeAIDamagePlayerOnIntervalsPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(BaboonBirdAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class BaboonBirdAIOnCollideWithPlayerPatch { public static void Postfix(Collider other) { try { Plugin.Instance.PluginLogger.LogDebug("Handling Baboon Hawk damage..."); PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (component.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_BaboonHawk); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in BaboonBirdAIOnCollideWithPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(PlayerControllerB))] [HarmonyPatch("DamagePlayerFromOtherClientClientRpc")] internal class PlayerControllerBDamagePlayerFromOtherClientClientRpcPatch { public static void Postfix(PlayerControllerB __instance) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Invalid comparison between Unknown and I4 //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Invalid comparison between Unknown and I4 //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Invalid comparison between Unknown and I4 try { Plugin.Instance.PluginLogger.LogDebug("Handling friendly fire damage..."); if ((Object)(object)__instance == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access victim after death!"); } else if (__instance.isPlayerDead) { if ((int)__instance.causeOfDeath == 1) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Melee); } else if ((int)__instance.causeOfDeath == 6) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Melee); } else if ((int)__instance.causeOfDeath == 7) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(__instance, AdvancedCauseOfDeath.Player_Murder_Shotgun); } else { Plugin.Instance.PluginLogger.LogWarning("Player was killed by someone else but we don't know how! " + ((object)(CauseOfDeath)(ref __instance.causeOfDeath)).ToString()); } } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in PlayerControllerBDamagePlayerFromOtherClientClientRpcPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(PufferAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class PufferAIOnCollideWithPlayerPatch { public static void Postfix(Collider other) { try { Plugin.Instance.PluginLogger.LogDebug("Handling Spore Lizard damage..."); PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (component.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_SporeLizard); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in PufferAIOnCollideWithPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(SpringManAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class SpringManAIOnCollideWithPlayerPatch { public static void Postfix(Collider other) { try { Plugin.Instance.PluginLogger.LogDebug("Handling Coil Head damage..."); PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (component.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_CoilHead); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in SpringManAIOnCollideWithPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(BlobAI))] [HarmonyPatch("SlimeKillPlayerEffectServerRpc")] internal class BlobAISlimeKillPlayerEffectServerRpcPatch { public static void Postfix(int playerKilled) { try { PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerKilled]; if ((Object)(object)val == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (val.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(val, AdvancedCauseOfDeath.Enemy_Hygrodere); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in BlobAISlimeKillPlayerEffectServerRpcPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(HoarderBugAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class HoarderBugAIOnCollideWithPlayerPatch { public static void Postfix(Collider other) { try { Plugin.Instance.PluginLogger.LogDebug("Handling Hoarder Bug damage..."); PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (component.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_HoarderBug); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in HoarderBugAIOnCollideWithPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(CrawlerAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class CrawlerAIOnCollideWithPlayerPatch { public static void Postfix(Collider other) { try { Plugin.Instance.PluginLogger.LogDebug("Handling Thumper damage..."); PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (component.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_Thumper); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in CrawlerAIOnCollideWithPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(SandSpiderAI))] [HarmonyPatch("OnCollideWithPlayer")] internal class SandSpiderAIOnCollideWithPlayerPatch { public static void Postfix(Collider other) { try { Plugin.Instance.PluginLogger.LogDebug("Handling Bunker Spider damage..."); PlayerControllerB component = ((Component)other).gameObject.GetComponent<PlayerControllerB>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (component.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(component, AdvancedCauseOfDeath.Enemy_BunkerSpider); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in SandSpiderAIOnCollideWithPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(NutcrackerEnemyAI))] [HarmonyPatch("LegKickPlayer")] internal class NutcrackerEnemyAILegKickPlayerPatch { public static void Postfix(int playerId) { try { Plugin.Instance.PluginLogger.LogDebug("Nutcracker kicked a player to death!"); PlayerControllerB playerController = StartOfRound.Instance.allPlayerScripts[playerId]; Plugin.Instance.PluginLogger.LogDebug("Player is dying! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(playerController, AdvancedCauseOfDeath.Enemy_Nutcracker_Kicked); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in NutcrackerEnemyAILegKickPlayerPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(ShotgunItem))] [HarmonyPatch("ShootGun")] internal class ShotgunItemShootGunPatch { public static void Postfix(ShotgunItem __instance) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Invalid comparison between Unknown and I4 try { Plugin.Instance.PluginLogger.LogDebug("Handling shotgun shot..."); PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if ((Object)(object)localPlayerController == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access local player after shotgun shot!"); } else if (localPlayerController.isPlayerDead && (int)localPlayerController.causeOfDeath == 7) { if (((GrabbableObject)__instance).isHeldByEnemy) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Enemy_Nutcracker_Shot); } else { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Player_Murder_Shotgun); } } else if (localPlayerController.isPlayerDead) { Plugin.Instance.PluginLogger.LogWarning("Player died while attacked by shotgun? Skipping... " + ((object)(CauseOfDeath)(ref localPlayerController.causeOfDeath)).ToString()); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in ShotgunItemShootGunPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(MaskedPlayerEnemy))] [HarmonyPatch("killAnimation")] internal class MaskedPlayerEnemykillAnimationPatch { public static void Postfix(MaskedPlayerEnemy __instance) { try { Plugin.Instance.PluginLogger.LogDebug("Masked Player killed someone..."); PlayerControllerB inSpecialAnimationWithPlayer = ((EnemyAI)__instance).inSpecialAnimationWithPlayer; if ((Object)(object)inSpecialAnimationWithPlayer == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); return; } Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(inSpecialAnimationWithPlayer, AdvancedCauseOfDeath.Enemy_MaskedPlayer_Victim); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in MaskedPlayerEnemykillAnimationPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(HauntedMaskItem))] [HarmonyPatch("FinishAttaching")] internal class HauntedMaskItemFinishAttachingPatch { public static void Postfix(HauntedMaskItem __instance) { try { Plugin.Instance.PluginLogger.LogDebug("Masked Player killed someone..."); PlayerControllerB value = Traverse.Create((object)__instance).Field("previousPlayerHeldBy").GetValue<PlayerControllerB>(); if ((Object)(object)value == (Object)null) { Plugin.Instance.PluginLogger.LogWarning("Could not access player after death!"); } else if (value.isPlayerDead) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(value, AdvancedCauseOfDeath.Enemy_MaskedPlayer_Wear); } else { Plugin.Instance.PluginLogger.LogDebug("Player is somehow still alive! Skipping..."); } } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in HauntedMaskItemFinishAttachingPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(ExtensionLadderItem))] [HarmonyPatch("StartLadderAnimation")] internal class ExtensionLadderItemStartLadderAnimationPatch { public static void Postfix(ExtensionLadderItem __instance) { //IL_00cf: Unknown result type (might be due to invalid IL or missing references) try { Plugin.Instance.PluginLogger.LogDebug("Extension ladder started animation! Modifying kill trigger..."); GameObject gameObject = ((Component)__instance).gameObject; if ((Object)(object)gameObject == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch GameObject from ExtensionLadderItem."); } Transform val = gameObject.transform.Find("AnimContainer/MeshContainer/LadderMeshContainer/BaseLadder/LadderSecondPart/KillTrigger"); if ((Object)(object)val == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger Transform from ExtensionLadderItem."); } GameObject gameObject2 = ((Component)val).gameObject; if ((Object)(object)gameObject2 == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger GameObject from ExtensionLadderItem."); } KillLocalPlayer component = gameObject2.GetComponent<KillLocalPlayer>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch KillLocalPlayer from KillTrigger GameObject."); } component.causeOfDeath = (CauseOfDeath)8; } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in ExtensionLadderItemStartLadderAnimationPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(ItemDropship))] [HarmonyPatch("Start")] internal class ItemDropshipStartPatch { public static void Postfix(ItemDropship __instance) { //IL_00d3: Unknown result type (might be due to invalid IL or missing references) try { Plugin.Instance.PluginLogger.LogDebug("Item dropship spawned! Modifying kill trigger..."); GameObject gameObject = ((Component)__instance).gameObject; if ((Object)(object)gameObject == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch GameObject from ItemDropship."); } Transform val = gameObject.transform.Find("ItemShip/KillTrigger"); if ((Object)(object)val == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger Transform from ItemDropship."); } GameObject gameObject2 = ((Component)val).gameObject; if ((Object)(object)gameObject2 == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch KillTrigger GameObject from ItemDropship."); } KillLocalPlayer component = gameObject2.GetComponent<KillLocalPlayer>(); if ((Object)(object)component == (Object)null) { Plugin.Instance.PluginLogger.LogError("Could not fetch KillLocalPlayer from KillTrigger GameObject."); } component.causeOfDeath = (CauseOfDeath)300; } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in ItemDropshipStartPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } } [HarmonyPatch(typeof(Turret))] [HarmonyPatch("Update")] public class TurretUpdatePatch { public static void Postfix(Turret __instance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 if ((int)__instance.turretMode == 2) { PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if (localPlayerController.isPlayerDead && (int)localPlayerController.causeOfDeath == 7) { Plugin.Instance.PluginLogger.LogDebug("Player is now dead! Setting special cause of death..."); AdvancedDeathTracker.SetCauseOfDeath(localPlayerController, AdvancedCauseOfDeath.Other_Turret); } } } } [HarmonyPatch(typeof(Landmine))] [HarmonyPatch("SpawnExplosion")] public class LandmineSpawnExplosionPatch { private const string KILL_PLAYER_SIGNATURE = "Void KillPlayer(UnityEngine.Vector3, Boolean, CauseOfDeath, Int32)"; private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase method) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); List<CodeInstruction> list2 = BuildInstructionsToInsert(method); if (list2 == null) { Plugin.Instance.PluginLogger.LogError("Could not build instructions to insert in LandmineSpawnExplosionPatch! Safely aborting..."); return instructions; } int num = -1; for (int i = 0; i < list.Count; i++) { CodeInstruction val = list[i]; if (val.opcode == OpCodes.Callvirt && val.operand.ToString() == "Void KillPlayer(UnityEngine.Vector3, Boolean, CauseOfDeath, Int32)") { num = i; break; } } if (num == -1) { Plugin.Instance.PluginLogger.LogError("Could not find PlayerControllerB.KillPlayer call in LandmineSpawnExplosionPatch! Safely aborting..."); return instructions; } Plugin.Instance.PluginLogger.LogInfo("Injecting patch into Landmine.SpawnExplosion..."); list.InsertRange(num, list2); Plugin.Instance.PluginLogger.LogInfo("Done."); return list; } private static List<CodeInstruction> BuildInstructionsToInsert(MethodBase method) { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown List<CodeInstruction> list = new List<CodeInstruction>(); int num = 2; IList<LocalVariableInfo> localVariables = method.GetMethodBody().LocalVariables; LocalVariableInfo localVariableInfo = null; for (int i = 0; i < localVariables.Count; i++) { LocalVariableInfo localVariableInfo2 = localVariables[i]; if (localVariableInfo2.LocalType == typeof(PlayerControllerB)) { if (localVariableInfo != null) { Plugin.Instance.PluginLogger.LogError("Found multiple PlayerControllerB local variables in LandmineSpawnExplosionPatch!"); return null; } localVariableInfo = localVariableInfo2; break; } } list.Add(new CodeInstruction(OpCodes.Ldloc_S, (object)localVariableInfo.LocalIndex)); list.Add(new CodeInstruction(OpCodes.Ldarg, (object)num)); list.Add(new CodeInstruction(OpCodes.Call, (object)typeof(LandmineSpawnExplosionPatch).GetMethod("RewriteCauseOfDeath"))); return list; } public static void RewriteCauseOfDeath(PlayerControllerB targetPlayer, float killRange) { AdvancedCauseOfDeath causeOfDeath = AdvancedCauseOfDeath.Blast; if (killRange == 5f) { causeOfDeath = AdvancedCauseOfDeath.Player_Jetpack_Blast; } else if (killRange == 5.7f) { causeOfDeath = AdvancedCauseOfDeath.Other_Landmine; } else if (killRange == 2.4f) { causeOfDeath = AdvancedCauseOfDeath.Other_Lightning; } AdvancedDeathTracker.SetCauseOfDeath(targetPlayer, causeOfDeath); } } [HarmonyPatch(typeof(HUDManager))] [HarmonyPatch("FillEndGameStats")] internal class HUDManagerFillEndGameStatsPatch { private const string EMPTY_NOTES = "Notes: \n"; public static void Postfix(HUDManager __instance) { try { OverridePerformanceReport(__instance); } catch (Exception ex) { Plugin.Instance.PluginLogger.LogError("Error in HUDManagerFillEndGameStatsPatch.Postfix: " + ex); Plugin.Instance.PluginLogger.LogError(ex.StackTrace); } } private static Random BuildSyncedRandom() { int randomMapSeed = StartOfRound.Instance.randomMapSeed; Plugin.Instance.PluginLogger.LogDebug("Syncing randomization to map seed: '" + randomMapSeed + "'"); return new Random(randomMapSeed); } private static void OverridePerformanceReport(HUDManager __instance) { Plugin.Instance.PluginLogger.LogDebug("Applying Coroner patches to player notes..."); Random random = BuildSyncedRandom(); for (int i = 0; i < __instance.statsUIElements.playerNotesText.Length; i++) { PlayerControllerB val = __instance.playersManager.allPlayerScripts[i]; if (!val.disconnectedMidGame && !val.isPlayerDead && !val.isPlayerControlled) { Plugin.Instance.PluginLogger.LogInfo("Player " + i + " is not controlled by a player. Skipping..."); continue; } TextMeshProUGUI val2 = __instance.statsUIElements.playerNotesText[i]; if (val.isPlayerDead) { if (Plugin.Instance.PluginConfig.ShouldDisplayCauseOfDeath()) { if (Plugin.Instance.PluginConfig.ShouldDeathReplaceNotes()) { Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead! Replacing notes with Cause of Death..."); ((TMP_Text)val2).text = LanguageHandler.GetValueByTag("UICauseOfDeath") + "\n"; } else { Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead! Appending notes with Cause of Death..."); } AdvancedCauseOfDeath causeOfDeath = AdvancedDeathTracker.GetCauseOfDeath(val); ((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + AdvancedDeathTracker.StringifyCauseOfDeath(causeOfDeath, random) + "\n"; } else { Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " is dead, but Config says leave it be..."); } } else if (((TMP_Text)val2).text == "Notes: \n") { if (Plugin.Instance.PluginConfig.ShouldDisplayFunnyNotes()) { Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has no notes! Injecting something funny..."); ((TMP_Text)val2).text = LanguageHandler.GetValueByTag("UINotes") + "\n"; ((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + AdvancedDeathTracker.StringifyCauseOfDeath(null, random) + "\n"; } else { Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has no notes, but Config says leave it be..."); } } else { Plugin.Instance.PluginLogger.LogInfo("[REPORT] Player " + i + " has notes, don't override them..."); } } AdvancedDeathTracker.ClearDeathTracker(); } } } namespace Coroner.LCAPI { internal class DeathBroadcasterLCAPI { private const string SIGNATURE_DEATH = "com.elitemastereric.coroner.death"; public static void Initialize() { Plugin.Instance.PluginLogger.LogDebug("Initializing DeathBroadcaster..."); if (Plugin.Instance.IsLCAPIPresent) { Plugin.Instance.PluginLogger.LogDebug("LC_API is present! Registering signature..."); Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(OnBroadcastString)); } else { Plugin.Instance.PluginLogger.LogError("LC_API is not present! Why did you try to register the DeathBroadcaster?"); } } private static void OnBroadcastString(string data, string signature) { if (signature == "com.elitemastereric.coroner.death") { Plugin.Instance.PluginLogger.LogDebug("Broadcast has been received from LC_API!"); string[] array = data.Split('|'); int playerIndex = int.Parse(array[0]); int num = int.Parse(array[1]); AdvancedCauseOfDeath advancedCauseOfDeath = (AdvancedCauseOfDeath)num; Plugin.Instance.PluginLogger.LogDebug("Player " + playerIndex + " died of " + AdvancedDeathTracker.StringifyCauseOfDeath((AdvancedCauseOfDeath?)advancedCauseOfDeath)); AdvancedDeathTracker.SetCauseOfDeath(playerIndex, advancedCauseOfDeath, broadcast: false); } } public static void AttemptBroadcast(string data, string signature) { if (Plugin.Instance.IsLCAPIPresent) { Plugin.Instance.PluginLogger.LogDebug("LC_API is present! Broadcasting..."); Networking.Broadcast(data, signature); } else { Plugin.Instance.PluginLogger.LogDebug("LC_API is not present! Skipping broadcast..."); } } } }
BepInEx/plugins/CustomBoomboxFix.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("CustomBoomboxFix")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("CustomBoomboxFix")] [assembly: AssemblyTitle("CustomBoomboxFix")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 CustomBoomboxFix { [BepInPlugin("CustomBoomboxFix", "CustomBoomboxFix", "1.0.0")] public class Plugin : BaseUnityPlugin { private string CustomSongsPluginPath => Path.Combine(Paths.PluginPath, "Custom Songs"); private string TargetPath => Path.Combine(Paths.BepInExRootPath, "Custom Songs", "Boombox Music"); private void Awake() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin CustomBoomboxFix is loaded!"); CreatePluginCustomSongsFolder(); DeleteAllFilesInTargetPath(); SearchAndCopyCustomSongs(); CopyMusicFiles(); } private void CreatePluginCustomSongsFolder() { if (!Directory.Exists(CustomSongsPluginPath)) { Directory.CreateDirectory(CustomSongsPluginPath); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Created 'Custom Songs' folder in plugin directory."); } } private void CopyMusicFiles() { if (!Directory.Exists(TargetPath)) { Directory.CreateDirectory(TargetPath); } IEnumerable<string> enumerable = Directory.GetFiles(CustomSongsPluginPath, "*.mp3").Concat(Directory.GetFiles(CustomSongsPluginPath, "*.wav")); foreach (string item in enumerable) { string fileName = Path.GetFileName(item); string text = Path.Combine(TargetPath, fileName); if (!File.Exists(text)) { File.Copy(item, text); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Copied " + fileName + " to Boombox Music folder.")); } } } private void DeleteAllFilesInTargetPath() { try { if (Directory.Exists(TargetPath)) { string[] files = Directory.GetFiles(TargetPath); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Deleting files in '" + TargetPath + "'...")); string[] array = files; foreach (string path in array) { File.Delete(path); } ((BaseUnityPlugin)this).Logger.LogInfo((object)("Deleted files in '" + TargetPath + "'")); } else { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Target path '" + TargetPath + "' does not exist.")); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("An error occurred while trying to delete files: " + ex.Message)); } } private void SearchAndCopyCustomSongs() { string[] directories = Directory.GetDirectories(Paths.PluginPath); string[] array = directories; foreach (string path in array) { string text = Path.Combine(path, "Custom Songs"); if (!Directory.Exists(text)) { continue; } IEnumerable<string> enumerable = Directory.GetFiles(text, "*.mp3").Concat(Directory.GetFiles(text, "*.wav")); foreach (string item in enumerable) { string fileName = Path.GetFileName(item); string text2 = Path.Combine(TargetPath, fileName); if (!File.Exists(text2)) { File.Copy(item, text2); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Copied " + fileName + " from " + text + " to Boombox Music folder.")); } } } } } public static class PluginInfo { public const string PLUGIN_GUID = "CustomBoomboxFix"; public const string PLUGIN_NAME = "CustomBoomboxFix"; public const string PLUGIN_VERSION = "1.0.0"; } }
BepInEx/plugins/CustomBoomboxTracks.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using CustomBoomboxTracks.Configuration; using CustomBoomboxTracks.Managers; using CustomBoomboxTracks.Utilities; using HarmonyLib; using UnityEngine; using UnityEngine.Networking; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("CustomBoomboxTracks")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.4.0.0")] [assembly: AssemblyInformationalVersion("1.4.0")] [assembly: AssemblyProduct("CustomBoomboxTracks")] [assembly: AssemblyTitle("CustomBoomboxTracks")] [assembly: AssemblyVersion("1.4.0.0")] namespace CustomBoomboxTracks { [BepInPlugin("com.steven.lethalcompany.boomboxmusic", "Custom Boombox Music", "1.4.0")] public class BoomboxPlugin : BaseUnityPlugin { private const string GUID = "com.steven.lethalcompany.boomboxmusic"; private const string NAME = "Custom Boombox Music"; private const string VERSION = "1.4.0"; private static BoomboxPlugin Instance; private void Awake() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) Instance = this; LogInfo("Loading..."); AudioManager.GenerateFolders(); Config.Init(); new Harmony("com.steven.lethalcompany.boomboxmusic").PatchAll(); LogInfo("Loading Complete!"); } internal static void LogDebug(string message) { Instance.Log(message, (LogLevel)32); } internal static void LogInfo(string message) { Instance.Log(message, (LogLevel)16); } internal static void LogWarning(string message) { Instance.Log(message, (LogLevel)4); } internal static void LogError(string message) { Instance.Log(message, (LogLevel)2); } internal static void LogError(Exception ex) { Instance.Log(ex.Message + "\n" + ex.StackTrace, (LogLevel)2); } private void Log(string message, LogLevel logLevel) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) ((BaseUnityPlugin)this).Logger.Log(logLevel, (object)message); } } } namespace CustomBoomboxTracks.Utilities { public class SharedCoroutineStarter : MonoBehaviour { private static SharedCoroutineStarter _instance; public static Coroutine StartCoroutine(IEnumerator routine) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_instance == (Object)null) { _instance = new GameObject("Shared Coroutine Starter").AddComponent<SharedCoroutineStarter>(); Object.DontDestroyOnLoad((Object)(object)_instance); } return ((MonoBehaviour)_instance).StartCoroutine(routine); } } } namespace CustomBoomboxTracks.Patches { [HarmonyPatch(typeof(BoomboxItem), "PocketItem")] internal class BoomboxItem_PocketItem { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = instructions.ToList(); bool flag = false; for (int i = 0; i < list.Count; i++) { if (!flag) { if (list[i].opcode == OpCodes.Call) { flag = true; } continue; } if (list[i].opcode == OpCodes.Ret) { break; } list[i].opcode = OpCodes.Nop; } return list; } } [HarmonyPatch(typeof(BoomboxItem), "Start")] internal class BoomboxItem_Start { private static void Postfix(BoomboxItem __instance) { if (AudioManager.FinishedLoading) { AudioManager.ApplyClips(__instance); return; } AudioManager.OnAllSongsLoaded += delegate { AudioManager.ApplyClips(__instance); }; } } [HarmonyPatch(typeof(BoomboxItem), "StartMusic")] internal class BoomboxItem_StartMusic { private static void Postfix(BoomboxItem __instance, bool startMusic) { if (startMusic) { BoomboxPlugin.LogInfo("Playing " + ((Object)__instance.boomboxAudio.clip).name); } } } [HarmonyPatch(typeof(StartOfRound), "Awake")] internal class StartOfRound_Awake { private static void Prefix() { AudioManager.Load(); } } } namespace CustomBoomboxTracks.Managers { internal static class AudioManager { private static string[] allSongPaths; private static List<AudioClip> clips = new List<AudioClip>(); private static bool firstRun = true; private static bool finishedLoading = false; private static readonly string directory = Path.Combine(Paths.BepInExRootPath, "Custom Songs", "Boombox Music"); public static bool FinishedLoading => finishedLoading; public static bool HasNoSongs => allSongPaths.Length == 0; public static event Action OnAllSongsLoaded; public static void GenerateFolders() { Directory.CreateDirectory(directory); BoomboxPlugin.LogInfo("Created directory at " + directory); } public static void Load() { if (!firstRun) { return; } firstRun = false; allSongPaths = Directory.GetFiles(directory); if (allSongPaths.Length == 0) { BoomboxPlugin.LogWarning("No songs found!"); return; } BoomboxPlugin.LogInfo("Preparing to load AudioClips..."); List<Coroutine> list = new List<Coroutine>(); string[] array = allSongPaths; for (int i = 0; i < array.Length; i++) { Coroutine item = SharedCoroutineStarter.StartCoroutine(LoadAudioClip(array[i])); list.Add(item); } SharedCoroutineStarter.StartCoroutine(WaitForAllClips(list)); } private static IEnumerator LoadAudioClip(string filePath) { BoomboxPlugin.LogInfo("Loading " + filePath + "!"); if ((int)GetAudioType(filePath) == 0) { BoomboxPlugin.LogError("Failed to load AudioClip from " + filePath + "\nUnsupported file extension!"); yield break; } UnityWebRequest loader = UnityWebRequestMultimedia.GetAudioClip(filePath, GetAudioType(filePath)); if (Config.StreamFromDisk) { DownloadHandler downloadHandler = loader.downloadHandler; ((DownloadHandlerAudioClip)((downloadHandler is DownloadHandlerAudioClip) ? downloadHandler : null)).streamAudio = true; } loader.SendWebRequest(); while (!loader.isDone) { yield return null; } if (loader.error != null) { BoomboxPlugin.LogError("Error loading clip from path: " + filePath + "\n" + loader.error); BoomboxPlugin.LogError(loader.error); yield break; } AudioClip content = DownloadHandlerAudioClip.GetContent(loader); if (Object.op_Implicit((Object)(object)content) && (int)content.loadState == 2) { BoomboxPlugin.LogInfo("Loaded " + filePath); ((Object)content).name = Path.GetFileName(filePath); clips.Add(content); } else { BoomboxPlugin.LogError("Failed to load clip at: " + filePath + "\nThis might be due to an mismatch between the audio codec and the file extension!"); } } private static IEnumerator WaitForAllClips(List<Coroutine> coroutines) { foreach (Coroutine coroutine in coroutines) { yield return coroutine; } clips.Sort((AudioClip first, AudioClip second) => ((Object)first).name.CompareTo(((Object)second).name)); finishedLoading = true; AudioManager.OnAllSongsLoaded?.Invoke(); AudioManager.OnAllSongsLoaded = null; } public static void ApplyClips(BoomboxItem __instance) { BoomboxPlugin.LogInfo("Applying clips!"); if (Config.UseDefaultSongs) { __instance.musicAudios = __instance.musicAudios.Concat(clips).ToArray(); } else { __instance.musicAudios = clips.ToArray(); } BoomboxPlugin.LogInfo($"Total Clip Count: {__instance.musicAudios.Length}"); } private static AudioType GetAudioType(string path) { string text = Path.GetExtension(path).ToLower(); switch (text) { case ".wav": return (AudioType)20; case ".ogg": return (AudioType)14; case ".mp3": return (AudioType)13; default: BoomboxPlugin.LogError("Unsupported extension type: " + text); return (AudioType)0; } } } } namespace CustomBoomboxTracks.Configuration { internal static class Config { private const string CONFIG_FILE_NAME = "boombox.cfg"; private static ConfigFile _config; private static ConfigEntry<bool> _useDefaultSongs; private static ConfigEntry<bool> _streamAudioFromDisk; public static bool UseDefaultSongs { get { if (!_useDefaultSongs.Value) { return AudioManager.HasNoSongs; } return true; } } public static bool StreamFromDisk => _streamAudioFromDisk.Value; public static void Init() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown BoomboxPlugin.LogInfo("Initializing config..."); _config = new ConfigFile(Path.Combine(Paths.ConfigPath, "boombox.cfg"), true); _useDefaultSongs = _config.Bind<bool>("Config", "Use Default Songs", false, "Include the default songs in the rotation."); _streamAudioFromDisk = _config.Bind<bool>("Config", "Stream Audio From Disk", false, "Requires less memory and takes less time to load, but prevents playing the same song twice at once."); BoomboxPlugin.LogInfo("Config initialized!"); } private static void PrintConfig() { BoomboxPlugin.LogInfo($"Use Default Songs: {_useDefaultSongs.Value}"); BoomboxPlugin.LogInfo($"Stream From Disk: {_streamAudioFromDisk}"); } } }
BepInEx/plugins/EmployeeAssignments.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using PersonalAssignments.AssignmentLogic; using PersonalAssignments.Components; using PersonalAssignments.Data; using PersonalAssignments.Network; using PersonalAssignments.UI; using TMPro; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.Networking; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("EmployeeAssignments")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("PersonalAssignments")] [assembly: AssemblyFileVersion("1.0.9.0")] [assembly: AssemblyInformationalVersion("1.0.9")] [assembly: AssemblyProduct("EmployeeAssignments")] [assembly: AssemblyTitle("EmployeeAssignments")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.9.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 PersonalAssignments { [BepInPlugin("EmployeeAssignments", "EmployeeAssignments", "1.0.9")] public class Plugin : BaseUnityPlugin { private static bool Initialized; public static ManualLogSource Log { get; private set; } private void Start() { Initialize(); } private void OnDestroy() { Initialize(); } private void Initialize() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; if (!Initialized) { Initialized = true; GameObject val = new GameObject("PersonalAssignmentManager"); Object.DontDestroyOnLoad((Object)(object)val); PersonalAssignmentManager personalAssignmentManager = val.AddComponent<PersonalAssignmentManager>(); personalAssignmentManager.Config = new PAConfig(((BaseUnityPlugin)this).Config); val.AddComponent<KillableEnemiesOutput>(); val.AddComponent<UpdateChecker>(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin EmployeeAssignments is loaded!"); } } } [Serializable] public enum AssignmentType { CollectScrapItem, KillMonster, RepairValve } [Serializable] public struct Assignment { public string Name; public string UID; public byte ID; public string BodyText; public string ShortText; public string TargetText; public string FailureReason; public int CashReward; public int XPReward; public AssignmentType Type; public ulong PlayerId; public ulong[] TargetIds; public int TargetsComplete; public Vector3 FixedTargetPosition; } public static class Assignments { public static readonly Assignment[] All = new Assignment[3] { new Assignment { Name = "SCRAP RETRIEVAL", UID = "collect_scrap", BodyText = "YOU MUST COLLECT THE FOLLOWING SCRAP ITEM: [{0}] IT WILL BE MARKED AS [ASSIGNMENT TARGET]", ShortText = "FIND THE [{0}] MARKED 'ASSIGNMENT TARGET'", FailureReason = "ANOTHER EMPLOYEE COLLECTED THE ITEM", CashReward = 100, XPReward = 0, Type = AssignmentType.CollectScrapItem, TargetIds = new ulong[1] }, new Assignment { Name = "HUNT & KILL", UID = "hunt_kill", BodyText = "YOU MUST HUNT AND KILL THE FOLLOWING ENEMY: [{0}] IT WILL BE MARKED AS [ASSIGNMENT TARGET]", ShortText = "FIND AND KILL THE [{0}]", FailureReason = "THE ENEMY WAS NOT KILLED", CashReward = 200, XPReward = 0, Type = AssignmentType.KillMonster, TargetIds = new ulong[1] }, new Assignment { Name = "REPAIR VALVE", UID = "repair_valve", BodyText = "YOU MUST FIND AND REPAIR THE BROKEN VALVE", ShortText = "FIND AND REPAIR THE BROKEN VALVE", TargetText = "BROKEN VALVE", FailureReason = "THE BROKEN VALVE WAS NOT FIXED", CashReward = 100, XPReward = 0, Type = AssignmentType.RepairValve, TargetIds = new ulong[1] } }; public static Assignment GetAssignment(string guid) { Assignment[] all = All; for (int i = 0; i < all.Length; i++) { Assignment result = all[i]; if (result.UID == guid) { return result; } } return default(Assignment); } } public class PersonalAssignmentManager : MonoBehaviour { private readonly List<IAssignmentLogic> _assignmentLogic = new List<IAssignmentLogic>(); private NetworkUtils _networkUtils; private AssignmentUI _assignmentUI; private PAContext _context; private GameContext _gameContext; private int _maxAssignedPlayers = 20; private int _minAssignedPlayers = 1; public PAConfig Config; private Coroutine _lootValueSyncRoutine; private WaitForSecondsRealtime _rewardValueSyncDelay = new WaitForSecondsRealtime(1f); private void Log(string log) { Plugin.Log.LogInfo((object)log); } public void Awake() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) _context = new PAContext(); _assignmentUI = new GameObject("UI").AddComponent<AssignmentUI>(); ((Component)_assignmentUI).transform.SetParent(((Component)this).transform); _networkUtils = ((Component)this).gameObject.AddComponent<NetworkUtils>(); NetworkUtils networkUtils = _networkUtils; networkUtils.OnNetworkData = (Action<string, byte[]>)Delegate.Combine(networkUtils.OnNetworkData, new Action<string, byte[]>(OnNetworkData)); NetworkUtils networkUtils2 = _networkUtils; networkUtils2.OnDisconnect = (Action)Delegate.Combine(networkUtils2.OnDisconnect, new Action(OnDisconnect)); _gameContext = new GameContext(); GameStateSync gameStateSync = ((Component)this).gameObject.AddComponent<GameStateSync>(); gameStateSync.Inject(_gameContext, _networkUtils); GameContext gameContext = _gameContext; gameContext.GameStateChanged = (Action<GameStateEnum>)Delegate.Combine(gameContext.GameStateChanged, new Action<GameStateEnum>(GameStateChanged)); InstallAssignmentLogic(); } private void InstallAssignmentLogic() { _assignmentLogic.Add(new CollectScrapLogic(_context)); _assignmentLogic.Add(new HuntAndKillLogic(_context)); _assignmentLogic.Add(new RepairValveLogic(_context)); } public void Start() { _maxAssignedPlayers = Config.MaxAssignedPlayers.Value; _minAssignedPlayers = Config.MinAssignedPlayers.Value; _context.AssignAllPlayers = Config.AssignAllPlayers.Value; _context.AllPlayersComplete = Config.AllPlayersCanComplete.Value; Assignments.All[0].CashReward = Config.ScrapRetrievalReward.Value; Assignments.All[2].CashReward = Config.BrokenValveReward.Value; _context.ParseStringArray(ref _context.EnemyWhitelist, Config.HuntAndKillWhitelist); _context.ParseStringArray(ref _context.AssignmentWhitelist, Config.AssignmentWhiteList); _context.ParseIntArray(ref _context.AssignmentWeights, Config.AssignmentWeights); _context.ParseIntArray(ref _context.EnemyWeights, Config.HuntAndKillWeights); _context.ParseIntArray(ref _context.EnemyRewards, Config.HuntAndKillRewards); } private void OnDisconnect() { HandleResetEvent(); } private void SendNetworkEvent<T>(T netEvent) where T : IPAEvent { string s = JsonUtility.ToJson((object)netEvent); byte[] bytes = Encoding.UTF8.GetBytes(s); _networkUtils.SendToAll(netEvent.TAG, bytes); } private void OnNetworkData(string tag, byte[] data) { if (tag.StartsWith("PA-")) { string @string = Encoding.UTF8.GetString(data); Log("Incoming data " + tag + " " + @string); switch (tag) { case "PA-Reset": HandleResetEvent(); break; case "PA-Allocation": { AssignmentEvent assignmentEvent2 = JsonUtility.FromJson<AssignmentEvent>(@string); HandleAllocationEvent(assignmentEvent2); break; } case "PA-Complete": { CompleteEvent assignmentEvent = JsonUtility.FromJson<CompleteEvent>(@string); HandleCompleteEvent(assignmentEvent); break; } case "PA-Failed": { FailedEvent failedEvent = JsonUtility.FromJson<FailedEvent>(@string); HandleFailedEvent(failedEvent); break; } } } } private void HandleResetEvent() { _context.AssignmentsGenerated = false; _context.CurrentAssignment = null; _context.ActiveAssignments.Clear(); _context.CompletedAssignments.Clear(); _assignmentUI.ClearAssignment(); } private void HandleAllocationEvent(AssignmentEvent assignmentEvent) { Assignment assignment = Assignments.GetAssignment(assignmentEvent.AssignmentUID); assignment.PlayerId = assignmentEvent.PlayerId; assignment.TargetIds = assignmentEvent.TargetIds; assignment.CashReward = assignmentEvent.RewardValue; assignment.TargetText = assignmentEvent.TargetName; assignment.ID = assignmentEvent.AssignmentID; bool flag = assignment.PlayerId == NetworkManager.Singleton.LocalClientId; bool flag2 = _assignmentLogic[(int)assignment.Type].HandleAllocationEvent(ref assignment, flag); if (flag && flag2) { _context.CurrentAssignment = assignment; ShowAssignment(_context.CurrentAssignment.Value); } else { Log($"Assignment not assigned to local player: (ForLocalPlayer){flag} | (SetupComplete){flag2}"); } } private void HandleCompleteEvent(CompleteEvent assignmentEvent) { Assignment assignment = Assignments.GetAssignment(assignmentEvent.AssignmentUID); assignment.CashReward = assignmentEvent.RewardValue; assignment.TargetIds = assignmentEvent.TargetIds; assignment.PlayerId = assignmentEvent.PlayerId; assignment.ID = assignmentEvent.AssignmentID; bool flag = _context.CurrentAssignment.HasValue && _context.CurrentAssignment.Value.ID == assignmentEvent.AssignmentID && assignment.PlayerId == NetworkManager.Singleton.LocalClientId; _assignmentLogic[(int)assignment.Type].CompleteAssignment(ref assignment, flag); if (flag) { CompleteAssignment(); } } private void HandleFailedEvent(FailedEvent failedEvent) { if (_context.CurrentAssignment.HasValue && _context.CurrentAssignment.Value.ID == failedEvent.AssignmentID && failedEvent.PlayerId == NetworkManager.Singleton.LocalClientId) { FailAssignment(failedEvent.Reason); } } private void GameStateChanged(GameStateEnum state) { switch (state) { case GameStateEnum.MainMenu: HandleResetEvent(); break; case GameStateEnum.Orbit: ShipTookOff(); break; case GameStateEnum.CompanyHQ: HandleResetEvent(); break; case GameStateEnum.Level: LandedOnMoon(); if (NetworkManager.Singleton.IsHost) { GenerateAssignments(); } break; } } public void LandedOnMoon() { } public void ShipTookOff() { ClearAllAssignments(); } private void ClearAllAssignments() { SendNetworkEvent(default(ResetEvent)); } public void Update() { if (_gameContext.GameState != GameStateEnum.Level) { return; } if (_context.CurrentAssignment.HasValue) { _assignmentUI.SetAssignment(_context.CurrentAssignment.Value); } if (NetworkManager.Singleton.IsHost) { if (_context.ActiveAssignments.Count > 0) { CheckCompleted(); } if (_lootValueSyncRoutine == null && _context.SyncedRewardValues.Count > 0) { _lootValueSyncRoutine = ((MonoBehaviour)this).StartCoroutine(SyncLootValues()); } } } private IEnumerator SyncLootValues() { yield return _rewardValueSyncDelay; for (int i = _context.SyncedRewardValues.Count - 1; i >= 0; i--) { if ((Object)(object)_context.SyncedRewardValues[i].Item1 == (Object)null) { _context.SyncedRewardValues.RemoveAt(i); } } if (_context.SyncedRewardValues.Count > 0) { List<NetworkObjectReference> references = new List<NetworkObjectReference>(); List<int> values = new List<int>(); foreach (var item in _context.SyncedRewardValues) { references.Add(NetworkObjectReference.op_Implicit(item.Item1)); values.Add(item.Item2); } RoundManager.Instance.SyncScrapValuesClientRpc(references.ToArray(), values.ToArray()); } _lootValueSyncRoutine = null; } private void GenerateAssignments() { int num = 0; _context.CompletedAssignments.Clear(); _context.ActiveAssignments.Clear(); _context.ExcludeTargetIds.Clear(); IReadOnlyList<ulong> connectedClientsIds = NetworkManager.Singleton.ConnectedClientsIds; int num2 = Mathf.Max(_minAssignedPlayers, Mathf.Min(_maxAssignedPlayers, RoundManager.Instance.playersManager.connectedPlayersAmount / 2)); List<int> list = new List<int>(); for (int i = 0; i < connectedClientsIds.Count; i++) { list.Add(i); } num2 = Mathf.Min(num2, list.Count); if (_context.AssignAllPlayers) { num2 = list.Count; } Log($"Starting assignment generation for {num2} players"); byte b = 0; for (int j = 0; j < num2; j++) { b++; int index = Random.Range(0, list.Count); int index2 = list[index]; int num3 = Utils.WeightedRandom(_context.AssignmentWeights); Assignment assignment = Assignments.GetAssignment(_context.AssignmentWhitelist[num3]); if (!string.IsNullOrEmpty(assignment.UID)) { assignment.PlayerId = connectedClientsIds[index2]; assignment.ID = b; bool flag = _assignmentLogic[(int)assignment.Type].ServerSetupAssignment(ref assignment); if (!flag && num < 5) { j--; Log($"trying to find another assignment {connectedClientsIds[index2]}"); num++; } else if (flag) { Log($"created assignment for player {connectedClientsIds[index2]}"); AssignmentEvent assignmentEvent = default(AssignmentEvent); assignmentEvent.PlayerId = connectedClientsIds[index2]; assignmentEvent.AssignmentUID = _context.AssignmentWhitelist[num3]; assignmentEvent.TargetIds = assignment.TargetIds; assignmentEvent.RewardValue = assignment.CashReward; assignmentEvent.TargetName = assignment.TargetText; assignmentEvent.AssignmentID = b; AssignmentEvent netEvent = assignmentEvent; SendNetworkEvent(netEvent); _context.ActiveAssignments.Add(assignment); list.RemoveAt(index); } } } _context.AssignmentsGenerated = true; Log("Finishing assignment generation"); } private void CheckCompleted() { bool wasPressedThisFrame = ((ButtonControl)Keyboard.current.oKey).wasPressedThisFrame; bool wasPressedThisFrame2 = ((ButtonControl)Keyboard.current.pKey).wasPressedThisFrame; for (int num = _context.ActiveAssignments.Count - 1; num >= 0; num--) { Assignment assignment = _context.ActiveAssignments[num]; AssignmentState assignmentState = _assignmentLogic[(int)assignment.Type].CheckCompletion(ref assignment); if (assignmentState != 0) { _context.ActiveAssignments.RemoveAt(num); _context.CompletedAssignments.Add(assignment); } switch (assignmentState) { case AssignmentState.Complete: SendNetworkEvent(new CompleteEvent { PlayerId = assignment.PlayerId, AssignmentUID = assignment.UID, TargetIds = assignment.TargetIds, RewardValue = assignment.CashReward, AssignmentID = assignment.ID }); break; case AssignmentState.Failed: SendNetworkEvent(new FailedEvent { PlayerId = assignment.PlayerId, Reason = assignment.FailureReason, AssignmentID = assignment.ID }); break; } } } private void ShowAssignment(Assignment assignment) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown if (!((Object)(object)HUDManager.Instance == (Object)null)) { DialogueSegment[] array = (DialogueSegment[])(object)new DialogueSegment[1] { new DialogueSegment { speakerText = "ASSIGNMENT:" + assignment.Name, bodyText = "YOU HAVE BEEN SELECTED BY THE COMPANY FOR ASSIGNMENT, " + string.Format(assignment.BodyText, assignment.TargetText), waitTime = 10f } }; _assignmentUI.SetAssignment(assignment); HUDManager.Instance.ReadDialogue(array); } } private void CompleteAssignment() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown if (_context.CurrentAssignment.HasValue) { DialogueSegment[] array = (DialogueSegment[])(object)new DialogueSegment[1] { new DialogueSegment { speakerText = "ASSIGNMENT COMPLETE", bodyText = "YOU HAVE COMPLETED THE ASSIGNMENT, WELL DONE. THE COMPANY VALUES YOUR LOYALTY", waitTime = 5f } }; _assignmentUI.ClearAssignment(); HUDManager.Instance.ReadDialogue(array); _context.CurrentAssignment = null; } } private void FailAssignment(string reason) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown if (_context.CurrentAssignment.HasValue) { DialogueSegment[] array = (DialogueSegment[])(object)new DialogueSegment[1] { new DialogueSegment { speakerText = "ASSIGNMENT FAILED", bodyText = "YOU FAILED TO COMPLETE THE ASSIGNMENT. REASON: " + reason, waitTime = 5f } }; _assignmentUI.ClearAssignment(); HUDManager.Instance.ReadDialogue(array); _context.CurrentAssignment = null; } } } public static class Utils { private const float EASE_IN_OUT_MAGIC1 = 1.7f; private const float EASE_IN_OUT_MAGIC2 = 2.5500002f; public static float EaseInOutBack(float x) { return (x < 0.5f) ? (MathF.Pow(2f * x, 2f) * (7.1000004f * x - 2.5500002f) / 2f) : ((MathF.Pow(2f * x - 2f, 2f) * (3.5500002f * (x * 2f - 2f) + 2.5500002f) + 2f) / 2f); } public static int WeightedRandom(int[] weights) { int num = 0; for (int i = 0; i < weights.Length; i++) { num += weights[i]; } int num2 = Random.Range(0, num); int num3 = 0; for (int j = 0; j < weights.Length; j++) { num3 += weights[j]; if (num3 >= num2) { return j; } } return 0; } } public static class PluginInfo { public const string PLUGIN_GUID = "EmployeeAssignments"; public const string PLUGIN_NAME = "EmployeeAssignments"; public const string PLUGIN_VERSION = "1.0.9"; } } namespace PersonalAssignments.UI { public class AssignmentUI : MonoBehaviour { private enum State { Showing, Shown, Hiding, Hidden } private readonly Color NONE_TEXT_COLOR = new Color(1f, 0.8277124f, 0.5235849f, 0.3254902f); private readonly Color BG_COLOR = new Color(1f, 0.6916346f, 0.259434f, 1f); private readonly Color TITLE_COLOR = new Color(1f, 0.9356132f, 0.8160377f, 1f); private readonly Color TEXT_COLOR = new Color(0.3584906f, 0.2703371f, 0f, 1f); private const float SHOW_SPEED = 1f; private const float HIDE_SPEED = 2f; private readonly Vector2 SHOW_POSITION = new Vector2(-50f, -350f); private readonly Vector2 HIDE_POSITION = new Vector2(500f, -350f); private Canvas _canvas; private GameObject _noneText; private RectTransform _assignment; private Text _assignmentTitle; private Text _assignmentText; private Font _font; private QuickMenuManager _menuManager; private State _state; private float _animationProgress; public Assignment? _activeAssignment; private void Awake() { //IL_0037: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_016f: 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_0187: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0335: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_0419: Unknown result type (might be due to invalid IL or missing references) //IL_0430: Unknown result type (might be due to invalid IL or missing references) //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) //IL_046b: Unknown result type (might be due to invalid IL or missing references) Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); _state = State.Hidden; ((Component)this).gameObject.layer = 5; _font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf"); _canvas = new GameObject("Canvas").AddComponent<Canvas>(); ((Component)_canvas).transform.SetParent(((Component)this).transform); _canvas.sortingOrder = -100; _canvas.renderMode = (RenderMode)0; RectTransform component = ((Component)_canvas).GetComponent<RectTransform>(); component.sizeDelta = new Vector2(1920f, 1080f); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.zero; component.pivot = Vector2.zero / 2f; CanvasScaler val = ((Component)_canvas).gameObject.AddComponent<CanvasScaler>(); val.uiScaleMode = (ScaleMode)1; val.screenMatchMode = (ScreenMatchMode)2; val.referenceResolution = new Vector2(1920f, 1080f); _noneText = new GameObject("NoneText"); Text val2 = _noneText.AddComponent<Text>(); val2.fontSize = 20; val2.font = _font; val2.fontStyle = (FontStyle)1; val2.text = "NO ASSIGNMENT ACTIVE"; ((Graphic)val2).color = NONE_TEXT_COLOR; val2.alignment = (TextAnchor)4; RectTransform component2 = _noneText.GetComponent<RectTransform>(); ((Transform)component2).SetParent((Transform)(object)component); component2.pivot = Vector2.one; component2.anchorMin = Vector2.one; component2.anchorMax = Vector2.one; component2.anchoredPosition = new Vector2(-70f, -360f); component2.sizeDelta = new Vector2(310f, 50f); CanvasGroup val3 = new GameObject("AssignmentPanel").AddComponent<CanvasGroup>(); val3.alpha = 0.5f; Image val4 = ((Component)val3).gameObject.AddComponent<Image>(); ((Graphic)val4).color = BG_COLOR; _assignment = ((Component)val3).gameObject.GetComponent<RectTransform>(); ((Transform)_assignment).SetParent((Transform)(object)component); _assignment.pivot = Vector2.one; _assignment.anchorMin = Vector2.one; _assignment.anchorMax = Vector2.one; _assignment.anchoredPosition = new Vector2(-50f, -350f); _assignment.sizeDelta = new Vector2(350f, 80f); _assignmentTitle = new GameObject("Title").AddComponent<Text>(); _assignmentTitle.font = _font; _assignmentTitle.fontSize = 20; _assignmentTitle.fontStyle = (FontStyle)1; _assignmentTitle.text = "NO ASSIGNMENT ACTIVE"; ((Graphic)_assignmentTitle).color = TITLE_COLOR; _assignmentTitle.alignment = (TextAnchor)0; RectTransform component3 = ((Component)_assignmentTitle).gameObject.GetComponent<RectTransform>(); ((Transform)component3).SetParent((Transform)(object)_assignment); component3.pivot = new Vector2(0.5f, 1f); component3.anchorMin = new Vector2(0f, 1f); component3.anchorMax = Vector2.one; component3.anchoredPosition = new Vector2(0f, -10f); component3.sizeDelta = new Vector2(-40f, 100f); _assignmentText = new GameObject("Text").AddComponent<Text>(); _assignmentText.font = _font; _assignmentText.fontSize = 16; _assignmentText.fontStyle = (FontStyle)1; _assignmentText.text = "NO ASSIGNMENT ACTIVE"; ((Graphic)_assignmentText).color = TEXT_COLOR; _assignmentText.alignment = (TextAnchor)6; RectTransform component4 = ((Component)_assignmentText).gameObject.GetComponent<RectTransform>(); ((Transform)component4).SetParent((Transform)(object)_assignment); component4.pivot = new Vector2(0.5f, 0.5f); component4.anchorMin = new Vector2(0f, 0f); component4.anchorMax = Vector2.one; component4.anchoredPosition = new Vector2(0f, -10f); component4.sizeDelta = new Vector2(-40f, -40f); } public void SetAssignment(Assignment assignment) { if (_state == State.Hidden || _state == State.Hiding) { ChangeState(State.Showing); _activeAssignment = assignment; _assignmentTitle.text = assignment.Name; _assignmentText.text = string.Format(assignment.ShortText, assignment.TargetText); } } public void ClearAssignment(bool force = false) { if (force || _state == State.Shown || _state == State.Showing) { ChangeState(State.Hiding); _activeAssignment = null; } } private void ChangeState(State state) { _state = state; _animationProgress = 0f; } private void PanelAnimation() { //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) if (_state == State.Shown || _state == State.Hidden) { return; } if (_animationProgress >= 1f) { _state++; return; } float num = 1f; if (_state == State.Hiding) { num = 2f; } _animationProgress += num * Time.deltaTime; float num2 = _animationProgress; if (_state == State.Hiding) { num2 = 1f - num2; } _assignment.anchoredPosition = Vector2.Lerp(HIDE_POSITION, SHOW_POSITION, Utils.EaseInOutBack(num2)); } private void Update() { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: 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) PanelAnimation(); bool flag = (Object)(object)GameNetworkManager.Instance?.localPlayerController != (Object)null && !GameNetworkManager.Instance.localPlayerController.isPlayerDead; if ((Object)(object)_menuManager == (Object)null) { flag = false; _menuManager = Object.FindAnyObjectByType<QuickMenuManager>(); } else { flag &= !_menuManager.isMenuOpen; } if (_activeAssignment.HasValue && _activeAssignment.Value.FixedTargetPosition != Vector3.zero) { float num = Vector3.Distance(_activeAssignment.Value.FixedTargetPosition, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position); _assignmentText.text = string.Format(_activeAssignment.Value.ShortText, _activeAssignment.Value.TargetText) + $" {(int)num}m"; } ((Component)_assignment).gameObject.SetActive(_state != State.Hidden); _noneText.SetActive(!_activeAssignment.HasValue); ((Behaviour)_canvas).enabled = flag; } } } namespace PersonalAssignments.Network { [Serializable] public struct NetworkMessage { public string MessageTag; public ulong TargetId; public Hash128 Checksum; public byte[] Data; } public class NetworkUtils : MonoBehaviour { public Action<string, byte[]> OnNetworkData; public Action OnDisconnect; public Action OnConnect; private bool _initialized; private bool _connected; public bool IsConnected => _connected; private void Initialize() { if (!((Object)(object)NetworkManager.Singleton == (Object)null) && NetworkManager.Singleton.CustomMessagingManager != null) { _initialized = true; Debug.Log((object)"[Network Transport] Initialized"); } } private void UnInitialize() { if (_connected) { Disconnected(); } _initialized = false; } private void Connected() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown NetworkManager.Singleton.CustomMessagingManager.OnUnnamedMessage += new UnnamedMessageDelegate(OnMessageEvent); OnConnect?.Invoke(); _connected = true; Debug.Log((object)"[Network Transport] Connected"); } private void Disconnected() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown NetworkManager singleton = NetworkManager.Singleton; if (((singleton != null) ? singleton.CustomMessagingManager : null) != null) { NetworkManager.Singleton.CustomMessagingManager.OnUnnamedMessage -= new UnnamedMessageDelegate(OnMessageEvent); } OnDisconnect?.Invoke(); _connected = false; Debug.Log((object)"[Network Transport] Disconnected"); } public void Update() { if (!_initialized) { Initialize(); } else if ((Object)(object)NetworkManager.Singleton == (Object)null) { UnInitialize(); } else if (!_connected && NetworkManager.Singleton.IsConnectedClient) { Connected(); } else if (_connected && !NetworkManager.Singleton.IsConnectedClient) { Disconnected(); } } private void OnMessageEvent(ulong clientId, FastBufferReader reader) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) Hash128 val = default(Hash128); string text = ""; NetworkMessage networkMessage = default(NetworkMessage); try { ((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false); Debug.Log((object)$"[Network Transport] Incoming message from {clientId} {text}"); networkMessage = JsonUtility.FromJson<NetworkMessage>(text); val = Hash128.Compute<byte>(networkMessage.Data); } catch (Exception ex) { Debug.LogException(ex); } if (!(val == default(Hash128)) && ((Hash128)(ref val)).CompareTo(val) == 0) { OnNetworkData?.Invoke(networkMessage.MessageTag, networkMessage.Data); } } public void SendToAll(string tag, byte[] data) { if (!_initialized) { return; } foreach (var (num2, val2) in NetworkManager.Singleton.ConnectedClients) { SendTo(val2.ClientId, tag, data); } } public void SendTo(ulong clientId, string tag, byte[] data) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_00a2: Unknown result type (might be due to invalid IL or missing references) if (!_initialized) { return; } NetworkMessage networkMessage = default(NetworkMessage); networkMessage.MessageTag = tag; networkMessage.TargetId = clientId; networkMessage.Data = data; networkMessage.Checksum = Hash128.Compute<byte>(data); NetworkMessage networkMessage2 = networkMessage; string text = JsonUtility.ToJson((object)networkMessage2); byte[] bytes = Encoding.UTF8.GetBytes(text); int writeSize = FastBufferWriter.GetWriteSize(text, false); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(writeSize + 1, (Allocator)2, -1); FastBufferWriter val2 = val; try { ((FastBufferWriter)(ref val)).WriteValueSafe(text, false); Debug.Log((object)$"[Network Transport] Sending message to {clientId} {text}"); NetworkManager.Singleton.CustomMessagingManager.SendUnnamedMessage(clientId, val, (NetworkDelivery)3); } finally { ((IDisposable)(FastBufferWriter)(ref val2)).Dispose(); } } } } namespace PersonalAssignments.Data { public interface IPAEvent { string TAG { get; } } [Serializable] public struct AssignmentEvent : IPAEvent { public byte AssignmentID; public ulong PlayerId; public string AssignmentUID; public int RewardValue; public ulong[] TargetIds; public string TargetName; public string TAG => "PA-Allocation"; } [Serializable] public struct CompleteEvent : IPAEvent { public byte AssignmentID; public ulong PlayerId; public string AssignmentUID; public int RewardValue; public ulong[] TargetIds; public string TAG => "PA-Complete"; } [Serializable] public struct FailedEvent : IPAEvent { public byte AssignmentID; public ulong PlayerId; public string Reason; public string TAG => "PA-Failed"; } [Serializable] [StructLayout(LayoutKind.Sequential, Size = 1)] public struct ResetEvent : IPAEvent { public string TAG => "PA-Reset"; } public class GameContext { private GameStateEnum _gameState; public Action<GameStateEnum> GameStateChanged; public GameStateEnum GameState { get { return _gameState; } set { if (value != _gameState) { _gameState = value; GameStateChanged?.Invoke(value); } } } } public enum GameStateEnum { MainMenu, Orbit, CompanyHQ, Level } public class PAConfig { public readonly ConfigEntry<int> MaxAssignedPlayers; public readonly ConfigEntry<int> MinAssignedPlayers; public readonly ConfigEntry<bool> AssignAllPlayers; public readonly ConfigEntry<int> ScrapRetrievalReward; public readonly ConfigEntry<string> HuntAndKillWhitelist; public readonly ConfigEntry<string> HuntAndKillWeights; public readonly ConfigEntry<string> HuntAndKillRewards; public readonly ConfigEntry<int> BrokenValveReward; public readonly ConfigEntry<bool> AllPlayersCanComplete; public readonly ConfigEntry<string> AssignmentWhiteList; public readonly ConfigEntry<string> AssignmentWeights; public PAConfig(ConfigFile configFile) { MaxAssignedPlayers = configFile.Bind<int>("0_HostOnly.0_General", "MaxAssignedPlayers", 10, "The maximum number of players that can be assigned each round."); MinAssignedPlayers = configFile.Bind<int>("0_HostOnly.0_General", "MinAssignedPlayers", 1, "The minimum number of players that can be assigned each round."); AssignAllPlayers = configFile.Bind<bool>("0_HostOnly.0_General", "AssignAllPlayers", false, "When this is true all connected players will always get an assignment each time you land."); AllPlayersCanComplete = configFile.Bind<bool>("0_HostOnly.0_General", "AllPlayersCanComplete", false, "All players can complete someone elses assignment and it will not fail for the owner"); AssignmentWhiteList = configFile.Bind<string>("0_HostOnly.0_General", "AssignmentWhiteList", "collect_scrap,hunt_kill,repair_valve", "All allowed Assignments"); AssignmentWeights = configFile.Bind<string>("0_HostOnly.0_General", "AssignmentWeights", "50,25,25", "Weights for allowed assignments"); ScrapRetrievalReward = configFile.Bind<int>("0_HostOnly.1_ScrapRetrieval", "AssignmentReward", 100, "The reward for completing a Scrap Retrieval Assignment"); HuntAndKillWhitelist = configFile.Bind<string>("0_HostOnly.2_HuntAndKill", "EnemyWhitelist", "Centipede,Bunker Spider,Hoarding bug,Crawler", "The EnemyNames that are allowed to spawn"); HuntAndKillRewards = configFile.Bind<string>("0_HostOnly.2_HuntAndKill", "EnemyRewards", "100,200,100,200", "The reward for completing a Hunt And KillReward Assignment for each enemy in the whitelist"); HuntAndKillWeights = configFile.Bind<string>("0_HostOnly.2_HuntAndKill", "EnemyWeights", "50,25,50,25", "Spawn Weights for each enemy in the whitelist"); BrokenValveReward = configFile.Bind<int>("0_HostOnly.3_BrokenValve", "AssignmentReward", 100, "The reward for completing a Broken Valve Assignment"); } } public class PAContext { public bool AssignmentsGenerated; public readonly List<Assignment> ActiveAssignments = new List<Assignment>(); public readonly List<Assignment> CompletedAssignments = new List<Assignment>(); public readonly List<ulong> ExcludeTargetIds = new List<ulong>(); public readonly List<(NetworkObject, int)> SyncedRewardValues = new List<(NetworkObject, int)>(); public string[] EnemyWhitelist = new string[0]; public int[] EnemyWeights = new int[0]; public int[] EnemyRewards = new int[0]; public string[] AssignmentWhitelist = new string[0]; public int[] AssignmentWeights = new int[0]; public Assignment? CurrentAssignment; public bool AssignAllPlayers; public bool AllPlayersComplete; public void ParseStringArray(ref string[] array, ConfigEntry<string> data) { string[] array2 = GetConfigValue(data).Split(',', StringSplitOptions.RemoveEmptyEntries); array = new string[array2.Length]; for (int i = 0; i < array2.Length; i++) { array[i] = array2[i].TrimEnd(',').TrimStart(','); } } public void ParseIntArray(ref int[] array, ConfigEntry<string> data) { string[] array2 = GetConfigValue(data).Split(',', StringSplitOptions.RemoveEmptyEntries); array = new int[array2.Length]; for (int i = 0; i < array2.Length; i++) { string s = array2[i].TrimEnd(',').TrimStart(','); if (int.TryParse(s, out var result)) { array[i] = result; } else { array[i] = 0; } } } private string GetConfigValue(ConfigEntry<string> data) { string text = data.Value; if (string.IsNullOrWhiteSpace(text)) { text = (string)((ConfigEntryBase)data).DefaultValue; } return text; } } public static class PAEventTags { public const string PREFIX = "PA-"; public const string RESET = "PA-Reset"; public const string ALLOCATION = "PA-Allocation"; public const string COMPLETE = "PA-Complete"; public const string FAILED = "PA-Failed"; } } namespace PersonalAssignments.Components { public class GameStateSync : MonoBehaviour { private const string COMPANY_BUILDING_SCENE = "CompanyBuilding"; private GameContext _gameContext; private NetworkUtils _networkUtils; private bool _hasLanded; public void Inject(GameContext gameContext, NetworkUtils networkUtils) { _gameContext = gameContext; _networkUtils = networkUtils; } public void Update() { if (!_networkUtils.IsConnected || (Object)(object)StartOfRound.Instance == (Object)null) { _gameContext.GameState = GameStateEnum.MainMenu; } else if (StartOfRound.Instance.inShipPhase && _hasLanded) { _hasLanded = false; _gameContext.GameState = GameStateEnum.Orbit; } else if (StartOfRound.Instance.shipHasLanded && !_hasLanded) { _hasLanded = true; Debug.Log((object)("Landed on moon : " + RoundManager.Instance.currentLevel.sceneName)); if (RoundManager.Instance.currentLevel.sceneName == "CompanyBuilding") { _gameContext.GameState = GameStateEnum.CompanyHQ; } else { _gameContext.GameState = GameStateEnum.Level; } } } } public class KillableEnemiesOutput : MonoBehaviour { private const string OUTPUT_PATH = "/../BepInEx/config2/KillableEnemies.md"; private const string OUTPUT_PREFIX = "#KILLABLE ENEMIES LIST\r\nCopy the names from this list into the enemy assignment whilelist config entry to allow them to spawn.\r\nNote that some enemies would normally be spawnable on certain maps only, I'm not sure how well some\r\nenemies will handle being spawned on those maps but they should work I would have thought."; public void Update() { if (!((Object)(object)StartOfRound.Instance == (Object)null)) { OutputList(); Object.Destroy((Object)(object)this); } } private void OutputList() { List<string> list = new List<string>(); string text = "#KILLABLE ENEMIES LIST\r\nCopy the names from this list into the enemy assignment whilelist config entry to allow them to spawn.\r\nNote that some enemies would normally be spawnable on certain maps only, I'm not sure how well some\r\nenemies will handle being spawned on those maps but they should work I would have thought."; SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { foreach (SpawnableEnemyWithRarity enemy in val.Enemies) { if (!list.Contains(enemy.enemyType.enemyName) && enemy.enemyType.canDie) { list.Add(enemy.enemyType.enemyName); text = text + "\n" + enemy.enemyType.enemyName; } } } try { FileStream fileStream = File.OpenWrite(Application.dataPath + "/../BepInEx/config2/KillableEnemies.md"); using (StreamWriter streamWriter = new StreamWriter(fileStream)) { streamWriter.Write(text); } fileStream.Close(); } catch (Exception ex) { Debug.Log((object)ex); } } } public class UpdateChecker : MonoBehaviour { public const string EXPECTED_VERSION = "1.1.0"; public const int MAINMENU_BUILDINDEX = 2; public const string THUNDERSTORE_URL = "https://thunderstore.io/package/download/amnsoft/EmployeeAssignments/"; private UnityWebRequestAsyncOperation _webRequest; public bool IsLatestVersion { get; private set; } private void Awake() { SceneManager.sceneLoaded += OnSceneLoaded; } private void OnSceneLoaded(Scene scene, LoadSceneMode sceneMode) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown if (((Scene)(ref scene)).buildIndex == 2) { UnityWebRequest val = new UnityWebRequest("https://thunderstore.io/package/download/amnsoft/EmployeeAssignments/" + "1.1.0"); _webRequest = val.SendWebRequest(); ((AsyncOperation)_webRequest).completed += OnComplete; SceneManager.sceneLoaded -= OnSceneLoaded; } } private void OnComplete(AsyncOperation obj) { IsLatestVersion = _webRequest.webRequest.responseCode == 404; if (!IsLatestVersion) { MenuManager val = Object.FindObjectOfType<MenuManager>(); ((TMP_Text)val.menuNotificationText).SetText("Employee Assignments mod is out of date, new version is atleast 1.1.0. Please update the mod.", true); ((TMP_Text)val.menuNotificationButtonText).SetText("[ CLOSE ]", true); val.menuNotification.SetActive(true); } _webRequest = null; } } } namespace PersonalAssignments.AssignmentLogic { public class CollectScrapLogic : IAssignmentLogic { private readonly PAContext _context; public CollectScrapLogic(PAContext context) { _context = context; } public bool ServerSetupAssignment(ref Assignment assignment) { GrabbableObject[] array = Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0); for (int i = 0; i < array.Length; i++) { if (!_context.ExcludeTargetIds.Contains(((NetworkBehaviour)array[i]).NetworkObjectId) && !array[i].scrapPersistedThroughRounds && array[i].itemProperties.isScrap) { assignment.TargetIds[0] = ((NetworkBehaviour)array[i]).NetworkObjectId; assignment.TargetText = array[i].itemProperties.itemName.ToUpper(); _context.ExcludeTargetIds.Add(((NetworkBehaviour)array[i]).NetworkObjectId); return true; } } return false; } public bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer) { if (!localPlayer) { return false; } GrabbableObject[] array = Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0); for (int i = 0; i < array.Length; i++) { if (((NetworkBehaviour)array[i]).NetworkObjectId == assignment.TargetIds[0]) { assignment.TargetText = array[i].itemProperties.itemName.ToUpper(); ScanNodeProperties componentInChildren = ((Component)array[i]).gameObject.GetComponentInChildren<ScanNodeProperties>(); if ((Object)(object)componentInChildren == (Object)null) { Debug.LogError((object)("Scan node is missing for item!: " + ((Object)((Component)array[i]).gameObject).name)); return false; } componentInChildren.headerText = "ASSIGNMENT TARGET"; componentInChildren.subText = "Value : ???"; break; } } return true; } public AssignmentState CheckCompletion(ref Assignment assignment) { foreach (GrabbableObject item in RoundManager.Instance.scrapCollectedThisRound) { if (item.isInShipRoom && ((NetworkBehaviour)item).NetworkObjectId == assignment.TargetIds[0]) { if (_context.AllPlayersComplete || ((NetworkBehaviour)item).OwnerClientId == assignment.PlayerId) { return AssignmentState.Complete; } return AssignmentState.Failed; } } return AssignmentState.InProgress; } public void CompleteAssignment(ref Assignment assignment, bool localPlayer) { if (((NetworkBehaviour)RoundManager.Instance).NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(assignment.TargetIds[0], out var value)) { GrabbableObject component = ((Component)value).gameObject.GetComponent<GrabbableObject>(); component.SetScrapValue(assignment.CashReward + component.scrapValue); ScanNodeProperties componentInChildren = ((Component)component).gameObject.GetComponentInChildren<ScanNodeProperties>(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.headerText = component.itemProperties.itemName; } if (NetworkManager.Singleton.IsHost) { _context.SyncedRewardValues.Add((((NetworkBehaviour)component).NetworkObject, component.scrapValue)); } } } } public class HuntAndKillLogic : IAssignmentLogic { private const float MAX_SPAWNDISTANCE = 20f; private const float MAX_PLAYERDISTANCE = 10f; private const string REWARD = "Gold bar"; private readonly PAContext _context; public HuntAndKillLogic(PAContext context) { _context = context; } public bool ServerSetupAssignment(ref Assignment assignment) { //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0335: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)RoundManager.Instance == (Object)null) { return false; } int num = Utils.WeightedRandom(_context.EnemyWeights); string text = _context.EnemyWhitelist[num]; assignment.CashReward = _context.EnemyRewards[num]; bool flag = false; for (int i = 0; i < RoundManager.Instance.SpawnedEnemies.Count; i++) { EnemyAI val = RoundManager.Instance.SpawnedEnemies[i]; if (!(val.enemyType.enemyName != text) && ((NetworkBehaviour)val).IsSpawned && !val.isEnemyDead && !_context.ExcludeTargetIds.Contains(((NetworkBehaviour)val).NetworkObjectId)) { assignment.TargetIds[0] = ((NetworkBehaviour)val).NetworkObjectId; assignment.TargetText = val.enemyType.enemyName.ToUpper(); _context.ExcludeTargetIds.Add(((NetworkBehaviour)val).NetworkObjectId); flag = true; ScanNodeProperties componentInChildren = ((Component)val).gameObject.GetComponentInChildren<ScanNodeProperties>(); componentInChildren.headerText = "ASSIGNMENT TARGET"; break; } } if (!flag) { SpawnableEnemyWithRarity val2 = null; num = 0; for (int j = 0; j < RoundManager.Instance.currentLevel.Enemies.Count; j++) { if (RoundManager.Instance.currentLevel.Enemies[j].enemyType.enemyName == text) { val2 = RoundManager.Instance.currentLevel.Enemies[j]; num = j; break; } } if (val2 == null) { return false; } Vector3 val3 = Vector3.zero; EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>(); for (int k = 0; k < array.Length; k++) { if (!array[k].isEntranceToBuilding && array[k].entranceId == 0) { val3 = ((Component)array[k]).transform.position; } } List<(EnemyVent, float)> list = new List<(EnemyVent, float)>(); EnemyVent[] allEnemyVents = RoundManager.Instance.allEnemyVents; foreach (EnemyVent val4 in allEnemyVents) { list.Add((val4, Vector3.Distance(val4.floorNode.position, val3))); } list = list.OrderByDescending<(EnemyVent, float), float>(((EnemyVent vent, float distance) a) => a.distance).ToList(); bool flag2 = false; int num2 = 0; Vector3 val5 = Vector3.zero; NavMeshHit val6 = default(NavMeshHit); while (!flag2 && num2 < 5) { EnemyVent item = list[Random.Range(0, list.Count / 2)].Item1; flag2 = NavMesh.SamplePosition(item.floorNode.position, ref val6, 20f, -1); val5 = ((NavMeshHit)(ref val6)).position; num2++; } if (!flag2) { return false; } RoundManager.Instance.SpawnEnemyOnServer(val5, 0f, num); ulong[] targetIds = assignment.TargetIds; List<EnemyAI> spawnedEnemies = RoundManager.Instance.SpawnedEnemies; targetIds[0] = ((NetworkBehaviour)spawnedEnemies[spawnedEnemies.Count - 1]).NetworkObjectId; List<EnemyAI> spawnedEnemies2 = RoundManager.Instance.SpawnedEnemies; assignment.TargetText = spawnedEnemies2[spawnedEnemies2.Count - 1].enemyType.enemyName.ToUpper(); _context.ExcludeTargetIds.Add(assignment.TargetIds[0]); List<EnemyAI> spawnedEnemies3 = RoundManager.Instance.SpawnedEnemies; ScanNodeProperties componentInChildren2 = ((Component)spawnedEnemies3[spawnedEnemies3.Count - 1]).gameObject.GetComponentInChildren<ScanNodeProperties>(); componentInChildren2.headerText = "ASSIGNMENT TARGET"; } return true; } public bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer) { foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies) { if (((NetworkBehaviour)spawnedEnemy).NetworkObjectId == assignment.TargetIds[0]) { assignment.TargetText = spawnedEnemy.enemyType.enemyName.ToUpper(); ScanNodeProperties componentInChildren = ((Component)spawnedEnemy).gameObject.GetComponentInChildren<ScanNodeProperties>(); componentInChildren.headerText = "ASSIGNMENT TARGET"; return true; } } return true; } public AssignmentState CheckCompletion(ref Assignment assignment) { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies) { if (((NetworkBehaviour)spawnedEnemy).NetworkObjectId != assignment.TargetIds[0] || !spawnedEnemy.isEnemyDead) { continue; } float num = float.MaxValue; foreach (NetworkClient connectedClients in NetworkManager.Singleton.ConnectedClientsList) { float num2 = Vector3.Distance(((Component)connectedClients.PlayerObject).transform.position, ((Component)spawnedEnemy.agent).transform.position); if (num2 < num) { num = num2; } } if (num < 10f) { return AssignmentState.Complete; } return AssignmentState.Failed; } return AssignmentState.InProgress; } public void CompleteAssignment(ref Assignment assignment, bool localPlayer) { //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsHost) { return; } foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies) { if (((NetworkBehaviour)spawnedEnemy).NetworkObjectId == assignment.TargetIds[0]) { GameObject val = (from a in StartOfRound.Instance.allItemsList.itemsList?.Where((Item a) => a.itemName == "Gold bar") select a.spawnPrefab).First(); GameObject val2 = Object.Instantiate<GameObject>(val, spawnedEnemy.serverPosition, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer); GrabbableObject component = val2.GetComponent<GrabbableObject>(); ((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation); component.fallTime = 0f; component.SetScrapValue(assignment.CashReward); NetworkObject component2 = val2.GetComponent<NetworkObject>(); component2.Spawn(false); _context.SyncedRewardValues.Add((component2, assignment.CashReward)); break; } } } } public interface IAssignmentLogic { bool ServerSetupAssignment(ref Assignment assignment); bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer); AssignmentState CheckCompletion(ref Assignment assignment); void CompleteAssignment(ref Assignment assignment, bool localPlayer); } public enum AssignmentState { InProgress, Complete, Failed } public class RepairValveLogic : IAssignmentLogic { private readonly PAContext _context; public RepairValveLogic(PAContext context) { _context = context; } public bool ServerSetupAssignment(ref Assignment assignment) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) SteamValveHazard[] array = Object.FindObjectsByType<SteamValveHazard>((FindObjectsSortMode)0); if (array.Length == 0) { return false; } Vector3 val = RoundManager.FindMainEntrancePosition(false, false); float num = 0f; int num2 = 0; for (int i = 0; i < array.Length; i++) { float num3 = Vector3.Distance(val, ((Component)array[i]).transform.position); if (num3 > num && num3 > 80f) { num2 = i; num = num3; } } if (!_context.ExcludeTargetIds.Contains(((NetworkBehaviour)array[num2]).NetworkObjectId) && ((NetworkBehaviour)array[num2]).IsSpawned) { assignment.TargetIds[0] = ((NetworkBehaviour)array[num2]).NetworkObjectId; _context.ExcludeTargetIds.Add(((NetworkBehaviour)array[num2]).NetworkObjectId); array[num2].valveCrackTime = 0.001f; array[num2].valveBurstTime = 0.01f; array[num2].triggerScript.interactable = true; assignment.FixedTargetPosition = ((Component)array[num2]).gameObject.transform.position; return true; } return false; } public bool HandleAllocationEvent(ref Assignment assignment, bool localPlayer) { return true; } public AssignmentState CheckCompletion(ref Assignment assignment) { SteamValveHazard[] array = Object.FindObjectsOfType<SteamValveHazard>(); SteamValveHazard[] array2 = array; foreach (SteamValveHazard val in array2) { if (((NetworkBehaviour)val).NetworkObjectId == assignment.TargetIds[0] && !val.triggerScript.interactable) { if (_context.AllPlayersComplete || ((NetworkBehaviour)val.triggerScript).OwnerClientId == assignment.PlayerId) { return AssignmentState.Complete; } return AssignmentState.Failed; } } return AssignmentState.InProgress; } public void CompleteAssignment(ref Assignment assignment, bool localPlayer) { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsHost) { return; } SteamValveHazard[] array = Object.FindObjectsOfType<SteamValveHazard>(); SteamValveHazard[] array2 = array; foreach (SteamValveHazard val in array2) { if (((NetworkBehaviour)val).NetworkObjectId == assignment.TargetIds[0]) { GameObject val2 = (from a in StartOfRound.Instance.allItemsList.itemsList?.Where((Item a) => a.itemName == "Gold bar") select a.spawnPrefab).First(); GameObject val3 = Object.Instantiate<GameObject>(val2, ((Component)val).gameObject.transform.position, Quaternion.identity, RoundManager.Instance.spawnedScrapContainer); GrabbableObject component = val3.GetComponent<GrabbableObject>(); ((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation); component.fallTime = 0f; component.SetScrapValue(assignment.CashReward); NetworkObject component2 = val3.GetComponent<NetworkObject>(); component2.Spawn(false); _context.SyncedRewardValues.Add((component2, assignment.CashReward)); break; } } } } }
BepInEx/plugins/FasterItemDropship.dll
Decompiled a year agousing System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("FasterItemDropship")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("Mod made by flipf17")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FasterItemDropship")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("a5a250fd-b706-48b9-9be9-da360fd939dc")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace FasterItemDropship { public static class ConfigSettings { public static ConfigEntry<int> dropshipDeliveryTime; public static ConfigEntry<int> dropshipMaxStayDuration; public static ConfigEntry<int> dropshipLeaveAfterSecondsOpenDoors; public static void BindConfigSettings() { Plugin.Log("BindingConfigs"); dropshipDeliveryTime = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("FasterItemDropship", "DeliveryTime", 10, "How long it takes (in seconds) for the item dropship to arrive."); dropshipMaxStayDuration = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("FasterItemDropship", "MaxLandDuration", 40, "The max duration (in seconds) the item dropship will stay."); dropshipLeaveAfterSecondsOpenDoors = ((BaseUnityPlugin)Plugin.instance).Config.Bind<int>("FasterItemDropship", "LeaveAfterSecondsOpenDoors", 3, "How long (in seconds) the item dropship will stay for after opening its doors."); } } [BepInPlugin("FlipMods.FasterItemDropship", "FasterItemDropship", "1.2.0")] public class Plugin : BaseUnityPlugin { private Harmony _harmony; public static Plugin instance; private void Awake() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown instance = this; ConfigSettings.BindConfigSettings(); _harmony = new Harmony("FasterItemDropship"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"FasterItemDropship loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.FasterItemDropship"; public const string PLUGIN_NAME = "FasterItemDropship"; public const string PLUGIN_VERSION = "1.2.0"; } } namespace FasterItemDropship.Patches { [HarmonyPatch] internal class FasterItemDropshipPatcher { private static Terminal terminalScript; private static StartOfRound playersManager; private static List<int> itemsToDeliver; private static List<int> orderedItemsFromTerminal; [HarmonyPatch(typeof(ItemDropship), "Start")] [HarmonyPrefix] public static void InitializeDropship(ItemDropship __instance) { playersManager = Object.FindObjectOfType<StartOfRound>(); terminalScript = Object.FindObjectOfType<Terminal>(); itemsToDeliver = (List<int>)Traverse.Create((object)__instance).Field("itemsToDeliver").GetValue(); } [HarmonyPatch(typeof(Terminal), "Start")] [HarmonyPrefix] public static void InitializeTerminal(Terminal __instance) { orderedItemsFromTerminal = __instance.orderedItemsFromTerminal; } [HarmonyPatch(typeof(ItemDropship), "Update")] [HarmonyPrefix] public static void DropshipUpdate(ItemDropship __instance) { if (((NetworkBehaviour)__instance).IsServer && !__instance.deliveringOrder && terminalScript.orderedItemsFromTerminal.Count > 0 && !playersManager.shipHasLanded) { __instance.shipTimer += Time.deltaTime; } } [HarmonyPatch(typeof(ItemDropship), "Update")] private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldc_R4) { if ((float)list[i].operand == 20f) { list[i].operand = (float)ConfigSettings.dropshipMaxStayDuration.Value; } else if ((float)list[i].operand == 40f) { list[i].operand = (float)(ConfigSettings.dropshipMaxStayDuration.Value + ConfigSettings.dropshipDeliveryTime.Value); } else if ((float)list[i].operand == 30f) { list[i].operand = (float)ConfigSettings.dropshipMaxStayDuration.Value; break; } } } return list.AsEnumerable(); } [HarmonyPatch(typeof(ItemDropship), "OpenShipDoorsOnServer")] [HarmonyPostfix] public static void OnOpenShipDoors(ItemDropship __instance) { if (((NetworkBehaviour)__instance).IsServer) { __instance.shipTimer = Mathf.Max(__instance.shipTimer, (float)(ConfigSettings.dropshipMaxStayDuration.Value - ConfigSettings.dropshipLeaveAfterSecondsOpenDoors.Value)); } } [HarmonyPatch(typeof(ItemDropship), "ShipLandedAnimationEvent")] [HarmonyPrefix] public static void AddLateItemsServer(ItemDropship __instance) { if (((NetworkBehaviour)__instance).IsServer && __instance.shipLanded && !__instance.shipDoorsOpened) { while (orderedItemsFromTerminal.Count > 0 && itemsToDeliver.Count < 12) { itemsToDeliver.Add(orderedItemsFromTerminal[0]); orderedItemsFromTerminal.RemoveAt(0); } } } } }
BepInEx/plugins/firearmlicense.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using LethalLib.Modules; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("firearmlicense")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Allows you to purchase Nutcracker shotguns from the store")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0")] [assembly: AssemblyProduct("firearmlicense")] [assembly: AssemblyTitle("firearmlicense")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 firearmlicense { public static class PluginInfo { public const string PLUGIN_GUID = "firearmlicense"; public const string PLUGIN_NAME = "firearmlicense"; public const string PLUGIN_VERSION = "1.1.0"; } } namespace enemyalert { [BepInPlugin("firearmlicense", "firearmlicense", "1.1.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInProcess("Lethal Company.exe")] public class Plugin : BaseUnityPlugin { public static ManualLogSource Log; private static ConfigEntry<int> gunPrice; private static ConfigEntry<bool> gunEnabled; private static ConfigEntry<int> shellPrice; private static ConfigEntry<bool> shellEnabled; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Log.LogInfo((object)"firearmlicense v. 1.1.0"); Log.LogInfo((object)"Allows you to purchase Nutcracker shotguns from the store"); gunPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Shotgun", "StorePrice", 1000, "Store price for the Nutcracker shotgun"); gunEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Shotgun", "Enabled", true, "If true, the shotgun will be available in store"); shellPrice = ((BaseUnityPlugin)this).Config.Bind<int>("Shotgun", "ShellStorePrice", 200, "Store price for the shotgun shells"); shellEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Shotgun", "ShellEnabled", true, "If true, the shotgun shells will be available in store"); SceneManager.sceneLoaded += OnSceneLoaded; } private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (gunEnabled.Value) { Item obj = Object.Instantiate<Item>(getItem("Shotgun")); ((Object)obj).name = "PurchasableShotgun"; obj.isScrap = false; obj.creditsWorth = gunPrice.Value; TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val).name = "ShotgunInfoNode"; val.displayText = "The Company takes no liability for casualties inflicted by this item. Remember the 5 firearm handling rules: [INFORMATION EXPUNGED]\n\n"; val.clearPreviousText = true; val.maxCharactersToType = 25; Items.RegisterShopItem(obj, (TerminalNode)null, (TerminalNode)null, val, gunPrice.Value); Log.LogInfo((object)$"shotgun added to the store with price {gunPrice.Value}"); } if (shellEnabled.Value) { Item obj2 = Object.Instantiate<Item>(getItem("GunAmmo")); ((Object)obj2).name = "PurchasableShells"; obj2.isScrap = false; obj2.creditsWorth = shellPrice.Value; TerminalNode val2 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val2).name = "ShellInfoNode"; val2.displayText = "Ammo required for the shotgun to remain a practical weapon.\n\n"; val2.clearPreviousText = true; val2.maxCharactersToType = 25; Items.RegisterShopItem(obj2, (TerminalNode)null, (TerminalNode)null, val2, shellPrice.Value); Log.LogInfo((object)$"shells added to the store with price {shellPrice.Value}"); } } private static Item getItem(string v) { Item[] array = Resources.FindObjectsOfTypeAll<Item>(); foreach (Item val in array) { if (((Object)val).name == v) { return val; } } return null; } } }
BepInEx/plugins/Goblin.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using JesterMusic; using LC_API.BundleAPI; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("Goblin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Goblin")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("550de047-daa4-4fda-9dfa-0b34a799754e")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace MyWay { [BepInPlugin("My.Way", "MyWay", "1.0.0.0")] public class MyWayBase : BaseUnityPlugin { private const string modGUID = "My.Way"; private const string modName = "MyWay"; private const string modVersion = "1.0.0.0"; private readonly Harmony harmony = new Harmony("My.Way"); private static MyWayBase Instance; internal ManualLogSource mls; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("My.Way"); mls.LogInfo((object)"My Way has awoken:"); harmony.PatchAll(typeof(MyWayBase)); harmony.PatchAll(typeof(AudioPatch)); } } } namespace JesterMusic { [HarmonyPatch(typeof(JesterAI), "Start")] internal class AudioPatch { private static void Postfix(JesterAI __instance) { __instance.screamingSFX = BundleLoader.GetLoadedAsset<AudioClip>("Assets/assetbundle/Audio/MyWay.wav"); } } }
BepInEx/plugins/HDLethalCompany.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using GameNetcodeStuff; using HDLethalCompany.Patch; using HDLethalCompany.Tools; using HarmonyLib; using TMPro; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("HDLethalCompanyRemake")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HDLethalCompanyRemake")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("7f379bc1-1fd4-4c72-9247-a181862eec6b")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace HDLethalCompany { [BepInPlugin("HDLethalCompany", "HDLethalCompany-Sligili", "1.5.6")] public class HDLethalCompanyInitialization : BaseUnityPlugin { private static ConfigEntry<float> config_ResMult; private static ConfigEntry<bool> config_EnablePostProcessing; private static ConfigEntry<bool> config_EnableFog; private static ConfigEntry<bool> config_EnableAntialiasing; private static ConfigEntry<bool> config_EnableResolution; private static ConfigEntry<bool> config_EnableFoliage; private static ConfigEntry<int> config_FogQuality; private static ConfigEntry<int> config_TextureQuality; private static ConfigEntry<int> config_LOD; private static ConfigEntry<int> config_ShadowmapQuality; private Harmony _harmony; private void Awake() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown ((BaseUnityPlugin)this).Logger.LogInfo((object)"HDLethalCompany loaded"); ConfigFile(); GraphicsPatch.assetBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "HDLethalCompany/hdlethalcompany")); _harmony = new Harmony("HDLethalCompany"); _harmony.PatchAll(typeof(GraphicsPatch)); } private void ConfigFile() { config_ResMult = ((BaseUnityPlugin)this).Config.Bind<float>("RESOLUTION", "Value", 2.233f, "Resolution Scale Multiplier - <EXAMPLES -> | 1.000 = 860x520p | 2.233 =~ 1920x1080p | 2.977 = 2560x1440p | 4.465 = 3840x2060p > - The UI scanned elements have slightly incorrect offsets after 3.000"); config_EnableResolution = ((BaseUnityPlugin)this).Config.Bind<bool>("RESOLUTION", "EnableRes", true, "Resolution Fix - In case you wanna use another resolution mod or apply any widescreen mod while keeping the graphics settings"); config_EnableAntialiasing = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnableAA", false, "Anti-Aliasing (Unity's SMAA)"); config_EnablePostProcessing = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnablePP", true, "Post-Processing (Color grading)"); config_TextureQuality = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "TextureQuality", 3, "Texture Resolution Quality - <PRESETS -> | 0 = VERY LOW (1/8) | 1 = LOW (1/4) | 2 = MEDIUM (1/2) | 3 = HIGH (1/1 VANILLA) >"); config_FogQuality = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "FogQuality", 1, "Volumetric Fog Quality - <PRESETS -> | 0 = VERY LOW | 1 = VANILLA FOG | 2 = MEDIUM | 3 = HIGH >"); config_EnableFog = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnableFOG", true, "Volumetric Fog Toggle - Use this as a last resource in case lowering the fog quality is not enough to get decent performance"); config_LOD = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "LOD", 1, "Level Of Detail - <PRESETS -> | 0 = LOW (HALF DISTANCE) | 1 = VANILLA | 2 = HIGH (TWICE THE DISTANCE) >"); config_ShadowmapQuality = ((BaseUnityPlugin)this).Config.Bind<int>("EFFECTS", "ShadowQuality", 3, "Shadows Resolution - <PRESETS -> 0 = VERY LOW (SHADOWS DISABLED)| 1 = LOW (256) | 2 = MEDIUM (1024) | 3 = VANILLA (2048) > - Shadowmap max resolution"); config_EnableFoliage = ((BaseUnityPlugin)this).Config.Bind<bool>("EFFECTS", "EnableF", true, "Foliage Toggle - If the game camera should or not render bushes/grass (trees won't be affected)"); GraphicsPatch.m_enableFoliage = config_EnableFoliage.Value; GraphicsPatch.m_enableResolutionFix = config_EnableResolution.Value; GraphicsPatch.m_setShadowQuality = config_ShadowmapQuality.Value; GraphicsPatch.m_setLOD = config_LOD.Value; GraphicsPatch.m_setTextureResolution = config_TextureQuality.Value; GraphicsPatch.m_setFogQuality = config_FogQuality.Value; GraphicsPatch.multiplier = config_ResMult.Value; GraphicsPatch.anchorOffsetZ = 0.123f * config_ResMult.Value + 0.877f; GraphicsPatch.m_widthResolution = 860f * config_ResMult.Value; GraphicsPatch.m_heightResolution = 520f * config_ResMult.Value; GraphicsPatch.m_enableAntiAliasing = config_EnableAntialiasing.Value; GraphicsPatch.m_enableFog = config_EnableFog.Value; GraphicsPatch.m_enablePostProcessing = config_EnablePostProcessing.Value; } } public static class PluginInfo { public const string Guid = "HDLethalCompany"; public const string Name = "HDLethalCompany-Sligili"; public const string Ver = "1.5.6"; } } namespace HDLethalCompany.Tools { public class Reflection { public static object GetInstanceField(Type type, object instance, string fieldName) { BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; FieldInfo field = type.GetField(fieldName, bindingAttr); return field.GetValue(instance); } public static object CallMethod(object instance, string methodName, params object[] args) { MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic); if (method != null) { return method.Invoke(instance, args); } return null; } } } namespace HDLethalCompany.Patch { internal class GraphicsPatch { public static bool m_enablePostProcessing; public static bool m_enableFog; public static bool m_enableAntiAliasing; public static bool m_enableResolutionFix; public static bool m_enableFoliage = true; public static int m_setFogQuality; public static int m_setTextureResolution; public static int m_setLOD; public static int m_setShadowQuality; private static HDRenderPipelineAsset myAsset; public static AssetBundle assetBundle; public static float anchorOffsetX = 439.48f; public static float anchorOffsetY = 244.8f; public static float anchorOffsetZ; public static float multiplier; public static float m_widthResolution; public static float m_heightResolution; [HarmonyPatch(typeof(PlayerControllerB), "Start")] [HarmonyPrefix] private static void StartPrefix(PlayerControllerB __instance) { //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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) Object[] array = Resources.FindObjectsOfTypeAll(typeof(HDAdditionalCameraData)); foreach (Object obj in array) { HDAdditionalCameraData val = (HDAdditionalCameraData)(object)((obj is HDAdditionalCameraData) ? obj : null); if (!(((Object)((Component)val).gameObject).name == "MapCamera")) { val.customRenderingSettings = true; ToggleCustomPass(val, m_enablePostProcessing); SetLevelOfDetail(val); ToggleVolumetricFog(val, m_enableFog); if (!m_enableFoliage) { LayerMask val2 = LayerMask.op_Implicit(((Component)val).GetComponent<Camera>().cullingMask); val2 = LayerMask.op_Implicit(LayerMask.op_Implicit(val2) & -1025); ((Component)val).GetComponent<Camera>().cullingMask = LayerMask.op_Implicit(val2); } SetShadowQuality(assetBundle, val); if (!(((Object)((Component)val).gameObject).name == "SecurityCamera") && !(((Object)((Component)val).gameObject).name == "ShipCamera")) { SetAntiAliasing(val); } } } array = null; SetTextureQuality(); SetFogQuality(); if (m_enableResolutionFix && multiplier != 1f) { int width = (int)Math.Round(m_widthResolution, 0); int height = (int)Math.Round(m_heightResolution, 0); ((Texture)__instance.gameplayCamera.targetTexture).width = width; ((Texture)__instance.gameplayCamera.targetTexture).height = height; } } [HarmonyPatch(typeof(RoundManager), "GenerateNewFloor")] [HarmonyPrefix] private static void RoundPostFix() { SetFogQuality(); if (m_setLOD == 0) { RemoveLodFromGameObject("CatwalkStairs"); } } [HarmonyPatch(typeof(HUDManager), "UpdateScanNodes")] [HarmonyPostfix] private static void UpdateScanNodesPostfix(PlayerControllerB playerScript, HUDManager __instance) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_02fe: Unknown result type (might be due to invalid IL or missing references) if (anchorOffsetZ > 1.238f) { anchorOffsetZ = 1.238f; } if (!m_enableResolutionFix || multiplier == 1f) { return; } Vector3 zero = Vector3.zero; bool flag = false; for (int i = 0; i < __instance.scanElements.Length; i++) { if ((Traverse.Create((object)__instance).Field("scanNodes").GetValue() as Dictionary<RectTransform, ScanNodeProperties>).Count > 0 && (Traverse.Create((object)__instance).Field("scanNodes").GetValue() as Dictionary<RectTransform, ScanNodeProperties>).TryGetValue(__instance.scanElements[i], out var value) && (Object)(object)value != (Object)null) { try { if ((bool)Reflection.CallMethod(__instance, "NodeIsNotVisible", value, i)) { continue; } if (!((Component)__instance.scanElements[i]).gameObject.activeSelf) { ((Component)__instance.scanElements[i]).gameObject.SetActive(true); ((Component)__instance.scanElements[i]).GetComponent<Animator>().SetInteger("colorNumber", value.nodeType); if (value.creatureScanID != -1) { Traverse.Create((object)__instance).Method("AttemptScanNewCreature", new object[1] { value.creatureScanID }); } } goto IL_0186; } catch (Exception arg) { Debug.LogError((object)$"Error in updatescanNodes A: {arg}"); goto IL_0186; } } (Traverse.Create((object)__instance).Field("scanNodes").GetValue() as Dictionary<RectTransform, ScanNodeProperties>).Remove(__instance.scanElements[i]); ((Component)__instance.scanElements[i]).gameObject.SetActive(false); continue; IL_0186: try { Traverse.Create((object)__instance).Field("scanElementText").SetValue((object)((Component)__instance.scanElements[i]).gameObject.GetComponentsInChildren<TextMeshProUGUI>()); if ((Traverse.Create((object)__instance).Field("scanElementText").GetValue() as TextMeshProUGUI[]).Length > 1) { ((TMP_Text)(Traverse.Create((object)__instance).Field("scanElementText").GetValue() as TextMeshProUGUI[])[0]).text = value.headerText; ((TMP_Text)(Traverse.Create((object)__instance).Field("scanElementText").GetValue() as TextMeshProUGUI[])[1]).text = value.subText; } if (value.nodeType == 2) { flag = true; } zero = playerScript.gameplayCamera.WorldToScreenPoint(((Component)value).transform.position); ((Transform)__instance.scanElements[i]).position = new Vector3(((Transform)__instance.scanElements[i]).position.x, ((Transform)__instance.scanElements[i]).position.y, 12.17f * anchorOffsetZ); __instance.scanElements[i].anchoredPosition = Vector2.op_Implicit(new Vector3(zero.x - anchorOffsetX * multiplier, zero.y - anchorOffsetY * multiplier)); if (!(multiplier > 3f)) { ((Transform)__instance.scanElements[i]).localScale = new Vector3(multiplier, multiplier, multiplier); } else { ((Transform)__instance.scanElements[i]).localScale = new Vector3(3f, 3f, 3f); } } catch (Exception arg2) { Debug.LogError((object)$"Error in updatescannodes B: {arg2}"); } } try { if (!flag) { __instance.totalScrapScanned = 0; Traverse.Create((object)__instance).Field("totalScrapScannedDisplayNum").SetValue((object)0); Traverse.Create((object)__instance).Field("addToDisplayTotalInterval").SetValue((object)0.35f); } __instance.scanInfoAnimator.SetBool("display", (int)Reflection.GetInstanceField(typeof(HUDManager), __instance, "scannedScrapNum") >= 2 && flag); } catch (Exception arg3) { Debug.LogError((object)$"Error in updatescannodes C: {arg3}"); } } public static void SetShadowQuality(AssetBundle assetBundle, HDAdditionalCameraData cameraData) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)assetBundle == (Object)null) { Debug.LogError((object)"HDLETHALCOMPANY: Something is wrong with the Asset Bundle - Null"); return; } ((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[20u] = true; ((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)20, (m_setShadowQuality != 0) ? true : false); myAsset = (HDRenderPipelineAsset)((m_setShadowQuality != 1) ? ((m_setShadowQuality != 2) ? ((object)(HDRenderPipelineAsset)QualitySettings.renderPipeline) : ((object)(myAsset = assetBundle.LoadAsset<HDRenderPipelineAsset>("Assets/HDLethalCompany/MediumShadowsAsset.asset")))) : (myAsset = assetBundle.LoadAsset<HDRenderPipelineAsset>("Assets/HDLethalCompany/VeryLowShadowsAsset.asset"))); QualitySettings.renderPipeline = (RenderPipelineAsset)(object)myAsset; } public static void SetLevelOfDetail(HDAdditionalCameraData cameraData) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) if (m_setLOD != 1) { ((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[60u] = true; ((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[61u] = true; ((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)60, true); ((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)61, true); cameraData.renderingPathCustomFrameSettings.lodBiasMode = (LODBiasMode)2; cameraData.renderingPathCustomFrameSettings.lodBias = ((m_setLOD == 0) ? 0.6f : 2.3f); if (m_setLOD == 0 && ((Component)cameraData).GetComponent<Camera>().farClipPlane > 180f) { ((Component)cameraData).GetComponent<Camera>().farClipPlane = 170f; } } } public static void SetTextureQuality() { if (m_setTextureResolution < 3) { int globalTextureMipmapLimit = 3 - m_setTextureResolution; QualitySettings.globalTextureMipmapLimit = globalTextureMipmapLimit; } } public static void SetAntiAliasing(HDAdditionalCameraData cameraData) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (m_enableAntiAliasing) { cameraData.antialiasing = (AntialiasingMode)3; } } public static void ToggleCustomPass(HDAdditionalCameraData cameraData, bool enable) { ((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[6u] = true; ((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)6, enable); } public static void ToggleVolumetricFog(HDAdditionalCameraData cameraData, bool enable) { ((BitArray128)(ref cameraData.renderingPathCustomFrameSettingsOverrideMask.mask))[28u] = true; ((FrameSettings)(ref cameraData.renderingPathCustomFrameSettings)).SetEnabled((FrameSettingsField)28, enable); } public static void SetFogQuality() { Object[] array = Resources.FindObjectsOfTypeAll(typeof(Volume)); if (array.Length == 0) { Debug.LogError((object)"No volumes found"); return; } Fog val2 = default(Fog); foreach (Object obj in array) { Volume val = (Volume)(object)((obj is Volume) ? obj : null); if (val.sharedProfile.TryGet<Fog>(ref val2)) { ((VolumeParameter<int>)(object)((VolumeComponentWithQuality)val2).quality).Override(3); switch (m_setFogQuality) { case -1: val2.volumetricFogBudget = 0.05f; val2.resolutionDepthRatio = 0.5f; break; case 0: val2.volumetricFogBudget = 0.05f; val2.resolutionDepthRatio = 0.5f; break; case 2: val2.volumetricFogBudget = 0.333f; val2.resolutionDepthRatio = 0.666f; break; case 3: val2.volumetricFogBudget = 0.666f; val2.resolutionDepthRatio = 0.5f; break; } } } } public static void RemoveLodFromGameObject(string name) { Object[] array = Resources.FindObjectsOfTypeAll(typeof(LODGroup)); foreach (Object obj in array) { LODGroup val = (LODGroup)(object)((obj is LODGroup) ? obj : null); if (((Object)((Component)val).gameObject).name == name) { val.enabled = false; } } } } }
BepInEx/plugins/HealthMetrics.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("HealthMetrics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HealthMetrics")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("eba7b111-51e5-4353-807d-1268e6290901")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace HealthMetrics { [BepInPlugin("Matsuura.HealthMetrics", "HealthMetrics", "1.0.0")] public class HealthMetricsBase : BaseUnityPlugin { private const string modGUID = "Matsuura.HealthMetrics"; private const string modName = "HealthMetrics"; private const string modVersion = "1.0.0"; private readonly Harmony _harmony = new Harmony("Matsuura.HealthMetrics"); private static HealthMetricsBase _instance; private static ManualLogSource _logSource; internal void Awake() { if ((Object)(object)_instance == (Object)null) { _instance = this; } if (_logSource == null) { _logSource = Logger.CreateLogSource("Matsuura.HealthMetrics"); } _harmony.PatchAll(); _logSource.LogInfo((object)"HealthMetrics Awake"); } internal static void Log(string message) { if (_logSource != null) { _logSource.LogInfo((object)message); } } internal static void LogD(string message) { if (_logSource != null) { _logSource.LogDebug((object)message); } } } } namespace HealthMetrics.Patches { [HarmonyPatch(typeof(HUDManager))] internal class HealthHUDPatches { private static TextMeshProUGUI _healthText; private static readonly string DefaultValueHealthText = " ¤"; public static int _oldValuehealthValueForUpdater = 0; public static int _healthValueForUpdater = 100; private static readonly Color _healthyColor = Color32.op_Implicit(new Color32((byte)0, byte.MaxValue, (byte)0, byte.MaxValue)); private static readonly Color _criticalHealthColor = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)0, (byte)0, byte.MaxValue)); [HarmonyPatch("Start")] [HarmonyPostfix] private static void Start(ref HUDManager __instance) { //IL_0005: 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_0039: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("HealthHUDDisplay"); val.AddComponent<RectTransform>(); TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>(); RectTransform rectTransform = ((TMP_Text)obj).rectTransform; ((Transform)rectTransform).SetParent(((Component)__instance.PTTIcon).transform, false); rectTransform.anchoredPosition = new Vector2(8f, -57f); ((TMP_Text)obj).font = ((TMP_Text)__instance.controlTipLines[0]).font; ((TMP_Text)obj).fontSize = 16f; ((TMP_Text)obj).text = "100"; ((Graphic)obj).color = _healthyColor; ((TMP_Text)obj).overflowMode = (TextOverflowModes)0; ((Behaviour)obj).enabled = true; _healthText = obj; } [HarmonyPatch("Update")] [HarmonyPostfix] private static void Update() { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_healthText != (Object)null && _healthValueForUpdater != _oldValuehealthValueForUpdater) { _oldValuehealthValueForUpdater = _healthValueForUpdater; if (_healthValueForUpdater > 0) { ((TMP_Text)_healthText).text = _healthValueForUpdater.ToString().PadLeft((_healthValueForUpdater < 10) ? 2 : 3, ' '); } else { ((TMP_Text)_healthText).text = DefaultValueHealthText; } double percentage = (double)_healthValueForUpdater / 100.0; ((Graphic)_healthText).color = ColorInterpolation(_criticalHealthColor, _healthyColor, percentage); } } public static int LinearInterpolation(int start, int end, double percentage) { return start + (int)Math.Round(percentage * (double)(end - start)); } public static Color ColorInterpolation(Color start, Color end, double percentage) { //IL_0000: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: 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_006a: Unknown result type (might be due to invalid IL or missing references) return new Color(hexToFloat(LinearInterpolation(floatToHex(start.r), floatToHex(end.r), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.g), floatToHex(end.g), percentage)), hexToFloat(LinearInterpolation(floatToHex(start.b), floatToHex((int)end.b), percentage)), 1f); } public static float hexToFloat(int hex) { return (float)hex / 255f; } public static int floatToHex(float f) { return (int)f * 255; } } [HarmonyPatch(typeof(PlayerControllerB))] internal class PlayerPatches { [HarmonyPrefix] [HarmonyPatch("LateUpdate")] private static void LateUpdate_Prefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject)) { HealthHUDPatches._healthValueForUpdater = ((__instance.health >= 0) ? __instance.health : 0); } } } }
BepInEx/plugins/HideModList.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using HarmonyLib; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("HideModList")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Hides the LC api modlist info")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("HideModList")] [assembly: AssemblyTitle("HideModList")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 HideModList { [HarmonyPatch(typeof(HUDManager), "DisplayTip")] public static class DisplayTipPatch { public static bool Prefix(HUDManager __instance, string headerText, string bodyText, bool isWarning = false, bool useSave = false, string prefsKey = "LC_Tip1") { if (headerText.StartsWith("Mod List")) { return false; } return true; } } [BepInPlugin("HideModList", "HideModList", "1.0.0")] public class Plugin : BaseUnityPlugin { private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown Harmony val = new Harmony("plugin.HideModList"); val.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin HideModList is loaded!"); } } public static class PluginInfo { public const string PLUGIN_GUID = "HideModList"; public const string PLUGIN_NAME = "HideModList"; public const string PLUGIN_VERSION = "1.0.0"; } }
BepInEx/plugins/LaserPointerDetonator.dll
Decompiled a year agousing System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using HarmonyLib; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("LaserTweaks")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LaserTweaks")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4963e0ea-7a99-4390-9cae-a4bdd01b6b43")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } } namespace LaserPointerDetonator { public class LaserPointerTarget : MonoBehaviour { public static List<LaserPointerTarget> Instances = new List<LaserPointerTarget>(); public float radius = 0.53f; public Vector3 offset = Vector3.up * 0.1f; private const float maxTemp = 1f; private float temp; private bool triggered; private Landmine landmine; private Vector3 hitPoint; public static int Count => Instances.Count; private void Awake() { landmine = ((Component)this).GetComponent<Landmine>(); Instances.Add(this); } private void OnDestroy() { Instances.Remove(this); } public void AddTemp(Transform origin) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) if (!triggered && !landmine.hasExploded && LTDI(origin.position, origin.forward, ((Component)this).transform.position + offset, radius) && !Physics.Linecast(origin.position, hitPoint, 1051400, (QueryTriggerInteraction)1)) { temp += Time.deltaTime; if (temp > 1f) { landmine.TriggerMineOnLocalClientByExiting(); triggered = true; } } } private bool LTDI(Vector3 point, Vector3 direction, Vector3 center, float diskRadius = 1f) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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) float num = Vector3.Dot(center - point, Vector3.up) / Vector3.Dot(direction, Vector3.up); hitPoint = point + direction * num; if (num > 0f) { return Vector3.Distance(center, hitPoint) <= diskRadius; } return false; } } internal class LaserPointerRaycast : MonoBehaviour { private FlashlightItem item; private Light light { get { if (!item.usingPlayerHelmetLight || !((Object)(object)((GrabbableObject)item).playerHeldBy != (Object)null)) { return item.flashlightBulb; } return ((GrabbableObject)item).playerHeldBy.helmetLight; } } private bool state { get { if (((GrabbableObject)item).isBeingUsed) { return ((NetworkBehaviour)item).IsOwner; } return false; } } private void Awake() { item = ((Component)this).GetComponent<FlashlightItem>(); } private void Update() { if (!state || LaserPointerTarget.Count <= 0) { return; } foreach (LaserPointerTarget instance in LaserPointerTarget.Instances) { instance.AddTemp(((Component)light).transform); } } } [BepInPlugin("Kittenji.LaserPointerDetonator", "Laser Pointer Detonator", "1.0.0")] public class Loader : BaseUnityPlugin { [HarmonyPatch(typeof(Landmine))] internal class LandminePatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref Landmine __instance) { ((Component)__instance).gameObject.AddComponent<LaserPointerTarget>(); } } [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void AwakePatch(ref StartOfRound __instance) { AllItemsList allItemsList = __instance.allItemsList; if ((Object)(object)allItemsList == (Object)null) { return; } List<Item> itemsList = allItemsList.itemsList; if (itemsList != null) { Item val = itemsList.Find((Item itm) => Object.op_Implicit((Object)(object)itm.spawnPrefab) && ((Object)itm.spawnPrefab).name == "LaserPointer"); if ((Object)(object)val == (Object)null || (Object)(object)val.spawnPrefab == (Object)null) { Debug.LogError((object)"----------------- Failed to patch laser pointer item"); return; } Debug.Log((object)"--------------------- Patching GameObject prefab"); val.spawnPrefab.AddComponent<LaserPointerRaycast>(); } } } private const string modGUID = "Kittenji.LaserPointerDetonator"; private readonly Harmony harmony = new Harmony("Kittenji.LaserPointerDetonator"); private void Awake() { harmony.PatchAll(); } } }
BepInEx/plugins/LateCompanyV1.0.9.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")] [assembly: AssemblyCompany("LateCompany")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+45a32594ae7b3615a3d1703738f777272caa8e30")] [assembly: AssemblyProduct("LateCompany")] [assembly: AssemblyTitle("LateCompany")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 LateCompany { public static class PluginInfo { public const string GUID = "twig.latecompany"; public const string PrintName = "Late Company"; public const string Version = "1.0.9"; } [BepInPlugin("twig.latecompany", "Late Company", "1.0.9")] internal class Plugin : BaseUnityPlugin { private ConfigEntry<bool> configLateJoinOrbitOnly; public static bool AllowJoiningWhileLanded = false; public static bool LobbyJoinable = true; public void Awake() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown configLateJoinOrbitOnly = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Allow joining while landed", false, "Allow players to join while the ship is landed. (Will probably break some things)"); AllowJoiningWhileLanded = configLateJoinOrbitOnly.Value; Harmony val = new Harmony("twig.latecompany"); val.PatchAll(typeof(Plugin).Assembly); ((BaseUnityPlugin)this).Logger.Log((LogLevel)16, (object)"Late Company loaded!"); } public static void SetLobbyJoinable(bool joinable) { LobbyJoinable = joinable; GameNetworkManager.Instance.SetLobbyJoinable(joinable); QuickMenuManager val = Object.FindObjectOfType<QuickMenuManager>(); if (Object.op_Implicit((Object)(object)val)) { val.inviteFriendsTextAlpha.alpha = (joinable ? 1f : 0.2f); } } } } namespace LateCompany.Patches { [HarmonyPatch(typeof(GameNetworkManager), "LeaveLobbyAtGameStart")] [HarmonyWrapSafe] internal static class LeaveLobbyAtGameStart_Patch { [HarmonyPrefix] private static bool Prefix() { return false; } } [HarmonyPatch(typeof(GameNetworkManager), "ConnectionApproval")] [HarmonyWrapSafe] internal static class ConnectionApproval_Patch { [HarmonyPostfix] private static void Postfix(ConnectionApprovalRequest request, ConnectionApprovalResponse response) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (request.ClientNetworkId != NetworkManager.Singleton.LocalClientId && response.Reason.Contains("Game has already started") && Plugin.LobbyJoinable) { response.Reason = ""; response.CreatePlayerObject = false; response.Approved = true; response.Pending = false; } } } [HarmonyPatch(typeof(QuickMenuManager), "DisableInviteFriendsButton")] internal static class DisableInviteFriendsButton_Patch { [HarmonyPrefix] private static bool Prefix() { return false; } } [HarmonyPatch(typeof(QuickMenuManager), "InviteFriendsButton")] internal static class InviteFriendsButton_Patch { [HarmonyPrefix] private static bool Prefix() { if (Plugin.LobbyJoinable) { GameNetworkManager.Instance.InviteFriendsUI(); } return false; } } internal class RpcEnum : NetworkBehaviour { public static int None => 0; public static int Client => 2; public static int Server => 1; } internal static class WeatherSync { public static bool DoOverride = false; public static LevelWeatherType CurrentWeather = (LevelWeatherType)(-1); } [HarmonyPatch(typeof(RoundManager), "__rpc_handler_1193916134")] [HarmonyWrapSafe] internal static class __rpc_handler_1193916134_Patch { public static FieldInfo RPCExecStage = typeof(NetworkBehaviour).GetField("__rpc_exec_stage", BindingFlags.Instance | BindingFlags.NonPublic); [HarmonyPrefix] private static bool Prefix(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if ((Object)(object)networkManager != (Object)null && networkManager.IsListening && !networkManager.IsHost) { try { int num = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref num); int num2 = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref num2); if (((FastBufferReader)(ref reader)).Position < ((FastBufferReader)(ref reader)).Length) { int num3 = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref num3); num3 -= 255; if (num3 < 0) { throw new Exception("In case of emergency, break glass."); } WeatherSync.CurrentWeather = (LevelWeatherType)num3; WeatherSync.DoOverride = true; } RPCExecStage.SetValue(target, RpcEnum.Client); ((RoundManager)((target is RoundManager) ? target : null)).GenerateNewLevelClientRpc(num, num2); RPCExecStage.SetValue(target, RpcEnum.None); return false; } catch { WeatherSync.DoOverride = false; ((FastBufferReader)(ref reader)).Seek(0); return true; } } return true; } } [HarmonyPatch(typeof(RoundManager), "SetToCurrentLevelWeather")] internal static class SetToCurrentLevelWeather_Patch { [HarmonyPrefix] private static void Prefix() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (WeatherSync.DoOverride) { RoundManager.Instance.currentLevel.currentWeather = WeatherSync.CurrentWeather; WeatherSync.DoOverride = false; } } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")] [HarmonyWrapSafe] internal static class OnPlayerConnectedClientRpc_Patch { public static MethodInfo BeginSendClientRpc = typeof(RoundManager).GetMethod("__beginSendClientRpc", BindingFlags.Instance | BindingFlags.NonPublic); public static MethodInfo EndSendClientRpc = typeof(RoundManager).GetMethod("__endSendClientRpc", BindingFlags.Instance | BindingFlags.NonPublic); [HarmonyPostfix] private static void Postfix(ulong clientId, int connectedPlayers, ulong[] connectedPlayerIdsOrdered, int assignedPlayerObjectId, int serverMoneyAmount, int levelID, int profitQuota, int timeUntilDeadline, int quotaFulfilled, int randomSeed) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: 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_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Expected I4, but got Unknown //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; PlayerControllerB val = instance.allPlayerScripts[assignedPlayerObjectId]; if (instance.connectedPlayersAmount + 1 >= instance.allPlayerScripts.Length) { Plugin.SetLobbyJoinable(joinable: false); } val.DisablePlayerModel(instance.allPlayerObjects[assignedPlayerObjectId], true, true); if (((NetworkBehaviour)instance).IsServer && !instance.inShipPhase) { RoundManager instance2 = RoundManager.Instance; ClientRpcParams val2 = default(ClientRpcParams); val2.Send = new ClientRpcSendParams { TargetClientIds = new List<ulong> { clientId } }; ClientRpcParams val3 = val2; FastBufferWriter val4 = (FastBufferWriter)BeginSendClientRpc.Invoke(instance2, new object[3] { 1193916134u, val3, 0 }); BytePacker.WriteValueBitPacked(val4, StartOfRound.Instance.randomMapSeed); BytePacker.WriteValueBitPacked(val4, StartOfRound.Instance.currentLevelID); BytePacker.WriteValueBitPacked(val4, instance2.currentLevel.currentWeather + 255); EndSendClientRpc.Invoke(instance2, new object[4] { val4, 1193916134u, val3, 0 }); FastBufferWriter val5 = (FastBufferWriter)BeginSendClientRpc.Invoke(instance2, new object[3] { 2729232387u, val3, 0 }); EndSendClientRpc.Invoke(instance2, new object[4] { val5, 2729232387u, val3, 0 }); } instance.livingPlayers = instance.connectedPlayersAmount + 1; for (int i = 0; i < instance.allPlayerScripts.Length; i++) { PlayerControllerB val6 = instance.allPlayerScripts[i]; if (val6.isPlayerControlled && val6.isPlayerDead) { instance.livingPlayers--; } } } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerDC")] [HarmonyWrapSafe] internal static class OnPlayerDC_Patch { [HarmonyPostfix] private static void Postfix() { if (StartOfRound.Instance.inShipPhase || (Plugin.AllowJoiningWhileLanded && StartOfRound.Instance.shipHasLanded)) { Plugin.SetLobbyJoinable(joinable: true); } } } [HarmonyPatch(typeof(StartOfRound), "SetShipReadyToLand")] internal static class SetShipReadyToLand_Patch { [HarmonyPostfix] private static void Postfix() { if (StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length) { Plugin.SetLobbyJoinable(joinable: true); } } } [HarmonyPatch(typeof(StartOfRound), "StartGame")] internal static class StartGame_Patch { [HarmonyPrefix] private static void Prefix() { Plugin.SetLobbyJoinable(joinable: false); } } [HarmonyPatch(typeof(StartOfRound), "OnShipLandedMiscEvents")] internal static class OnShipLandedMiscEvents_Patch { [HarmonyPostfix] private static void Postfix() { if (Plugin.AllowJoiningWhileLanded && StartOfRound.Instance.connectedPlayersAmount + 1 < StartOfRound.Instance.allPlayerScripts.Length) { Plugin.SetLobbyJoinable(joinable: true); } } } [HarmonyPatch(typeof(StartOfRound), "ShipLeave")] internal static class ShipLeave_Patch { [HarmonyPostfix] private static void Postfix() { Plugin.SetLobbyJoinable(joinable: false); } } }
BepInEx/plugins/LaterNights.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using HarmonyLib; using LaterNights.Patches; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("LaterNights")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("LaterNights")] [assembly: AssemblyTitle("LaterNights")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] 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 LaterNights { [BepInPlugin("atk.lethalcompany.laternights", "Later Nights", "1.0.0")] public class LaterNightsMod : BaseUnityPlugin { public const string pluginGuid = "atk.lethalcompany.laternights"; public const string pluginName = "Later Nights"; public const string pluginVersion = "1.0.0"; public static Harmony harmony; public void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown harmony = new Harmony("atk.lethalcompany.laternights"); harmony.PatchAll(typeof(LaterNights.Patches.Patches)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Later Nights mod loaded"); } } } namespace LaterNights.Patches { [HarmonyPatch] internal class Patches { private static float realTotalTime; private static float offset; [HarmonyPatch(typeof(TimeOfDay), "Start")] [HarmonyPostfix] public static void Start(ref TimeOfDay __instance) { realTotalTime = __instance.lengthOfHours * (float)__instance.numberOfHours; __instance.numberOfHours = 24; __instance.totalTime = __instance.lengthOfHours * (float)__instance.numberOfHours; offset = (float)(__instance.numberOfHours - 18) / (float)__instance.numberOfHours; } [HarmonyPatch(typeof(TimeOfDay), "MoveTimeOfDay")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> MoveTimeOfDay(IEnumerable<CodeInstruction> instructions) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(typeof(Patches), "offset"); List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (list[i].opcode == OpCodes.Ldfld && list[i + 1].opcode == OpCodes.Ldc_R4 && (float)list[i + 1].operand == 0f) { list.Insert(i + 1, new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo)); list.Insert(i + 2, new CodeInstruction(OpCodes.Add, (object)null)); } } return list.AsEnumerable(); } [HarmonyPatch(typeof(HUDManager), "SetClock")] [HarmonyPrefix] public static bool SetClock(ref HUDManager __instance, ref string __result, ref string ___newLine, ref string ___amPM, float timeNormalized, float numberOfHours, bool createNewLine = true) { int num = (int)(timeNormalized * (60f * numberOfHours)) + 360; int num2 = (int)Mathf.Floor((float)(num / 60)); if (!createNewLine) { ___newLine = " "; } else { ___newLine = "\n"; } ___amPM = ___newLine + "AM"; if (num2 >= 24) { num2 %= 24; } if (num2 < 12) { ___amPM = ___newLine + "AM"; } else { ___amPM = ___newLine + "PM"; } if (num2 > 12) { num2 %= 12; } int num3 = num % 60; string text = $"{num2:00}:{num3:00}" + ___amPM; ((TMP_Text)__instance.clockNumber).text = text; __result = text; return false; } [HarmonyPatch(typeof(RoundManager), "SpawnEnemiesOutside")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> SpawnEnemiesOutside(IEnumerable<CodeInstruction> instructions) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(typeof(TimeOfDay), "totalTime"); FieldInfo fieldInfo2 = AccessTools.Field(typeof(Patches), "realTotalTime"); List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false)) { list[i] = new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo2); list.RemoveAt(i - 1); list.RemoveAt(i - 2); i -= -2; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(RoundManager), "SpawnDaytimeEnemiesOutside")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> SpawnDaytimeEnemiesOutside(IEnumerable<CodeInstruction> instructions) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(typeof(TimeOfDay), "totalTime"); FieldInfo fieldInfo2 = AccessTools.Field(typeof(Patches), "realTotalTime"); List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false)) { list[i] = new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo2); list.RemoveAt(i - 1); list.RemoveAt(i - 2); i -= -2; } } return list.AsEnumerable(); } [HarmonyPatch(typeof(RoundManager), "SpawnRandomDaytimeEnemy")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> SpawnRandomDaytimeEnemy(IEnumerable<CodeInstruction> instructions) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(typeof(TimeOfDay), "totalTime"); FieldInfo fieldInfo2 = AccessTools.Field(typeof(TimeOfDay), "normalizedTimeOfDay"); FieldInfo fieldInfo3 = AccessTools.Field(typeof(Patches), "realTotalTime"); FieldInfo fieldInfo4 = AccessTools.Field(typeof(Patches), "offset"); List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false)) { list[i] = new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo3); list.RemoveAt(i - 1); list.RemoveAt(i - 2); i -= -2; } else if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo2, false)) { list.Insert(i + 1, new CodeInstruction(OpCodes.Add, (object)null)); list.Insert(i + 1, new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo4)); } } return list.AsEnumerable(); } [HarmonyPatch(typeof(RoundManager), "AssignRandomEnemyToVent")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> AssignRandomEnemyToVent(IEnumerable<CodeInstruction> instructions) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(typeof(TimeOfDay), "totalTime"); FieldInfo fieldInfo2 = AccessTools.Field(typeof(TimeOfDay), "normalizedTimeOfDay"); FieldInfo fieldInfo3 = AccessTools.Field(typeof(Patches), "realTotalTime"); FieldInfo fieldInfo4 = AccessTools.Field(typeof(Patches), "offset"); List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false)) { list[i] = new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo3); list.RemoveAt(i - 1); list.RemoveAt(i - 2); i -= -2; } else if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo2, false)) { list.Insert(i + 1, new CodeInstruction(OpCodes.Add, (object)null)); list.Insert(i + 1, new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo4)); } } return list.AsEnumerable(); } [HarmonyPatch(typeof(RoundManager), "AdvanceHourAndSpawnNewBatchOfEnemies")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> AdvanceHourAndSpawnNewBatchOfEnemies(IEnumerable<CodeInstruction> instructions) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown FieldInfo fieldInfo = AccessTools.Field(typeof(TimeOfDay), "totalTime"); FieldInfo fieldInfo2 = AccessTools.Field(typeof(TimeOfDay), "normalizedTimeOfDay"); FieldInfo fieldInfo3 = AccessTools.Field(typeof(Patches), "realTotalTime"); FieldInfo fieldInfo4 = AccessTools.Field(typeof(Patches), "offset"); List<CodeInstruction> list = new List<CodeInstruction>(instructions); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo, false)) { list[i] = new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo3); list.RemoveAt(i - 1); list.RemoveAt(i - 2); i -= -2; } else if (CodeInstructionExtensions.LoadsField(list[i], fieldInfo2, false)) { list.Insert(i + 1, new CodeInstruction(OpCodes.Add, (object)null)); list.Insert(i + 1, new CodeInstruction(OpCodes.Ldsfld, (object)fieldInfo4)); } } return list.AsEnumerable(); } } }
BepInEx/plugins/LCbetterTeleport.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LCbetterTeleport.Patches; using UnityEngine; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("LCbetterTeleport")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LCbetterTeleport")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("e90b554f-0e11-4f79-b4b2-bd66da220a4f")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace LCbetterTeleport { [BepInPlugin("Poseidon.LCbetterTeleport", "Better Teleport Mod", "1.0.0")] public class BetterTeleport : BaseUnityPlugin { private const string modGUID = "Poseidon.LCbetterTeleport"; private const string modName = "Better Teleport Mod"; private const string modVersion = "1.0.0"; private readonly Harmony harmony = new Harmony("Poseidon.LCbetterTeleport"); public static string[] fullPath = new string[5] { "BepInEx/CustomVideoPlaylist/television_video1.mp4", "BepInEx/CustomVideoPlaylist/television_video2.mp4", "BepInEx/CustomVideoPlaylist/television_video3.mp4", "BepInEx/CustomVideoPlaylist/television_video4.mp4", "BepInEx/CustomVideoPlaylist/television_video5.mp4" }; private static BetterTeleport Instance; internal ManualLogSource mls; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Poseidon.LCbetterTeleport"); mls.LogInfo((object)"The Teleport Mod is Active"); harmony.PatchAll(typeof(BetterTeleport)); harmony.PatchAll(typeof(ShipTeleporterPatch)); } } } namespace LCbetterTeleport.Patches { [HarmonyPatch(typeof(PlayerControllerB))] internal class PlayerControllerBPatch { [HarmonyPatch("DropAllHeldItems")] [HarmonyPrefix] private static bool keepItemsPatch() { return false; } } [HarmonyPatch(typeof(ShipTeleporter))] internal class ShipTeleporterPatch { private static AudioClip teleporterBeamUpSFX; private static AudioSource shipTeleporterAudio; private static AudioClip teleporterSpinSFX; private static AudioClip beamUpPlayerBodySFX; private static Transform teleporterPosition; [HarmonyPatch("Awake")] [HarmonyPrefix] private static void noCooldown(ref float ___cooldownAmount) { ___cooldownAmount = 0f; } [HarmonyPatch("TeleportPlayerOutWithInverseTeleporter")] [HarmonyPrefix] private static bool noDropItemsInverse(ref int playerObj, ref Vector3 teleportPos) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) if (StartOfRound.Instance.allPlayerScripts[playerObj].isPlayerDead) { StartCoroutine(teleportBodyOut(playerObj, teleportPos)); return false; } PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[playerObj]; SetPlayerTeleporterId(val, -1); if (Object.op_Implicit((Object)(object)Object.FindObjectOfType<AudioReverbPresets>())) { Object.FindObjectOfType<AudioReverbPresets>().audioPresets[2].ChangeAudioReverbForPlayer(val); } val.isInElevator = false; val.isInHangarShipRoom = false; val.isInsideFactory = true; val.averageVelocity = 0f; val.velocityLastFrame = Vector3.zero; StartOfRound.Instance.allPlayerScripts[playerObj].TeleportPlayer(teleportPos, false, 0f, false, true); StartOfRound.Instance.allPlayerScripts[playerObj].beamOutParticle.Play(); shipTeleporterAudio.PlayOneShot(teleporterBeamUpSFX); StartOfRound.Instance.allPlayerScripts[playerObj].movementAudio.PlayOneShot(teleporterBeamUpSFX); if ((Object)(object)val == (Object)(object)GameNetworkManager.Instance.localPlayerController) { Debug.Log((object)"Teleporter shaking camera"); HUDManager.Instance.ShakeCamera((ScreenShakeType)1); } return false; } private static void StartCoroutine(string v) { } private static void SetPlayerTeleporterId(PlayerControllerB playerControllerB, int v) { } private static string teleportBodyOut(int playerObj, Vector3 teleportPos) { return "test"; } } [HarmonyPatch] internal class CustomTelevisionPlaylistPatch { public static Random videoRandomizer = new Random(); [HarmonyPatch(typeof(TVScript), "TVFinishedClip")] [HarmonyPrefix] public static bool TVFinishedClip() { return false; } [HarmonyPatch(typeof(TVScript), "Update")] [HarmonyPrefix] public static bool Update() { return false; } [HarmonyPatch(typeof(TVScript), "TurnTVOnOff")] [HarmonyPrefix] public static bool TurnTVOnOff(bool on, TVScript __instance) { __instance.tvOn = on; if (on) { __instance.video.clip = null; __instance.tvSFX.clip = null; __instance.video.url = $"file:///{BetterTeleport.fullPath[videoRandomizer.Next(0, BetterTeleport.fullPath.Length)]}"; __instance.video.source = (VideoSource)1; __instance.video.controlledAudioTrackCount = 1; __instance.video.audioOutputMode = (VideoAudioOutputMode)1; __instance.video.SetTargetAudioSource((ushort)0, __instance.tvSFX); __instance.video.Prepare(); __instance.video.Stop(); __instance.tvSFX.Stop(); SetTVScreenMaterial(__instance, b: true); __instance.video.Play(); __instance.tvSFX.Play(); __instance.tvSFX.PlayOneShot(__instance.switchTVOn); WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOn, 1f); } else { SetTVScreenMaterial(__instance, b: false); __instance.tvSFX.Stop(); __instance.tvSFX.PlayOneShot(__instance.switchTVOff); __instance.video.Stop(); WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOff, 1f); } return false; } public static void SetTVScreenMaterial(TVScript instance, bool b) { ((object)instance).GetType().GetMethod("SetTVScreenMaterial", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(instance, new object[1] { b }); } } }
BepInEx/plugins/LCFartLizards.dll
Decompiled a year agousing System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using HarmonyLib; using LCFartLizards.Properties; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LCFartLizards")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Spore lizards fart instead")] [assembly: AssemblyFileVersion("1.2.1.0")] [assembly: AssemblyInformationalVersion("1.2.1+0e5b5b266cd12247451733a48a210dfba5fe1c79")] [assembly: AssemblyProduct("LCFartLizards")] [assembly: AssemblyTitle("LCFartLizards")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 LCFartLizards { [BepInPlugin("LCFartLizards", "LCFartLizards", "1.2.1")] public class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(PufferAI), "Start")] public static class PufferAIPatch { public static void Prefix(ref PufferAI __instance) { __instance.puff = audioClip; } } private Harmony harmony; public static AudioClip audioClip; public static bool audioClipLoaded; public void Awake() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LCFartLizards is loaded!"); harmony = new Harmony("LCFartLizards"); harmony.PatchAll(); LoadAudioClip(); } private void LoadAudioClip() { AssetBundle val = AssetBundle.LoadFromMemory(Resources.lcfartlizards); if ((Object)(object)val != (Object)null) { audioClip = val.LoadAsset<AudioClip>("Assets/LizardSound.mp3"); if ((Object)(object)audioClip != (Object)null) { audioClipLoaded = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Audio clip loaded successfully!"); } else { ((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load audio clip!"); } } else { ((BaseUnityPlugin)this).Logger.LogError((object)"Failed to load asset bundle!"); } } } public static class PluginInfo { public const string PLUGIN_GUID = "LCFartLizards"; public const string PLUGIN_NAME = "LCFartLizards"; public const string PLUGIN_VERSION = "1.2.1"; } } namespace LCFartLizards.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] public class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] public static ResourceManager ResourceManager { get { if (resourceMan == null) { ResourceManager resourceManager = new ResourceManager("LCFartLizards.Properties.Resources", typeof(Resources).Assembly); resourceMan = resourceManager; } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static byte[] lcfartlizards { get { object @object = ResourceManager.GetObject("lcfartlizards", resourceCulture); return (byte[])@object; } } internal Resources() { } } }
BepInEx/plugins/LCSymphony.dll
Decompiled a year agousing System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using LCSymphony.Patches; using Steamworks; using TMPro; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("LCSymphony")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LCSymphony")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("047A9A10-3A21-461E-A7A5-DD6CA798B0A3")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace LCSymphony { public static class ConfigSettings { public static ConfigEntry<bool> PingEnabled { get; set; } public static ConfigEntry<string> LaunchOption { get; set; } public static ConfigEntry<bool> SkipTerminalBoot { get; set; } public static void Init() { PingEnabled = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Ping Management", "PingEnabled", true, "Enable or disable the ping display in the top right corner."); LaunchOption = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<string>("Launch Options", "LaunchOption", "online", "Choose between launching into online mode, lan mode, or normal startup. Online will launch the game directly to online mode, lan will launch the game directly to lan mode, and normal will launch the game normally. Valid options are: online, lan, normal."); SkipTerminalBoot = ((BaseUnityPlugin)Plugin.Instance).Config.Bind<bool>("Launch Options", "SkipTerminalBoot", true, "Skip the terminal boot screen."); } } public class PingManager : MonoBehaviour { private Coroutine _coroutine; public int Ping { get; private set; } private void Start() { if (ConfigSettings.PingEnabled.Value) { _coroutine = ((MonoBehaviour)this).StartCoroutine(UpdatePingData()); } } private void Update() { } private void OnDestroy() { ((MonoBehaviour)this).StopCoroutine(_coroutine); } private IEnumerator UpdatePingData() { while (true) { yield return (object)new WaitForSeconds(0.5f); if (GameNetworkManager.Instance.currentLobby.HasValue || !SteamNetworkingUtils.LocalPingLocation.HasValue) { if (SteamNetworkingUtils.LocalPingLocation.HasValue) { Ping = SteamNetworkingUtils.EstimatePingTo(SteamNetworkingUtils.LocalPingLocation.Value); } } else { Plugin.Log("Could not update ping data. Retrying in 5 seconds."); yield return (object)new WaitForSeconds(5f); } } } } [BepInPlugin("dev.alexanderdiaz.lcsymphony", "LC Symphony", "1.2.0")] public class Plugin : BaseUnityPlugin { private const string ModGuid = "dev.alexanderdiaz.lcsymphony"; private const string ModName = "LC Symphony"; private const string ModVersion = "1.2.0"; private readonly Harmony _harmony = new Harmony("dev.alexanderdiaz.lcsymphony"); public static Plugin Instance; public static PingManager PingManager; public void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } ConfigSettings.Init(); _harmony.PatchAll(typeof(SkipToStartPatch)); if (ConfigSettings.PingEnabled.Value && ConfigSettings.LaunchOption.Value != "lan") { _harmony.PatchAll(typeof(HudManagerPatch)); } InitPingManager(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LC Symphony-1.2.0 loaded!"); } private void InitPingManager() { //IL_0005: 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_0010: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("PingManager"); Object.DontDestroyOnLoad((Object)val); ((Object)val).hideFlags = (HideFlags)61; val.AddComponent<PingManager>(); PingManager = val.GetComponent<PingManager>(); } public static void Log(string message) { ((BaseUnityPlugin)Instance).Logger.LogInfo((object)message); } } public class PluginInfo { public const string PLUGIN_GUID = "dev.alexanderdiaz.lcsymphony"; public const string PLUGIN_NAME = "LC Symphony"; public const string PLUGIN_VERSION = "1.2.0"; } } namespace LCSymphony.Patches { [HarmonyPatch(typeof(HUDManager))] internal class HudManagerPatch { private static TextMeshProUGUI _displayText; [HarmonyPatch("Start")] [HarmonyPostfix] private static void PatchHudManagerStart(ref HUDManager __instance) { //IL_0005: 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_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("PingManagerDisplay"); val.AddComponent<RectTransform>(); TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>(); RectTransform rectTransform = ((TMP_Text)obj).rectTransform; ((Transform)rectTransform).SetParent(((TMP_Text)__instance.debugText).transform.parent.parent.parent, false); ((Transform)rectTransform).parent = ((Transform)((TMP_Text)__instance.debugText).rectTransform).parent.parent.parent; rectTransform.anchorMin = new Vector2(1f, 1f); rectTransform.anchorMax = new Vector2(1f, 1f); rectTransform.pivot = new Vector2(1f, 1f); rectTransform.sizeDelta = new Vector2(100f, 100f); rectTransform.anchoredPosition = new Vector2(50f, -1f); ((TMP_Text)obj).font = ((TMP_Text)__instance.controlTipLines[0]).font; ((TMP_Text)obj).fontSize = 7f; ((TMP_Text)obj).text = $"Ping: {Plugin.PingManager.Ping}ms"; ((TMP_Text)obj).overflowMode = (TextOverflowModes)0; ((Behaviour)obj).enabled = true; _displayText = obj; Plugin.Log("PingManagerDisplay component added to Canvas."); } [HarmonyPatch("Update")] [HarmonyPostfix] private static void PatchHudManagerUpdate(ref HUDManager __instance) { if (((NetworkBehaviour)__instance).NetworkManager.IsHost) { ((TMP_Text)_displayText).text = "Ping: Host"; } else { ((TMP_Text)_displayText).text = $"Ping: {Plugin.PingManager.Ping}ms"; } } } internal class SkipToStartPatch { [HarmonyPatch(typeof(PreInitSceneScript), "Start")] [HarmonyPostfix] private static void SetLaunchModePatch(ref PreInitSceneScript __instance) { Plugin.Log("Setting chosen quick-launch option."); switch (ConfigSettings.LaunchOption.Value) { case "online": Plugin.Log("Launching into online mode."); __instance.ChooseLaunchOption(true); break; case "lan": Plugin.Log("Launching into LAN mode."); __instance.ChooseLaunchOption(false); break; case "normal": Plugin.Log("Allowing user choice of launch mode."); break; } } [HarmonyPatch(typeof(InitializeGame), "Awake")] [HarmonyPostfix] private static void SkipTerminalBootPatch(ref InitializeGame __instance) { Plugin.Log("Skipping boot-up screen."); if (ConfigSettings.SkipTerminalBoot.Value) { __instance.runBootUpScreen = false; } } } }
BepInEx/plugins/LethalCompany.Doom.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using LethalCompany.Doom.Unity; using ManagedDoom; using ManagedDoom.Audio; using ManagedDoom.UserInput; using ManagedDoom.Video; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Samuel Steele")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("2023 Samuel Steele")] [assembly: AssemblyDescription("Play DOOM in the Ship's Terminal")] [assembly: AssemblyFileVersion("1.1.2.0")] [assembly: AssemblyInformationalVersion("1.1.2+2e3fe63fa663bee40733b6ea1c95f8150d066ecf")] [assembly: AssemblyProduct("LethalCompany.Doom")] [assembly: AssemblyTitle("LethalCompany.Doom")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/cryptoc1/lc-doom.git")] [assembly: AssemblyVersion("1.1.2.0")] [module: RefSafetyRules(11)] 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 System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string? message) { Message = message; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CollectionBuilderAttribute : Attribute { public Type BuilderType { get; } public string MethodName { get; } public CollectionBuilderAttribute(Type builderType, string methodName) { BuilderType = builderType; MethodName = methodName; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; set; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal sealed class RequiresLocationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SkipLocalsInitAttribute : Attribute { } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = new object[0]; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class UnscopedRefAttribute : Attribute { } } namespace LethalCompany.Doom { [BepInPlugin("cryptoc1.lethalcompany.doom", "LC-DOOM", "1.1.2")] public sealed class DoomPlugin : BaseUnityPlugin { public static DoomPlugin Value { get; private set; } public ManualLogSource Logger => ((BaseUnityPlugin)this).Logger; public void Awake() { Value = this; Harmony.CreateAndPatchAll(typeof(DoomPlugin).Assembly, "cryptoc1.lethalcompany.doom"); } } internal static class GeneratedPluginInfo { public const string Identifier = "cryptoc1.lethalcompany.doom"; public const string Name = "LC-DOOM"; public const string Version = "1.1.2"; } } namespace LethalCompany.Doom.Unity { internal static class DoomAudioSource { public static AudioSource Create(string name) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) AudioSource obj = new GameObject("LCDoomAudio_" + name) { hideFlags = (HideFlags)61 }.AddComponent<AudioSource>(); obj.playOnAwake = false; obj.spatialBlend = 0f; return obj; } } internal sealed class UnityDoom : IDisposable { private readonly DoomConfigBinder binder; private readonly Config config; private readonly GameContent content; private readonly Doom? doom; private readonly int fpsScale; private int frameCount; private UnitySound? sound; private UnityUserInput? userInput; private UnityVideo? video; public Texture2D? Texture => video?.Texture; public UnityDoom(DoomConfigBinder binder) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown try { CommandLineArgs val = new CommandLineArgs(new string[2] { "iwad", binder.Wad.Value }); this.binder = binder; config = binder.GetConfig(); content = new GameContent(val); doom = new Doom(val, config, content, (IVideo)(object)(video = new UnityVideo(config, content)), (ISound)(object)(sound = ((!val.nosound.Present && !val.nosfx.Present) ? new UnitySound(config, content) : null)), (IMusic)null, (IUserInput)(object)(userInput = new UnityUserInput(config))); frameCount = -1; fpsScale = (val.timedemo.Present ? 1 : config.video_fpsscale); } catch (Exception source) { Dispose(); ExceptionDispatchInfo.Throw(source); } } public void Dispose() { if (sound != null) { sound.Dispose(); sound = null; } if (video != null) { video.Dispose(); video = null; } if (userInput != null) { userInput.Dispose(); userInput = null; } binder.Save(config); } public unsafe void Input(Mouse mouse, Keyboard keyboard) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) userInput.MoveMouse(Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)mouse).delta).value)); foreach (var (val, button2) in UnityUserInput.MouseButtons(Mouse.current)) { if (val.wasPressedThisFrame) { PressButton(button2); } if (val.wasReleasedThisFrame) { ReleaseButton(button2); } } foreach (var (val2, key2) in UnityUserInput.Keys) { if (((ButtonControl)keyboard[val2]).wasPressedThisFrame) { PressKey(key2); } if (((ButtonControl)keyboard[val2]).wasReleasedThisFrame) { ReleaseKey(key2); } } void PressButton(DoomMouseButton button) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if ((int)button != -1 && !userInput.PressedButtons.Contains(button)) { userInput.PressedButtons.Add(button); } doom.PostEvent(new DoomEvent((EventType)2, (DoomKey)(-1))); } void PressKey(DoomKey key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_002f: 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_003a: Expected O, but got Unknown //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if ((int)key != -1 && !userInput.PressedKeys.Contains(key)) { userInput.PressedKeys.Add(key); } doom.PostEvent(new DoomEvent((EventType)0, key)); } void ReleaseButton(DoomMouseButton button) { //IL_000b: 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_0024: Expected O, but got Unknown userInput.PressedButtons.Remove(button); doom.PostEvent(new DoomEvent((EventType)2, (DoomKey)(-1))); } void ReleaseKey(DoomKey key) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown userInput.PressedKeys.Remove(key); doom.PostEvent(new DoomEvent((EventType)1, key)); } } public bool Render() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Invalid comparison between Unknown and I4 //IL_0045: 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) if (++frameCount % fpsScale == 0) { if ((int)doom.Update() == 1) { return false; } video.Render(doom, Fixed.FromInt(frameCount % fpsScale + 1) / fpsScale); } return true; } } public sealed class DoomConfigBinder { [CompilerGenerated] private ConfigFile <file>P; [CompilerGenerated] private (int width, int height) <size>P; private static readonly Lazy<string> DefaultWadPath = new Lazy<string>(GetWadPath); private static readonly Lazy<string> DefaultSoundFontPath = new Lazy<string>(GetSoundFontPath); public ConfigEntry<bool> AlwaysRun { get; } public ConfigEntry<string?> Wad { get; } public ConfigEntry<string> KeyBackward { get; } public ConfigEntry<string> KeyForward { get; } public ConfigEntry<string> KeyFire { get; } public ConfigEntry<string> KeyRun { get; } public ConfigEntry<string> KeyStrafe { get; } public ConfigEntry<string> KeyStrafeLeft { get; } public ConfigEntry<string> KeyStrafeRight { get; } public ConfigEntry<string> KeyTurnLeft { get; } public ConfigEntry<string> KeyTurnRight { get; } public ConfigEntry<string> KeyUse { get; } public ConfigEntry<bool> MouseDisableYAxis { get; } public ConfigEntry<int> MouseSensitivity { get; } public ConfigEntry<bool> SfxRandomPitch { get; } public ConfigEntry<int> SfxVolume { get; } public ConfigEntry<bool> VideoDisplayMessage { get; } public ConfigEntry<int> VideoFpsScale { get; } public ConfigEntry<int> VideoGammaCorrection { get; } public ConfigEntry<bool> VideoHighResolution { get; } public ConfigEntry<int> VideoScreenSize { get; } public DoomConfigBinder(ConfigFile file, (int width, int height) size) { <file>P = file; <size>P = size; AlwaysRun = <file>P.Bind<bool>("General", "Always Run", true, (ConfigDescription)null); Wad = <file>P.Bind<string>("General", "WAD", DefaultWadPath.Value, "An absolute path to the WAD file to be loaded."); KeyBackward = <file>P.Bind<string>("Keybinds", "Backward", "s,down", (ConfigDescription)null); KeyForward = <file>P.Bind<string>("Keybinds", "Forward", "w,up", (ConfigDescription)null); KeyFire = <file>P.Bind<string>("Keybinds", "Fire", "mouse1,f,lcontrol,rcontrol", (ConfigDescription)null); KeyRun = <file>P.Bind<string>("Keybinds", "Run", "lshift,rshift", (ConfigDescription)null); KeyStrafe = <file>P.Bind<string>("Keybinds", "Strafe", "lalt,ralt", (ConfigDescription)null); KeyStrafeLeft = <file>P.Bind<string>("Keybinds", "Strafe Left", "a", (ConfigDescription)null); KeyStrafeRight = <file>P.Bind<string>("Keybinds", "Strafe Right", "d", (ConfigDescription)null); KeyTurnLeft = <file>P.Bind<string>("Keybinds", "Turn Left", "left", (ConfigDescription)null); KeyTurnRight = <file>P.Bind<string>("Keybinds", "Turn Right", "right", (ConfigDescription)null); KeyUse = <file>P.Bind<string>("Keybinds", "Use", "space,mouse2", (ConfigDescription)null); MouseDisableYAxis = <file>P.Bind<bool>("Mouse", "Disable Y-Axis", false, (ConfigDescription)null); MouseSensitivity = <file>P.Bind<int>("Mouse", "Sensitivity", 8, (ConfigDescription)null); SfxRandomPitch = <file>P.Bind<bool>("Sfx", "Random Pitch", true, (ConfigDescription)null); SfxVolume = <file>P.Bind<int>("Sfx", "Volume", 8, "The volume of sound effects."); VideoDisplayMessage = <file>P.Bind<bool>("Video", "Display Message", true, (ConfigDescription)null); VideoFpsScale = <file>P.Bind<int>("Video", "FPS Scale", 2, (ConfigDescription)null); VideoGammaCorrection = <file>P.Bind<int>("Video", "Gamma Correction", 2, (ConfigDescription)null); VideoHighResolution = <file>P.Bind<bool>("Video", "High Resolution", true, (ConfigDescription)null); VideoScreenSize = <file>P.Bind<int>("Video", "Screen Size", 7, (ConfigDescription)null); base..ctor(); } public Config GetConfig() { //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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_0064: 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_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Expected O, but got Unknown return new Config { audio_randompitch = SfxRandomPitch.Value, audio_soundvolume = SfxVolume.Value, game_alwaysrun = AlwaysRun.Value, key_backward = KeyBinding.Parse(KeyBackward.Value), key_fire = KeyBinding.Parse(KeyFire.Value), key_forward = KeyBinding.Parse(KeyForward.Value), key_run = KeyBinding.Parse(KeyRun.Value), key_strafe = KeyBinding.Parse(KeyStrafe.Value), key_strafeleft = KeyBinding.Parse(KeyStrafeLeft.Value), key_straferight = KeyBinding.Parse(KeyStrafeRight.Value), key_turnleft = KeyBinding.Parse(KeyTurnLeft.Value), key_turnright = KeyBinding.Parse(KeyTurnRight.Value), key_use = KeyBinding.Parse(KeyUse.Value), mouse_disableyaxis = MouseDisableYAxis.Value, mouse_sensitivity = MouseSensitivity.Value, video_displaymessage = VideoDisplayMessage.Value, video_fpsscale = VideoFpsScale.Value, video_fullscreen = false, video_gamescreensize = VideoScreenSize.Value, video_gammacorrection = VideoGammaCorrection.Value, video_highresolution = VideoHighResolution.Value, video_screenheight = <size>P.height, video_screenwidth = <size>P.width }; } private static string GetSoundFontPath() { return Path.Combine(Path.GetDirectoryName(typeof(DoomPlugin).Assembly.Location), "RLNDGM.SF2"); } private static string GetWadPath() { return Path.Combine(Path.GetDirectoryName(typeof(DoomPlugin).Assembly.Location), "DOOM1.WAD"); } public void Save(Config config) { AlwaysRun.Value = config.game_alwaysrun; KeyBackward.Value = ((object)config.key_backward).ToString(); KeyForward.Value = ((object)config.key_forward).ToString(); KeyFire.Value = ((object)config.key_fire).ToString(); KeyRun.Value = ((object)config.key_run).ToString(); KeyStrafe.Value = ((object)config.key_strafe).ToString(); KeyStrafeLeft.Value = ((object)config.key_strafeleft).ToString(); KeyStrafeRight.Value = ((object)config.key_straferight).ToString(); KeyTurnLeft.Value = ((object)config.key_turnleft).ToString(); KeyTurnRight.Value = ((object)config.key_turnright).ToString(); KeyUse.Value = ((object)config.key_use).ToString(); MouseDisableYAxis.Value = config.mouse_disableyaxis; MouseSensitivity.Value = config.mouse_sensitivity; SfxRandomPitch.Value = config.audio_randompitch; SfxVolume.Value = config.audio_soundvolume; VideoDisplayMessage.Value = config.video_displaymessage; VideoFpsScale.Value = config.video_fpsscale; VideoGammaCorrection.Value = config.video_gammacorrection; VideoHighResolution.Value = config.video_highresolution; VideoScreenSize.Value = config.video_gamescreensize; <file>P.Save(); } } internal sealed class UnitySound : ISound, IDisposable { private sealed class ChannelInfo { public Sfx Reserved; public Sfx Playing; public float Priority; public Mobj? Source; public SfxType Type; public int Volume; public Fixed LastX; public Fixed LastY; public void Clear() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) Reserved = (Sfx)0; Playing = (Sfx)0; Priority = 0f; Source = null; Type = (SfxType)0; Volume = 0; LastX = Fixed.Zero; LastY = Fixed.Zero; } } private static readonly int ChannelCount = 8; private static readonly float FastDecay = (float)Math.Pow(0.5, 1.0 / 7.0); private static readonly float SlowDecay = (float)Math.Pow(0.5, 1.0 / 35.0); private static readonly float ClipDist = 1200f; private static readonly float CloseDist = 160f; private static readonly float Attenuator = ClipDist - CloseDist; private readonly float[] amplitudes; private readonly Config config; private readonly ChannelInfo[] infos; private readonly DoomRandom? random; private AudioClip[] buffers; private AudioSource[] channels; private AudioSource uiChannel; private Sfx uiReserved; private DateTime lastUpdate; private Mobj listener; private float masterVolumeDecay; public int MaxVolume => 15; public int Volume { get { return config.audio_soundvolume; } set { config.audio_soundvolume = value; masterVolumeDecay = (float)config.audio_soundvolume / (float)MaxVolume; } } public UnitySound(Config config, GameContent content) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0176: Unknown result type (might be due to invalid IL or missing references) try { this.config = config; config.audio_soundvolume = Math.Clamp(config.audio_soundvolume, 0, MaxVolume); buffers = (AudioClip[])(object)new AudioClip[DoomInfo.SfxNames.Length]; amplitudes = new float[DoomInfo.SfxNames.Length]; if (config.audio_randompitch) { random = new DoomRandom(); } for (int i = 0; i < DoomInfo.SfxNames.Length; i++) { string text = $"DS{DoomInfo.SfxNames[i]}".ToUpperInvariant(); if (content.Wad.GetLumpNumber(text) != -1) { int sampleRate; int sampleCount; float[] samples = GetSamples(content.Wad, text, out sampleRate, out sampleCount); if ((samples?.Length).HasValue) { AudioClip val = AudioClip.Create(text, samples.Length, 1, sampleRate, false); val.SetData(samples, 0); buffers[i] = val; amplitudes[i] = GetAmplitude(samples, sampleRate, samples.Length); } } } channels = CreateChannels(ChannelCount); infos = new ChannelInfo[ChannelCount]; for (int j = 0; j < ChannelCount; j++) { infos[j] = new ChannelInfo(); } lastUpdate = DateTime.MinValue; masterVolumeDecay = (float)config.audio_soundvolume / (float)MaxVolume; uiChannel = DoomAudioSource.Create("UI"); uiReserved = (Sfx)0; } catch { Dispose(); throw; } } private AudioSource[] CreateChannels(int channelCount) { AudioSource[] array = (AudioSource[])(object)new AudioSource[channelCount]; for (int i = 0; i < channelCount; i++) { AudioSource val = DoomAudioSource.Create($"SFX_{i}"); val.spatialBlend = 0f; val.playOnAwake = false; array[i] = val; } return array; } public void Dispose() { if (channels != null) { for (int i = 0; i < channels.Length; i++) { if (channels[i] != null) { channels[i].Stop(); Object.DestroyImmediate((Object)(object)((Component)channels[i]).gameObject, true); channels[i] = null; } } channels = null; } if (buffers != null) { for (int j = 0; j < buffers.Length; j++) { if (buffers[j] != null) { Object.DestroyImmediate((Object)(object)buffers[j], true); buffers[j] = null; } } buffers = null; } if (uiChannel != null) { Object.DestroyImmediate((Object)(object)((Component)uiChannel).gameObject, true); uiChannel = null; } } private static float[]? GetSamples(Wad wad, string name, out int sampleRate, out int sampleCount) { byte[] array = wad.ReadLump(name); if (array.Length < 8) { sampleRate = -1; sampleCount = -1; return null; } sampleRate = BitConverter.ToUInt16(array, 2); sampleCount = BitConverter.ToInt32(array, 4); int num = 8; if (ContainsDmxPadding(array)) { num += 16; sampleCount -= 32; } if (sampleCount > 0) { float[] array2 = new float[sampleCount]; for (int i = num; i < sampleCount; i++) { array2[i] = (float)(int)array[i] / 127f - 1f; } return array2; } return Array.Empty<float>(); } private static bool ContainsDmxPadding(byte[] data) { int num = BitConverter.ToInt32(data, 4); if (num < 32) { return false; } byte b = data[8]; for (int i = 1; i < 16; i++) { if (data[8 + i] != b) { return false; } } byte b2 = data[8 + num - 1]; for (int j = 1; j < 16; j++) { if (data[8 + num - j - 1] != b2) { return false; } } return true; } private static float GetAmplitude(float[] samples, int sampleRate, int sampleCount) { float num = 0f; if (sampleCount > 0) { int num2 = Math.Min(sampleRate / 5, sampleCount); for (int i = 0; i < num2; i++) { float num3 = samples[i] - 0.5f; if (num3 < 0f) { num3 = 0f - num3; } if (num3 > num) { num = num3; } } } return num; } public void SetListener(Mobj listener) { this.listener = listener; } public void Update() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) DateTime now = DateTime.Now; if ((now - lastUpdate).TotalSeconds < 0.01) { return; } for (int i = 0; i < infos.Length; i++) { ChannelInfo channelInfo = infos[i]; AudioSource val = channels[i]; if ((int)channelInfo.Playing != 0) { channelInfo.Priority *= (((int)channelInfo.Type == 0) ? SlowDecay : FastDecay); UpdateAudioSource(val, channelInfo); } if ((int)channelInfo.Reserved != 0) { if ((int)channelInfo.Playing != 0) { val.Stop(); } val.clip = buffers[channelInfo.Reserved]; UpdateAudioSource(val, channelInfo); val.pitch = GetPitch(channelInfo.Type, channelInfo.Reserved); val.PlayOneShot(val.clip); channelInfo.Playing = channelInfo.Reserved; channelInfo.Reserved = (Sfx)0; } } if ((int)uiReserved != 0) { if (uiChannel.isPlaying) { uiChannel.Stop(); } uiChannel.volume = masterVolumeDecay; uiChannel.clip = buffers[uiReserved]; uiChannel.Play(); uiReserved = (Sfx)0; } lastUpdate = now; } public void StartSound(Sfx sfx) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (buffers[sfx] != null) { uiReserved = sfx; } } public void StartSound(Mobj mobj, Sfx sfx, SfxType type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) StartSound(mobj, sfx, type, 100); } public void StartSound(Mobj mobj, Sfx sfx, SfxType type, int volume) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005f: 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_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0170: 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_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) if (buffers[sfx] == null) { return; } Fixed val = mobj.X - listener.X; float num = ((Fixed)(ref val)).ToFloat(); val = mobj.Y - listener.Y; float num2 = ((Fixed)(ref val)).ToFloat(); float dist = MathF.Sqrt(num * num + num2 * num2); float num3 = (((int)type == 0) ? ((float)volume) : (amplitudes[sfx] * GetDistanceDecay(dist) * (float)volume)); for (int i = 0; i < infos.Length; i++) { ChannelInfo channelInfo = infos[i]; if (channelInfo.Source == mobj && channelInfo.Type == type) { channelInfo.Reserved = sfx; channelInfo.Priority = num3; channelInfo.Volume = volume; return; } } for (int j = 0; j < infos.Length; j++) { ChannelInfo channelInfo2 = infos[j]; if ((int)channelInfo2.Reserved == 0 && (int)channelInfo2.Playing == 0) { channelInfo2.Reserved = sfx; channelInfo2.Priority = num3; channelInfo2.Source = mobj; channelInfo2.Type = type; channelInfo2.Volume = volume; return; } } float num4 = float.MaxValue; int num5 = -1; for (int k = 0; k < infos.Length; k++) { ChannelInfo channelInfo3 = infos[k]; if (channelInfo3.Priority < num4) { num4 = channelInfo3.Priority; num5 = k; } } if (num3 >= num4) { ChannelInfo obj = infos[num5]; obj.Reserved = sfx; obj.Priority = num3; obj.Source = mobj; obj.Type = type; obj.Volume = volume; } } public void StopSound(Mobj mobj) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_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) for (int i = 0; i < infos.Length; i++) { ChannelInfo channelInfo = infos[i]; if (channelInfo.Source == mobj) { channelInfo.LastX = channelInfo.Source.X; channelInfo.LastY = channelInfo.Source.Y; channelInfo.Source = null; channelInfo.Volume /= 5; } } } public void Reset() { DoomRandom? obj = random; if (obj != null) { obj.Clear(); } for (int i = 0; i < infos.Length; i++) { channels[i].Stop(); infos[i].Clear(); } listener = null; } public void Pause() { } public void Resume() { } private void UpdateAudioSource(AudioSource sound, ChannelInfo info) { //IL_0001: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_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_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) if ((int)info.Type == 0) { sound.panStereo = 0f; sound.volume = 0.01f * masterVolumeDecay * (float)info.Volume; return; } Fixed val; Fixed val2; if (info.Source == null) { val = info.LastX; val2 = info.LastY; } else { val = info.Source.X; val2 = info.Source.Y; } Fixed val3 = val - listener.X; float num = ((Fixed)(ref val3)).ToFloat(); val3 = val2 - listener.Y; float num2 = ((Fixed)(ref val3)).ToFloat(); if (Math.Abs(num) < 16f && Math.Abs(num2) < 16f) { sound.panStereo = 0f; sound.volume = 0.01f * masterVolumeDecay * (float)info.Volume; return; } float dist = MathF.Sqrt(num * num + num2 * num2); float num3 = MathF.Atan2(num2, num); Angle angle = listener.Angle; float num4 = num3 - (float)((Angle)(ref angle)).ToRadian(); num4 = num4 * 57.29578f / 180f; num4 = Mathf.Clamp(num4, -0.2f, 0.2f); sound.panStereo = num4; sound.volume = 0.01f * masterVolumeDecay * GetDistanceDecay(dist) * (float)info.Volume; } private float GetDistanceDecay(float dist) { if (dist < CloseDist) { return 1f; } return Math.Max((ClipDist - dist) / Attenuator, 0f); } private float GetPitch(SfxType type, Sfx sfx) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Invalid comparison between Unknown and I4 if (random != null) { if ((int)type == 2) { return 1f + 0.075f * (float)(random.Next() - 128) / 128f; } if ((int)sfx == 32 || (int)sfx == 87 || (int)sfx == 108) { return 1f; } return 1f + 0.025f * (float)(random.Next() - 128) / 128f; } return 1f; } } internal sealed class UnityUserInput : IUserInput, IDisposable { private readonly Config config; private readonly bool[] weaponKeys; private Vector2 mouseDelta = new Vector2(0f, 0f); private Vector2 mousePosition = new Vector2(0f, 0f); private Vector2 mousePreviousPosition = new Vector2(0f, 0f); private int turnHeld; public static readonly IEnumerable<(Key InputKey, DoomKey Key)> Keys = new <>z__ReadOnlyArray<(Key, DoomKey)>(new(Key, DoomKey)[95] { ((Key)1, (DoomKey)57), ((Key)7, (DoomKey)49), ((Key)13, (DoomKey)68), ((Key)8, (DoomKey)50), ((Key)9, (DoomKey)52), ((Key)50, (DoomKey)26), ((Key)41, (DoomKey)27), ((Key)42, (DoomKey)28), ((Key)43, (DoomKey)29), ((Key)44, (DoomKey)30), ((Key)45, (DoomKey)31), ((Key)46, (DoomKey)32), ((Key)47, (DoomKey)33), ((Key)48, (DoomKey)34), ((Key)49, (DoomKey)35), ((Key)6, (DoomKey)48), ((Key)83, (DoomKey)55), ((Key)15, (DoomKey)0), ((Key)16, (DoomKey)1), ((Key)17, (DoomKey)2), ((Key)18, (DoomKey)3), ((Key)19, (DoomKey)4), ((Key)20, (DoomKey)5), ((Key)21, (DoomKey)6), ((Key)22, (DoomKey)7), ((Key)23, (DoomKey)8), ((Key)24, (DoomKey)9), ((Key)25, (DoomKey)10), ((Key)26, (DoomKey)11), ((Key)27, (DoomKey)12), ((Key)28, (DoomKey)13), ((Key)29, (DoomKey)14), ((Key)30, (DoomKey)15), ((Key)31, (DoomKey)16), ((Key)32, (DoomKey)17), ((Key)33, (DoomKey)18), ((Key)34, (DoomKey)19), ((Key)35, (DoomKey)20), ((Key)36, (DoomKey)21), ((Key)37, (DoomKey)22), ((Key)38, (DoomKey)23), ((Key)39, (DoomKey)24), ((Key)40, (DoomKey)25), ((Key)11, (DoomKey)46), ((Key)10, (DoomKey)53), ((Key)12, (DoomKey)47), ((Key)60, (DoomKey)36), ((Key)2, (DoomKey)58), ((Key)3, (DoomKey)60), ((Key)65, (DoomKey)59), ((Key)70, (DoomKey)65), ((Key)71, (DoomKey)66), ((Key)62, (DoomKey)72), ((Key)61, (DoomKey)71), ((Key)64, (DoomKey)74), ((Key)63, (DoomKey)73), ((Key)67, (DoomKey)61), ((Key)66, (DoomKey)62), ((Key)68, (DoomKey)64), ((Key)69, (DoomKey)63), ((Key)76, (DoomKey)100), ((Key)94, (DoomKey)85), ((Key)95, (DoomKey)86), ((Key)96, (DoomKey)87), ((Key)97, (DoomKey)88), ((Key)98, (DoomKey)89), ((Key)99, (DoomKey)90), ((Key)100, (DoomKey)91), ((Key)101, (DoomKey)92), ((Key)102, (DoomKey)93), ((Key)103, (DoomKey)94), ((Key)104, (DoomKey)95), ((Key)105, (DoomKey)96), ((Key)84, (DoomKey)75), ((Key)85, (DoomKey)76), ((Key)86, (DoomKey)77), ((Key)87, (DoomKey)78), ((Key)88, (DoomKey)79), ((Key)89, (DoomKey)80), ((Key)90, (DoomKey)81), ((Key)91, (DoomKey)82), ((Key)92, (DoomKey)83), ((Key)93, (DoomKey)84), ((Key)78, (DoomKey)70), ((Key)79, (DoomKey)69), ((Key)81, (DoomKey)68), ((Key)80, (DoomKey)67), ((Key)77, (DoomKey)58), ((Key)51, (DoomKey)38), ((Key)55, (DoomKey)37), ((Key)53, (DoomKey)39), ((Key)52, (DoomKey)42), ((Key)56, (DoomKey)41), ((Key)54, (DoomKey)43), ((Key)59, (DoomKey)45) }); public int MaxMouseSensitivity => 15; public int MouseSensitivity { get { return config.mouse_sensitivity; } set { config.mouse_sensitivity = value; } } public List<DoomMouseButton> PressedButtons { get; } = new List<DoomMouseButton>(); public List<DoomKey> PressedKeys { get; } = new List<DoomKey>(); public UnityUserInput(Config config) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) try { this.config = config; weaponKeys = new bool[7]; } catch { Dispose(); throw; } } public void BuildTicCmd(TicCmd cmd) { bool num = IsPressed(config.key_forward); bool flag = IsPressed(config.key_backward); bool flag2 = IsPressed(config.key_strafeleft); bool flag3 = IsPressed(config.key_straferight); bool flag4 = IsPressed(config.key_turnleft); bool flag5 = IsPressed(config.key_turnright); bool flag6 = IsPressed(config.key_fire); bool flag7 = IsPressed(config.key_use); bool flag8 = IsPressed(config.key_run); bool num2 = IsPressed(config.key_strafe); weaponKeys[0] = PressedKeys.Contains((DoomKey)27); weaponKeys[1] = PressedKeys.Contains((DoomKey)28); weaponKeys[2] = PressedKeys.Contains((DoomKey)29); weaponKeys[3] = PressedKeys.Contains((DoomKey)30); weaponKeys[4] = PressedKeys.Contains((DoomKey)31); weaponKeys[5] = PressedKeys.Contains((DoomKey)32); weaponKeys[6] = PressedKeys.Contains((DoomKey)33); cmd.Clear(); bool flag9 = num2; int num3 = (flag8 ? 1 : 0); int num4 = 0; int num5 = 0; if (config.game_alwaysrun) { num3 = 1 - num3; } turnHeld = ((flag4 || flag5) ? (turnHeld + 1) : (turnHeld = 0)); int num6 = ((turnHeld < PlayerBehavior.SlowTurnTics) ? 2 : num3); if (flag9) { if (flag5) { num5 += PlayerBehavior.SideMove[num3]; } if (flag4) { num5 -= PlayerBehavior.SideMove[num3]; } } else { if (flag5) { cmd.AngleTurn -= (short)PlayerBehavior.AngleTurn[num6]; } if (flag4) { cmd.AngleTurn += (short)PlayerBehavior.AngleTurn[num6]; } } if (num) { num4 += PlayerBehavior.ForwardMove[num3]; } if (flag) { num4 -= PlayerBehavior.ForwardMove[num3]; } if (flag2) { num5 -= PlayerBehavior.SideMove[num3]; } if (flag3) { num5 += PlayerBehavior.SideMove[num3]; } if (flag6) { cmd.Buttons |= TicCmdButtons.Attack; } if (flag7) { cmd.Buttons |= TicCmdButtons.Use; } for (int i = 0; i < weaponKeys.Length; i++) { if (weaponKeys[i]) { cmd.Buttons |= TicCmdButtons.Change; cmd.Buttons |= (byte)(i << (int)TicCmdButtons.WeaponShift); break; } } float num7 = 0.5f * (float)config.mouse_sensitivity; int num8 = (int)MathF.Round(num7 * mouseDelta.x); int num9 = (int)MathF.Round(num7 * (0f - mouseDelta.y)); num4 += num9; if (flag9) { num5 += num8 * 2; } else { cmd.AngleTurn -= (short)(num8 * 22); } if (num4 > PlayerBehavior.MaxMove) { num4 = PlayerBehavior.MaxMove; } else if (num4 < -PlayerBehavior.MaxMove) { num4 = -PlayerBehavior.MaxMove; } if (num5 > PlayerBehavior.MaxMove) { num5 = PlayerBehavior.MaxMove; } else if (num5 < -PlayerBehavior.MaxMove) { num5 = -PlayerBehavior.MaxMove; } cmd.ForwardMove += (sbyte)num4; cmd.SideMove += (sbyte)num5; } public void Dispose() { PressedButtons.Clear(); PressedKeys.Clear(); } public void GrabMouse() { } private bool IsPressed(KeyBinding binding) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) foreach (DoomKey key in binding.Keys) { if (PressedKeys.Contains(key)) { return true; } } foreach (DoomMouseButton mouseButton in binding.MouseButtons) { if (PressedButtons.Contains(mouseButton)) { return true; } } return false; } public void MoveMouse(Vector2 delta) { //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) //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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_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) mousePreviousPosition.x = mousePosition.x; mousePreviousPosition.y = mousePosition.y; mousePosition += delta; mouseDelta = mousePosition - mousePreviousPosition; if (config.mouse_disableyaxis) { mouseDelta.y = 0f; } } public void ReleaseMouse() { } public void Reset() { } public static IEnumerable<(ButtonControl Control, DoomMouseButton Button)> MouseButtons(Mouse mouse) { return new <>z__ReadOnlyArray<(ButtonControl, DoomMouseButton)>(new(ButtonControl, DoomMouseButton)[5] { (mouse.leftButton, (DoomMouseButton)0), (mouse.rightButton, (DoomMouseButton)1), (mouse.middleButton, (DoomMouseButton)2), (mouse.backButton, (DoomMouseButton)3), (mouse.forwardButton, (DoomMouseButton)4) }); } } internal sealed class UnityVideo : IVideo, IDisposable { private byte[] buffer; private readonly Renderer renderer; public Texture2D Texture { get; private set; } public bool DisplayMessage { get { return renderer.DisplayMessage; } set { renderer.DisplayMessage = value; } } public int GammaCorrectionLevel { get { return renderer.GammaCorrectionLevel; } set { renderer.GammaCorrectionLevel = value; } } public int MaxGammaCorrectionLevel => renderer.MaxGammaCorrectionLevel; public int MaxWindowSize => renderer.MaxWindowSize; public int WindowSize { get { return renderer.WindowSize; } set { renderer.WindowSize = value; } } public int WipeBandCount => renderer.WipeBandCount; public int WipeHeight => renderer.WipeHeight; public UnityVideo(Config config, GameContent content) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown try { int num; int num2; if (!config.video_highresolution) { num = 200; num2 = 320; } else { num = 400; num2 = 640; } renderer = new Renderer(config, content); buffer = new byte[4 * num * num2]; Texture = new Texture2D(num, num2, (TextureFormat)4, false, false) { filterMode = (FilterMode)0, name = "LCDoomScreen" }; } catch { Dispose(); throw; } } public void Dispose() { buffer = null; if (Texture != null) { Object.DestroyImmediate((Object)(object)Texture, true); Texture = null; } } public bool HasFocus() { return true; } public void InitializeWipe() { renderer.InitializeWipe(); } public void Render(Doom doom, Fixed frame) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) renderer.Render(doom, buffer, frame); Texture.SetPixelData<byte>(buffer, 0, 0); Texture.Apply(false, false); } } } namespace LethalCompany.Doom.Patches { [HarmonyPatch(typeof(Terminal))] internal static class TerminalPatches { private static readonly Vector2 TerminalImageSize = new Vector2(428f, 500f); private static readonly Vector3 TerminalImageRotation = new Vector3(0f, 0f, 90f); private static readonly Vector2 TerminalImageTranslation = new Vector2(11.65f, -48f); private static Coroutine? cpu; private static UnityDoom? doom; private static Vector2? terminalImageSize; [MemberNotNullWhen(true, new string[] { "cpu", "doom", "terminalImageSize" })] private static bool isRunning { [MemberNotNullWhen(true, new string[] { "cpu", "doom", "terminalImageSize" })] get { if (cpu != null && doom != null) { return terminalImageSize.HasValue; } return false; } } private static void DestroyDoom(Terminal terminal) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_006e: Unknown result type (might be due to invalid IL or missing references) if (isRunning) { ((MonoBehaviour)terminal).StopCoroutine(cpu); cpu = null; doom.Dispose(); doom = null; RectTransform rectTransform = ((Graphic)terminal.terminalImage).rectTransform; rectTransform.anchoredPosition -= TerminalImageTranslation; ((Transform)((Graphic)terminal.terminalImage).rectTransform).Rotate(TerminalImageRotation); ((Graphic)terminal.terminalImage).rectTransform.sizeDelta = terminalImageSize.Value; terminalImageSize = null; ((Behaviour)terminal.screenText).enabled = true; TMP_InputField screenText = terminal.screenText; screenText.text += "EXIT (0)\n\n"; ((Behaviour)terminal.terminalImageMask).enabled = true; ((Behaviour)terminal.topRightText).enabled = true; GC.Collect(); DoomPlugin.Value.Logger.LogInfo((object)"TerminalPatches: destroyed doom instance"); } } [HarmonyPatch("Awake")] [HarmonyPostfix] public static void OnPostAwake(Terminal __instance) { TerminalNodesList terminalNodes = __instance.terminalNodes; TerminalKeyword[] allKeywords = __instance.terminalNodes.allKeywords; int num = 0; TerminalKeyword[] array = (TerminalKeyword[])(object)new TerminalKeyword[1 + allKeywords.Length]; TerminalKeyword[] array2 = allKeywords; foreach (TerminalKeyword val in array2) { array[num] = val; num++; } array[num] = DoomKeyword(); num++; terminalNodes.allKeywords = array; TerminalKeyword val2 = __instance.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "other"); val2.specialKeywordResult.displayText = val2.specialKeywordResult.displayText.TrimEnd() + "\n\n>DOOM\nBoss makes a dollar, I make a dime. That's why I play DOOM on company time.\n\n"; static TerminalKeyword DoomKeyword() { TerminalNode val3 = ScriptableObject.CreateInstance<TerminalNode>(); val3.clearPreviousText = true; val3.displayText = "LC-DOOM v1.1.2\nhttps://github.com/cryptoc1/lc-doom\n \nCREDITS:\n• id Software\n https://www.idsoftware.com\n\n• " + ApplicationInfo.Title + "\n https://github.com/sinshu/managed-doom\n\n• DoomInUnityInspector\n https://github.com/xabblll/DoomInUnityInspector\n\nLOADING .... "; val3.persistentImage = true; val3.terminalEvent = "doom"; TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>(); obj.isVerb = false; obj.specialKeywordResult = val3; obj.word = "doom"; return obj; } } [HarmonyPatch("QuitTerminal")] [HarmonyPostfix] public static void OnPostQuitTerminal(Terminal __instance) { DestroyDoom(__instance); } [HarmonyPatch("LoadTerminalImage")] [HarmonyPostfix] public static void OnPostLoadTerminalImage(Terminal __instance, TerminalNode node) { if (node.terminalEvent == "doom" && doom != null) { TMP_InputField screenText = __instance.screenText; screenText.text += "LOADED!\n\n"; __instance.terminalImage.texture = (Texture)(object)doom.Texture; if (StartOfRound.Instance.inShipPhase) { __instance.displayingPersistentImage = (Texture)(object)doom.Texture; } cpu = ((MonoBehaviour)__instance).StartCoroutine(RenderDoom(__instance)); ((Behaviour)__instance.terminalImage).enabled = true; ((Behaviour)__instance.topRightText).enabled = false; ((Behaviour)__instance.screenText).enabled = false; } } [HarmonyPatch("LoadNewNode")] [HarmonyPrefix] public static void OnPreLoadNewNode(Terminal __instance, TerminalNode node) { //IL_002a: 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_0059: 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_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) //IL_007e: Unknown result type (might be due to invalid IL or missing references) if (node.terminalEvent == "doom" && doom == null) { terminalImageSize = ((Graphic)__instance.terminalImage).rectTransform.sizeDelta; ((Graphic)__instance.terminalImage).rectTransform.sizeDelta = TerminalImageSize; ((Transform)((Graphic)__instance.terminalImage).rectTransform).Rotate(-TerminalImageRotation); RectTransform rectTransform = ((Graphic)__instance.terminalImage).rectTransform; rectTransform.anchoredPosition += TerminalImageTranslation; ((Behaviour)__instance.terminalImageMask).enabled = false; doom = new UnityDoom(new DoomConfigBinder(((BaseUnityPlugin)DoomPlugin.Value).Config, (Mathf.RoundToInt(TerminalImageSize.x), Mathf.RoundToInt(TerminalImageSize.y)))); } } [HarmonyPatch("PressESC")] [HarmonyPrefix] public static bool OnPrePressESC() { return !isRunning; } [HarmonyPatch("Update")] [HarmonyPrefix] public static void OnPreUpdate() { if (isRunning) { doom.Input(Mouse.current, Keyboard.current); } } private static IEnumerator RenderDoom(Terminal terminal) { while (doom != null) { if (!doom.Render()) { DestroyDoom(terminal); break; } yield return (object)new WaitForEndOfFrame(); } } } } internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.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(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } }
BepInEx/plugins/LethalCompany.Doom.ManagedDoom.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using ManagedDoom.Audio; using ManagedDoom.UserInput; using ManagedDoom.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Samuel Steele")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("2023 Samuel Steele")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+2e3fe63fa663bee40733b6ea1c95f8150d066ecf")] [assembly: AssemblyProduct("LethalCompany.Doom.ManagedDoom")] [assembly: AssemblyTitle("LethalCompany.Doom.ManagedDoom")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/cryptoc1/lc-doom.git")] [assembly: AssemblyVersion("1.0.0.0")] namespace ManagedDoom { public static class ApplicationInfo { public static readonly string Title = "Managed Doom v2.1a"; } public enum Bgm { NONE, E1M1, E1M2, E1M3, E1M4, E1M5, E1M6, E1M7, E1M8, E1M9, E2M1, E2M2, E2M3, E2M4, E2M5, E2M6, E2M7, E2M8, E2M9, E3M1, E3M2, E3M3, E3M4, E3M5, E3M6, E3M7, E3M8, E3M9, INTER, INTRO, BUNNY, VICTOR, INTROA, RUNNIN, STALKS, COUNTD, BETWEE, DOOM, THE_DA, SHAWN, DDTBLU, IN_CIT, DEAD, STLKS2, THEDA2, DOOM2, DDTBL2, RUNNI2, DEAD2, STLKS3, ROMERO, SHAWN2, MESSAG, COUNT2, DDTBL3, AMPIE, THEDA3, ADRIAN, MESSG2, ROMER2, TENSE, SHAWN3, OPENIN, EVIL, ULTIMA, READ_M, DM2TTL, DM2INT } public enum Sfx { NONE, PISTOL, SHOTGN, SGCOCK, DSHTGN, DBOPN, DBCLS, DBLOAD, PLASMA, BFG, SAWUP, SAWIDL, SAWFUL, SAWHIT, RLAUNC, RXPLOD, FIRSHT, FIRXPL, PSTART, PSTOP, DOROPN, DORCLS, STNMOV, SWTCHN, SWTCHX, PLPAIN, DMPAIN, POPAIN, VIPAIN, MNPAIN, PEPAIN, SLOP, ITEMUP, WPNUP, OOF, TELEPT, POSIT1, POSIT2, POSIT3, BGSIT1, BGSIT2, SGTSIT, CACSIT, BRSSIT, CYBSIT, SPISIT, BSPSIT, KNTSIT, VILSIT, MANSIT, PESIT, SKLATK, SGTATK, SKEPCH, VILATK, CLAW, SKESWG, PLDETH, PDIEHI, PODTH1, PODTH2, PODTH3, BGDTH1, BGDTH2, SGTDTH, CACDTH, SKLDTH, BRSDTH, CYBDTH, SPIDTH, BSPDTH, VILDTH, KNTDTH, PEDTH, SKEDTH, POSACT, BGACT, DMACT, BSPACT, BSPWLK, VILACT, NOWAY, BAREXP, PUNCH, HOOF, METAL, CHGUN, TINK, BDOPN, BDCLS, ITMBK, FLAME, FLAMST, GETPOW, BOSPIT, BOSCUB, BOSSIT, BOSPN, BOSDTH, MANATK, MANDTH, SSSIT, SSDTH, KEENPN, KEENDT, SKEACT, SKESIT, SKEATK, RADIO } public enum SfxType { Diffuse, Weapon, Voice, Footstep, Misc } public sealed class CommandLineArgs { public class Arg { private bool present; public bool Present => present; public Arg() { present = false; } public Arg(bool present) { this.present = present; } } public class Arg<T> { private bool present; private T value; public bool Present => present; public T Value => value; public Arg() { present = false; value = default(T); } public Arg(T value) { present = true; this.value = value; } } public readonly Arg<string> iwad; public readonly Arg<string[]> file; public readonly Arg<string[]> deh; public readonly Arg<Tuple<int, int>> warp; public readonly Arg<int> episode; public readonly Arg<int> skill; public readonly Arg deathmatch; public readonly Arg altdeath; public readonly Arg fast; public readonly Arg respawn; public readonly Arg nomonsters; public readonly Arg solonet; public readonly Arg<string> playdemo; public readonly Arg<string> timedemo; public readonly Arg<int> loadgame; public readonly Arg nomouse; public readonly Arg nosound; public readonly Arg nosfx; public readonly Arg nomusic; public readonly Arg nodeh; public CommandLineArgs(string[] args) { iwad = GetString(args, "-iwad"); file = Check_file(args); deh = Check_deh(args); warp = Check_warp(args); episode = GetInt(args, "-episode"); skill = GetInt(args, "-skill"); deathmatch = new Arg(args.Contains("-deathmatch")); altdeath = new Arg(args.Contains("-altdeath")); fast = new Arg(args.Contains("-fast")); respawn = new Arg(args.Contains("-respawn")); nomonsters = new Arg(args.Contains("-nomonsters")); solonet = new Arg(args.Contains("-solo-net")); playdemo = GetString(args, "-playdemo"); timedemo = GetString(args, "-timedemo"); loadgame = GetInt(args, "-loadgame"); nomouse = new Arg(args.Contains("-nomouse")); nosound = new Arg(args.Contains("-nosound")); nosfx = new Arg(args.Contains("-nosfx")); nomusic = new Arg(args.Contains("-nomusic")); nodeh = new Arg(args.Contains("-nodeh")); if (args.Length == 0 || !args.All((string arg) => arg.FirstOrDefault() != '-')) { return; } string text = null; List<string> list = new List<string>(); List<string> list2 = new List<string>(); foreach (string text2 in args) { string text3 = Path.GetExtension(text2).ToLower(); if (text3 == ".wad") { if (ConfigUtilities.IsIwad(text2)) { text = text2; } else { list.Add(text2); } } else if (text3 == ".deh") { list2.Add(text2); } } if (text != null) { iwad = new Arg<string>(text); } if (list.Count > 0) { file = new Arg<string[]>(list.ToArray()); } if (list2.Count > 0) { deh = new Arg<string[]>(list2.ToArray()); } } private static Arg<string[]> Check_file(string[] args) { string[] values = GetValues(args, "-file"); if (values.Length >= 1) { return new Arg<string[]>(values); } return new Arg<string[]>(); } private static Arg<string[]> Check_deh(string[] args) { string[] values = GetValues(args, "-deh"); if (values.Length >= 1) { return new Arg<string[]>(values); } return new Arg<string[]>(); } private static Arg<Tuple<int, int>> Check_warp(string[] args) { string[] values = GetValues(args, "-warp"); int result2; int result3; if (values.Length == 1) { if (int.TryParse(values[0], out var result)) { return new Arg<Tuple<int, int>>(Tuple.Create(1, result)); } } else if (values.Length == 2 && int.TryParse(values[0], out result2) && int.TryParse(values[1], out result3)) { return new Arg<Tuple<int, int>>(Tuple.Create(result2, result3)); } return new Arg<Tuple<int, int>>(); } private static Arg<string> GetString(string[] args, string name) { string[] values = GetValues(args, name); if (values.Length == 1) { return new Arg<string>(values[0]); } return new Arg<string>(); } private static Arg<int> GetInt(string[] args, string name) { string[] values = GetValues(args, name); if (values.Length == 1 && int.TryParse(values[0], out var result)) { return new Arg<int>(result); } return new Arg<int>(); } private static string[] GetValues(string[] args, string name) { return args.SkipWhile((string arg) => arg != name).Skip(1).TakeWhile((string arg) => arg[0] != '-') .ToArray(); } } public sealed class Config { public KeyBinding key_forward; public KeyBinding key_backward; public KeyBinding key_strafeleft; public KeyBinding key_straferight; public KeyBinding key_turnleft; public KeyBinding key_turnright; public KeyBinding key_fire; public KeyBinding key_use; public KeyBinding key_run; public KeyBinding key_strafe; public int mouse_sensitivity; public bool mouse_disableyaxis; public bool game_alwaysrun; public int video_screenwidth; public int video_screenheight; public bool video_fullscreen; public bool video_highresolution; public bool video_displaymessage; public int video_gamescreensize; public int video_gammacorrection; public int video_fpsscale; public int audio_soundvolume; public int audio_musicvolume; public bool audio_randompitch; public string audio_soundfont; public bool audio_musiceffect; private bool isRestoredFromFile; public bool IsRestoredFromFile => isRestoredFromFile; public Config() { key_forward = new KeyBinding(new DoomKey[2] { DoomKey.Up, DoomKey.W }); key_backward = new KeyBinding(new DoomKey[2] { DoomKey.Down, DoomKey.S }); key_strafeleft = new KeyBinding(new DoomKey[1]); key_straferight = new KeyBinding(new DoomKey[1] { DoomKey.D }); key_turnleft = new KeyBinding(new DoomKey[1] { DoomKey.Left }); key_turnright = new KeyBinding(new DoomKey[1] { DoomKey.Right }); key_fire = new KeyBinding(new DoomKey[2] { DoomKey.LControl, DoomKey.RControl }, new DoomMouseButton[1]); key_use = new KeyBinding(new DoomKey[1] { DoomKey.Space }, new DoomMouseButton[1] { DoomMouseButton.Mouse2 }); key_run = new KeyBinding(new DoomKey[2] { DoomKey.LShift, DoomKey.RShift }); key_strafe = new KeyBinding(new DoomKey[2] { DoomKey.LAlt, DoomKey.RAlt }); mouse_sensitivity = 8; mouse_disableyaxis = false; game_alwaysrun = true; video_screenwidth = 640; video_screenheight = 400; video_fullscreen = false; video_highresolution = true; video_gamescreensize = 7; video_displaymessage = true; video_gammacorrection = 2; video_fpsscale = 2; audio_soundvolume = 8; audio_musicvolume = 8; audio_randompitch = true; audio_soundfont = "TimGM6mb.sf2"; audio_musiceffect = true; isRestoredFromFile = false; } public Config(string path) : this() { try { Console.Write("Restore settings: "); Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (string item in File.ReadLines(path)) { string[] array = item.Split('=', StringSplitOptions.RemoveEmptyEntries); if (array.Length == 2) { dictionary[array[0].Trim()] = array[1].Trim(); } } key_forward = GetKeyBinding(dictionary, "key_forward", key_forward); key_backward = GetKeyBinding(dictionary, "key_backward", key_backward); key_strafeleft = GetKeyBinding(dictionary, "key_strafeleft", key_strafeleft); key_straferight = GetKeyBinding(dictionary, "key_straferight", key_straferight); key_turnleft = GetKeyBinding(dictionary, "key_turnleft", key_turnleft); key_turnright = GetKeyBinding(dictionary, "key_turnright", key_turnright); key_fire = GetKeyBinding(dictionary, "key_fire", key_fire); key_use = GetKeyBinding(dictionary, "key_use", key_use); key_run = GetKeyBinding(dictionary, "key_run", key_run); key_strafe = GetKeyBinding(dictionary, "key_strafe", key_strafe); mouse_sensitivity = GetInt(dictionary, "mouse_sensitivity", mouse_sensitivity); mouse_disableyaxis = GetBool(dictionary, "mouse_disableyaxis", mouse_disableyaxis); game_alwaysrun = GetBool(dictionary, "game_alwaysrun", game_alwaysrun); video_screenwidth = GetInt(dictionary, "video_screenwidth", video_screenwidth); video_screenheight = GetInt(dictionary, "video_screenheight", video_screenheight); video_fullscreen = GetBool(dictionary, "video_fullscreen", video_fullscreen); video_highresolution = GetBool(dictionary, "video_highresolution", video_highresolution); video_displaymessage = GetBool(dictionary, "video_displaymessage", video_displaymessage); video_gamescreensize = GetInt(dictionary, "video_gamescreensize", video_gamescreensize); video_gammacorrection = GetInt(dictionary, "video_gammacorrection", video_gammacorrection); video_fpsscale = GetInt(dictionary, "video_fpsscale", video_fpsscale); audio_soundvolume = GetInt(dictionary, "audio_soundvolume", audio_soundvolume); audio_musicvolume = GetInt(dictionary, "audio_musicvolume", audio_musicvolume); audio_randompitch = GetBool(dictionary, "audio_randompitch", audio_randompitch); audio_soundfont = GetString(dictionary, "audio_soundfont", audio_soundfont); audio_musiceffect = GetBool(dictionary, "audio_musiceffect", audio_musiceffect); isRestoredFromFile = true; Console.WriteLine("OK"); } catch { Console.WriteLine("Failed"); } } public void Save(string path) { try { using StreamWriter streamWriter = new StreamWriter(path); streamWriter.WriteLine("key_forward = " + key_forward); streamWriter.WriteLine("key_backward = " + key_backward); streamWriter.WriteLine("key_strafeleft = " + key_strafeleft); streamWriter.WriteLine("key_straferight = " + key_straferight); streamWriter.WriteLine("key_turnleft = " + key_turnleft); streamWriter.WriteLine("key_turnright = " + key_turnright); streamWriter.WriteLine("key_fire = " + key_fire); streamWriter.WriteLine("key_use = " + key_use); streamWriter.WriteLine("key_run = " + key_run); streamWriter.WriteLine("key_strafe = " + key_strafe); streamWriter.WriteLine("mouse_sensitivity = " + mouse_sensitivity); streamWriter.WriteLine("mouse_disableyaxis = " + BoolToString(mouse_disableyaxis)); streamWriter.WriteLine("game_alwaysrun = " + BoolToString(game_alwaysrun)); streamWriter.WriteLine("video_screenwidth = " + video_screenwidth); streamWriter.WriteLine("video_screenheight = " + video_screenheight); streamWriter.WriteLine("video_fullscreen = " + BoolToString(video_fullscreen)); streamWriter.WriteLine("video_highresolution = " + BoolToString(video_highresolution)); streamWriter.WriteLine("video_displaymessage = " + BoolToString(video_displaymessage)); streamWriter.WriteLine("video_gamescreensize = " + video_gamescreensize); streamWriter.WriteLine("video_gammacorrection = " + video_gammacorrection); streamWriter.WriteLine("video_fpsscale = " + video_fpsscale); streamWriter.WriteLine("audio_soundvolume = " + audio_soundvolume); streamWriter.WriteLine("audio_musicvolume = " + audio_musicvolume); streamWriter.WriteLine("audio_randompitch = " + BoolToString(audio_randompitch)); streamWriter.WriteLine("audio_soundfont = " + audio_soundfont); streamWriter.WriteLine("audio_musiceffect = " + BoolToString(audio_musiceffect)); } catch { } } private static int GetInt(Dictionary<string, string> dic, string name, int defaultValue) { if (dic.TryGetValue(name, out var value) && int.TryParse(value, out var result)) { return result; } return defaultValue; } private static string GetString(Dictionary<string, string> dic, string name, string defaultValue) { if (dic.TryGetValue(name, out var value)) { return value; } return defaultValue; } private static bool GetBool(Dictionary<string, string> dic, string name, bool defaultValue) { if (dic.TryGetValue(name, out var value)) { if (value == "true") { return true; } if (value == "false") { return false; } } return defaultValue; } private static KeyBinding GetKeyBinding(Dictionary<string, string> dic, string name, KeyBinding defaultValue) { if (dic.TryGetValue(name, out var value)) { return KeyBinding.Parse(value); } return defaultValue; } private static string BoolToString(bool value) { if (!value) { return "false"; } return "true"; } } public static class ConfigUtilities { private static readonly string[] iwadNames = new string[7] { "DOOM2.WAD", "PLUTONIA.WAD", "TNT.WAD", "DOOM.WAD", "DOOM1.WAD", "FREEDOOM2.WAD", "FREEDOOM1.WAD" }; public static string GetExeDirectory() { return Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); } public static string GetConfigPath() { return Path.Combine(GetExeDirectory(), "managed-doom.cfg"); } public static string GetDefaultIwadPath() { string exeDirectory = GetExeDirectory(); string[] array = iwadNames; foreach (string path in array) { string text = Path.Combine(exeDirectory, path); if (File.Exists(text)) { return text; } } string currentDirectory = Directory.GetCurrentDirectory(); array = iwadNames; foreach (string path2 in array) { string text2 = Path.Combine(currentDirectory, path2); if (File.Exists(text2)) { return text2; } } throw new Exception("No IWAD was found!"); } public static bool IsIwad(string path) { string value = Path.GetFileName(path).ToUpper(); return iwadNames.Contains(value); } public static string[] GetWadPaths(CommandLineArgs args) { List<string> list = new List<string>(); if (args.iwad.Present) { list.Add(args.iwad.Value); } else { list.Add(GetDefaultIwadPath()); } if (args.file.Present) { string[] value = args.file.Value; foreach (string item in value) { list.Add(item); } } return list.ToArray(); } } public static class DoomDebug { public static int CombineHash(int a, int b) { return (3 * a) ^ b; } public static int GetMobjHash(Mobj mobj) { return CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(CombineHash(0, mobj.X.Data), mobj.Y.Data), mobj.Z.Data), (int)mobj.Angle.Data), (int)mobj.Sprite), mobj.Frame), mobj.FloorZ.Data), mobj.CeilingZ.Data), mobj.Radius.Data), mobj.Height.Data), mobj.MomX.Data), mobj.MomY.Data), mobj.MomZ.Data), mobj.Tics), (int)mobj.Flags), mobj.Health), (int)mobj.MoveDir), mobj.MoveCount), mobj.ReactionTime), mobj.Threshold); } public static int GetMobjHash(World world) { int num = 0; foreach (Thinker thinker in world.Thinkers) { if (thinker is Mobj mobj) { num = CombineHash(num, GetMobjHash(mobj)); } } return num; } private static string GetMobjCsv(Mobj mobj) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(mobj.X.Data).Append(","); stringBuilder.Append(mobj.Y.Data).Append(","); stringBuilder.Append(mobj.Z.Data).Append(","); stringBuilder.Append((int)mobj.Angle.Data).Append(","); stringBuilder.Append((int)mobj.Sprite).Append(","); stringBuilder.Append(mobj.Frame).Append(","); stringBuilder.Append(mobj.FloorZ.Data).Append(","); stringBuilder.Append(mobj.CeilingZ.Data).Append(","); stringBuilder.Append(mobj.Radius.Data).Append(","); stringBuilder.Append(mobj.Height.Data).Append(","); stringBuilder.Append(mobj.MomX.Data).Append(","); stringBuilder.Append(mobj.MomY.Data).Append(","); stringBuilder.Append(mobj.MomZ.Data).Append(","); stringBuilder.Append(mobj.Tics).Append(","); stringBuilder.Append((int)mobj.Flags).Append(","); stringBuilder.Append(mobj.Health).Append(","); stringBuilder.Append((int)mobj.MoveDir).Append(","); stringBuilder.Append(mobj.MoveCount).Append(","); stringBuilder.Append(mobj.ReactionTime).Append(","); stringBuilder.Append(mobj.Threshold); return stringBuilder.ToString(); } public static void DumpMobjCsv(string path, World world) { using StreamWriter streamWriter = new StreamWriter(path); foreach (Thinker thinker in world.Thinkers) { if (thinker is Mobj mobj) { streamWriter.WriteLine(GetMobjCsv(mobj)); } } } public static int GetSectorHash(Sector sector) { return CombineHash(CombineHash(CombineHash(0, sector.FloorHeight.Data), sector.CeilingHeight.Data), sector.LightLevel); } public static int GetSectorHash(World world) { int num = 0; Sector[] sectors = world.Map.Sectors; foreach (Sector sector in sectors) { num = CombineHash(num, GetSectorHash(sector)); } return num; } } public static class DoomInterop { public static string ToString(byte[] data, int offset, int maxLength) { int num = 0; for (int i = 0; i < maxLength && data[offset + i] != 0; i++) { num++; } char[] array = new char[num]; for (int j = 0; j < array.Length; j++) { byte b = data[offset + j]; if (97 <= b && b <= 122) { b -= 32; } array[j] = (char)b; } return new string(array); } } public sealed class DoomRandom { private static readonly int[] table = new int[256] { 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66, 74, 21, 211, 47, 80, 242, 154, 27, 205, 128, 161, 89, 77, 36, 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188, 52, 140, 202, 120, 68, 145, 62, 70, 184, 190, 91, 197, 152, 224, 149, 104, 25, 178, 252, 182, 202, 182, 141, 197, 4, 81, 181, 242, 145, 42, 39, 227, 156, 198, 225, 193, 219, 93, 122, 175, 249, 0, 175, 143, 70, 239, 46, 246, 163, 53, 163, 109, 168, 135, 2, 235, 25, 92, 20, 145, 138, 77, 69, 166, 78, 176, 173, 212, 166, 113, 94, 161, 41, 50, 239, 49, 111, 164, 70, 60, 2, 37, 171, 75, 136, 156, 11, 56, 42, 146, 138, 229, 73, 146, 77, 61, 98, 196, 135, 106, 63, 197, 195, 86, 96, 203, 113, 101, 170, 247, 181, 113, 80, 250, 108, 7, 255, 237, 129, 226, 79, 107, 112, 166, 103, 241, 24, 223, 239, 120, 198, 58, 60, 82, 128, 3, 184, 66, 143, 224, 145, 224, 81, 206, 163, 45, 63, 90, 168, 114, 59, 33, 159, 95, 28, 139, 123, 98, 125, 196, 15, 70, 194, 253, 54, 14, 109, 226, 71, 17, 161, 93, 186, 87, 244, 138, 20, 52, 123, 251, 26, 36, 17, 46, 52, 231, 232, 76, 31, 221, 84, 37, 216, 165, 212, 106, 197, 242, 98, 43, 39, 175, 254, 145, 190, 84, 118, 222, 187, 136, 120, 163, 236, 249 }; private int index; public DoomRandom() { index = 0; } public DoomRandom(int seed) { index = seed & 0xFF; } public int Next() { index = (index + 1) & 0xFF; return table[index]; } public void Clear() { index = 0; } } public sealed class DoomString { private static Dictionary<string, DoomString> valueTable = new Dictionary<string, DoomString>(); private static Dictionary<string, DoomString> nameTable = new Dictionary<string, DoomString>(); private string original; private string replaced; public char this[int index] => replaced[index]; public DoomString(string original) { this.original = original; replaced = original; if (!valueTable.ContainsKey(original)) { valueTable.Add(original, this); } } public DoomString(string name, string original) : this(original) { nameTable.Add(name, this); } public override string ToString() { return replaced; } public static implicit operator string(DoomString ds) { return ds.replaced; } public static void ReplaceByValue(string original, string replaced) { if (valueTable.TryGetValue(original, out var value)) { value.replaced = replaced; } } public static void ReplaceByName(string name, string value) { if (nameTable.TryGetValue(name, out var value2)) { value2.replaced = value; } } } public static class DeHackEd { private enum Block { None, Thing, Frame, Pointer, Sound, Ammo, Weapon, Cheat, Misc, Text, Sprite, BexStrings, BexPars } private static Tuple<Action<World, Player, PlayerSpriteDef>, Action<World, Mobj>>[] sourcePointerTable; public static void Initialize(CommandLineArgs args, Wad wad) { if (args.deh.Present) { ReadFiles(args.deh.Value); } if (!args.nodeh.Present) { ReadDeHackEdLump(wad); } } private static void ReadFiles(params string[] fileNames) { string text = null; try { DoomInfo.Strings.PRESSKEY.GetHashCode(); Console.Write("Load DeHackEd patches: "); for (int i = 0; i < fileNames.Length; i++) { ProcessLines(File.ReadLines(text = fileNames[i])); } Console.WriteLine("OK (" + string.Join(", ", fileNames.Select((string x) => Path.GetFileName(x))) + ")"); } catch (Exception innerException) { Console.WriteLine("Failed"); throw new Exception("Failed to apply DeHackEd patch: " + text, innerException); } } private static void ReadDeHackEdLump(Wad wad) { int lumpNumber = wad.GetLumpNumber("DEHACKED"); if (lumpNumber != -1) { DoomInfo.Strings.PRESSKEY.GetHashCode(); try { Console.Write("Load DeHackEd patch from WAD: "); ProcessLines(ReadLines(wad.ReadLump(lumpNumber))); Console.WriteLine("OK"); } catch (Exception innerException) { Console.WriteLine("Failed"); throw new Exception("Failed to apply DeHackEd patch!", innerException); } } } private static IEnumerable<string> ReadLines(byte[] data) { using MemoryStream ms = new MemoryStream(data); using StreamReader sr = new StreamReader(ms); for (string text = sr.ReadLine(); text != null; text = sr.ReadLine()) { yield return text; } } private static void ProcessLines(IEnumerable<string> lines) { if (sourcePointerTable == null) { sourcePointerTable = new Tuple<Action<World, Player, PlayerSpriteDef>, Action<World, Mobj>>[DoomInfo.States.Length]; for (int i = 0; i < sourcePointerTable.Length; i++) { Action<World, Player, PlayerSpriteDef> playerAction = DoomInfo.States[i].PlayerAction; Action<World, Mobj> mobjAction = DoomInfo.States[i].MobjAction; sourcePointerTable[i] = Tuple.Create(playerAction, mobjAction); } } int num = 0; List<string> list = new List<string>(); Block type = Block.None; int lineNumber = 0; foreach (string line in lines) { num++; if (line.Length <= 0 || line[0] != '#') { Block blockType = GetBlockType(line.Split(' ')); if (blockType == Block.None) { list.Add(line); continue; } ProcessBlock(type, list, lineNumber); list.Clear(); list.Add(line); type = blockType; lineNumber = num; } } ProcessBlock(type, list, lineNumber); } private static void ProcessBlock(Block type, List<string> data, int lineNumber) { try { switch (type) { case Block.Thing: ProcessThingBlock(data); break; case Block.Frame: ProcessFrameBlock(data); break; case Block.Pointer: ProcessPointerBlock(data); break; case Block.Sound: ProcessSoundBlock(data); break; case Block.Ammo: ProcessAmmoBlock(data); break; case Block.Weapon: ProcessWeaponBlock(data); break; case Block.Cheat: ProcessCheatBlock(data); break; case Block.Misc: ProcessMiscBlock(data); break; case Block.Text: ProcessTextBlock(data); break; case Block.Sprite: ProcessSpriteBlock(data); break; case Block.BexStrings: ProcessBexStringsBlock(data); break; case Block.BexPars: ProcessBexParsBlock(data); break; } } catch (Exception innerException) { throw new Exception("Failed to process block: " + type.ToString() + " (line " + lineNumber + ")", innerException); } } private static void ProcessThingBlock(List<string> data) { int num = int.Parse(data[0].Split(' ')[1]) - 1; MobjInfo mobjInfo = DoomInfo.MobjInfos[num]; Dictionary<string, string> keyValuePairs = GetKeyValuePairs(data); mobjInfo.DoomEdNum = GetInt(keyValuePairs, "ID #", mobjInfo.DoomEdNum); mobjInfo.SpawnState = (MobjState)GetInt(keyValuePairs, "Initial frame", (int)mobjInfo.SpawnState); mobjInfo.SpawnHealth = GetInt(keyValuePairs, "Hit points", mobjInfo.SpawnHealth); mobjInfo.SeeState = (MobjState)GetInt(keyValuePairs, "First moving frame", (int)mobjInfo.SeeState); mobjInfo.SeeSound = (Sfx)GetInt(keyValuePairs, "Alert sound", (int)mobjInfo.SeeSound); mobjInfo.ReactionTime = GetInt(keyValuePairs, "Reaction time", mobjInfo.ReactionTime); mobjInfo.AttackSound = (Sfx)GetInt(keyValuePairs, "Attack sound", (int)mobjInfo.AttackSound); mobjInfo.PainState = (MobjState)GetInt(keyValuePairs, "Injury frame", (int)mobjInfo.PainState); mobjInfo.PainChance = GetInt(keyValuePairs, "Pain chance", mobjInfo.PainChance); mobjInfo.PainSound = (Sfx)GetInt(keyValuePairs, "Pain sound", (int)mobjInfo.PainSound); mobjInfo.MeleeState = (MobjState)GetInt(keyValuePairs, "Close attack frame", (int)mobjInfo.MeleeState); mobjInfo.MissileState = (MobjState)GetInt(keyValuePairs, "Far attack frame", (int)mobjInfo.MissileState); mobjInfo.DeathState = (MobjState)GetInt(keyValuePairs, "Death frame", (int)mobjInfo.DeathState); mobjInfo.XdeathState = (MobjState)GetInt(keyValuePairs, "Exploding frame", (int)mobjInfo.XdeathState); mobjInfo.DeathSound = (Sfx)GetInt(keyValuePairs, "Death sound", (int)mobjInfo.DeathSound); mobjInfo.Speed = GetInt(keyValuePairs, "Speed", mobjInfo.Speed); mobjInfo.Radius = new Fixed(GetInt(keyValuePairs, "Width", mobjInfo.Radius.Data)); mobjInfo.Height = new Fixed(GetInt(keyValuePairs, "Height", mobjInfo.Height.Data)); mobjInfo.Mass = GetInt(keyValuePairs, "Mass", mobjInfo.Mass); mobjInfo.Damage = GetInt(keyValuePairs, "Missile damage", mobjInfo.Damage); mobjInfo.ActiveSound = (Sfx)GetInt(keyValuePairs, "Action sound", (int)mobjInfo.ActiveSound); mobjInfo.Flags = (MobjFlags)GetInt(keyValuePairs, "Bits", (int)mobjInfo.Flags); mobjInfo.Raisestate = (MobjState)GetInt(keyValuePairs, "Respawn frame", (int)mobjInfo.Raisestate); } private static void ProcessFrameBlock(List<string> data) { int num = int.Parse(data[0].Split(' ')[1]); MobjStateDef mobjStateDef = DoomInfo.States[num]; Dictionary<string, string> keyValuePairs = GetKeyValuePairs(data); mobjStateDef.Sprite = (Sprite)GetInt(keyValuePairs, "Sprite number", (int)mobjStateDef.Sprite); mobjStateDef.Frame = GetInt(keyValuePairs, "Sprite subnumber", mobjStateDef.Frame); mobjStateDef.Tics = GetInt(keyValuePairs, "Duration", mobjStateDef.Tics); mobjStateDef.Next = (MobjState)GetInt(keyValuePairs, "Next frame", (int)mobjStateDef.Next); mobjStateDef.Misc1 = GetInt(keyValuePairs, "Unknown 1", mobjStateDef.Misc1); mobjStateDef.Misc2 = GetInt(keyValuePairs, "Unknown 2", mobjStateDef.Misc2); } private static void ProcessPointerBlock(List<string> data) { Dictionary<string, string> keyValuePairs = GetKeyValuePairs(data); int num = data[0].IndexOf('(') + 1; int length = data[0].IndexOf(')') - num; int num2 = int.Parse(data[0].Substring(num, length).Split(' ')[1]); int @int = GetInt(keyValuePairs, "Codep Frame", -1); if (@int != -1) { MobjStateDef obj = DoomInfo.States[num2]; obj.PlayerAction = sourcePointerTable[@int].Item1; obj.MobjAction = sourcePointerTable[@int].Item2; } } private static void ProcessSoundBlock(List<string> data) { } private static void ProcessAmmoBlock(List<string> data) { int num = int.Parse(data[0].Split(' ')[1]); Dictionary<string, string> keyValuePairs = GetKeyValuePairs(data); int[] max = DoomInfo.AmmoInfos.Max; int[] clip = DoomInfo.AmmoInfos.Clip; max[num] = GetInt(keyValuePairs, "Max ammo", max[num]); clip[num] = GetInt(keyValuePairs, "Per ammo", clip[num]); } private static void ProcessWeaponBlock(List<string> data) { int num = int.Parse(data[0].Split(' ')[1]); WeaponInfo weaponInfo = DoomInfo.WeaponInfos[num]; Dictionary<string, string> keyValuePairs = GetKeyValuePairs(data); weaponInfo.Ammo = (AmmoType)GetInt(keyValuePairs, "Ammo type", (int)weaponInfo.Ammo); weaponInfo.UpState = (MobjState)GetInt(keyValuePairs, "Deselect frame", (int)weaponInfo.UpState); weaponInfo.DownState = (MobjState)GetInt(keyValuePairs, "Select frame", (int)weaponInfo.DownState); weaponInfo.ReadyState = (MobjState)GetInt(keyValuePairs, "Bobbing frame", (int)weaponInfo.ReadyState); weaponInfo.AttackState = (MobjState)GetInt(keyValuePairs, "Shooting frame", (int)weaponInfo.AttackState); weaponInfo.FlashState = (MobjState)GetInt(keyValuePairs, "Firing frame", (int)weaponInfo.FlashState); } private static void ProcessCheatBlock(List<string> data) { } private static void ProcessMiscBlock(List<string> data) { Dictionary<string, string> keyValuePairs = GetKeyValuePairs(data); DoomInfo.DeHackEdConst.InitialHealth = GetInt(keyValuePairs, "Initial Health", DoomInfo.DeHackEdConst.InitialHealth); DoomInfo.DeHackEdConst.InitialBullets = GetInt(keyValuePairs, "Initial Bullets", DoomInfo.DeHackEdConst.InitialBullets); DoomInfo.DeHackEdConst.MaxHealth = GetInt(keyValuePairs, "Max Health", DoomInfo.DeHackEdConst.MaxHealth); DoomInfo.DeHackEdConst.MaxArmor = GetInt(keyValuePairs, "Max Armor", DoomInfo.DeHackEdConst.MaxArmor); DoomInfo.DeHackEdConst.GreenArmorClass = GetInt(keyValuePairs, "Green Armor Class", DoomInfo.DeHackEdConst.GreenArmorClass); DoomInfo.DeHackEdConst.BlueArmorClass = GetInt(keyValuePairs, "Blue Armor Class", DoomInfo.DeHackEdConst.BlueArmorClass); DoomInfo.DeHackEdConst.MaxSoulsphere = GetInt(keyValuePairs, "Max Soulsphere", DoomInfo.DeHackEdConst.MaxSoulsphere); DoomInfo.DeHackEdConst.SoulsphereHealth = GetInt(keyValuePairs, "Soulsphere Health", DoomInfo.DeHackEdConst.SoulsphereHealth); DoomInfo.DeHackEdConst.MegasphereHealth = GetInt(keyValuePairs, "Megasphere Health", DoomInfo.DeHackEdConst.MegasphereHealth); DoomInfo.DeHackEdConst.GodModeHealth = GetInt(keyValuePairs, "God Mode Health", DoomInfo.DeHackEdConst.GodModeHealth); DoomInfo.DeHackEdConst.IdfaArmor = GetInt(keyValuePairs, "IDFA Armor", DoomInfo.DeHackEdConst.IdfaArmor); DoomInfo.DeHackEdConst.IdfaArmorClass = GetInt(keyValuePairs, "IDFA Armor Class", DoomInfo.DeHackEdConst.IdfaArmorClass); DoomInfo.DeHackEdConst.IdkfaArmor = GetInt(keyValuePairs, "IDKFA Armor", DoomInfo.DeHackEdConst.IdkfaArmor); DoomInfo.DeHackEdConst.IdkfaArmorClass = GetInt(keyValuePairs, "IDKFA Armor Class", DoomInfo.DeHackEdConst.IdkfaArmorClass); DoomInfo.DeHackEdConst.BfgCellsPerShot = GetInt(keyValuePairs, "BFG Cells/Shot", DoomInfo.DeHackEdConst.BfgCellsPerShot); DoomInfo.DeHackEdConst.MonstersInfight = GetInt(keyValuePairs, "Monsters Infight", 0) == 221; } private static void ProcessTextBlock(List<string> data) { string[] array = data[0].Split(' '); int num = int.Parse(array[1]); int num2 = int.Parse(array[2]); int num3 = 1; int num4 = 0; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < num; i++) { if (num4 == data[num3].Length) { stringBuilder.Append('\n'); num3++; num4 = 0; } else { stringBuilder.Append(data[num3][num4]); num4++; } } StringBuilder stringBuilder2 = new StringBuilder(); for (int j = 0; j < num2; j++) { if (num4 == data[num3].Length) { stringBuilder2.Append('\n'); num3++; num4 = 0; } else { stringBuilder2.Append(data[num3][num4]); num4++; } } DoomString.ReplaceByValue(stringBuilder.ToString(), stringBuilder2.ToString()); } private static void ProcessSpriteBlock(List<string> data) { } private static void ProcessBexStringsBlock(List<string> data) { string text = null; StringBuilder stringBuilder = null; foreach (string item in data.Skip(1)) { if (text == null) { int num = item.IndexOf('='); if (num != -1) { string text2 = item.Substring(0, num).Trim(); string text3 = item.Substring(num + 1).Trim().Replace("\\n", "\n"); if (text3.Last() != '\\') { DoomString.ReplaceByName(text2, text3); continue; } text = text2; stringBuilder = new StringBuilder(); stringBuilder.Append(text3, 0, text3.Length - 1); } } else { string text4 = item.Trim().Replace("\\n", "\n"); if (text4.Last() != '\\') { stringBuilder.Append(text4); DoomString.ReplaceByName(text, stringBuilder.ToString()); text = null; stringBuilder = null; } else { stringBuilder.Append(text4, 0, text4.Length - 1); } } } } private static void ProcessBexParsBlock(List<string> data) { foreach (string item in data.Skip(1)) { string[] array = item.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (array.Length < 3 || !(array[0] == "par")) { continue; } List<int> list = new List<int>(); using (IEnumerator<string> enumerator2 = array.Skip(1).GetEnumerator()) { int result; while (enumerator2.MoveNext() && int.TryParse(enumerator2.Current, out result)) { list.Add(result); } } if (list.Count == 2 && list[0] <= DoomInfo.ParTimes.Doom2.Count) { DoomInfo.ParTimes.Doom2[list[0] - 1] = list[1]; } if (list.Count >= 3 && list[0] <= DoomInfo.ParTimes.Doom1.Count && list[1] <= DoomInfo.ParTimes.Doom1[list[0] - 1].Count) { DoomInfo.ParTimes.Doom1[list[0] - 1][list[1] - 1] = list[2]; } } } private static Block GetBlockType(string[] split) { if (IsThingBlockStart(split)) { return Block.Thing; } if (IsFrameBlockStart(split)) { return Block.Frame; } if (IsPointerBlockStart(split)) { return Block.Pointer; } if (IsSoundBlockStart(split)) { return Block.Sound; } if (IsAmmoBlockStart(split)) { return Block.Ammo; } if (IsWeaponBlockStart(split)) { return Block.Weapon; } if (IsCheatBlockStart(split)) { return Block.Cheat; } if (IsMiscBlockStart(split)) { return Block.Misc; } if (IsTextBlockStart(split)) { return Block.Text; } if (IsSpriteBlockStart(split)) { return Block.Sprite; } if (IsBexStringsBlockStart(split)) { return Block.BexStrings; } if (IsBexParsBlockStart(split)) { return Block.BexPars; } return Block.None; } private static bool IsThingBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Thing") { return false; } if (!IsNumber(split[1])) { return false; } return true; } private static bool IsFrameBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Frame") { return false; } if (!IsNumber(split[1])) { return false; } return true; } private static bool IsPointerBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Pointer") { return false; } return true; } private static bool IsSoundBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Sound") { return false; } if (!IsNumber(split[1])) { return false; } return true; } private static bool IsAmmoBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Ammo") { return false; } if (!IsNumber(split[1])) { return false; } return true; } private static bool IsWeaponBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Weapon") { return false; } if (!IsNumber(split[1])) { return false; } return true; } private static bool IsCheatBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Cheat") { return false; } if (split[1] != "0") { return false; } return true; } private static bool IsMiscBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Misc") { return false; } if (split[1] != "0") { return false; } return true; } private static bool IsTextBlockStart(string[] split) { if (split.Length < 3) { return false; } if (split[0] != "Text") { return false; } if (!IsNumber(split[1])) { return false; } if (!IsNumber(split[2])) { return false; } return true; } private static bool IsSpriteBlockStart(string[] split) { if (split.Length < 2) { return false; } if (split[0] != "Sprite") { return false; } if (!IsNumber(split[1])) { return false; } return true; } private static bool IsBexStringsBlockStart(string[] split) { if (split[0] == "[STRINGS]") { return true; } return false; } private static bool IsBexParsBlockStart(string[] split) { if (split[0] == "[PARS]") { return true; } return false; } private static bool IsNumber(string value) { foreach (char c in value) { if ('0' > c || c > '9') { return false; } } return true; } private static Dictionary<string, string> GetKeyValuePairs(List<string> data) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (string datum in data) { string[] array = datum.Split('='); if (array.Length == 2) { dictionary[array[0].Trim()] = array[1].Trim(); } } return dictionary; } private static int GetInt(Dictionary<string, string> dic, string key, int defaultValue) { if (dic.TryGetValue(key, out var value) && int.TryParse(value, out var result)) { return result; } return defaultValue; } } public class Doom { private CommandLineArgs args; private Config config; private GameContent content; private IVideo video; private ISound sound; private IMusic music; private IUserInput userInput; private List<DoomEvent> events; private GameOptions options; private DoomMenu menu; private OpeningSequence opening; private DemoPlayback demoPlayback; private TicCmd[] cmds; private DoomGame game; private WipeEffect wipeEffect; private bool wiping; private DoomState currentState; private DoomState nextState; private bool needWipe; private bool sendPause; private bool quit; private string quitMessage; private bool mouseGrabbed; public DoomState State => currentState; public OpeningSequence Opening => opening; public DemoPlayback DemoPlayback => demoPlayback; public GameOptions Options => options; public DoomGame Game => game; public DoomMenu Menu => menu; public WipeEffect WipeEffect => wipeEffect; public bool Wiping => wiping; public string QuitMessage => quitMessage; public Doom(CommandLineArgs args, Config config, GameContent content, IVideo video, ISound sound, IMusic music, IUserInput userInput) { video = video ?? NullVideo.GetInstance(); sound = sound ?? NullSound.GetInstance(); music = music ?? NullMusic.GetInstance(); userInput = userInput ?? NullUserInput.GetInstance(); this.args = args; this.config = config; this.content = content; this.video = video; this.sound = sound; this.music = music; this.userInput = userInput; events = new List<DoomEvent>(); options = new GameOptions(args, content); options.Video = video; options.Sound = sound; options.Music = music; options.UserInput = userInput; menu = new DoomMenu(this); opening = new OpeningSequence(content, options); cmds = new TicCmd[Player.MaxPlayerCount]; for (int i = 0; i < Player.MaxPlayerCount; i++) { cmds[i] = new TicCmd(); } game = new DoomGame(content, options); wipeEffect = new WipeEffect(video.WipeBandCount, video.WipeHeight); wiping = false; currentState = DoomState.None; nextState = DoomState.Opening; needWipe = false; sendPause = false; quit = false; quitMessage = null; mouseGrabbed = false; CheckGameArgs(); } private void CheckGameArgs() { if (args.warp.Present) { nextState = DoomState.Game; options.Episode = args.warp.Value.Item1; options.Map = args.warp.Value.Item2; game.DeferedInitNew(); } else if (args.episode.Present) { nextState = DoomState.Game; options.Episode = args.episode.Value; options.Map = 1; game.DeferedInitNew(); } if (args.skill.Present) { options.Skill = (GameSkill)(args.skill.Value - 1); } if (args.deathmatch.Present) { options.Deathmatch = 1; } if (args.altdeath.Present) { options.Deathmatch = 2; } if (args.fast.Present) { options.FastMonsters = true; } if (args.respawn.Present) { options.RespawnMonsters = true; } if (args.nomonsters.Present) { options.NoMonsters = true; } if (args.loadgame.Present) { nextState = DoomState.Game; game.LoadGame(args.loadgame.Value); } if (args.playdemo.Present) { nextState = DoomState.DemoPlayback; demoPlayback = new DemoPlayback(args, content, options, args.playdemo.Value); } if (args.timedemo.Present) { nextState = DoomState.DemoPlayback; demoPlayback = new DemoPlayback(args, content, options, args.timedemo.Value); } } public void NewGame(GameSkill skill, int episode, int map) { game.DeferedInitNew(skill, episode, map); nextState = DoomState.Game; } public void EndGame() { nextState = DoomState.Opening; } private void DoEvents() { if (wiping) { return; } foreach (DoomEvent @event in events) { if (menu.DoEvent(@event) || (@event.Type == EventType.KeyDown && CheckFunctionKey(@event.Key))) { continue; } if (currentState == DoomState.Game) { if (@event.Key == DoomKey.Pause && @event.Type == EventType.KeyDown) { sendPause = true; } else if (!game.DoEvent(@event)) { } } else if (currentState == DoomState.DemoPlayback) { demoPlayback.DoEvent(@event); } } events.Clear(); } private bool CheckFunctionKey(DoomKey key) { switch (key) { case DoomKey.F1: menu.ShowHelpScreen(); return true; case DoomKey.F2: menu.ShowSaveScreen(); return true; case DoomKey.F3: menu.ShowLoadScreen(); return true; case DoomKey.F4: menu.ShowVolumeControl(); return true; case DoomKey.F6: menu.QuickSave(); return true; case DoomKey.F7: if (currentState == DoomState.Game) { menu.EndGame(); } else { options.Sound.StartSound(Sfx.OOF); } return true; case DoomKey.F8: video.DisplayMessage = !video.DisplayMessage; if (currentState == DoomState.Game && game.State == GameState.Level) { string message2 = ((!video.DisplayMessage) ? ((string)DoomInfo.Strings.MSGOFF) : ((string)DoomInfo.Strings.MSGON)); game.World.ConsolePlayer.SendMessage(message2); } menu.StartSound(Sfx.SWTCHN); return true; case DoomKey.F9: menu.QuickLoad(); return true; case DoomKey.F10: menu.Quit(); return true; case DoomKey.F11: { int gammaCorrectionLevel = video.GammaCorrectionLevel; gammaCorrectionLevel++; if (gammaCorrectionLevel > video.MaxGammaCorrectionLevel) { gammaCorrectionLevel = 0; } video.GammaCorrectionLevel = gammaCorrectionLevel; if (currentState == DoomState.Game && game.State == GameState.Level) { string message = ((gammaCorrectionLevel != 0) ? ("Gamma correction level " + gammaCorrectionLevel) : ((string)DoomInfo.Strings.GAMMALVL0)); game.World.ConsolePlayer.SendMessage(message); } return true; } case DoomKey.Quote: case DoomKey.Equal: case DoomKey.Add: if (currentState == DoomState.Game && game.State == GameState.Level && game.World.AutoMap.Visible) { return false; } video.WindowSize = Math.Min(video.WindowSize + 1, video.MaxWindowSize); sound.StartSound(Sfx.STNMOV); return true; case DoomKey.Semicolon: case DoomKey.Hyphen: case DoomKey.Subtract: if (currentState == DoomState.Game && game.State == GameState.Level && game.World.AutoMap.Visible) { return false; } video.WindowSize = Math.Max(video.WindowSize - 1, 0); sound.StartSound(Sfx.STNMOV); return true; default: return false; } } public UpdateResult Update() { DoEvents(); if (!wiping) { menu.Update(); if (nextState != currentState) { if (nextState != DoomState.Opening) { opening.Reset(); } if (nextState != DoomState.DemoPlayback) { demoPlayback = null; } currentState = nextState; } if (quit) { return UpdateResult.Completed; } if (needWipe) { needWipe = false; StartWipe(); } } if (!wiping) { switch (currentState) { case DoomState.Opening: if (opening.Update() == UpdateResult.NeedWipe) { StartWipe(); } break; case DoomState.DemoPlayback: switch (demoPlayback.Update()) { case UpdateResult.NeedWipe: StartWipe(); break; case UpdateResult.Completed: Quit("FPS: " + demoPlayback.Fps.ToString("0.0")); break; } break; case DoomState.Game: userInput.BuildTicCmd(cmds[options.ConsolePlayer]); if (sendPause) { sendPause = false; cmds[options.ConsolePlayer].Buttons |= (byte)(TicCmdButtons.Special | TicCmdButtons.Pause); } if (game.Update(cmds) == UpdateResult.NeedWipe) { StartWipe(); } break; default: throw new Exception("Invalid application state!"); } } if (wiping && wipeEffect.Update() == UpdateResult.Completed) { wiping = false; } sound.Update(); CheckMouseState(); return UpdateResult.None; } private void CheckMouseState() { bool flag = video.HasFocus() && (config.video_fullscreen || (currentState == DoomState.Game && !menu.Active)); if (mouseGrabbed) { if (!flag) { userInput.ReleaseMouse(); mouseGrabbed = false; } } else if (flag) { userInput.GrabMouse(); mouseGrabbed = true; } } private void StartWipe() { wipeEffect.Start(); video.InitializeWipe(); wiping = true; } public void PauseGame() { if (currentState == DoomState.Game && game.State == GameState.Level && !game.Paused && !sendPause) { sendPause = true; } } public void ResumeGame() { if (currentState == DoomState.Game && game.State == GameState.Level && game.Paused && !sendPause) { sendPause = true; } } public bool SaveGame(int slotNumber, string description) { if (currentState == DoomState.Game && game.State == GameState.Level) { game.SaveGame(slotNumber, description); return true; } return false; } public void LoadGame(int slotNumber) { game.LoadGame(slotNumber); nextState = DoomState.Game; } public void Quit() { quit = true; } public void Quit(string message) { quit = true; quitMessage = message; } public void PostEvent(DoomEvent e) { if (events.Count < 64) { events.Add(e); } } } public enum DoomState { None, Opening, DemoPlayback, Game } public sealed class DoomEvent { private EventType type; private DoomKey key; public EventType Type => type; public DoomKey Key => key; public DoomEvent(EventType type, DoomKey key) { this.type = type; this.key = key; } } public enum EventType { KeyDown, KeyUp, Mouse, Joystick } public sealed class Demo { private int p; private byte[] data; private GameOptions options; private int playerCount; public GameOptions Options => options; public Demo(byte[] data) { p = 0; if (data[p++] != 109) { throw new Exception("Demo is from a different game version!"); } this.data = data; options = new GameOptions(); options.Skill = (GameSkill)data[p++]; options.Episode = data[p++]; options.Map = data[p++]; options.Deathmatch = data[p++]; options.RespawnMonsters = data[p++] != 0; options.FastMonsters = data[p++] != 0; options.NoMonsters = data[p++] != 0; options.ConsolePlayer = data[p++]; options.Players[0].InGame = data[p++] != 0; options.Players[1].InGame = data[p++] != 0; options.Players[2].InGame = data[p++] != 0; options.Players[3].InGame = data[p++] != 0; options.DemoPlayback = true; playerCount = 0; for (int i = 0; i < Player.MaxPlayerCount; i++) { if (options.Players[i].InGame) { playerCount++; } } if (playerCount >= 2) { options.NetGame = true; } } public Demo(string fileName) : this(File.ReadAllBytes(fileName)) { } public bool ReadCmd(TicCmd[] cmds) { if (p == data.Length) { return false; } if (data[p] == 128) { return false; } if (p + 4 * playerCount > data.Length) { return false; } Player[] players = options.Players; for (int i = 0; i < Player.MaxPlayerCount; i++) { if (players[i].InGame) { TicCmd obj = cmds[i]; obj.ForwardMove = (sbyte)data[p++]; obj.SideMove = (sbyte)data[p++]; obj.AngleTurn = (short)(data[p++] << 8); obj.Buttons = data[p++]; } } return true; } } public sealed class DoomGame { private enum GameAction { Nothing, LoadLevel, NewGame, LoadGame, SaveGame, Completed, Victory, WorldDone } private GameContent content; private GameOptions options; private GameAction gameAction; private GameState gameState; private int gameTic; private World world; private Intermission intermission; private Finale finale; private bool paused; private int loadGameSlotNumber; private int saveGameSlotNumber; private string saveGameDescription; public GameOptions Options => options; public GameState State => gameState; public int GameTic => gameTic; public World World => world; public Intermission Intermission => intermission; public Finale Finale => finale; public bool Paused => paused; public DoomGame(GameContent content, GameOptions options) { this.content = content; this.options = options; gameAction = GameAction.Nothing; gameTic = 0; } public void DeferedInitNew() { gameAction = GameAction.NewGame; } public void DeferedInitNew(GameSkill skill, int episode, int map) { options.Skill = skill; options.Episode = episode; options.Map = map; gameAction = GameAction.NewGame; } public void LoadGame(int slotNumber) { loadGameSlotNumber = slotNumber; gameAction = GameAction.LoadGame; } public void SaveGame(int slotNumber, string description) { saveGameSlotNumber = slotNumber; saveGameDescription = description; gameAction = GameAction.SaveGame; } public UpdateResult Update(TicCmd[] cmds) { Player[] players = options.Players; for (int i = 0; i < Player.MaxPlayerCount; i++) { if (players[i].InGame && players[i].PlayerState == PlayerState.Reborn) { DoReborn(i); } } while (gameAction != 0) { switch (gameAction) { case GameAction.LoadLevel: DoLoadLevel(); break; case GameAction.NewGame: DoNewGame(); break; case GameAction.LoadGame: DoLoadGame(); break; case GameAction.SaveGame: DoSaveGame(); break; case GameAction.Completed: DoCompleted(); break; case GameAction.Victory: DoFinale(); break; case GameAction.WorldDone: DoWorldDone(); break; } } for (int j = 0; j < Player.MaxPlayerCount; j++) { if (players[j].InGame) { TicCmd cmd = players[j].Cmd; cmd.CopyFrom(cmds[j]); if (cmd.ForwardMove > GameConst.TurboThreshold && (world.LevelTime & 0x1F) == 0 && ((world.LevelTime >> 5) & 3) == j) { players[options.ConsolePlayer].SendMessage(players[j].Name + " is turbo!"); } } } for (int k = 0; k < Player.MaxPlayerCount; k++) { if (players[k].InGame && (players[k].Cmd.Buttons & TicCmdButtons.Special) != 0 && (players[k].Cmd.Buttons & TicCmdButtons.SpecialMask) == TicCmdButtons.Pause) { paused = !paused; if (paused) { options.Sound.Pause(); } else { options.Sound.Resume(); } } } UpdateResult updateResult = UpdateResult.None; switch (gameState) { case GameState.Level: if (!paused || world.FirstTicIsNotYetDone) { updateResult = world.Update(); if (updateResult == UpdateResult.Completed) { gameAction = GameAction.Completed; } } break; case GameState.Intermission: updateResult = intermission.Update(); if (updateResult != UpdateResult.Completed) { break; } gameAction = GameAction.WorldDone; if (world.SecretExit) { players[options.ConsolePlayer].DidSecret = true; } if (options.GameMode != GameMode.Commercial) { break; } switch (options.Map) { case 6: case 11: case 20: case 30: DoFinale(); updateResult = UpdateResult.NeedWipe; break; case 15: case 31: if (world.SecretExit) { DoFinale(); updateResult = UpdateResult.NeedWipe; } break; } break; case GameState.Finale: updateResult = finale.Update(); if (updateResult == UpdateResult.Completed) { gameAction = GameAction.WorldDone; } break; } gameTic++; if (updateResult == UpdateResult.NeedWipe) { return UpdateResult.NeedWipe; } return UpdateResult.None; } private void DoLoadLevel() { gameAction = GameAction.Nothing; gameState = GameState.Level; Player[] players = options.Players; for (int i = 0; i < Player.MaxPlayerCount; i++) { if (players[i].InGame && players[i].PlayerState == PlayerState.Dead) { players[i].PlayerState = PlayerState.Reborn; } Array.Clear(players[i].Frags, 0, players[i].Frags.Length); } intermission = null; options.Sound.Reset(); world = new World(content, options, this); options.UserInput.Reset(); } private void DoNewGame() { gameAction = GameAction.Nothing; InitNew(options.Skill, options.Episode, options.Map); } private void DoLoadGame() { gameAction = GameAction.Nothing; string path = Path.Combine(ConfigUtilities.GetExeDirectory(), "doomsav" + loadGameSlotNumber + ".dsg"); SaveAndLoad.Load(this, path); } private void DoSaveGame() { gameAction = GameAction.Nothing; string path = Path.Combine(ConfigUtilities.GetExeDirectory(), "doomsav" + saveGameSlotNumber + ".dsg"); SaveAndLoad.Save(this, saveGameDescription, path); world.ConsolePlayer.SendMessage(DoomInfo.Strings.GGSAVED); } private void DoCompleted() { gameAction = GameAction.Nothing; for (int i = 0; i < Player.MaxPlayerCount; i++) { if (options.Players[i].InGame) { options.Players[i].FinishLevel(); } } if (options.GameMode != GameMode.Commercial) { switch (options.Map) { case 8: gameAction = GameAction.Victory; return; case 9: { for (int j = 0; j < Player.MaxPlayerCount; j++) { options.Players[j].DidSecret = true; } break; } } } if (options.Map == 8 && options.GameMode != GameMode.Commercial) { gameAction = GameAction.Victory; return; } if (options.Map == 9 && options.GameMode != GameMode.Commercial) { for (int k = 0; k < Player.MaxPlayerCount; k++) { options.Players[k].DidSecret = true; } } IntermissionInfo intermissionInfo = options.IntermissionInfo; intermissionInfo.DidSecret = options.Players[options.ConsolePlayer].DidSecret; intermissionInfo.Episode = options.Episode - 1; intermissionInfo.LastLevel = options.Map - 1; if (options.GameMode == GameMode.Commercial) { if (world.SecretExit) { switch (options.Map) { case 15: intermissionInfo.NextLevel = 30; break; case 31: intermissionInfo.NextLevel = 31; break; } } else { int map = options.Map; if ((uint)(map - 31) <= 1u) { intermissionInfo.NextLevel = 15; } else { intermissionInfo.NextLevel = options.Map; } } } else if (world.SecretExit) { intermissionInfo.NextLevel = 8; } else if (options.Map == 9) { switch (options.Episode) { case 1: intermissionInfo.NextLevel = 3; break; case 2: intermissionInfo.NextLevel = 5; break; case 3: intermissionInfo.NextLevel = 6; break; case 4: intermissionInfo.NextLevel = 2; break; } } else { intermissionInfo.NextLevel = options.Map; } intermissionInfo.MaxKillCount = world.TotalKills; intermissionInfo.MaxItemCount = world.TotalItems; intermissionInfo.MaxSecretCount = world.TotalSecrets; intermissionInfo.TotalFrags = 0; if (options.GameMode == GameMode.Commercial) { intermissionInfo.ParTime = 35 * DoomInfo.ParTimes.Doom2[options.Map - 1]; } else { intermissionInfo.ParTime = 35 * DoomInfo.ParTimes.Doom1[options.Episode - 1][options.Map - 1]; } Player[] players = options.Players; for (int l = 0; l < Player.MaxPlayerCount; l++) { intermissionInfo.Players[l].InGame = players[l].InGame; intermissionInfo.Players[l].KillCount = players[l].KillCount; intermissionInfo.Players[l].ItemCount = players[l].ItemCount; intermissionInfo.Players[l].SecretCount = players[l].SecretCount; intermissionInfo.Players[l].Time = world.LevelTime; Array.Copy(players[l].Frags, intermissionInfo.Players[l].Frags, Player.MaxPlayerCount); } gameState = GameState.Intermission; intermission = new Intermission(options, intermissionInfo); } private void DoWorldDone() { gameAction = GameAction.Nothing; gameState = GameState.Level; options.Map = options.IntermissionInfo.NextLevel + 1; DoLoadLevel(); } private void DoFinale() { gameAction = GameAction.Nothing; gameState = GameState.Finale; finale = new Finale(options); } public void InitNew(GameSkill skill, int episode, int map) { options.Skill = (GameSkill)Math.Clamp((int)skill, 0, 4); if (options.GameMode == GameMode.Retail) { options.Episode = Math.Clamp(episode, 1, 4); } else if (options.GameMode == GameMode.Shareware) { options.Episode = 1; } else { options.Episode = Math.Clamp(episode, 1, 4); } if (options.GameMode == GameMode.Commercial) { options.Map = Math.Clamp(map, 1, 32); } else { options.Map = Math.Clamp(map, 1, 9); } options.Random.Clear(); for (int i = 0; i < Player.MaxPlayerCount; i++) { options.Players[i].PlayerState = PlayerState.Reborn; } DoLoadLevel(); } public bool DoEvent(DoomEvent e) { if (gameState == GameState.Level) { return world.DoEvent(e); } if (gameState == GameState.Finale) { return finale.DoEvent(e); } return false; } private void DoReborn(int playerNumber) { if (!options.NetGame) { gameAction = GameAction.LoadLevel; return; } options.Players[playerNumber].Mobj.Player = null; ThingAllocation thingAllocation = world.ThingAllocation; if (options.Deathmatch != 0) { thingAllocation.DeathMatchSpawnPlayer(playerNumber); return; } if (thingAllocation.CheckSpot(playerNumber, thingAllocation.PlayerStarts[playerNumber])) { thingAllocation.SpawnPlayer(thingAllocation.PlayerStarts[playerNumber]); return; } for (int i = 0; i < Player.MaxPlayerCount; i++) { if (thingAllocation.CheckSpot(playerNumber, thingAllocation.PlayerStarts[i])) { thingAllocation.PlayerStarts[i].Type = playerNumber + 1; world.ThingAllocation.SpawnPlayer(thingAllocation.PlayerStarts[i]); thingAllocation.PlayerStarts[i].Type = i + 1; return; } } world.ThingAllocation.SpawnPlayer(thingAllocation.PlayerStarts[playerNumber]); } } public static class GameConst { public static readonly int TicRate = 35; public static readonly Fixed MaxThingRadius = Fixed.FromInt(32); public static readonly int TurboThreshold = 50; } public sealed class GameContent : IDisposable { private Wad wad; private Palette palette; private ColorMap colorMap; private ITextureLookup textures; private IFlatLookup flats; private ISpriteLookup sprites; private TextureAnimation animation; public Wad Wad => wad; public Palette Palette => palette; public ColorMap ColorMap => colorMap; public ITextureLookup Textures => textures; public IFlatLookup Flats => flats; public ISpriteLookup Sprites => sprites; public TextureAnimation Animation => animation; private GameContent() { } public GameContent(CommandLineArgs args) { wad = new Wad(ConfigUtilities.GetWadPaths(args)); DeHackEd.Initialize(args, wad); palette = new Palette(wad); colorMap = new ColorMap(wad); textures = new TextureLookup(wad); flats = new FlatLookup(wad); sprites = new SpriteLookup(wad); animation = new TextureAnimation(textures, flats); } public static GameContent CreateDummy(params string[] wadPaths) { GameContent gameContent = new GameContent(); gameContent.wad = new Wad(wadPaths); gameContent.palette = new Palette(gameContent.wad); gameContent.colorMap = new ColorMap(gameContent.wad); gameContent.textures = new DummyTextureLookup(gameContent.wad); gameContent.flats = new DummyFlatLookup(gameContent.wad); gameContent.sprites = new DummySpriteLookup(gameContent.wad); gameContent.animation = new TextureAnimation(gameContent.textures, gameContent.flats); return gameContent; } public void Dispose() { if (wad != null) { wad.Dispose(); wad = null; } } } public enum GameMode { Shareware, Registered, Commercial, Retail, Indetermined } public sealed class GameOptions { private GameVersion gameVersion; private GameMode gameMode; private MissionPack missionPack; private Player[] players; private int consolePlayer; private int episode; private int map; private GameSkill skill; private bool demoPlayback; private bool netGame; private int deathmatch; private bool fastMonsters; private bool respawnMonsters; private bool noMonsters; private IntermissionInfo intermissionInfo; private DoomRandom random; private IVideo video; private ISound sound; private IMusic music; private IUserInput userInput; public GameVersion GameVersion { get { return gameVersion; } set { gameVersion = value; } } public GameMode GameMode { get { return gameMode; } set { gameMode = value; } } public MissionPack MissionPack { get { return missionPack; } set { missionPack = value; } } public Player[] Players => players; public int ConsolePlayer { get { return consolePlayer; } set { consolePlayer = value; } } public int Episode { get { return episode; } set { episode = value; } } public int Map { get { return map; } set { map = value; } } public GameSkill Skill { get { return skill; } set { skill = value; } } public bool DemoPlayback { get { return demoPlayback; } set { demoPlayback = value; } } public bool NetGame { get { return netGame; } set { netGame = value; } } public int Deathmatch { get { return deathmatch; } set { deathmatch = value; } } public bool FastMonsters { get { return fastMonsters; } set { fastMonsters = value; } } public bool RespawnMonsters { get { return respawnMonsters; } set { respawnMonsters = value; } } public bool NoMonsters { get { return noMonsters; } set { noMonsters = value; } } public IntermissionInfo IntermissionInfo => intermissionInfo; public DoomRandom Random => random; public IVideo Video { get { return video; } set { video = value; } } public ISound Sound { get { return sound; } set { sound = value; } } public IMusic Music { get { return music; } set { music = value; } } public IUserInput UserInput { get { return userInput; } set { userInput = value; } } public GameOptions() { gameVersion = GameVersion.Version109; gameMode = GameMode.Commercial; missionPack = MissionPack.Doom2; players = new Player[Player.MaxPlayerCount]; for (int i = 0; i < Player.MaxPlayerCount; i++) { players[i] = new Player(i); } players[0].InGame = true; consolePlayer = 0; episode = 1; map = 1; skill = GameSkill.Medium; demoPlayback = false; netGame = false; deathmatch = 0; fastMonsters = false; respawnMonsters = false; noMonsters = false; intermissionInfo = new IntermissionInfo(); random = new DoomRandom(); video = NullVideo.GetInstance(); sound = NullSound.GetInstance(); music = NullMusic.GetInstance(); userInput = NullUserInput.GetInstance(); } public GameOptions(CommandLineArgs args, GameContent content) : this() { if (args.solonet.Present) { netGame = true; } gameVersion = content.Wad.GameVersion; gameMode = content.Wad.GameMode; missionPack = content.Wad.MissionPack; } } public enum GameSkill { Baby, Easy, Medium, Hard, Nightmare } public enum GameState { Level, Intermission, Finale } public enum GameVersion { Version109, Ultimate, Final, Final2 } public enum MissionPack { Doom2, Plutonia, Tnt } public sealed class Player { public static readonly int MaxPlayerCount = 4; public static readonly Fixed NormalViewHeight = Fixed.FromInt(41); private static readonly string[] defaultPlayerNames = new string[4] { "Green", "Indigo", "Brown", "Red" }; private int number; private string name; private bool inGame; private Mobj mobj; private PlayerState playerState; private TicCmd cmd; private Fixed viewZ; private Fixed viewHeight; private Fixed deltaViewHeight; private Fixed bob; private int health; private int armorPoints; private int armorType; private int[] powers; private bool[] cards; private bool backpack; private int[] frags; private WeaponType readyWeapon; private WeaponType pendingWeapon; private bool[] weaponOwned; private int[] ammo; private int[] maxAmmo; private bool attackDown; private bool useDown; private CheatFlags cheats; private int refire; private int killCount; private int itemCount; private int secretCount; private string message; private int messageTime; private int damageCount; private int bonusCount; private Mobj attacker; private int extraLight; private int fixedColorMap; private int colorMap; private PlayerSpriteDef[] playerSprites; private bool didSecret; private bool interpolate; private Fixed oldViewZ; private Angle oldAngle; public int Number => number; public string Name => name; public bool InGame { get { return inGame; } set { inGame = value; } } public Mobj Mobj { get { return mobj; } set { mobj = value; } } public PlayerState PlayerState { get { return playerState; } set { playerState = value; } } public TicCmd Cmd => cmd; public Fixed ViewZ { get { return viewZ; } set { viewZ = value; } } public Fixed ViewHeight { get { return viewHeight; } set { viewHeight = value; } } public Fixed DeltaViewHeight { get { return deltaViewHeight; } set { deltaViewHeight = value; } } public Fixed Bob { get { return bob; } set { bob = value; } } public int Health { get { return health; } set { health = value; } } public int ArmorPoints { get { return armorPoints; } set { armorPoints = value; } } public int ArmorType { get { return armorType; } set { armorType = value; } } public int[] Powers => powers; public bool[] Cards => cards; public bool Backpack { get { return backpack; } set { backpack = value; } } public int[] Frags => frags; public WeaponType ReadyWeapon { get { return readyWeapon; } set { readyWeapon = value; } } public WeaponType PendingWeapon { get { return pendingWeapon; } set { pendingWeapon = value; } } public bool[] WeaponOwned => weaponOwned; public int[] Ammo => ammo; public int[] MaxAmmo => maxAmmo; public bool AttackDown { get { return attackDown; } set { attackDown = value; } } public bool UseDown { get { return useDown; } set { useDown = value; } } public CheatFlags Cheats { get { return cheats; } set { cheats = value; } } public int Refire { get { return refire; } set { refire = value; } } public int KillCount { get { return killCount; } set { killCount = value; } } public int ItemCount { get { return itemCount; } set { itemCount = value; } } public int SecretCount { get { return secretCount; } set { secretCount = value; } } public string Message { get { return message; } set { message = value; } } public int MessageTime { get { return messageTime; } set { messageTime = value; } } public int DamageCount { get { return damageCount; } set { damageCount = value; } } public int BonusCount { get { return bonusCount; } set { bonusCount = value; } } public Mobj Attacker { get { return attacker; } set { attacker = value; } } public int ExtraLight { get { return extraLight; } set { extraLight = value; } } public int FixedColorMap { get { return fixedColorMap; } set { fixedColorMap = value; } } public int ColorMap { get { return colorMap; } set { colorMap = value; } } public PlayerSpriteDef[] PlayerSprites => playerSprites; public bool DidSecret { get { return didSecret; } set { didSecret = value; } } public Player(int number) { this.number = number; name = defaultPlayerNames[number]; cmd = new TicCmd(); powers = new int[6]; cards = new bool[6]; frags = new int[MaxPlayerCount]; weaponOwned = new bool[9]; ammo = new int[4]; maxAmmo = new int[4]; playerSprites = new PlayerSpriteDef[2]; for (int i = 0; i < playerSprites.Length; i++) { playerSprites[i] = new PlayerSpriteDef(); } } public void Clear() { mobj = null; playerState = PlayerState.Live; cmd.Clear(); viewZ = Fixed.Zero; viewHeight = Fixed.Zero; deltaViewHeight = Fixed.Zero; bob = Fixed.Zero; health = 0; armorPoints = 0; armorType = 0; Array.Clear(powers, 0, powers.Length); Array.Clear(cards, 0, cards.Length); backpack = false; Array.Clear(frags, 0, frags.Length); readyWeapon = WeaponType.Fist; pendingWeapon = WeaponType.Fist; Array.Clear(weaponOwned, 0, weaponOwned.Length); Array.Clear(ammo, 0, ammo.Length); Array.Clear(maxAmmo, 0, maxAmmo.Length); useDown = false; attackDown = false; cheats = (CheatFlags)0; refire = 0; killCount = 0; itemCount = 0; secretCount = 0; message = null; messageTime = 0; damageCount = 0; bonusCount = 0; attacker = null; extraLight = 0; fixedColorMap = 0; colorMap = 0; PlayerSpriteDef[] array = playerSprites; for (int i = 0; i < array.Length; i++) { array[i].Clear(); } didSecret = false; interpolate = false; oldViewZ = Fixed.Zero; oldAngle = Angle.Ang0; } public void Reborn() { mobj = null; playerState = PlayerState.Live; cmd.Clear(); viewZ = Fixed.Zero; viewHeight = Fixed.Zero; deltaViewHeight = Fixed.Zero; bob = Fixed.Zero; health = DoomInfo.DeHackEdConst.InitialHealth; armorPoints = 0; armorType = 0; Array.Clear(powers, 0, powers.Length); Array.Clear(cards, 0, cards.Length); backpack = false; readyWeapon = WeaponType.Pistol; pendingWeapon = WeaponType.Pistol; Array.Clear(weaponOwned, 0, weaponOwned.Length); Array.Clear(ammo, 0, ammo.Length); Array.Clear(maxAmmo, 0, maxAmmo.Length); weaponOwned[0] = true; weaponOwned[1] = true; ammo[0] = DoomInfo.DeHackEdConst.InitialBullets; for (int i = 0; i < 4; i++) { maxAmmo[i] = DoomInfo.AmmoInfos.Max[i]; } useDown = true; attackDown = true; cheats = (CheatFlags)0; refire = 0; message = null; messageTime = 0; damageCount = 0; bonusCount = 0; attacker = null; extraLight = 0; fixedColorMap = 0; colorMap = 0; PlayerSpriteDef[] array = playerSprites; for (int j = 0; j < array.Length; j++) { array[j].Clear(); } didSecret = false; interpolate = false; oldViewZ = Fixed.Zero; oldAngle = Angle.Ang0; } public void FinishLevel() { Array.Clear(powers, 0, powers.Length); Array.Clear(cards, 0, cards.Length); mobj.Flags &= ~MobjFlags.Shadow; extraLight = 0; fixedColorMap = 0; damageCount = 0; bonusCount = 0; } public void SendMessage(string message) { if ((object)this.message != (string)DoomInfo.Strings.MSGOFF || (object)message == (string)DoomInfo.Strings.MSGON) { this.message = message; messageTime = 4 * GameConst.TicRate; } } public void UpdateFrameInterpolationInfo() { interpolate = true; oldViewZ = viewZ; oldAngle = mobj.Angle; } public void DisableFrameInterpolationForOneFrame() { interpolate = false; } public Fixed GetInterpolatedViewZ(Fixed frameFrac) { if (interpolate && mobj.World.LevelTime > 1) { return oldViewZ + frameFrac * (viewZ - oldViewZ); } return viewZ; } public Angle GetInterpolatedAngle(Fixed frameFrac) { if (interpolate) { Angle angle = mobj.Angle - oldAngle; if (angle < Angle.Ang180) { return oldAngle + Angle.FromDegree(frameFrac.ToDouble() * angle.ToDegree()); } return oldAngle - Angle.FromDegree(frameFrac.ToDouble() * (360.0 - angle.ToDegree())); } return mobj.Angle; } } public enum PlayerState { Live, Dead, Reborn } public static class SaveAndLoad { private enum ThinkerClass { End, Mobj } private enum SpecialClass { Ceiling, Door, Floor, Plat, Flash, Strobe, Glow, EndSpecials } private class SaveGame { private byte[] data; private int ptr; public SaveGame(string description) { data = new byte[saveBufferSize]; ptr = 0; WriteDescription(description); WriteVersion(); } private void WriteDescription(string description) { for (int i = 0; i < description.Length; i++) { data[i] = (byte)description[i]; } ptr += DescriptionSize; } private void WriteVersion() { string text = "version 109"; for (int i = 0; i < text.Length; i++) { data[ptr + i] = (byte)text[i]; } ptr += versionSize; } public void Save(DoomGame game, string path) { GameOptions options = game.World.Options; data[ptr++] = (byte)options.Skill; data[ptr++] = (byte)options.Episode; data[ptr++] = (byte)options.Map; for (int i = 0; i < Player.MaxPlayerCount; i++) { data[ptr++] = (options.Players[i].InGame ? ((byte)1) : ((byte)0)); } data[ptr++] = (byte)(game.World.LevelTime >> 16); data[ptr++] = (byte)(game.World.LevelTime >> 8); data[ptr++] = (byte)game.World.LevelTime; ArchivePlayers(game.World); ArchiveWorld(game.World); ArchiveThinkers(game.World); ArchiveSpecials(game.World); data[ptr++] = 29; using FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write); fileStream.Write(data, 0, ptr); } private void PadPointer() { ptr += (4 - (ptr & 3)) & 3; } private void ArchivePlayers(World world) { Player[] players = world.Options.Players; for (int i = 0; i < Player.MaxPlayerCount; i++) { if (players[i].InGame) { PadPointer(); ptr = ArchivePlayer(players[i], data, ptr); } } } private void ArchiveWorld(World world) { Sector[] sectors = world.Map.Sectors; for (int i = 0; i < sectors.Length; i++) { ptr = ArchiveSector(sectors[i], data, ptr); } LineDef[] lines = world.Map.Lines; for (int j = 0; j < lines.Length; j++) { ptr = ArchiveLine(lines[j], data, ptr); } } private void ArchiveThinkers(World world) { foreach (Thinker thinker in world.Thinkers) { if (thinker is Mobj mobj) { data[ptr++] = 1; PadPointer(); WriteThinkerState(data, ptr + 8, mobj.ThinkerState); Write(data, ptr + 12, mobj.X.Data); Write(data, ptr + 16, mobj.Y.Data); Write(data, ptr + 20, mobj.Z.Data); Write(data, ptr + 32, mobj.Angle.Data); Write(data, ptr + 36, (int)mobj.Sprite); Write(data, ptr + 40, mobj.Frame); Write(data, ptr + 56, mobj.FloorZ.Data); Write(data, ptr + 60, mobj.CeilingZ.Data); Write(data, ptr + 64, mobj.Radius.Data); Write(data, ptr + 68, mobj.Height.Data); Write(data, ptr + 72, mobj.MomX.Data); Write(data, ptr + 76, mobj.MomY.Data); Write(data, ptr + 80, mobj.MomZ.Data); Write(data, ptr + 88, (int)mobj.Type); Write(data, ptr + 96, mobj.Tics); Write(data, ptr + 100, mobj.State.Number); Write(data, ptr + 104, (int)mobj.Flags); Write(data, ptr + 108, mobj.Health); Write(data, ptr + 112, (int)mobj.MoveDir); Write(data, ptr + 116, mobj.MoveCount); Write(data, ptr + 124, mobj.ReactionTime); Write(data, ptr + 128, mobj.Threshold); if (mobj.Player == null) { Write(data, ptr + 132, 0); } else { Write(data, ptr + 132, mobj.Player.Number + 1); } Write(data, ptr + 136, mobj.LastLook); if (mobj.SpawnPoint == null) { Write(data, ptr + 140, (short)0); Write(data, ptr + 142, (short)0); Write(data, ptr + 144, (short)0); Write(data, ptr + 146, (short)0); Write(data, ptr + 148, (short)0); } else { Write(data, ptr + 140, (short)mobj.SpawnPoint.X.ToIntFloor()); Write(data, ptr + 142, (short)mobj.SpawnPoint.Y.ToIntFloor()); Write(data, ptr + 144, (short)Math.Round(mobj.SpawnPoint.Angle.ToDegree())); Write(data, ptr + 146, (short)mobj.SpawnPoint.Type); Write(data, ptr + 148, (short)mobj.SpawnPoint.Flags); } ptr += 154; } } data[ptr++] = 0; } private void ArchiveSpecials(World world) { Thinkers thinkers = world.Thinkers; SectorAction sectorAction = world.SectorAction; foreach (Thinker item in thinkers) { if (item.ThinkerState == ThinkerState.InStasis) { CeilingMove ceilingMove = item as CeilingMove; if (sectorAction.CheckActiveCeiling(ceilingMove)) { data[ptr++] = 0; PadPointer(); WriteThinkerState(data, ptr + 8, ceilingMove.ThinkerState); Write(data, ptr + 12, (int)ceilingMove.Type); Write(data, ptr + 16, ceilingMove.Sector.Number); Write(data, ptr + 20, ceilingMove.BottomHeight.Data); Write(data, ptr + 24, ceilingMove.TopHeight.Data); Write(data, ptr + 28, ceilingMove.Speed.Data); Write(data, ptr + 32, ceilingMove.Crush ? 1 : 0); Write(data, ptr + 36, ceilingMove.Direction); Write(data, ptr + 40, ceilingMove.Tag); Write(data, ptr + 44, ceilingMove.OldDirection); ptr += 48; } } else if (item is CeilingMove ceilingMove2) { data[ptr++] = 0; PadPointer(); WriteThinkerState(data, ptr + 8, ceilingMove2.ThinkerState); Write(data, ptr + 12, (int)ceilingMove2.Type); Write(data, ptr + 16, ceilingMove2.Sector.Number); Write(data, ptr + 20, ceilingMove2.BottomHeight.Data); Write(data, ptr + 24, ceilingMove2.TopHeight.Data); Write(data, ptr + 28, ceilingMove2.Speed.Data); Write(data, ptr + 32, ceilingMove2.Crush ? 1 : 0); Write(data, ptr + 36, ceilingMove2.Direction); Write(data, ptr + 40, ceilingMove2.Tag); Write(data, ptr + 44, ceilingMove2.OldDirection); ptr += 48; } else if (item is VerticalDoor verticalDoor) { data[ptr++] = 1; PadPointer(); WriteThinkerState(data, ptr + 8, verticalDoor.ThinkerState); Write(data, ptr + 12, (int)verticalDoor.Type); Write(data, ptr + 16, verticalDoor.Sector.Number); Write(data, ptr + 20, verticalDoor.TopHeight.Data); Write(data, ptr + 24, verticalDoor.Speed.Data); Write(data, ptr + 28, verticalDoor.Direction); Write(data, ptr + 32, verticalDoor.TopWait); Write(data, ptr + 36, verticalDoor.TopCountDown); ptr += 40; } else if (item is FloorMove floorMove) { data[ptr++] = 2; PadPointer(); WriteThinkerState(data, ptr + 8, floorMove.ThinkerState); Write(data, ptr + 12, (int)floorMove.Type); Write(data, ptr + 16, floorMove.Crush ? 1 : 0); Write(data, ptr + 20, floorMove.Sector.Number); Write(data, ptr + 24, floorMove.Direction); Write(data, ptr + 28, (int)floorMove.NewSpecial); Write(data, ptr + 32, floorMove.Texture); Write(data, ptr + 36, floorMove.FloorDestHeight.Data); Write(data, ptr + 40, floorMove.Speed.Data); ptr += 44; } else if (item is Platform platform) { data[ptr++] = 3; PadPointer(); WriteThinkerState(data, ptr + 8, platform.ThinkerState); Write(data, ptr + 12, platform.Sector.Number); Write(data, ptr + 16, platform.Speed.Data); Write(data, ptr + 20, platform.Low.Data); Write(data, ptr + 24, platform.High.Data); Write(data, ptr + 28, platform.Wait); Write(data, ptr + 32, platform.Count); Write(data, ptr + 36, (int)platform.Status); Write(data, ptr + 40, (int)platform.OldStatus); Write(data, ptr + 44, platform.Crush ? 1 : 0); Write(data, ptr + 48, platform.Tag); Write(data, ptr + 52, (int)platform.Type); ptr += 56; } else if (item is LightFlash lightFlash) { data[ptr++] = 4; PadPointer(); WriteThinkerState(data, ptr + 8, lightFlash.ThinkerState); Write(data, ptr + 12, lightFlash.Sector.Number); Write(data, ptr + 16, lightFlash.Count); Write(data, ptr + 20, lightFlash.MaxLight); Write(data, ptr + 24, lightFlash.MinLight); Write(data, ptr + 28, lightFlash.MaxTime); Write(data, ptr + 32, lightFlash.MinTime); ptr += 36; } else if (item is StrobeFlash strobeFlash) { data[ptr++] = 5; PadPointer(); WriteThinkerState(data, ptr + 8, strobeFlash.ThinkerState); Write(data, ptr + 12, strobeFlash.Sector.Number); Write(data, ptr + 16, strobeFlash.Count); Write(data, ptr + 20, strobeFlash.MinLight); Write(data, ptr + 24, strobeFlash.MaxLight); Write(data, ptr + 28, strobeFlash.DarkTime); Write(data, ptr + 32, strobeFlash.BrightTime); ptr += 36; } else if (item is GlowingLight glowingLight) { data[ptr++] = 6; PadPointer(); WriteThinkerState(data, ptr + 8, glowingLight.ThinkerState); Write(data, ptr + 12, glowingLight.Sector.Number); Write(data, ptr + 16, glowingLight.MinLight); Write(data, ptr + 20, glowingLight.MaxLight); Write(data, ptr + 24, glowingLight.Direction); ptr += 28; } } data[ptr++] = 7; } private static int ArchivePlayer(Player player, byte[] data, int p) { Write(data, p + 4, (int)player.PlayerState); Write(data, p + 16, player.ViewZ.Data); Write(data, p + 20, player.ViewHeight.Data); Write(data, p + 24, player.DeltaViewHeight.Data); Write(data, p + 28, player.Bob.Data); Write(data, p + 32, player.Health); Write(data, p + 36, player.ArmorPoints); Write(data, p + 40, player.ArmorType); for (int i = 0; i < 6; i++) { Write(data, p + 44 + 4 * i, player.Powers[i]); } for (int j = 0; j < 6; j++) { Write(data, p + 68 + 4 * j, player.Cards[j] ? 1 : 0); } Write(data, p + 92, player.Backpack ? 1 : 0); for (int k = 0; k < Player.MaxPlayerCount; k++) { Write(data, p + 96 + 4 * k, player.Frags[k]); } Write(data, p + 112, (int)player.ReadyWeapon); Write(data, p + 116, (int)player.PendingWeapon); for (int l = 0; l < 9; l++) { Write(data, p + 120 + 4 * l, player.WeaponOwned[l] ? 1 : 0); } for (int m = 0; m < 4; m++) { Write(data, p + 156 + 4 * m, player.Ammo[m]); } for (int n = 0; n < 4; n++) { Write(data, p + 172 + 4 * n, player.MaxAmmo[n]); } Write(data, p + 188, player.AttackDown ? 1 : 0); Write(data, p + 192, player.UseDown ? 1 : 0); Write(data, p + 196, (int)player.Cheats); Write(data, p + 200, player.Refire); Write(data, p + 204, player.KillCount); Write(data, p + 208, player.ItemCount); Write(data, p + 212, player.SecretCount); Write(data, p + 220, player.DamageCount); Write(data, p + 224, player.BonusCount); Write(data, p + 232, player.ExtraLight); Write(data, p + 236, player.FixedColorMap); Write(data, p + 240, player.ColorMap); for (int num = 0; num < 2; num++) { if (player.PlayerSprites[num].State == null) { Write(data, p + 244 + 16 * num, 0); } else { Write(data, p + 244 + 16 * num, player.PlayerSprites[num].State.Number); } Write(data, p + 244 + 16 * num + 4, player.PlayerSprites[num].Tics); Write(data, p + 244 + 16 * num + 8, player.PlayerSprites[num].Sx.Data); Write(data, p + 244 + 16 * num + 12, player.PlayerSprites[num].Sy.Data); } Write(data, p + 276, player.DidSecret ? 1 : 0); return p + 280; } private static int ArchiveSector(Sector sector, byte[] data, int p) { Write(data, p, (short)sector.FloorHeight.ToIntFloor()); Write(data, p + 2, (short)sector.CeilingHeight.ToIntFloor()); Write(data, p + 4, (short)sector.FloorFlat); Write(data, p + 6, (short)sector.CeilingFlat); Write(data, p + 8, (short)sector.LightLevel); Write(data, p + 10, (short)sector.Special); Write(data, p + 12, (short)sector.Tag); return p + 14; } private static int ArchiveLine(LineDef line, byte[] data, int p) { Write(data, p, (short)line.Flags); Write(data, p + 2, (short)line.Special); Write(data, p + 4, line.Tag); p += 6; if (line.FrontSide != null) { SideDef frontSide = line.FrontSide; Write(data, p, (short)frontSide.TextureOffset.ToIntFloor()); Write(data, p + 2, (short)frontSide.RowOffset.ToIntFloor()); Write(data, p + 4, (short)frontSide.TopTexture); Write(data, p + 6, (short)frontSide.BottomTexture); Write(data, p + 8, (short)frontSide.MiddleTexture); p += 10; } if (line.BackSide != null) { SideDef backSide = line.BackSide; Write(data, p, (short)backSide.TextureOffset.ToIntFloor()); Write(data, p + 2, (short)backSide.RowOffset.ToIntFloor()); Write(data, p + 4, (short)backSide.TopTexture); Write(data, p + 6, (short)backSide.BottomTexture); Write(data, p + 8, (short)backSide.MiddleTexture); p += 10; } return p; } private static void Write(byte[] data, int p, int value) { data[p] = (byte)value; data[p + 1] = (byte)(value >> 8); data[p + 2] = (byte)(value >> 16); data[p + 3] = (byte)(value >> 24); } private static void Write(byte[] data, int p, uint value) { data[p] = (byte)value; data[p + 1] = (byte)(value >> 8); data[p + 2] = (byte)(value >> 16); data[p + 3] = (byte)(value >> 24); } private static void Write(byte[] data, int p, short value) { data[p] = (byte)value; data[p + 1] = (byte)(value >> 8); } private static void WriteThinkerState(byte[] data, int p, ThinkerState state) { if (state == ThinkerState.InStasis) { Write(data, p, 0); } else { Write(data, p, 1); } } } private class LoadGame { private byte[] data; private int ptr; public LoadGame(byte[] data) { this.data = data; ptr = 0; ReadDescription(); if (ReadVersion() != "VERSION 109") { throw new Exception("Unsupported version!"); } } public void Load(DoomGame game) { GameOptions options = game.World.Options; options.Skill = (GameSkill)data[ptr++]; options.Episode = data[ptr++]; options.Map = data[ptr++]; for (int i = 0; i < Player.MaxPlayerCount; i++) { options.Players[i].InGame = data[ptr++] != 0; } game.InitNew(options.Skill, options.Episode, options.Map); byte num = data[ptr++]; byte b = data[ptr++]; byte b2 = data[ptr++]; int levelTime = (num << 16) + (b << 8) + b2; UnArchivePlayers(game.World); UnArchiveWorld(game.World); UnArchiveThinkers(game.World); UnArchiveSpecials(game.World); if (data[ptr] != 29) { throw new Exception("Bad savegame!"); } game.World.LevelTime = levelTime; options.Sound.SetListener(game.World.ConsolePlayer.Mobj); } private void PadPointer() { ptr += (4 - (ptr & 3)) & 3; } private string ReadDescription() { string result = DoomInterop.ToString(data, ptr, DescriptionSize); ptr += DescriptionSize; return result; } private string ReadVersion() { string result = DoomInterop.ToString(data, ptr, versionSize); ptr += versionSize; return result; } private void UnArchivePlayers(World world) { Player[] players = world.Options.Players; for (int i = 0; i < Player.MaxPlayerCount; i++) { if (players[i].InGame) { PadPointer(); ptr = UnArchivePlayer(players[i], data, ptr); } } } private void UnArchiveWorld(World world) { Sector[] sectors = world.Map.Sectors; for (int i = 0; i < sectors.Length; i++) { ptr = UnArchiveSector(sectors[i], data, ptr); } LineDef[] lines = world.Map.Lines; for (int j = 0; j < lines.Length; j++) { ptr = UnArchiveLine(lines[j], data, ptr); } } private void UnArchiveThinkers(World world) { Thinkers thinkers = world.Thinkers; ThingAllocation thingAllocation = world.ThingAllocation; foreach (Thinker item in thinkers) { if (item is Mobj mobj) { thingAllocation.RemoveMobj(mobj); } } thinkers.Reset(); while (true) { Mobj mobj2; switch ((ThinkerClass)data[ptr++]) { case ThinkerClass.End: return; case ThinkerClass.Mobj: { PadPointer(); mobj2 = new Mobj(world); mobj2.ThinkerState = ReadThinkerState(data, ptr + 8); mobj2.X = new Fixed(BitConverter.ToInt32(data, ptr + 12)); mobj2.Y = new Fixed(BitConverter.ToInt32(data, ptr + 16)); mobj2.Z = new Fixed(BitConverter.ToInt32(data, ptr + 20)); mobj2.Angle = new Angle(BitConverter.ToInt32(data, ptr + 32)); mobj2.Sprite = (Sprite)BitConverter.ToInt32(data, ptr + 36); mobj2.Frame = BitConverter.ToInt32(data, ptr + 40); mobj2.FloorZ = new Fixed(BitConverter.ToInt32(data, ptr + 56)); mobj2.CeilingZ = new Fixed(BitConverter.ToInt32(data, ptr + 60)); mobj2.Radius = new Fixed(BitConverter.ToInt32(data, ptr + 64)); mobj2.Height = new Fixed(BitConverter.ToInt32(data, ptr + 68)); mobj2.MomX = new Fixed(BitConverter.ToInt32(data, ptr + 72)); mobj2.MomY = new Fixed(BitConverter.ToInt32(data, ptr + 76)); mobj2.MomZ = new Fixed(BitConverter.ToInt32(data, ptr + 80)); mobj2.Type = (MobjType)BitConverter.ToInt32(data, ptr + 88); mobj2.Info = DoomInfo.MobjInfos[(int)mobj2.Type]; mobj2.Tics = BitConverter.ToInt32(data, ptr + 96); mobj2.State = DoomInfo.States[BitConverter.ToInt32(data, ptr + 100)]; mobj2.Flags = (MobjFlags)BitConverter.ToInt32(data, ptr + 104); mobj2.Health = BitConverter.ToInt32(data, ptr + 108); mobj2.MoveDir = (Direction)BitConverter.ToInt32(data, ptr + 112); mobj2.MoveCount = BitConverter.ToInt32(data, ptr + 116); mobj2.ReactionTime = BitConverter.ToInt32(data, ptr + 124); mobj2.Threshold = BitConverter.ToInt32(data, ptr + 128); int num = BitConverter.ToInt32(data, ptr + 132); if (num != 0) { mobj2.Player = world.Options.Players[num - 1]; mobj2.Player.Mobj = mobj2; } break; } default: throw new Exception("Unknown thinker class in savegame!"); } mobj2.LastLook = BitConverter.ToInt32(data, ptr + 136); mobj2.SpawnPoint = new MapThing(Fixed.FromInt(BitConverter.ToInt16(data, ptr + 140)), Fixed.FromInt(BitConverter.ToInt16(data, ptr + 142)), new Angle(Angle.Ang45.Data * (uint)(BitConverter.ToInt16(data, ptr + 144) / 45)), BitConverter.ToInt16(data, ptr + 146), (ThingFlags)BitConverter.ToInt16(data, ptr + 148)); ptr += 154; world.ThingMovement.SetThingPosition(mobj2); thinkers.Add(mobj2); } } private void UnArchiveSpecials(World world) { Thinkers thinkers = world.Thinkers; SectorAction sectorAction = world.SectorAction; while (true) { switch ((SpecialClass)data[ptr++]) { case SpecialClass.EndSpecials: return; case SpecialClass.Ceiling: { PadPointer(); CeilingMove ceilingMove = new CeilingMove(world); ceilingMove.ThinkerState = ReadThinkerState(data, ptr + 8); ceilingMove.Type = (CeilingMoveType)BitConverter.ToInt32(data, ptr + 12); ceilingMove.Sector = world.Map.Sectors[BitConverter.ToInt32(data, ptr + 16)]; ceilingMove.Sector.SpecialData = ceilingMove; ceilingMove.BottomHeight = new Fixed(BitConverter.ToInt32(data, ptr + 20)); ceilingMove.TopHeight = new Fixed(BitConverter.ToInt32(data, ptr + 24)); ceilingMove.Speed = new Fixed(BitConverter.ToInt32(data, ptr + 28)); ceilingMove.Crush = BitConverter.ToInt32(data, ptr + 32) != 0; ceilingMove.Direction = BitConverter.ToInt32(data, ptr + 36); ceilingMove.Tag = BitConverter.ToInt32(data, ptr + 40); ceilingMove.OldDirection = BitConverter.ToInt32(data, ptr + 44); ptr += 48; thinkers.Add(ceilingMove); sectorAction.AddActiveCeiling(ceilingMove); break; } case SpecialClass.Door: { PadPointer(); VerticalDoor verticalDoor = new VerticalDoor(world); verticalDoor.ThinkerState = ReadThinkerState(data, ptr + 8); verticalDoor.Type = (VerticalDoorType)BitConverter.ToInt32(data, ptr + 12); verticalDoor.Sector = world.Map.Sectors[BitConverter.ToInt32(data, ptr + 16)]; verticalDoor.Sector.SpecialData = verticalDoor; verticalDoor.TopHeight = new Fixed(BitConverter.ToInt32(data, ptr + 20)); verticalDoor.Speed = new Fixed(BitConverter.ToInt32(data, ptr + 24)); verticalDoor.Direction = BitConverter.ToInt32(data, ptr + 28); verticalDoor.TopWait = BitConverter.ToInt32(data, ptr + 32); verticalDoor.TopCountDown = BitConverter.ToInt32(data, ptr + 36); ptr += 40; thinkers.Add(verticalDoor); break; } case SpecialClass.Floor: { PadPointer(); FloorMove floorMove = new FloorMove(world); floorMove.ThinkerState = ReadThinkerState(data, ptr + 8); floorMove.Type = (FloorMoveType)BitConverter.ToInt32(data, ptr + 12); floorMove.Crush = BitConverter.ToInt32(data, ptr + 16) != 0; floorMove.Sector = world.Map.Sectors[BitConverter.ToInt32(data, ptr + 20)]; floorMove.Sector.SpecialData = floorMove; floorMove.Direction = BitConverter.ToInt32(data, ptr + 24); floorMove.NewSpecial = (SectorSpecial)BitConverter.ToInt32(data, ptr + 28); floorMove.Texture = BitConverter.ToInt32(data, ptr + 32); floorMove.FloorDestHeight = new Fixed(BitConverter.ToInt32(data, ptr + 36)); floorMove.Speed = new Fixed(BitConverter.ToInt32(data, ptr + 40)); ptr += 44; thinkers.Add(floorMove); break; } case SpecialClass.Plat: { PadPointer(); Platform platform = new Platform(world); platform.ThinkerState = ReadThinkerState(data, ptr + 8); platform.Sector = world.Map.Sectors[BitConverter.ToInt32(data, ptr + 12)]; platform.Sector.SpecialData = platform; platform.Speed = new Fixed(BitConverter.ToInt32(data, ptr + 16)); platform.Low = new Fixed(BitConverter.ToInt32(data, ptr + 20)); platform.High = new Fixed(BitConverter.ToInt32(data, ptr + 24)); platform.Wait = BitConverter.ToInt32(data, ptr + 28); platform.Count = BitConverter.ToInt32(data, ptr + 32); platform.Status = (PlatformState)BitConverter.ToInt32(data, ptr + 36); platform.OldStatus = (PlatformState)BitConverter.ToInt32(data, ptr + 40); platform.Crush = BitConverter.ToInt32(data, ptr + 44) != 0; platform.Tag = BitConverter.ToInt32(data, ptr + 48); platform.Type = (PlatformType)BitConverter.ToInt32(data, ptr + 52); ptr += 56; thinkers.Add(platform); sectorAction.AddAc
BepInEx/plugins/LethalCompanyInputUtils.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using LethalCompanyInputUtils.Api; using LethalCompanyInputUtils.Data; using LethalCompanyInputUtils.Utils; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using TMPro; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalCompanyInputUtils")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+9e95a88c49ab86635dbebf33cfb26802052a8769")] [assembly: AssemblyProduct("LethalCompanyInputUtils")] [assembly: AssemblyTitle("LethalCompanyInputUtils")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] 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 LethalCompanyInputUtils { public static class LcInputActionApi { private static readonly Dictionary<string, LcInputActions> InputActionsMap = new Dictionary<string, LcInputActions>(); private static IReadOnlyCollection<LcInputActions> InputActions => InputActionsMap.Values; internal static void LoadIntoUI(KepRemapPanel panel) { //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Expected O, but got Unknown UpdateFontScaling(panel); AdjustSizeAndPos(panel); LayoutElement val = EnsureLayoutElement(panel); val.minHeight = 0f; List<RemappableKey> remappableKeys = panel.remappableKeys; int num = remappableKeys.Count((RemappableKey key) => !key.gamepadOnly); foreach (LcInputActions inputAction in InputActions) { if (inputAction.Loaded) { continue; } foreach (InputActionReference actionRef in inputAction.ActionRefs) { InputBinding val2 = ((IEnumerable<InputBinding>)(object)actionRef.action.bindings).First(); string name = ((InputBinding)(ref val2)).name; RemappableKey item = new RemappableKey { ControlName = name, currentInput = actionRef, gamepadOnly = false }; remappableKeys.Insert(num++, item); RemappableKey item2 = new RemappableKey { ControlName = name, currentInput = actionRef, rebindingIndex = 1, gamepadOnly = true }; remappableKeys.Add(item2); } inputAction.Loaded = true; } float horizontalOffset = panel.horizontalOffset; Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect; float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset); panel.maxVertical = (float)num / num2; val.minHeight += (panel.maxVertical + 1f) * panel.verticalOffset; } private static void UpdateFontScaling(KepRemapPanel panel) { TextMeshProUGUI component = ((Component)panel.keyRemapSlotPrefab.transform.Find("Text (1)")).GetComponent<TextMeshProUGUI>(); if (!((TMP_Text)component).enableAutoSizing) { ((TMP_Text)component).fontSizeMax = ((TMP_Text)component).fontSize; ((TMP_Text)component).fontSizeMin = ((TMP_Text)component).fontSize - 4f; ((TMP_Text)component).enableAutoSizing = true; } } private static void AdjustSizeAndPos(KepRemapPanel panel) { GameObject gameObject = ((Component)((Transform)panel.keyRemapContainer).parent).gameObject; if (gameObject.GetComponent<ContentSizeFitter>() == null) { panel.keyRemapContainer.SetPivotY(1f); panel.keyRemapContainer.SetAnchorMinY(1f); panel.keyRemapContainer.SetAnchorMaxY(1f); panel.keyRemapContainer.SetAnchoredPosY(0f); panel.keyRemapContainer.SetLocalPosY(0f); ContentSizeFitter obj = gameObject.AddComponent<ContentSizeFitter>(); obj.horizontalFit = (FitMode)0; obj.verticalFit = (FitMode)1; } } private static LayoutElement EnsureLayoutElement(KepRemapPanel panel) { GameObject gameObject = ((Component)((Transform)panel.keyRemapContainer).parent).gameObject; LayoutElement component = gameObject.GetComponent<LayoutElement>(); if (component != null) { return component; } return gameObject.AddComponent<LayoutElement>(); } internal static void CalculateVerticalMaxForGamepad(KepRemapPanel panel) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) int num = panel.remappableKeys.Count((RemappableKey key) => key.gamepadOnly); float horizontalOffset = panel.horizontalOffset; Rect rect = ((Component)((Transform)panel.keyRemapContainer).parent).GetComponent<RectTransform>().rect; float num2 = Mathf.Floor(((Rect)(ref rect)).width / horizontalOffset); panel.maxVertical = (float)num / num2; LayoutElement obj = EnsureLayoutElement(panel); obj.minHeight += (panel.maxVertical + 3f) * panel.verticalOffset; } internal static void ResetLoadedInputActions() { foreach (LcInputActions inputAction in InputActions) { inputAction.Loaded = false; } } internal static void RegisterInputActions(LcInputActions lcInputActions, InputActionMapBuilder builder) { if (!InputActionsMap.TryAdd(lcInputActions.Id, lcInputActions)) { Logging.Logger.LogWarning((object)("The mod [" + lcInputActions.Plugin.GUID + "] instantiated an Actions class [" + lcInputActions.GetType().Name + "] more than once!\n\t These classes should be treated as singletons!, do not instantiate more than once!")); } else { lcInputActions.CreateInputActions(in builder); InputActionSetupExtensions.AddActionMap(lcInputActions.GetAsset(), builder.Build()); lcInputActions.GetAsset().Enable(); lcInputActions.OnAssetLoaded(); lcInputActions.Load(); lcInputActions.BuildActionRefs(); } } internal static void DisableForRebind() { foreach (LcInputActions inputAction in InputActions) { if (inputAction.Enabled) { inputAction.Disable(); } } } internal static void ReEnableFromRebind() { foreach (LcInputActions inputAction in InputActions) { if (inputAction.WasEnabled) { inputAction.Enable(); } } } internal static void SaveOverrides() { foreach (LcInputActions inputAction in InputActions) { inputAction.Save(); } } } [BepInPlugin("com.rune580.LethalCompanyInputUtils", "Lethal Company Input Utils", "0.4.4")] public class LethalCompanyInputUtilsPlugin : BaseUnityPlugin { public const string ModId = "com.rune580.LethalCompanyInputUtils"; public const string ModName = "Lethal Company Input Utils"; public const string ModVersion = "0.4.4"; private Harmony? _harmony; private void Awake() { Logging.SetLogSource(((BaseUnityPlugin)this).Logger); _harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "com.rune580.LethalCompanyInputUtils"); SceneManager.activeSceneChanged += OnSceneChanged; FsUtils.EnsureControlsDir(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin com.rune580.LethalCompanyInputUtils is loaded!"); } private static void OnSceneChanged(Scene current, Scene next) { LcInputActionApi.ResetLoadedInputActions(); } } } namespace LethalCompanyInputUtils.Utils { internal static class AssemblyUtils { public static BepInPlugin? GetBepInPlugin(this Assembly assembly) { foreach (Type validType in assembly.GetValidTypes()) { BepInPlugin customAttribute = ((MemberInfo)validType).GetCustomAttribute<BepInPlugin>(); if (customAttribute != null) { return customAttribute; } } return null; } public static IEnumerable<Type> GetValidTypes(this Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { return ex.Types.Where((Type type) => (object)type != null); } } } internal static class FsUtils { public static string SaveDir { get; } = GetSaveDir(); public static string Pre041ControlsDir { get; } = Path.Combine(Paths.BepInExRootPath, "controls"); public static string ControlsDir { get; } = Path.Combine(Paths.ConfigPath, "controls"); private static string GetSaveDir() { string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); return Path.Combine(folderPath, "AppData", "LocalLow", "ZeekerssRBLX", "Lethal Company"); } public static void EnsureControlsDir() { if (!Directory.Exists(ControlsDir)) { Directory.CreateDirectory(ControlsDir); } } } internal static class Logging { private static ManualLogSource? _logSource; internal static ManualLogSource Logger { get; } = _logSource; internal static void SetLogSource(ManualLogSource logSource) { _logSource = logSource; } } internal static class RuntimeHelper { public static void SetLocalPosY(this RectTransform rectTransform, float y) { //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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) Vector3 localPosition = ((Transform)rectTransform).localPosition; ((Transform)rectTransform).localPosition = new Vector3(localPosition.x, y, localPosition.z); } public static void SetPivotY(this RectTransform rectTransform, float y) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) rectTransform.pivot = new Vector2(rectTransform.pivot.x, y); } public static void SetAnchorMinY(this RectTransform rectTransform, float y) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) rectTransform.anchorMin = new Vector2(rectTransform.anchorMin.x, y); } public static void SetAnchorMaxY(this RectTransform rectTransform, float y) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) rectTransform.anchorMax = new Vector2(rectTransform.anchorMax.x, y); } public static void SetAnchoredPosY(this RectTransform rectTransform, float y) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) rectTransform.anchoredPosition = new Vector2(rectTransform.anchoredPosition.x, y); } } } namespace LethalCompanyInputUtils.Patches { public static class InputControlPathPatches { [HarmonyPatch] public static class ToHumanReadableStringPatch { public static IEnumerable<MethodBase> TargetMethods() { return from method in AccessTools.GetDeclaredMethods(typeof(InputControlPath)) where method.Name == "ToHumanReadableString" && method.ReturnType == typeof(string) select method; } public static void Postfix(ref string __result) { string text = __result; if ((text == "<InputUtils-Gamepad-Not-Bound>" || text == "<InputUtils-Kbm-Not-Bound>") ? true : false) { __result = ""; } } } } public static class KeyRemapPanelPatches { [HarmonyPatch(typeof(KepRemapPanel), "LoadKeybindsUI")] public static class LoadKeybindsUIPatch { public static void Prefix(KepRemapPanel __instance) { LcInputActionApi.DisableForRebind(); LcInputActionApi.LoadIntoUI(__instance); } public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Expected O, but got Unknown //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); FieldInfo maxVerticalField = AccessTools.Field(typeof(KepRemapPanel), "maxVertical"); val.MatchForward(true, (CodeMatch[])(object)new CodeMatch[6] { new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.IsLdarg(code, (int?)0)), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.LoadsField(code, maxVerticalField, false)), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Ldc_R4 && (float)code.operand == 2f), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Add), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => code.opcode == OpCodes.Conv_I4), (string)null), new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction code) => CodeInstructionExtensions.IsStloc(code, (LocalBuilder)null)), (string)null) }); val.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldarg_0, (object)null) }).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(LcInputActionApi), "CalculateVerticalMaxForGamepad", new Type[1] { typeof(KepRemapPanel) }, (Type[])null)) }); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(KepRemapPanel), "UnloadKeybindsUI")] public static class UnloadKeybindsUIPatch { public static void Prefix() { LcInputActionApi.SaveOverrides(); LcInputActionApi.ReEnableFromRebind(); } } } } namespace LethalCompanyInputUtils.Data { [Serializable] public struct BindingOverride { public string? action; public string? origPath; public string? path; } [Serializable] public class BindingOverrides { public List<BindingOverride> overrides; private BindingOverrides() { overrides = new List<BindingOverride>(); } public BindingOverrides(IEnumerable<InputBinding> bindings) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) overrides = new List<BindingOverride>(); foreach (InputBinding binding in bindings) { InputBinding current = binding; if (((InputBinding)(ref current)).hasOverrides) { BindingOverride item = new BindingOverride { action = ((InputBinding)(ref current)).action, origPath = ((InputBinding)(ref current)).path, path = ((InputBinding)(ref current)).overridePath }; overrides.Add(item); } } } public void LoadInto(InputActionAsset asset) { foreach (BindingOverride @override in overrides) { InputAction obj = asset.FindAction(@override.action, false); if (obj != null) { InputActionRebindingExtensions.ApplyBindingOverride(obj, @override.path, (string)null, @override.origPath); } } } public static BindingOverrides FromJson(string json) { BindingOverrides bindingOverrides = new BindingOverrides(); JToken value = JsonConvert.DeserializeObject<JObject>(json).GetValue("overrides"); bindingOverrides.overrides = value.ToObject<List<BindingOverride>>(); return bindingOverrides; } } } namespace LethalCompanyInputUtils.Api { [AttributeUsage(AttributeTargets.Property)] public class InputActionAttribute : Attribute { public readonly string KbmPath; public string? ActionId { get; set; } public string? GamepadPath { get; set; } public InputActionType ActionType { get; set; } = (InputActionType)1; public string? KbmInteractions { get; set; } public string? GamepadInteractions { get; set; } public string? Name { get; set; } [Obsolete("Prefer using the named optional params instead.")] public InputActionAttribute(string action, string kbmPath, string gamepadPath) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) ActionId = action; KbmPath = kbmPath; GamepadPath = gamepadPath; } public InputActionAttribute(string kbmPath) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) KbmPath = kbmPath; } } public class InputActionBindingBuilder { private readonly InputActionMapBuilder _mapBuilder; private string? _actionId; private string? _kbmPath; private string? _gamepadPath; private string? _kbmInteractions; private string? _gamepadInteractions; private InputActionType _actionType; private string? _name; internal InputActionBindingBuilder(InputActionMapBuilder mapBuilder) { _mapBuilder = mapBuilder; } public InputActionBindingBuilder WithActionId(string actionId) { _actionId = actionId; return this; } public InputActionBindingBuilder WithKbmPath(string kbmPath) { _kbmPath = kbmPath; return this; } public InputActionBindingBuilder WithGamepadPath(string gamepadPath) { _gamepadPath = gamepadPath; return this; } public InputActionBindingBuilder WithKbmInteractions(string? kbmInteractions) { _kbmInteractions = kbmInteractions; return this; } public InputActionBindingBuilder WithGamepadInteractions(string? gamepadInteractions) { _gamepadInteractions = gamepadInteractions; return this; } public InputActionBindingBuilder WithActionType(InputActionType actionType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) _actionType = actionType; return this; } public InputActionBindingBuilder WithBindingName(string? name) { _name = name; return this; } public InputAction Finish() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) if (_name == null) { _name = _actionId; } InputAction val = new InputAction(_actionId, _actionType, (string)null, (string)null, (string)null, (string)null); _mapBuilder.WithAction(val); if (_kbmPath != null) { _mapBuilder.WithBinding(new InputBinding(_kbmPath, _actionId, (string)null, (string)null, _kbmInteractions, _name)); } if (_gamepadPath != null) { _mapBuilder.WithBinding(new InputBinding(_gamepadPath, _actionId, (string)null, (string)null, _gamepadInteractions, _name)); } return val; } } public class InputActionMapBuilder { private readonly InputActionMap _actionMap = new InputActionMap(mapName); public InputActionMapBuilder(string mapName) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown public InputActionMapBuilder WithAction(InputAction action) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) InputActionSetupExtensions.AddAction(_actionMap, action.name, action.type, (string)null, (string)null, (string)null, (string)null, (string)null); return this; } public InputActionMapBuilder WithBinding(InputBinding binding) { //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) InputActionSetupExtensions.AddBinding(_actionMap, binding); return this; } public InputActionBindingBuilder NewActionBinding() { return new InputActionBindingBuilder(this); } internal InputActionMap Build() { return _actionMap; } } public abstract class LcInputActions { public const string UnboundKeyboardAndMouseIdentifier = "<InputUtils-Kbm-Not-Bound>"; public const string UnboundGamepadIdentifier = "<InputUtils-Gamepad-Not-Bound>"; private readonly string _jsonPath; private readonly List<InputActionReference> _actionRefs = new List<InputActionReference>(); internal bool Loaded; private readonly Dictionary<PropertyInfo, InputActionAttribute> _inputProps; public InputActionAsset Asset { get; } internal bool WasEnabled { get; private set; } public bool Enabled => Asset.enabled; internal IReadOnlyCollection<InputActionReference> ActionRefs => _actionRefs; internal string Id => Plugin.GUID + "." + MapName; public BepInPlugin Plugin { get; } protected virtual string MapName => GetType().Name; internal InputActionAsset GetAsset() { return Asset; } protected LcInputActions() { //IL_0118: Unknown result type (might be due to invalid IL or missing references) Asset = ScriptableObject.CreateInstance<InputActionAsset>(); Plugin = Assembly.GetCallingAssembly().GetBepInPlugin() ?? throw new InvalidOperationException(); _jsonPath = Path.Combine(FsUtils.ControlsDir, Id + ".json"); InputActionMapBuilder inputActionMapBuilder = new InputActionMapBuilder(Id); PropertyInfo[] properties = GetType().GetProperties(); _inputProps = new Dictionary<PropertyInfo, InputActionAttribute>(); PropertyInfo[] array = properties; foreach (PropertyInfo propertyInfo in array) { InputActionAttribute customAttribute = propertyInfo.GetCustomAttribute<InputActionAttribute>(); if (customAttribute != null && !(propertyInfo.PropertyType != typeof(InputAction))) { InputActionAttribute inputActionAttribute = customAttribute; if (inputActionAttribute.ActionId == null) { string text = (inputActionAttribute.ActionId = propertyInfo.Name); } inputActionAttribute = customAttribute; if (inputActionAttribute.GamepadPath == null) { string text = (inputActionAttribute.GamepadPath = "<InputUtils-Gamepad-Not-Bound>"); } string kbmPath = (string.IsNullOrEmpty(customAttribute.KbmPath) ? "<InputUtils-Kbm-Not-Bound>" : customAttribute.KbmPath); inputActionMapBuilder.NewActionBinding().WithActionId(customAttribute.ActionId).WithActionType(customAttribute.ActionType) .WithBindingName(customAttribute.Name) .WithKbmPath(kbmPath) .WithGamepadPath(customAttribute.GamepadPath) .WithKbmInteractions(customAttribute.KbmInteractions) .WithGamepadInteractions(customAttribute.GamepadInteractions) .Finish(); _inputProps[propertyInfo] = customAttribute; } } LcInputActionApi.RegisterInputActions(this, inputActionMapBuilder); } public virtual void CreateInputActions(in InputActionMapBuilder builder) { } public virtual void OnAssetLoaded() { } internal void BuildActionRefs() { //IL_0061: Unknown result type (might be due to invalid IL or missing references) foreach (KeyValuePair<PropertyInfo, InputActionAttribute> inputProp in _inputProps) { inputProp.Deconstruct(out var key, out var value); PropertyInfo propertyInfo = key; InputActionAttribute inputActionAttribute = value; InputAction value2 = Asset.FindAction(inputActionAttribute.ActionId, false); propertyInfo.SetValue(this, value2); } IEnumerable<InputActionReference> collection = ((IEnumerable<InputActionMap>)(object)Asset.actionMaps).SelectMany((InputActionMap map) => (IEnumerable<InputAction>)(object)map.actions).Select((Func<InputAction, InputActionReference>)InputActionReference.Create); _actionRefs.AddRange(collection); } public void Enable() { WasEnabled = Asset.enabled; Asset.Enable(); } public void Disable() { WasEnabled = Asset.enabled; Asset.Disable(); } internal void Save() { BindingOverrides bindingOverrides = new BindingOverrides(Asset.bindings); File.WriteAllText(_jsonPath, JsonConvert.SerializeObject((object)bindingOverrides)); } internal void Load() { try { ApplyMigrations(); } catch (Exception ex) { Logging.Logger.LogError((object)"Got error when applying migrations, skipping..."); Logging.Logger.LogError((object)ex); } if (!File.Exists(_jsonPath)) { return; } try { BindingOverrides.FromJson(File.ReadAllText(_jsonPath)).LoadInto(Asset); } catch (Exception ex2) { Logging.Logger.LogError((object)ex2); } } private void ApplyMigrations() { string text = Path.Combine(FsUtils.Pre041ControlsDir, Id + ".json"); if (File.Exists(text) && !File.Exists(_jsonPath)) { File.Move(text, _jsonPath); } if (!File.Exists(_jsonPath) || !File.ReadAllText(_jsonPath).Replace(" ", "").Contains("\"origPath\":\"\"")) { return; } BindingOverrides bindingOverrides = BindingOverrides.FromJson(File.ReadAllText(_jsonPath)); for (int i = 0; i < bindingOverrides.overrides.Count; i++) { BindingOverride value = bindingOverrides.overrides[i]; if (string.IsNullOrEmpty(value.origPath) && value.path != null) { if (value.path.StartsWith("<Keyboard>") || value.path.StartsWith("<Mouse>")) { value.origPath = "<InputUtils-Kbm-Not-Bound>"; } else { value.origPath = "<InputUtils-Gamepad-Not-Bound>"; } bindingOverrides.overrides[i] = value; } } File.WriteAllText(_jsonPath, JsonConvert.SerializeObject((object)bindingOverrides)); } } }
BepInEx/plugins/LethalExpansion.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using DunGen; using DunGen.Adapters; using DunGen.Graph; using GameNetcodeStuff; using HarmonyLib; using LethalExpansion.Extenders; using LethalExpansion.Patches; using LethalExpansion.Patches.Monsters; using LethalExpansion.Utils; using LethalExpansion.Utils.HUD; using LethalSDK.Component; using LethalSDK.ScriptableObjects; using LethalSDK.Utils; using TMPro; using Unity.AI.Navigation; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("LethalExpansion")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LethalExpansion")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("f80eb3fd-9563-4f80-9fc7-3fcce1655c13")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] public class AutoScrollText : MonoBehaviour { public TextMeshProUGUI textMeshPro; public float scrollSpeed = 15f; private Vector2 startPosition; private float textHeight; private bool startScrolling = false; private bool isWaitingToReset = false; private float displayHeight; private float fontSize; private void Start() { textMeshPro = ((Component)this).GetComponent<TextMeshProUGUI>(); InitializeScrolling(); } private void InitializeScrolling() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)textMeshPro != (Object)null) { startPosition = ((TMP_Text)textMeshPro).rectTransform.anchoredPosition; textHeight = ((TMP_Text)textMeshPro).preferredHeight; displayHeight = ((TMP_Text)textMeshPro).rectTransform.sizeDelta.y; fontSize = ((TMP_Text)textMeshPro).fontSize; } ((MonoBehaviour)this).StartCoroutine(WaitBeforeScrolling(5f)); } private IEnumerator WaitBeforeScrolling(float waitTime) { yield return (object)new WaitForSeconds(waitTime); startScrolling = true; } private IEnumerator WaitBeforeResetting(float waitTime) { isWaitingToReset = true; yield return (object)new WaitForSeconds(waitTime); ((TMP_Text)textMeshPro).rectTransform.anchoredPosition = startPosition; isWaitingToReset = false; ((MonoBehaviour)this).StartCoroutine(WaitBeforeScrolling(5f)); } private void Update() { //IL_0037: 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_0052: 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) if ((Object)(object)textMeshPro != (Object)null && startScrolling && !isWaitingToReset) { RectTransform rectTransform = ((TMP_Text)textMeshPro).rectTransform; rectTransform.anchoredPosition += new Vector2(0f, scrollSpeed * Time.deltaTime); if (((TMP_Text)textMeshPro).rectTransform.anchoredPosition.y >= startPosition.y + textHeight - displayHeight - fontSize) { startScrolling = false; ((MonoBehaviour)this).StartCoroutine(WaitBeforeResetting(5f)); } } } public void ResetScrolling() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) ((MonoBehaviour)this).StopAllCoroutines(); if ((Object)(object)textMeshPro != (Object)null) { ((TMP_Text)textMeshPro).rectTransform.anchoredPosition = startPosition; } isWaitingToReset = false; InitializeScrolling(); } } public class TooltipHandler : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler { private string description; private string netinfo; public static RectTransform ModSettingsToolTipPanel; public static TMP_Text ModSettingsToolTipPanelDescription; public static TMP_Text ModSettingsToolTipPanelNetInfo; public int index; private float delay = 0.5f; private bool isPointerOver = false; public void OnPointerEnter(PointerEventData eventData) { isPointerOver = true; ((MonoBehaviour)this).StartCoroutine(ShowTooltipAfterDelay()); } public void OnPointerExit(PointerEventData eventData) { isPointerOver = false; ((Component)ModSettingsToolTipPanel).gameObject.SetActive(false); } private IEnumerator ShowTooltipAfterDelay() { yield return (object)new WaitForSeconds(delay); if (isPointerOver) { ModSettingsToolTipPanel.anchoredPosition = new Vector2(-30f, ((Component)this).GetComponent<RectTransform>().anchoredPosition.y + -80f); description = ConfigManager.Instance.FindDescription(index); (bool, bool) info = ConfigManager.Instance.FindNetInfo(index); netinfo = "Network synchronization: " + (info.Item1 ? "Yes" : "No") + "\nMod required by clients: " + (info.Item2 ? "No" : "Yes"); ModSettingsToolTipPanelDescription.text = description; ModSettingsToolTipPanelNetInfo.text = netinfo; ((Component)ModSettingsToolTipPanel).gameObject.SetActive(true); } } } public class ConfigItem { public string Key { get; set; } public Type type { get; set; } public object Value { get; set; } public object DefaultValue { get; set; } public string Tab { get; set; } public string Description { get; set; } public object MinValue { get; set; } public object MaxValue { get; set; } public bool Sync { get; set; } public bool Hidden { get; set; } public bool Optional { get; set; } public bool RequireRestart { get; set; } public ConfigItem(string key, object defaultValue, string tab, string description, object minValue = null, object maxValue = null, bool sync = true, bool optional = false, bool hidden = false, bool requireRestart = false) { Key = key; DefaultValue = defaultValue; type = defaultValue.GetType(); Tab = tab; Description = description; if (minValue != null && maxValue != null) { if (minValue.GetType() == type && maxValue.GetType() == type) { MinValue = minValue; MaxValue = maxValue; } } else { MinValue = null; MaxValue = null; } Sync = sync; Optional = optional; Hidden = hidden; Value = DefaultValue; RequireRestart = requireRestart; } } namespace LethalExpansion { [BepInPlugin("LethalExpansion", "LethalExpansion", "1.3.12")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class LethalExpansion : BaseUnityPlugin { private enum compatibility { unknown, perfect, good, medium, bad, critical } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static Func<PluginInfo, bool> <>9__31_1; public static UnityAction <>9__31_0; public static Func<PluginInfo, bool> <>9__31_2; public static Func<PluginInfo, bool> <>9__31_3; public static Func<AudioMixerGroup, bool> <>9__32_0; public static Func<GameObject, bool> <>9__32_1; public static Func<AudioMixerGroup, bool> <>9__32_2; public static Func<AudioMixerGroup, bool> <>9__32_3; public static Func<AudioMixerGroup, bool> <>9__32_4; public static Func<PluginInfo, bool> <>9__35_0; public static Func<PluginInfo, bool> <>9__35_1; public static Func<PluginInfo, bool> <>9__35_2; public static Func<PluginInfo, bool> <>9__35_3; internal bool <OnSceneLoaded>b__31_1(PluginInfo p) { return p.Metadata.GUID == "CoomfyDungeon"; } internal void <OnSceneLoaded>b__31_0() { ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true); ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true); } internal bool <OnSceneLoaded>b__31_2(PluginInfo p) { return p.Metadata.GUID == "BiggerLobby"; } internal bool <OnSceneLoaded>b__31_3(PluginInfo p) { return p.Metadata.GUID == "KoderTech.BoomboxController"; } internal bool <LoadCustomMoon>b__32_0(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <LoadCustomMoon>b__32_1(GameObject o) { //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) Scene scene = o.scene; return ((Scene)(ref scene)).name != "InitSceneLaunchOptions"; } internal bool <LoadCustomMoon>b__32_2(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <LoadCustomMoon>b__32_3(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <LoadCustomMoon>b__32_4(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <waitForSession>b__35_0(PluginInfo p) { return p.Metadata.GUID == "BrutalCompanyPlus"; } internal bool <waitForSession>b__35_1(PluginInfo p) { return p.Metadata.GUID == "LethalAdjustments"; } internal bool <waitForSession>b__35_2(PluginInfo p) { return p.Metadata.GUID == "CoomfyDungeon"; } internal bool <waitForSession>b__35_3(PluginInfo p) { return p.Metadata.GUID == "299792458.MoreMoneyStart"; } } private const string PluginGUID = "LethalExpansion"; private const string PluginName = "LethalExpansion"; private const string VersionString = "1.3.12"; public static readonly Version ModVersion = new Version("1.3.12"); private readonly Dictionary<string, compatibility> CompatibleMods = new Dictionary<string, compatibility> { { "com.sinai.unityexplorer", compatibility.medium }, { "HDLethalCompany", compatibility.good }, { "LC_API", compatibility.good }, { "me.swipez.melonloader.morecompany", compatibility.medium }, { "BrutalCompanyPlus", compatibility.medium }, { "MoonOfTheDay", compatibility.good }, { "Television_Controller", compatibility.bad }, { "beeisyou.LandmineFix", compatibility.perfect }, { "LethalAdjustments", compatibility.good }, { "CoomfyDungeon", compatibility.bad }, { "BiggerLobby", compatibility.critical }, { "KoderTech.BoomboxController", compatibility.critical }, { "299792458.MoreMoneyStart", compatibility.good } }; private List<PluginInfo> loadedPlugins = new List<PluginInfo>(); public static readonly int[] CompatibleGameVersions = new int[1] { 45 }; public static bool sessionWaiting = true; public static bool hostDataWaiting = true; public static bool ishost = false; public static bool alreadypatched = false; public static bool weathersReadyToShare = false; public static bool isInGame = false; public static int delayedLevelChange = -1; public static string lastKickReason = string.Empty; private static readonly Harmony Harmony = new Harmony("LethalExpansion"); public static ManualLogSource Log = new ManualLogSource("LethalExpansion"); public static ConfigFile config; public static NetworkManager networkManager; public GameObject SpaceLight; public GameObject terrainfixer; public static Transform currentWaterSurface; private int width = 256; private int height = 256; private int depth = 20; private float scale = 20f; private void Awake() { //IL_0c17: Unknown result type (might be due to invalid IL or missing references) //IL_0c1d: Expected O, but got Unknown //IL_0c66: Unknown result type (might be due to invalid IL or missing references) //IL_0c73: Expected O, but got Unknown //IL_0c78: Unknown result type (might be due to invalid IL or missing references) //IL_0c85: Expected O, but got Unknown //IL_0cec: Unknown result type (might be due to invalid IL or missing references) //IL_0cf9: Expected O, but got Unknown //IL_0d00: Unknown result type (might be due to invalid IL or missing references) //IL_0d0d: Expected O, but got Unknown //IL_0d2b: Unknown result type (might be due to invalid IL or missing references) //IL_0d30: Unknown result type (might be due to invalid IL or missing references) //IL_0d3c: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"PluginName: LethalExpansion, VersionString: 1.3.12 is loading..."); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Getting other plugins list"); loadedPlugins = GetLoadedPlugins(); foreach (PluginInfo loadedPlugin in loadedPlugins) { if (!(loadedPlugin.Metadata.GUID != "LethalExpansion")) { continue; } if (CompatibleMods.ContainsKey(loadedPlugin.Metadata.GUID)) { switch (CompatibleMods[loadedPlugin.Metadata.GUID]) { case compatibility.unknown: Console.BackgroundColor = ConsoleColor.Gray; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}"); break; case compatibility.perfect: Console.BackgroundColor = ConsoleColor.Blue; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}"); break; case compatibility.good: Console.BackgroundColor = ConsoleColor.Green; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}"); break; case compatibility.medium: Console.BackgroundColor = ConsoleColor.Yellow; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogWarning((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}"); break; case compatibility.bad: Console.BackgroundColor = ConsoleColor.Red; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogError((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}"); break; case compatibility.critical: Console.BackgroundColor = ConsoleColor.Magenta; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogFatal((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}"); break; default: Console.BackgroundColor = ConsoleColor.Gray; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {CompatibleMods[loadedPlugin.Metadata.GUID]}"); break; } ((BaseUnityPlugin)this).Logger.LogInfo((object)"------------------------------"); } else { Console.BackgroundColor = ConsoleColor.Gray; ((BaseUnityPlugin)this).Logger.LogInfo((object)" "); Console.ResetColor(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Plugin: {loadedPlugin.Metadata.Name} - Version: {loadedPlugin.Metadata.Version} - Compatibility: {compatibility.unknown}"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"------------------------------"); } } config = ((BaseUnityPlugin)this).Config; ConfigManager.Instance.AddItem(new ConfigItem("GlobalTimeSpeedMultiplier", 1.4f, "Time", "Change the global time speed", 0.1f, 3f)); ConfigManager.Instance.AddItem(new ConfigItem("NumberOfHours", 18, "Time", "Max lenght of an Expedition in hours. (Begin at 6 AM | 18 = Midnight)", 6, 20)); ConfigManager.Instance.AddItem(new ConfigItem("DeadlineDaysAmount", 3, "Expeditions", "Change amount of days for the Quota.", 1, 9)); ConfigManager.Instance.AddItem(new ConfigItem("StartingCredits", 60, "Expeditions", "Change amount of starting Credit.", 0, 1000)); ConfigManager.Instance.AddItem(new ConfigItem("MoonsRoutePricesMultiplier", 1f, "Moons", "Change the Cost of the Moon Routes.", 0f, 5f)); ConfigManager.Instance.AddItem(new ConfigItem("StartingQuota", 130, "Expeditions", "Change the starting Quota.", 0, 1000, sync: true, optional: true)); ConfigManager.Instance.AddItem(new ConfigItem("ScrapAmountMultiplier", 1f, "Dungeons", "Change the amount of Scraps in dungeons.", 0f, 10f)); ConfigManager.Instance.AddItem(new ConfigItem("ScrapValueMultiplier", 0.4f, "Dungeons", "Change the value of Scraps.", 0f, 10f)); ConfigManager.Instance.AddItem(new ConfigItem("MapSizeMultiplier", 1.5f, "Dungeons", "Change the size of the Dungeons. (Can crash when under 1.0)", 0.8f, 10f)); ConfigManager.Instance.AddItem(new ConfigItem("PreventMineToExplodeWithItems", false, "Dungeons", "Prevent Landmines to explode by dropping items on them")); ConfigManager.Instance.AddItem(new ConfigItem("MineActivationWeight", 0.15f, "Dungeons", "Set the minimal weight to prevent Landmine's explosion (0.15 = 16 lb, Player = 2.0)", 0.01f, 5f)); ConfigManager.Instance.AddItem(new ConfigItem("WeightUnit", 0, "HUD", "Change the carried Weight unit : 0 = Pounds (lb), 1 = Kilograms (kg) and 2 = Both", 0, 2, sync: false)); ConfigManager.Instance.AddItem(new ConfigItem("ConvertPoundsToKilograms", true, "HUD", "Convert Pounds into Kilograms (16 lb = 7 kg) (Only effective if WeightUnit = 1)", null, null, sync: false)); ConfigManager.Instance.AddItem(new ConfigItem("PreventScrapWipeWhenAllPlayersDie", false, "Expeditions", "Prevent the Scraps Wipe when all players die.")); ConfigManager.Instance.AddItem(new ConfigItem("24HoursClock", false, "HUD", "Display a 24h clock instead of 12h.", null, null, sync: false)); ConfigManager.Instance.AddItem(new ConfigItem("ClockAlwaysVisible", false, "HUD", "Display clock while inside of the Ship.")); ConfigManager.Instance.AddItem(new ConfigItem("AutomaticDeadline", false, "Expeditions", "Automatically increase the Deadline depending of the required quota.")); ConfigManager.Instance.AddItem(new ConfigItem("AutomaticDeadlineStage", 300, "Expeditions", "Increase the quota deadline of one day each time the quota exceeds this value.", 100, 3000)); ConfigManager.Instance.AddItem(new ConfigItem("LoadModules", true, "Modules", "Load SDK Modules that add new content to the game. Disable it to play with Vanilla players. (RESTART REQUIRED)", null, null, sync: false, optional: false, hidden: false, requireRestart: true)); ConfigManager.Instance.AddItem(new ConfigItem("MaxItemsInShip", 45, "Expeditions", "Change the Items cap can be kept in the ship.", 10, 500)); ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonWeatherInCatalogue", true, "HUD", "Display the current weather of Moons in the Terminal's Moon Catalogue.")); ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonRankInCatalogue", false, "HUD", "Display the rank of Moons in the Terminal's Moon Catalogue.")); ConfigManager.Instance.AddItem(new ConfigItem("ShowMoonPriceInCatalogue", false, "HUD", "Display the route price of Moons in the Terminal's Moon Catalogue.")); ConfigManager.Instance.AddItem(new ConfigItem("QuotaIncreaseSteepness", 16, "Expeditions", "Change the Quota Increase Steepness. (Highter = less steep exponential increase)", 0, 32)); ConfigManager.Instance.AddItem(new ConfigItem("QuotaBaseIncrease", 100, "Expeditions", "Change the Quota Base Increase.", 0, 300)); ConfigManager.Instance.AddItem(new ConfigItem("KickPlayerWithoutMod", false, "Lobby", "Kick the players without Lethal Expansion installer. (Will be kicked anyway if LoadModules is True)")); ConfigManager.Instance.AddItem(new ConfigItem("BrutalCompanyPlusCompatibility", false, "Compatibility", "Leave Brutal Company Plus control the Quota settings.")); ConfigManager.Instance.AddItem(new ConfigItem("LethalAdjustmentsCompatibility", false, "Compatibility", "Leave Lethal Adjustments control the Dungeon settings.")); ConfigManager.Instance.AddItem(new ConfigItem("CoomfyDungeonCompatibility", false, "Compatibility", "Let Coomfy Dungeons control the Dungeon size & scrap settings.")); ConfigManager.Instance.AddItem(new ConfigItem("MoreMoneyStartCompatibility", false, "Compatibility", "Let MoreMoneyStart control the Starting credits amount.")); ConfigManager.Instance.AddItem(new ConfigItem("SettingsDebug", false, "Debug", "Show an output of every settings in the Console. (The Console must listen Info messages)", null, null, sync: false)); ConfigManager.Instance.ReadConfig(); ((BaseUnityPlugin)this).Config.SettingChanged += ConfigSettingChanged; AssetBundlesManager.Instance.LoadAllAssetBundles(); SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.sceneUnloaded += OnSceneUnloaded; Harmony.PatchAll(typeof(GameNetworkManager_Patch)); Harmony.PatchAll(typeof(Terminal_Patch)); Harmony.PatchAll(typeof(MenuManager_Patch)); Harmony.PatchAll(typeof(GrabbableObject_Patch)); Harmony.PatchAll(typeof(RoundManager_Patch)); Harmony.PatchAll(typeof(TimeOfDay_Patch)); Harmony.PatchAll(typeof(HUDManager_Patch)); Harmony.PatchAll(typeof(StartOfRound_Patch)); Harmony.PatchAll(typeof(EntranceTeleport_Patch)); Harmony.PatchAll(typeof(Landmine_Patch)); Harmony.PatchAll(typeof(AudioReverbTrigger_Patch)); Harmony.PatchAll(typeof(InteractTrigger_Patch)); Harmony.PatchAll(typeof(RuntimeDungeon)); Harmony val = new Harmony("LethalExpansion"); MethodInfo methodInfo = AccessTools.Method(typeof(BaboonBirdAI), "GrabScrap", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(HoarderBugAI), "GrabItem", (Type[])null, (Type[])null); MethodInfo methodInfo3 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "MonsterGrabItem", (Type[])null, (Type[])null); val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo methodInfo4 = AccessTools.Method(typeof(HoarderBugAI), "DropItem", (Type[])null, (Type[])null); MethodInfo methodInfo5 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "MonsterDropItem_Patch", (Type[])null, (Type[])null); MethodInfo methodInfo6 = AccessTools.Method(typeof(HoarderBugAI), "KillEnemy", (Type[])null, (Type[])null); MethodInfo methodInfo7 = AccessTools.Method(typeof(MonsterGrabItem_Patch), "KillEnemy_Patch", (Type[])null, (Type[])null); val.Patch((MethodBase)methodInfo4, (HarmonyMethod)null, new HarmonyMethod(methodInfo5), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, new HarmonyMethod(methodInfo7), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline; HDRenderPipelineAsset val2 = (HDRenderPipelineAsset)(object)((currentRenderPipeline is HDRenderPipelineAsset) ? currentRenderPipeline : null); if ((Object)(object)val2 != (Object)null) { RenderPipelineSettings currentPlatformRenderPipelineSettings = val2.currentPlatformRenderPipelineSettings; currentPlatformRenderPipelineSettings.supportWater = true; val2.currentPlatformRenderPipelineSettings = currentPlatformRenderPipelineSettings; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Water support applied to the HDRenderPipelineAsset."); } else { ((BaseUnityPlugin)this).Logger.LogError((object)"HDRenderPipelineAsset not found."); } ((BaseUnityPlugin)this).Logger.LogInfo((object)"PluginName: LethalExpansion, VersionString: 1.3.12 is loaded."); } private List<PluginInfo> GetLoadedPlugins() { return Chainloader.PluginInfos.Values.ToList(); } private float[,] GenerateHeights() { float[,] array = new float[width, height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { array[i, j] = CalculateHeight(i, j); } } return array; } private float CalculateHeight(int x, int y) { float num = (float)x / (float)width * scale; float num2 = (float)y / (float)height * scale; return Mathf.PerlinNoise(num, num2); } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_043b: Expected O, but got Unknown //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_0485: Expected O, but got Unknown //IL_04ac: 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_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Expected O, but got Unknown //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_075b: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) ((BaseUnityPlugin)this).Logger.LogInfo((object)("Loading scene: " + ((Scene)(ref scene)).name)); if (((Scene)(ref scene)).name == "InitScene") { networkManager = GameObject.Find("NetworkManager").GetComponent<NetworkManager>(); } if (((Scene)(ref scene)).name == "MainMenu") { sessionWaiting = true; hostDataWaiting = true; ishost = false; alreadypatched = false; delayedLevelChange = -1; isInGame = false; AssetGather.Instance.AddAudioMixer(GameObject.Find("Canvas/MenuManager").GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer); SettingsMenu.Instance.InitSettingsMenu(); if (lastKickReason != null && lastKickReason.Length > 0) { PopupManager.Instance.InstantiatePopup(scene, "Kicked from Lobby", "You have been kicked\r\nReason: " + lastKickReason, "Ok", "Ignore"); } if (!ConfigManager.Instance.FindEntryValue<bool>("CoomfyDungeonCompatibility") && loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "CoomfyDungeon")) { PopupManager instance = PopupManager.Instance; Scene sceneFocus = scene; object obj = <>c.<>9__31_0; if (obj == null) { UnityAction val = delegate { ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true); ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true); }; <>c.<>9__31_0 = val; obj = (object)val; } instance.InstantiatePopup(sceneFocus, "CoomfyDungeon mod found", "Warning: CoomfyDungeon is incompatible with LethalExpansion, Would you like to enable the compatibility mode? Otherwise dungeon generation Desync may occurs!", "Yes", "No", (UnityAction)obj, null, 20, 18); } if (loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "BiggerLobby")) { PopupManager.Instance.InstantiatePopup(scene, "BiggerLobby mod found", "Warning: BiggerLobby is incompatible with LethalExpansion, host/client synchronization will break and dungeon generation Desync may occurs!", "Ok", "Ignore", null, null, 20, 18); } if (loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "KoderTech.BoomboxController")) { PopupManager.Instance.InstantiatePopup(scene, "BoomboxController mod found", "Warning: BoomboxController is incompatible with LethalExpansion, host/client synchronization will break and dungeon generation Desync may occurs!", "Ok", "Ignore", null, null, 20, 18); } } if (((Scene)(ref scene)).name == "CompanyBuilding") { SpaceLight.SetActive(false); terrainfixer.SetActive(false); } if (((Scene)(ref scene)).name == "SampleSceneRelay") { SpaceLight = Object.Instantiate<GameObject>(AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/SpaceLight.prefab")); SceneManager.MoveGameObjectToScene(SpaceLight, scene); Mesh mesh = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Meshes/MonitorWall.fbx").GetComponent<MeshFilter>().mesh; GameObject val2 = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube"); val2.GetComponent<MeshFilter>().mesh = mesh; MeshRenderer component = val2.GetComponent<MeshRenderer>(); GameObject val3 = Object.Instantiate<GameObject>(GameObject.Find("Systems/GameSystems/TimeAndWeather/Flooding")); Object.Destroy((Object)(object)val3.GetComponent<FloodWeather>()); ((Object)val3).name = "WaterSurface"; val3.transform.position = Vector3.zero; ((Component)val3.transform.Find("Water")).GetComponent<MeshFilter>().sharedMesh = null; SpawnPrefab.Instance.waterSurface = val3; ((Renderer)component).materials = (Material[])(object)new Material[9] { ((Renderer)component).materials[0], ((Renderer)component).materials[1], ((Renderer)component).materials[1], ((Renderer)component).materials[1], ((Renderer)component).materials[1], ((Renderer)component).materials[1], ((Renderer)component).materials[1], ((Renderer)component).materials[1], ((Renderer)component).materials[2] }; ((Component)StartOfRound.Instance.screenLevelDescription).gameObject.AddComponent<AutoScrollText>(); AssetGather.Instance.AddAudioMixer(GameObject.Find("Systems/Audios/DiageticBackground").GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer); terrainfixer = new GameObject(); ((Object)terrainfixer).name = "terrainfixer"; terrainfixer.transform.position = new Vector3(0f, -500f, 0f); Terrain val4 = terrainfixer.AddComponent<Terrain>(); TerrainData val5 = new TerrainData(); val5.heightmapResolution = width + 1; val5.size = new Vector3((float)width, (float)depth, (float)height); val5.SetHeights(0, 0, GenerateHeights()); val4.terrainData = val5; Terminal_Patch.ResetFireExitAmounts(); Object[] array = Resources.FindObjectsOfTypeAll(typeof(Volume)); for (int i = 0; i < array.Length; i++) { Object obj2 = array[i]; if ((Object)(object)((Volume)((obj2 is Volume) ? obj2 : null)).sharedProfile == (Object)null) { Object obj3 = array[i]; ((Volume)((obj3 is Volume) ? obj3 : null)).sharedProfile = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<VolumeProfile>("Assets/Mods/LethalExpansion/Sky and Fog Global Volume Profile.asset"); } } waitForSession().GetAwaiter(); isInGame = true; } if (((Scene)(ref scene)).name.StartsWith("Level")) { SpaceLight.SetActive(false); terrainfixer.SetActive(false); if (ConfigManager.Instance.FindItemValue<bool>("SettingsDebug")) { foreach (ConfigItem item in ConfigManager.Instance.GetAll()) { Log.LogInfo((object)"=========="); Log.LogInfo((object)item.Key); Log.LogInfo(item.Value); Log.LogInfo(item.DefaultValue); Log.LogInfo((object)item.Sync); } } } if (!(((Scene)(ref scene)).name == "InitSceneLaunchOptions") || !isInGame) { return; } SpaceLight.SetActive(false); terrainfixer.SetActive(false); GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects(); foreach (GameObject val6 in rootGameObjects) { val6.SetActive(false); } if (ConfigManager.Instance.FindItemValue<bool>("SettingsDebug")) { foreach (ConfigItem item2 in ConfigManager.Instance.GetAll()) { Log.LogInfo((object)"=========="); Log.LogInfo((object)item2.Key); Log.LogInfo(item2.Value); Log.LogInfo(item2.DefaultValue); Log.LogInfo((object)item2.Sync); } } LoadCustomMoon(scene).GetAwaiter(); } private async Task LoadCustomMoon(Scene scene) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) await Task.Delay(400); try { if ((Object)(object)Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab != (Object)null && (Object)(object)Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab.transform != (Object)null) { CheckAndRemoveIllegalComponents(Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab.transform); GameObject mainPrefab = Object.Instantiate<GameObject>(Terminal_Patch.newMoons[StartOfRound.Instance.currentLevelID].MainPrefab); currentWaterSurface = mainPrefab.transform.Find("Environment/Water"); if ((Object)(object)mainPrefab != (Object)null) { SceneManager.MoveGameObjectToScene(mainPrefab, scene); Transform DiageticBackground = mainPrefab.transform.Find("Systems/Audio/DiageticBackground"); if ((Object)(object)DiageticBackground != (Object)null) { ((Component)DiageticBackground).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null); } Terrain[] Terrains = mainPrefab.GetComponentsInChildren<Terrain>(); if (Terrains != null && Terrains.Length != 0) { Terrain[] array = Terrains; foreach (Terrain terrain in array) { terrain.drawInstanced = true; } } } } string[] _tmp = new string[5] { "MapPropsContainer", "OutsideAINode", "SpawnDenialPoint", "ItemShipLandingNode", "OutsideLevelNavMesh" }; string[] array2 = _tmp; foreach (string s in array2) { if ((Object)(object)GameObject.FindGameObjectWithTag(s) == (Object)null || GameObject.FindGameObjectsWithTag(s).Any(delegate(GameObject o) { //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) Scene scene2 = o.scene; return ((Scene)(ref scene2)).name != "InitSceneLaunchOptions"; })) { GameObject obj = new GameObject(); ((Object)obj).name = s; obj.tag = s; obj.transform.position = new Vector3(0f, -200f, 0f); SceneManager.MoveGameObjectToScene(obj, scene); } } await Task.Delay(200); GameObject DropShip = GameObject.Find("ItemShipAnimContainer"); if ((Object)(object)DropShip != (Object)null) { Transform ItemShip = DropShip.transform.Find("ItemShip"); if ((Object)(object)ItemShip != (Object)null) { ((Component)ItemShip).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null); } Transform ItemShipMusicClose = DropShip.transform.Find("ItemShip/Music"); if ((Object)(object)ItemShipMusicClose != (Object)null) { ((Component)ItemShipMusicClose).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null); } Transform ItemShipMusicFar = DropShip.transform.Find("ItemShip/Music/Music (1)"); if ((Object)(object)ItemShipMusicFar != (Object)null) { ((Component)ItemShipMusicFar).GetComponent<AudioSource>().outputAudioMixerGroup = (AssetGather.Instance.audioMixers.ContainsKey("Diagetic") ? AssetGather.Instance.audioMixers["Diagetic"].Item2.First((AudioMixerGroup a) => ((Object)a).name == "Master") : null); } } await Task.Delay(200); RuntimeDungeon runtimeDungeon2 = Object.FindObjectOfType<RuntimeDungeon>(false); if ((Object)(object)runtimeDungeon2 == (Object)null) { GameObject dungeonGenerator = new GameObject(); ((Object)dungeonGenerator).name = "DungeonGenerator"; dungeonGenerator.tag = "DungeonGenerator"; dungeonGenerator.transform.position = new Vector3(0f, -200f, 0f); runtimeDungeon2 = dungeonGenerator.AddComponent<RuntimeDungeon>(); runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0]; runtimeDungeon2.Generator.LengthMultiplier = 0.8f; runtimeDungeon2.Generator.PauseBetweenRooms = 0.2f; runtimeDungeon2.GenerateOnStart = false; runtimeDungeon2.Root = dungeonGenerator; runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0]; UnityNavMeshAdapter dungeonNavMesh = dungeonGenerator.AddComponent<UnityNavMeshAdapter>(); dungeonNavMesh.BakeMode = (RuntimeNavMeshBakeMode)3; dungeonNavMesh.LayerMask = LayerMask.op_Implicit(35072); SceneManager.MoveGameObjectToScene(dungeonGenerator, scene); } else if ((Object)(object)runtimeDungeon2.Generator.DungeonFlow == (Object)null) { runtimeDungeon2.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0]; } GameObject OutOfBounds = GameObject.CreatePrimitive((PrimitiveType)3); ((Object)OutOfBounds).name = "OutOfBounds"; OutOfBounds.layer = 13; OutOfBounds.transform.position = new Vector3(0f, -300f, 0f); OutOfBounds.transform.localScale = new Vector3(1000f, 5f, 1000f); BoxCollider boxCollider = OutOfBounds.GetComponent<BoxCollider>(); ((Collider)boxCollider).isTrigger = true; OutOfBounds.AddComponent<OutOfBoundsTrigger>(); Rigidbody rigidbody = OutOfBounds.AddComponent<Rigidbody>(); rigidbody.useGravity = false; rigidbody.isKinematic = true; rigidbody.collisionDetectionMode = (CollisionDetectionMode)1; SceneManager.MoveGameObjectToScene(OutOfBounds, scene); await Task.Delay(200); } catch (Exception ex2) { Exception ex = ex2; Log.LogError((object)ex); } } private void CheckAndRemoveIllegalComponents(Transform root) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown try { Component[] components = ((Component)root).GetComponents<Component>(); Component[] array = components; foreach (Component component in array) { if (!ComponentWhitelists.moonPrefabWhitelist.Any((Type whitelistType) => ((object)component).GetType() == whitelistType)) { Log.LogWarning((object)("Removed illegal " + ((object)component).GetType().Name + " component.")); Object.Destroy((Object)(object)component); } } foreach (Transform item in root) { Transform root2 = item; CheckAndRemoveIllegalComponents(root2); } } catch (Exception ex) { Log.LogError((object)ex.Message); } } private void OnSceneUnloaded(Scene scene) { if (((Scene)(ref scene)).name.Length > 0) { ((BaseUnityPlugin)this).Logger.LogInfo((object)("Unloading scene: " + ((Scene)(ref scene)).name)); } if (((Scene)(ref scene)).name.StartsWith("Level") || ((Scene)(ref scene)).name == "CompanyBuilding" || (((Scene)(ref scene)).name == "InitSceneLaunchOptions" && isInGame)) { if ((Object)(object)SpaceLight != (Object)null) { SpaceLight.SetActive(true); } if ((Object)(object)currentWaterSurface != (Object)null) { currentWaterSurface = null; } Terminal_Patch.ResetFireExitAmounts(); } } private async Task waitForSession() { while (sessionWaiting) { await Task.Delay(1000); } if (!ishost) { while (!sessionWaiting && hostDataWaiting) { NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.request, "hostconfig", string.Empty, 0L); await Task.Delay(3000); } } else { for (int i = 0; i < ConfigManager.Instance.GetAll().Count; i++) { if (ConfigManager.Instance.MustBeSync(i)) { ConfigManager.Instance.SetItemValue(i, ConfigManager.Instance.FindEntryValue(i)); } } } bool patchGlobalTimeSpeedMultiplier = true; bool patchNumberOfHours = true; bool patchDeadlineDaysAmount = true; bool patchStartingQuota = true; bool patchStartingCredits = true; bool patchBaseIncrease = true; bool patchIncreaseSteepness = true; bool patchScrapValueMultiplier = true; bool patchScrapAmountMultiplier = true; bool patchMapSizeMultiplier = true; bool patchMaxShipItemCapacity = true; if (!ConfigManager.Instance.FindItemValue<bool>("BrutalCompanyPlusCompatibility") || !loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "BrutalCompanyPlus")) { patchDeadlineDaysAmount = false; patchStartingQuota = false; patchStartingCredits = false; patchBaseIncrease = false; patchIncreaseSteepness = false; } if (!ConfigManager.Instance.FindItemValue<bool>("LethalAdjustmentsCompatibility") || !loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "LethalAdjustments")) { patchScrapValueMultiplier = false; patchScrapAmountMultiplier = false; patchMapSizeMultiplier = false; } if (!ConfigManager.Instance.FindItemValue<bool>("CoomfyDungeonCompatibility") || !loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "CoomfyDungeon")) { patchScrapAmountMultiplier = false; patchMapSizeMultiplier = false; } if (!ConfigManager.Instance.FindItemValue<bool>("MoreMoneyStartCompatibility") || !loadedPlugins.Any((PluginInfo p) => p.Metadata.GUID == "299792458.MoreMoneyStart")) { patchStartingCredits = false; } if (patchGlobalTimeSpeedMultiplier) { TimeOfDay.Instance.globalTimeSpeedMultiplier = ConfigManager.Instance.FindItemValue<float>("GlobalTimeSpeedMultiplier"); } if (patchNumberOfHours) { TimeOfDay.Instance.numberOfHours = ConfigManager.Instance.FindItemValue<int>("NumberOfHours"); } if (patchDeadlineDaysAmount) { TimeOfDay.Instance.quotaVariables.deadlineDaysAmount = ConfigManager.Instance.FindItemValue<int>("DeadlineDaysAmount"); } if (patchStartingQuota) { TimeOfDay.Instance.quotaVariables.startingQuota = ConfigManager.Instance.FindItemValue<int>("StartingQuota"); } if (patchStartingCredits) { TimeOfDay.Instance.quotaVariables.startingCredits = ConfigManager.Instance.FindItemValue<int>("StartingCredits"); } if (patchBaseIncrease) { TimeOfDay.Instance.quotaVariables.baseIncrease = ConfigManager.Instance.FindItemValue<int>("QuotaBaseIncrease"); } if (patchIncreaseSteepness) { TimeOfDay.Instance.quotaVariables.increaseSteepness = ConfigManager.Instance.FindItemValue<int>("QuotaIncreaseSteepness"); } if (patchScrapValueMultiplier) { RoundManager.Instance.scrapValueMultiplier = ConfigManager.Instance.FindItemValue<float>("ScrapValueMultiplier"); } if (patchScrapAmountMultiplier) { RoundManager.Instance.scrapAmountMultiplier = ConfigManager.Instance.FindItemValue<float>("ScrapAmountMultiplier"); } if (patchMapSizeMultiplier) { RoundManager.Instance.mapSizeMultiplier = ConfigManager.Instance.FindItemValue<float>("MapSizeMultiplier"); } if (patchMaxShipItemCapacity) { StartOfRound.Instance.maxShipItemCapacity = ConfigManager.Instance.FindItemValue<int>("MaxItemsInShip"); } if (!alreadypatched) { Terminal_Patch.MainPatch(GameObject.Find("TerminalScript").GetComponent<Terminal>()); alreadypatched = true; } } private void ConfigSettingChanged(object sender, EventArgs e) { SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null); if (val != null) { Log.LogInfo((object)$"{val.ChangedSetting.Definition.Key} Changed to {val.ChangedSetting.BoxedValue}"); } } } } namespace LethalExpansion.Utils { public class AssetBundlesManager { private static AssetBundlesManager _instance; public AssetBundle mainAssetBundle = AssetBundle.LoadFromFile(Assembly.GetExecutingAssembly().Location.Replace("LethalExpansion.dll", "lethalexpansion.lem")); public Dictionary<string, (AssetBundle, ModManifest)> assetBundles = new Dictionary<string, (AssetBundle, ModManifest)>(); public readonly string[] forcedNative = new string[2] { "templatemod", "oldseaport" }; public DirectoryInfo modPath = new DirectoryInfo(Assembly.GetExecutingAssembly().Location); public DirectoryInfo modDirectory; public DirectoryInfo pluginsDirectory; public static AssetBundlesManager Instance { get { if (_instance == null) { _instance = new AssetBundlesManager(); } return _instance; } } public (AssetBundle, ModManifest) Load(string name) { return assetBundles[name.ToLower()]; } public void LoadAllAssetBundles() { modDirectory = modPath.Parent; pluginsDirectory = modDirectory; while (pluginsDirectory != null && pluginsDirectory.Name != "plugins") { pluginsDirectory = pluginsDirectory.Parent; } if (pluginsDirectory != null) { LethalExpansion.Log.LogInfo((object)("Plugins folder found: " + pluginsDirectory.FullName)); LethalExpansion.Log.LogInfo((object)("Mod path is: " + modDirectory.FullName)); if (modDirectory.FullName == pluginsDirectory.FullName) { LethalExpansion.Log.LogWarning((object)("LethalExpansion is Rooting the Plugins folder, this is not recommended. " + modDirectory.FullName)); } string[] files = Directory.GetFiles(pluginsDirectory.FullName, "*.lem", SearchOption.AllDirectories); foreach (string file in files) { LoadBundle(file); } } else { LethalExpansion.Log.LogWarning((object)"Mod is not in a plugins folder."); } } public void LoadBundle(string file) { if (forcedNative.Contains<string>(Path.GetFileNameWithoutExtension(file)) && !file.Contains(modDirectory.FullName)) { LethalExpansion.Log.LogWarning((object)("Illegal use of reserved Asset Bundle name: " + Path.GetFileNameWithoutExtension(file) + " at: " + file + ".")); } else { if (!(Path.GetFileName(file) != "lethalexpansion.lem")) { return; } if (!assetBundles.ContainsKey(Path.GetFileNameWithoutExtension(file))) { Stopwatch stopwatch = new Stopwatch(); AssetBundle val = null; try { stopwatch.Start(); val = AssetBundle.LoadFromFile(file); stopwatch.Stop(); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex); } if ((Object)(object)val != (Object)null) { string text = "Assets/Mods/" + Path.GetFileNameWithoutExtension(file) + "/ModManifest.asset"; ModManifest modManifest = val.LoadAsset<ModManifest>(text); if ((Object)(object)modManifest != (Object)null) { if (!assetBundles.Any((KeyValuePair<string, (AssetBundle, ModManifest)> b) => b.Value.Item2.modName == modManifest.modName)) { LethalExpansion.Log.LogInfo((object)string.Format("Module found: {0} v{1} Loaded in {2}ms", modManifest.modName, (modManifest.GetVersion() != null) ? ((object)modManifest.GetVersion()).ToString() : "0.0.0.0", stopwatch.ElapsedMilliseconds)); if (modManifest.GetVersion() == null || ((object)modManifest.GetVersion()).ToString() == "0.0.0.0") { LethalExpansion.Log.LogWarning((object)("Module " + modManifest.modName + " have no version number, this is unsafe!")); } assetBundles.Add(Path.GetFileNameWithoutExtension(file).ToLower(), (val, modManifest)); } else { LethalExpansion.Log.LogWarning((object)("Another mod with same name is already loaded: " + modManifest.modName)); val.Unload(true); LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file))); } } else { LethalExpansion.Log.LogWarning((object)("AssetBundle have no ModManifest: " + Path.GetFileName(file))); val.Unload(true); LethalExpansion.Log.LogInfo((object)("AssetBundle unloaded: " + Path.GetFileName(file))); } } else { LethalExpansion.Log.LogWarning((object)("File is not an AssetBundle: " + Path.GetFileName(file))); } } else { LethalExpansion.Log.LogWarning((object)("AssetBundle with same name already loaded: " + Path.GetFileName(file))); } } } public bool BundleLoaded(string bundleName) { return assetBundles.ContainsKey(bundleName.ToLower()); } public bool BundlesLoaded(string[] bundleNames) { foreach (string text in bundleNames) { if (!assetBundles.ContainsKey(text.ToLower())) { return false; } } return true; } public bool IncompatibleBundlesLoaded(string[] bundleNames) { foreach (string text in bundleNames) { if (assetBundles.ContainsKey(text.ToLower())) { return true; } } return false; } } public class AssetGather { private static AssetGather _instance; public Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>(); public Dictionary<string, (AudioMixer, AudioMixerGroup[])> audioMixers = new Dictionary<string, (AudioMixer, AudioMixerGroup[])>(); public Dictionary<string, GameObject> planetPrefabs = new Dictionary<string, GameObject>(); public Dictionary<string, GameObject> mapObjects = new Dictionary<string, GameObject>(); public Dictionary<string, SpawnableOutsideObject> outsideObjects = new Dictionary<string, SpawnableOutsideObject>(); public Dictionary<string, Item> scraps = new Dictionary<string, Item>(); public Dictionary<string, LevelAmbienceLibrary> levelAmbiances = new Dictionary<string, LevelAmbienceLibrary>(); public Dictionary<string, EnemyType> enemies = new Dictionary<string, EnemyType>(); public Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>(); public static AssetGather Instance { get { if (_instance == null) { _instance = new AssetGather(); } return _instance; } } public void GetList() { LethalExpansion.Log.LogInfo((object)"Audio Clips"); foreach (KeyValuePair<string, AudioClip> audioClip in audioClips) { LethalExpansion.Log.LogInfo((object)audioClip.Key); } LethalExpansion.Log.LogInfo((object)"Audio Mixers"); foreach (KeyValuePair<string, (AudioMixer, AudioMixerGroup[])> audioMixer in audioMixers) { LethalExpansion.Log.LogInfo((object)audioMixer.Key); } LethalExpansion.Log.LogInfo((object)"Planet Prefabs"); foreach (KeyValuePair<string, GameObject> planetPrefab in planetPrefabs) { LethalExpansion.Log.LogInfo((object)planetPrefab.Key); } LethalExpansion.Log.LogInfo((object)"Map Objects"); foreach (KeyValuePair<string, GameObject> mapObject in mapObjects) { LethalExpansion.Log.LogInfo((object)mapObject.Key); } LethalExpansion.Log.LogInfo((object)"Outside Objects"); foreach (KeyValuePair<string, SpawnableOutsideObject> outsideObject in outsideObjects) { LethalExpansion.Log.LogInfo((object)outsideObject.Key); } LethalExpansion.Log.LogInfo((object)"Scraps"); foreach (KeyValuePair<string, Item> scrap in scraps) { LethalExpansion.Log.LogInfo((object)scrap.Key); } LethalExpansion.Log.LogInfo((object)"Level Ambiances"); foreach (KeyValuePair<string, LevelAmbienceLibrary> levelAmbiance in levelAmbiances) { LethalExpansion.Log.LogInfo((object)levelAmbiance.Key); } LethalExpansion.Log.LogInfo((object)"Enemies"); foreach (KeyValuePair<string, EnemyType> enemy in enemies) { LethalExpansion.Log.LogInfo((object)enemy.Key); } LethalExpansion.Log.LogInfo((object)"Sprites"); foreach (KeyValuePair<string, Sprite> sprite in sprites) { LethalExpansion.Log.LogInfo((object)sprite.Key); } } public void AddAudioClip(AudioClip clip) { if ((Object)(object)clip != (Object)null && !audioClips.ContainsKey(((Object)clip).name) && !audioClips.ContainsValue(clip)) { audioClips.Add(((Object)clip).name, clip); } } public void AddAudioClip(string name, AudioClip clip) { if ((Object)(object)clip != (Object)null && !audioClips.ContainsKey(name) && !audioClips.ContainsValue(clip)) { audioClips.Add(name, clip); } } public void AddAudioMixer(AudioMixer mixer) { if (!((Object)(object)mixer != (Object)null) || audioMixers.ContainsKey(((Object)mixer).name)) { return; } List<AudioMixerGroup> list = new List<AudioMixerGroup>(); AudioMixerGroup[] array = mixer.FindMatchingGroups(string.Empty); foreach (AudioMixerGroup val in array) { if ((Object)(object)val != (Object)null && !list.Contains(val)) { list.Add(val); } } audioMixers.Add(((Object)mixer).name, (mixer, list.ToArray())); } public void AddPlanetPrefabs(GameObject prefab) { if ((Object)(object)prefab != (Object)null && !planetPrefabs.ContainsKey(((Object)prefab).name) && !planetPrefabs.ContainsValue(prefab)) { planetPrefabs.Add(((Object)prefab).name, prefab); } } public void AddPlanetPrefabs(string name, GameObject prefab) { if ((Object)(object)prefab != (Object)null && !planetPrefabs.ContainsKey(name) && !planetPrefabs.ContainsValue(prefab)) { planetPrefabs.Add(name, prefab); } } public void AddMapObjects(GameObject mapObject) { if ((Object)(object)mapObject != (Object)null && !mapObjects.ContainsKey(((Object)mapObject).name) && !mapObjects.ContainsValue(mapObject)) { mapObjects.Add(((Object)mapObject).name, mapObject); } } public void AddOutsideObject(SpawnableOutsideObject outsideObject) { if ((Object)(object)outsideObject != (Object)null && !outsideObjects.ContainsKey(((Object)outsideObject).name) && !outsideObjects.ContainsValue(outsideObject)) { outsideObjects.Add(((Object)outsideObject).name, outsideObject); } } public void AddScrap(Item scrap) { if ((Object)(object)scrap != (Object)null && !scraps.ContainsKey(((Object)scrap).name) && !scraps.ContainsValue(scrap)) { scraps.Add(((Object)scrap).name, scrap); } } public void AddLevelAmbiances(LevelAmbienceLibrary levelAmbiance) { if ((Object)(object)levelAmbiance != (Object)null && !levelAmbiances.ContainsKey(((Object)levelAmbiance).name) && !levelAmbiances.ContainsValue(levelAmbiance)) { levelAmbiances.Add(((Object)levelAmbiance).name, levelAmbiance); } } public void AddEnemies(EnemyType enemie) { if ((Object)(object)enemie != (Object)null && !enemies.ContainsKey(((Object)enemie).name) && !enemies.ContainsValue(enemie)) { enemies.Add(((Object)enemie).name, enemie); } } public void AddSprites(Sprite sprite) { if ((Object)(object)sprite != (Object)null && !sprites.ContainsKey(((Object)sprite).name) && !sprites.ContainsValue(sprite)) { sprites.Add(((Object)sprite).name, sprite); } } public void AddSprites(string name, Sprite sprite) { if ((Object)(object)sprite != (Object)null && !sprites.ContainsKey(name) && !sprites.ContainsValue(sprite)) { sprites.Add(name, sprite); } } } public class ChatMessageProcessor { public static bool ProcessMessage(string message) { if (Regex.IsMatch(message, "^\\[sync\\].*\\[sync\\]$")) { try { string value = Regex.Match(message, "^\\[sync\\](.*)\\[sync\\]$").Groups[1].Value; string[] array = value.Split(new char[1] { '|' }); if (array.Length == 3) { NetworkPacketManager.packetType packetType = (NetworkPacketManager.packetType)int.Parse(array[0]); string[] array2 = array[1].Split(new char[1] { '>' }); ulong num = ulong.Parse(array2[0]); long num2 = long.Parse(array2[1]); string[] array3 = array[2].Split(new char[1] { '=' }); string header = array3[0]; string packet = array3[1]; if (num2 == -1 || num2 == (long)((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId) { if (num != 0) { NetworkPacketManager.Instance.CancelTimeout((long)num); } LethalExpansion.Log.LogInfo((object)message); switch (packetType) { case NetworkPacketManager.packetType.request: ProcessRequest(num, header, packet); break; case NetworkPacketManager.packetType.data: ProcessData(num, header, packet); break; case NetworkPacketManager.packetType.other: LethalExpansion.Log.LogInfo((object)"Unsupported type."); break; default: LethalExpansion.Log.LogInfo((object)"Unrecognized type."); break; } } } return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex); return false; } } return false; } private static void ProcessRequest(ulong sender, string header, string packet) { try { switch (header) { case "clientinfo": { if (LethalExpansion.ishost || sender != 0) { break; } string text2 = LethalExpansion.ModVersion.ToString() + "-"; foreach (KeyValuePair<string, (AssetBundle, ModManifest)> assetBundle in AssetBundlesManager.Instance.assetBundles) { text2 = text2 + assetBundle.Key + "v" + ((object)assetBundle.Value.Item2.GetVersion()).ToString() + "&"; } text2 = text2.Remove(text2.Length - 1); NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "clientinfo", text2, 0L); break; } case "hostconfig": if (LethalExpansion.ishost && sender != 0) { NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.request, "clientinfo", string.Empty, (long)sender); } break; case "hostweathers": if (LethalExpansion.ishost && sender != 0L && LethalExpansion.weathersReadyToShare) { string text = string.Empty; int[] currentWeathers = StartOfRound_Patch.currentWeathers; foreach (int num in currentWeathers) { text = text + num + "&"; } text = text.Remove(text.Length - 1); NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "hostweathers", text, (long)sender, waitForAnswer: false); } break; default: LethalExpansion.Log.LogInfo((object)"Unrecognized command."); break; } } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex); } } private static void ProcessData(ulong sender, string header, string packet) { //IL_04f6: Unknown result type (might be due to invalid IL or missing references) try { switch (header) { case "clientinfo": { if (!LethalExpansion.ishost || sender == 0) { break; } string[] array = ((!Enumerable.Contains(packet, '-')) ? new string[1] { packet } : packet.Split(new char[1] { '-' })); string text = string.Empty; foreach (KeyValuePair<string, (AssetBundle, ModManifest)> assetBundle in AssetBundlesManager.Instance.assetBundles) { text = text + assetBundle.Key + "v" + ((object)assetBundle.Value.Item2.GetVersion()).ToString() + "&"; } if (text.Length > 0) { text = text.Remove(text.Length - 1); } if (array[0] != LethalExpansion.ModVersion.ToString()) { if (StartOfRound.Instance.ClientPlayerList.ContainsKey(sender)) { LethalExpansion.Log.LogError((object)$"Kicking {sender} for wrong version."); NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "kickreason", "Wrong version.", (long)sender); StartOfRound.Instance.KickPlayer(StartOfRound.Instance.ClientPlayerList[sender]); } break; } if (array.Length > 1 && array[1] != text) { if (StartOfRound.Instance.ClientPlayerList.ContainsKey(sender)) { LethalExpansion.Log.LogError((object)$"Kicking {sender} for wrong bundles."); NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "kickreason", "Wrong bundles.", (long)sender); StartOfRound.Instance.KickPlayer(StartOfRound.Instance.ClientPlayerList[sender]); } break; } string text2 = string.Empty; foreach (ConfigItem item in ConfigManager.Instance.GetAll()) { switch (item.type.Name) { case "Int32": text2 = text2 + "i" + ((int)item.Value).ToString(CultureInfo.InvariantCulture); break; case "Single": text2 = text2 + "f" + ((float)item.Value).ToString(CultureInfo.InvariantCulture); break; case "Boolean": text2 = text2 + "b" + (bool)item.Value; break; case "String": text2 = text2 + "s" + item; break; } text2 += "&"; } text2 = text2.Remove(text2.Length - 1); NetworkPacketManager.Instance.sendPacket(NetworkPacketManager.packetType.data, "hostconfig", text2, (long)sender); break; } case "hostconfig": { if (LethalExpansion.ishost || sender != 0) { break; } string[] array2 = packet.Split(new char[1] { '&' }); LethalExpansion.Log.LogInfo((object)("Received host config: " + packet)); for (int i = 0; i < array2.Length; i++) { if (i < ConfigManager.Instance.GetCount() && ConfigManager.Instance.MustBeSync(i)) { ConfigManager.Instance.SetItemValue(i, array2[i].Substring(1), array2[i][0]); } } LethalExpansion.hostDataWaiting = false; LethalExpansion.Log.LogInfo((object)"Updated config"); break; } case "hostweathers": { if (LethalExpansion.ishost || sender != 0) { break; } string[] array3 = packet.Split(new char[1] { '&' }); LethalExpansion.Log.LogInfo((object)("Received host weathers: " + packet)); StartOfRound_Patch.currentWeathers = new int[array3.Length]; for (int j = 0; j < array3.Length; j++) { int result = 0; if (int.TryParse(array3[j], out result)) { StartOfRound_Patch.currentWeathers[j] = result; StartOfRound.Instance.levels[j].currentWeather = (LevelWeatherType)result; } } break; } case "kickreason": if (!LethalExpansion.ishost && sender == 0) { LethalExpansion.lastKickReason = packet; } break; default: LethalExpansion.Log.LogInfo((object)"Unrecognized property."); break; } } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex); } } } public class ComponentWhitelists { public static List<Type> moonPrefabWhitelist = new List<Type> { typeof(Transform), typeof(MeshFilter), typeof(MeshRenderer), typeof(SkinnedMeshRenderer), typeof(MeshCollider), typeof(BoxCollider), typeof(SphereCollider), typeof(CapsuleCollider), typeof(SphereCollider), typeof(TerrainCollider), typeof(WheelCollider), typeof(ArticulationBody), typeof(ConstantForce), typeof(ConfigurableJoint), typeof(FixedJoint), typeof(HingeJoint), typeof(Cloth), typeof(Rigidbody), typeof(NetworkObject), typeof(NetworkRigidbody), typeof(NetworkTransform), typeof(NetworkAnimator), typeof(Animator), typeof(Animation), typeof(Terrain), typeof(Tree), typeof(WindZone), typeof(DecalProjector), typeof(LODGroup), typeof(Light), typeof(HDAdditionalLightData), typeof(LightProbeGroup), typeof(LightProbeProxyVolume), typeof(LocalVolumetricFog), typeof(OcclusionArea), typeof(OcclusionPortal), typeof(ReflectionProbe), typeof(PlanarReflectionProbe), typeof(HDAdditionalReflectionData), typeof(Skybox), typeof(SortingGroup), typeof(SpriteRenderer), typeof(Volume), typeof(AudioSource), typeof(AudioReverbZone), typeof(AudioReverbFilter), typeof(AudioChorusFilter), typeof(AudioDistortionFilter), typeof(AudioEchoFilter), typeof(AudioHighPassFilter), typeof(AudioLowPassFilter), typeof(AudioListener), typeof(LensFlare), typeof(TrailRenderer), typeof(LineRenderer), typeof(ParticleSystem), typeof(ParticleSystemRenderer), typeof(ParticleSystemForceField), typeof(Projector), typeof(VideoPlayer), typeof(NavMeshSurface), typeof(NavMeshModifier), typeof(NavMeshModifierVolume), typeof(NavMeshLink), typeof(NavMeshObstacle), typeof(OffMeshLink), typeof(SI_AudioReverbPresets), typeof(SI_AudioReverbTrigger), typeof(SI_DungeonGenerator), typeof(SI_MatchLocalPlayerPosition), typeof(SI_AnimatedSun), typeof(SI_EntranceTeleport), typeof(SI_ScanNode), typeof(SI_DoorLock), typeof(SI_WaterSurface), typeof(SI_Ladder), typeof(SI_ItemDropship), typeof(SI_NetworkPrefabInstancier), typeof(SI_InteractTrigger), typeof(SI_DamagePlayer), typeof(SI_SoundYDistance), typeof(SI_AudioOutputInterface), typeof(PlayerShip) }; public static List<Type> scrapWhitelist = new List<Type> { typeof(Transform), typeof(MeshFilter), typeof(MeshRenderer), typeof(SkinnedMeshRenderer), typeof(MeshCollider), typeof(BoxCollider), typeof(SphereCollider), typeof(CapsuleCollider), typeof(SphereCollider), typeof(TerrainCollider), typeof(WheelCollider), typeof(ArticulationBody), typeof(ConstantForce), typeof(ConfigurableJoint), typeof(FixedJoint), typeof(HingeJoint), typeof(Cloth), typeof(Rigidbody), typeof(NetworkObject), typeof(NetworkRigidbody), typeof(NetworkTransform), typeof(NetworkAnimator), typeof(Animator), typeof(Animation), typeof(DecalProjector), typeof(LODGroup), typeof(Light), typeof(HDAdditionalLightData), typeof(LightProbeGroup), typeof(LightProbeProxyVolume), typeof(LocalVolumetricFog), typeof(OcclusionArea), typeof(OcclusionPortal), typeof(ReflectionProbe), typeof(PlanarReflectionProbe), typeof(HDAdditionalReflectionData), typeof(SortingGroup), typeof(SpriteRenderer), typeof(AudioSource), typeof(AudioReverbZone), typeof(AudioReverbFilter), typeof(AudioChorusFilter), typeof(AudioDistortionFilter), typeof(AudioEchoFilter), typeof(AudioHighPassFilter), typeof(AudioLowPassFilter), typeof(AudioListener), typeof(LensFlare), typeof(TrailRenderer), typeof(LineRenderer), typeof(ParticleSystem), typeof(ParticleSystemRenderer), typeof(ParticleSystemForceField), typeof(VideoPlayer) }; } public class ConfigManager { private static ConfigManager _instance; private List<ConfigItem> items = new List<ConfigItem>(); private List<ConfigEntryBase> entries = new List<ConfigEntryBase>(); public static ConfigManager Instance { get { if (_instance == null) { _instance = new ConfigManager(); } return _instance; } } public void AddItem(ConfigItem item) { try { items.Add(item); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); } } public void ReadConfig() { //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Expected O, but got Unknown //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Expected O, but got Unknown //IL_0308: Unknown result type (might be due to invalid IL or missing references) //IL_0312: Expected O, but got Unknown items = (from item in items orderby item.Tab, item.Key select item).ToList(); try { for (int i = 0; i < items.Count; i++) { if (!items[i].Hidden) { string description = items[i].Description; description = description + "\nNetwork synchronization: " + (items[i].Sync ? "Yes" : "No"); description = description + "\nMod required by clients: " + (items[i].Optional ? "No" : "Yes"); switch (items[i].type.Name) { case "Int32": entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<int>(items[i].Tab, items[i].Key, (int)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<int>((int)items[i].MinValue, (int)items[i].MaxValue), Array.Empty<object>()))); break; case "Single": entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<float>(items[i].Tab, items[i].Key, (float)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>((float)items[i].MinValue, (float)items[i].MaxValue), Array.Empty<object>()))); break; case "Boolean": entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<bool>(items[i].Tab, items[i].Key, (bool)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()))); break; case "String": entries.Add((ConfigEntryBase)(object)LethalExpansion.config.Bind<string>(items[i].Tab, items[i].Key, (string)items[i].DefaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()))); break; } if (!items[i].Sync) { items[i].Value = entries.Last().BoxedValue; } } else { entries.Add(null); } } } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); } } public object FindItemValue(string key) { try { return items.First((ConfigItem item) => item.Key == key).Value; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public object FindItemValue(int index) { try { return items[index].Value; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public object FindEntryValue(string key) { try { return entries.First((ConfigEntryBase item) => item.Definition.Key == key).BoxedValue; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public object FindEntryValue(int index) { try { return entries[index].BoxedValue; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public bool RequireRestart(string key) { try { return items.First((ConfigItem item) => item.Key == key).RequireRestart; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } public bool RequireRestart(int index) { try { return items[index].RequireRestart; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } public string FindDescription(string key) { try { return items.First((ConfigItem item) => item.Key == key).Description; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public string FindDescription(int index) { try { return items[index].Description; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public (bool, bool) FindNetInfo(string key) { try { ConfigItem configItem = items.First((ConfigItem item) => item.Key == key); return (configItem.Sync, configItem.Optional); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return (false, false); } } public (bool, bool) FindNetInfo(int index) { try { return (items[index].Sync, items[index].Optional); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return (false, false); } } public object FindDefaultValue(string key) { try { return items.First((ConfigItem item) => item.Key == key).DefaultValue; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public object FindDefaultValue(int index) { try { return items[index].DefaultValue; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public bool MustBeSync(string key) { try { return items.First((ConfigItem item) => item.Key == key).Sync; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return true; } } public bool MustBeSync(int index) { try { return items[index].Sync; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return true; } } public bool SetItemValue(string key, object value) { ConfigItem configItem = items.First((ConfigItem item) => item.Key == key); if (!items.First((ConfigItem item) => item.Key == key).RequireRestart) { try { configItem.Value = value; return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } return false; } public bool SetEntryValue(string key, object value) { try { entries.First((ConfigEntryBase item) => item.Definition.Key == key).BoxedValue = value; return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } public bool SetItemValue(int index, string value, char type) { if (!items[index].RequireRestart) { try { switch (type) { case 'i': items[index].Value = int.Parse(value, CultureInfo.InvariantCulture); break; case 'f': items[index].Value = float.Parse(value, CultureInfo.InvariantCulture); break; case 'b': items[index].Value = bool.Parse(value); break; case 's': items[index].Value = value; break; } return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } return false; } public bool SetEntryValue(int index, string value, char type) { try { switch (type) { case 'i': entries[index].BoxedValue = int.Parse(value); break; case 'f': entries[index].BoxedValue = float.Parse(value); break; case 'b': entries[index].BoxedValue = bool.Parse(value); break; case 's': entries[index].BoxedValue = value; break; } return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } public (object, int) FindValueAndIndex(string key) { try { return (items.First((ConfigItem item) => item.Key == key).Value, items.FindIndex((ConfigItem item) => item.Key == key)); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return (null, -1); } } public int FindIndex(string key) { try { return items.FindIndex((ConfigItem item) => item.Key == key); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return -1; } } public T FindItemValue<T>(string key) { try { ConfigItem configItem = items.First((ConfigItem item) => item.Key == key); if (configItem != null && configItem.Value is T) { return (T)configItem.Value; } LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type"); throw new InvalidOperationException("Key not found or value is of incorrect type"); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return default(T); } } public T FindItemValue<T>(int index) { try { ConfigItem configItem = items[index]; if (configItem != null && configItem.Value is T) { return (T)configItem.Value; } LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type"); throw new InvalidOperationException("Key not found or value is of incorrect type"); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return default(T); } } public T FindEntryValue<T>(string key) { try { ConfigEntryBase val = entries.First((ConfigEntryBase item) => item.Definition.Key == key); if (val != null && val.BoxedValue is T) { return (T)val.BoxedValue; } LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type"); throw new InvalidOperationException("Key not found or value is of incorrect type"); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return default(T); } } public T FindEntryValue<T>(int index) { try { ConfigEntryBase val = entries[index]; if (val != null && val.BoxedValue is T) { return (T)val.BoxedValue; } LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type"); throw new InvalidOperationException("Key not found or value is of incorrect type"); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return default(T); } } public bool SetItemValue<T>(string key, T value) { ConfigItem configItem = items.First((ConfigItem item) => item.Key == key); if (!configItem.RequireRestart) { try { if (configItem == null || !(configItem.Value is T)) { LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type"); throw new InvalidOperationException("Key not found or value is of incorrect type"); } configItem.Value = value; return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } return false; } public bool SetEntryValue<T>(string key, T value) { try { ConfigEntryBase val = entries.First((ConfigEntryBase item) => item.Definition.Key == key); if (val != null && val.BoxedValue is T) { val.BoxedValue = value; return true; } LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type"); throw new InvalidOperationException("Key not found or value is of incorrect type"); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } public bool SetItemValue<T>(int index, T value) { if (!items[index].RequireRestart) { try { items[index].Value = value; return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } return false; } public bool SetEntryValue<T>(int index, T value) { try { entries[index].BoxedValue = value; return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } public (T, int) FindValueAndIndex<T>(string key) { try { ConfigItem configItem = items.First((ConfigItem item) => item.Key == key); if (configItem != null && configItem.Value is T) { return ((T)configItem.Value, items.FindIndex((ConfigItem item) => item.Key == key)); } LethalExpansion.Log.LogError((object)"Key not found or value is of incorrect type"); throw new InvalidOperationException("Key not found or value is of incorrect type"); } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return (default(T), -1); } } public List<ConfigItem> GetAll() { try { return items; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public int GetCount() { try { return items.Count; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return -1; } } public int GetEntriesCount() { try { return entries.Count; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return -1; } } public object ReadConfigValue(string key) { try { return entries[FindIndex(key)].BoxedValue; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return null; } } public T ReadConfigValue<T>(string key) { try { return (T)entries[FindIndex(key)].BoxedValue; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return default(T); } } public bool WriteConfigValue(string key, object value) { try { int index = FindIndex(key); SetItemValue(index, value); entries[index].BoxedValue = value; return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } public bool WriteConfigValue<T>(string key, T value) { try { int index = FindIndex(key); SetItemValue(index, value); entries[index].BoxedValue = value; return true; } catch (Exception ex) { LethalExpansion.Log.LogError((object)ex.Message); return false; } } } public static class ModUtils { public static T[] RemoveElementFromArray<T>(T[] originalArray, int indexToRemove) { if (indexToRemove < 0 || indexToRemove >= originalArray.Length) { throw new ArgumentOutOfRangeException("indexToRemove"); } T[] array = new T[originalArray.Length - 1]; int i = 0; int num = 0; for (; i < originalArray.Length; i++) { if (i != indexToRemove) { array[num] = originalArray[i]; num++; } } return array; } } public class NetworkPacketManager { public enum packetType { request = 0, data = 1, other = -1 } private static NetworkPacketManager _instance; private ConcurrentDictionary<long, CancellationTokenSource> timeoutDictionary = new ConcurrentDictionary<long, CancellationTokenSource>(); public static NetworkPacketManager Instance { get { if (_instance == null) { _instance = new NetworkPacketManager(); } return _instance; } } private NetworkPacketManager() { } public void sendPacket(packetType type, string header, string packet, long destination = -1L, bool waitForAnswer = true) { HUDManager.Instance.AddTextToChatOnServer($"[sync]{(int)type}|{((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId}>{destination}|{header}={packet}[sync]", -1); if ((waitForAnswer && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ConfigManager.Instance.FindItemValue<bool>("LoadModules")) || ConfigManager.Instance.FindItemValue<bool>("KickPlayerWithoutMod")) { StartTimeout(destination); } } public void sendPacket(packetType type, string header, string packet, long[] destinations, bool waitForAnswer = true) { for (int i = 0; i < destinations.Length; i++) { int num = (int)destinations[i]; if (num != -1) { HUDManager.Instance.AddTextToChatOnServer($"[sync]{(int)type}|{((NetworkBehaviour)RoundManager.Instance).NetworkManager.LocalClientId}>{num}|{header}={packet}[sync]", -1); if ((waitForAnswer && ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost && ConfigManager.Instance.FindItemValue<bool>("LoadModules")) || ConfigManager.Instance.FindItemValue<bool>("KickPlayerWithoutMod")) { StartTimeout(num); } } } } public void StartTimeout(long id) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); if (!timeoutDictionary.TryAdd(id, cancellationTokenSource)) { return; } Task.Run(async delegate { try { await PacketTimeout(id, cancellationTokenSource.Token); } catch (OperationCanceledException) { } finally { timeoutDictionary.TryRemove(id, out var _); } }); } public void CancelTimeout(long id) { if (timeoutDictionary.TryRemove(id, out var value)) { value.Cancel(); } } private async Task PacketTimeout(long id, CancellationToken token) { await Task.Delay(5000, token); if (token.IsCancellationRequested) { } } } public class PopupManager { private static PopupManager _instance; private List<PopupObject> popups = new List<PopupObject>(); public static PopupManager Instance { get { if (_instance == null) { _instance = new PopupManager(); } return _instance; } } private PopupManager() { } public void InstantiatePopup(Scene sceneFocus, string title = "Popup", string content = "", string button1 = "Ok", string button2 = "Cancel", UnityAction button1Action = null, UnityAction button2Action = null, int titlesize = 24, int contentsize = 24, int button1size = 24, int button2size = 24) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Expected O, but got Unknown //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Expected O, but got Unknown //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Expected O, but got Unknown //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Expected O, but got Unknown if (!((Scene)(ref sceneFocus)).isLoaded) { return; } GameObject[] rootGameObjects = ((Scene)(ref sceneFocus)).GetRootGameObjects(); Canvas val = null; GameObject[] array = rootGameObjects; foreach (GameObject val2 in array) { val = val2.GetComponentInChildren<Canvas>(); if ((Object)(object)val != (Object)null) { break; } } if ((Object)(object)val == (Object)null || ((Component)val).gameObject.scene != sceneFocus) { GameObject val3 = new GameObject(); ((Object)val3).name = "Canvas"; val = val3.AddComponent<Canvas>(); SceneManager.MoveGameObjectToScene(((Component)val).gameObject, sceneFocus); } GameObject _tmp = Object.Instantiate<GameObject>(AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/HUD/Popup.prefab"), ((Component)val).transform); if ((Object)(object)_tmp != (Object)null) { ((Component)_tmp.transform.Find("DragAndDropSurface")).gameObject.AddComponent<SettingMenu_DragAndDrop>().rectTransform = _tmp.GetComponent<RectTransform>(); ((UnityEvent)((Component)_tmp.transform.Find("CloseButton")).gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { Object.Destroy((Object)(object)_tmp); }); if (button1Action != null) { ((UnityEvent)((Component)_tmp.transform.Find("Button1")).gameObject.GetComponent<Button>().onClick).AddListener(button1Action); } if (button2Action != null) { ((UnityEvent)((Component)_tmp.transform.Find("Button2")).gameObject.GetComponent<Button>().onClick).AddListener(button2Action); } ((UnityEvent)((Component)_tmp.transform.Find("Button1")).gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { Object.Destroy((Object)(object)_tmp); }); ((UnityEvent)((Component)_tmp.transform.Find("Button2")).gameObject.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { Object.Destroy((Object)(object)_tmp); }); PopupObject popupObject = new PopupObject(_tmp, ((Component)_tmp.transform.Find("Title")).GetComponent<TMP_Text>(), ((Component)_tmp.transform.Find("Panel/MainContent")).GetComponent<TMP_Text>(), ((Component)_tmp.transform.Find("Button1/Text")).GetComponent<TMP_Text>(), ((Component)_tmp.transform.Find("Button2/Text")).GetComponent<TMP_Text>()); popupObject.title.text = title; popupObject.title.fontSize = titlesize; popupObject.content.text = content; popupObject.content.fontSize = contentsize; popupObject.button1.text = button1; popupObject.button1.fontSize = button1size; popupObject.button2.text = button2; popupObject.button2.fontSize = button2size; popups.Add(popupObject); } } } public class PopupObject { public GameObject baseObject; public TMP_Text title; public TMP_Text content; public TMP_Text button1; public TMP_Text button2; public PopupObject(GameObject baseObject, TMP_Text title, TMP_Text content, TMP_Text button1, TMP_Text button2) { this.baseObject = baseObject; this.title = title; this.content = content; this.button1 = button1; this.button2 = button2; } } public class VersionChecker { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__1_0; internal void <CompareVersions>b__1_0() { Application.OpenURL("https://thunderstore.io/c/lethal-company/p/HolographicWings/LethalExpansion/"); } } public static async Task CheckVersion() { HttpClient httpClient = new HttpClient(); try { CompareVersions(await httpClient.GetStringAsync("https://raw.githubusercontent.com/HolographicWings/LethalExpansion/main/last.txt")); } catch (HttpRequestException val) { HttpRequestException val2 = val; HttpRequestException ex = val2; LethalExpansion.Log.LogError((object)((Exception)(object)ex).Message); } finally { ((IDisposable)httpClient)?.Dispose(); } } private static void CompareVersions(string onlineVersion) { //IL_0020: 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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown if (!(LethalExpansion.ModVersion < Version.Parse(onlineVersion))) { return; } PopupManager instance = PopupManager.Instance; Scene sceneByName = SceneManager.GetSceneByName("MainMenu"); string content = "Lethal Expansion is not up to date " + onlineVersion; object obj = <>c.<>9__1_0; if (obj == null) { UnityAction val = delegate { Application.OpenURL("https://thunderstore.io/c/lethal-company/p/HolographicWings/LethalExpansion/"); }; <>c.<>9__1_0 = val; obj = (object)val; } instance.InstantiatePopup(sceneByName, "Update", content, "Update", "Ignore", (UnityAction)obj); } } } namespace LethalExpansion.Utils.HUD { public class SettingMenu_DragAndDrop : MonoBehaviour, IBeginDragHandler, IEventSystemHandler, IDragHandler, IEndDragHandler { public UnityEvent onBeginDragEvent; public UnityEvent onDragEvent; public UnityEvent onEndDragEvent; public RectTransform rectTransform; private Canvas canvas; private void Awake() { if ((Object)(object)rectTransform == (Object)null) { rectTransform = ((Component)this).GetComponent<RectTransform>(); } canvas = Object.FindFirstObjectByType<Canvas>(); } public void OnBeginDrag(PointerEventData eventData) { if (onBeginDragEvent != null) { onBeginDragEvent.Invoke(); } } public void OnDrag(PointerEventData eventData) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if (eventData != null && (Object)(object)rectTransform != (Object)null) { rectTransform.anchoredPosition = ClampToWindow(rectTransform.anchoredPosition + eventData.delta / canvas.scaleFactor); if (onDragEvent != null) { onDragEvent.Invoke(); } } } public void OnEndDrag(PointerEventData eventData) { if (onEndDragEvent != null) { onEndDragEvent.Invoke(); } } private Vector2 ClampToWindow(Vector2 position) { //IL_0021: 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_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_004d: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = (Vector3[])(object)new Vector3[4]; float num = -260f; float num2 = 260f; float num3 = -60f; float num4 = 50f; float num5 = Mathf.Clamp(position.x, num, num2); float num6 = Mathf.Clamp(position.y, num3, num4); return new Vector2(num5, num6); } } public class SettingsMenu { private static SettingsMenu _instance; private bool initialized = false; private List<HUDSettingEntry> entries = new List<HUDSettingEntry>(); public static SettingsMenu Instance { get { if (_instance == null) { _instance = new SettingsMenu(); } return _instance; } } private SettingsMenu() { } public void InitSettingsMenu() { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: 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_00db: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Expected O, but got Unknown //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Expected O, but got Unknown //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Expected O, but got Unknown //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Expected O, but got Unknown //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Expected O, but got Unknown //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Expected O, but got Unknown //IL_0576: Unknown result type (might be due to invalid IL or missing references) //IL_04a5: Unknown result type (might be due to invalid IL or missing references) //IL_09ea: Unknown result type (might be due to invalid IL or missing references) //IL_0a0a: Unknown result type (might be due to invalid IL or missing references) //IL_0733: Unknown result type (might be due to invalid IL or missing references) //IL_073d: Expected O, but got Unknown //IL_0859: Unknown result type (might be due to invalid IL or missing references) //IL_0863: Expected O, but got Unknown //IL_08df: Unknown result type (might be due to invalid IL or missing references) //IL_08e9: Expected O, but got Unknown //IL_0965: Unknown result type (might be due to invalid IL or missing references) //IL_096f: Expected O, but got Unknown entries = new List<HUDSettingEntry>(); GameObject val = GameObject.Find("Canvas/MenuContainer"); if ((Object)(object)val == (Object)null) { LethalExpansion.Log.LogError((object)"MenuContainer not found in the scene!"); return; } RectTransform component = ((Component)val.transform.Find("MainButtons/HostButton")).GetComponent<RectTransform>(); component.anchoredPosition += new Vector2(0f, 38.5f); RectTransform component2 = ((Component)val.transform.Find("MainButtons/JoinACrew")).GetComponent<RectTransform>(); component2.anchoredPosition += new Vector2(0f, 38.5f); RectTransform component3 = ((Component)val.transform.Find("MainButtons/StartLAN")).GetComponent<RectTransform>(); component3.anchoredPosition += new Vector2(0f, 38.5f); GameObject gameObject = ((Component)val.transform.Find("MainButtons/SettingsButton")).gameObject; RectTransform component4 = gameObject.GetComponent<RectTransform>(); component4.anchoredPosition += new Vector2(0f, 38.5f); GameObject val2 = Object.Instantiate<GameObject>(gameObject, val.transform); val2.transform.SetParent(val.transform.Find("MainButtons")); ((Object)val2).name = "ModSettingsButton"; ((Component)val2.transform.Find("Text (TMP)")).GetComponent<TMP_Text>().text = "> Mod Settings"; val2.GetComponent<RectTransform>().anchoredPosition = gameObject.GetComponent<RectTransform>().anchoredPosition - new Vector2(0f, 38.5f); GameObject ModSettingsPanel = Object.Instantiate<GameObject>(AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/HUD/Settings/ModSettings.prefab")); GameObject val3 = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/HUD/Settings/SettingEntry.prefab"); GameObject val4 = AssetBundlesManager.Instance.mainAssetBundle.LoadAsset<GameObject>("Assets/Mods/LethalExpansion/Prefabs/HUD/Settings/SettingCategory.prefab"); ModSettingsPanel.transform.SetParent(val.transform); ModSettingsPanel.transform.localPosition = Vector3.zero; ModSettingsPanel.transform.localScale = Vector3.one; Button component5 = val2.GetComponent<Button>(); component5.onClick = new ButtonClickedEvent(); ((UnityEvent)component5.onClick).AddListener((UnityAction)delegate { ModSettingsPanel.SetActive(true); GetSettings(); }); SettingMenu_DragAndDrop settingMenu_DragAndDrop = ((Component)ModSettingsPanel.transform.Find("DragAndDropSurface")).gameObject.AddComponent<SettingMenu_DragAndDrop>(); settingMenu_DragAndDrop.rectTransform = ModSettingsPanel.GetComponent<RectTransform>(); Button component6 = ((Component)ModSettingsPanel.transform.Find("CloseButton")).GetComponent<Button>(); Button component7 = ((Component)ModSettingsPanel.transform.Find("ApplyButton")).GetComponent<Button>(); Button component8 = ((Component)ModSettingsPanel.transform.Find("CancelButton")).GetComponent<Button>(); ((UnityEvent)component
BepInEx/plugins/LethalFashion.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalFashion")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Adding immediate outfits for the crew")] [assembly: AssemblyFileVersion("1.0.4.0")] [assembly: AssemblyInformationalVersion("1.0.4")] [assembly: AssemblyProduct("LethalFashion")] [assembly: AssemblyTitle("LethalFashion")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.4.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 LethalFashion { [BepInPlugin("LethalFashion", "LethalFashion", "1.0.4")] public class Plugin : BaseUnityPlugin { public static ManualLogSource Log; private static Harmony harmonyInstance; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LethalFashion is loaded!"); InitializeHarmony(); } private void InitializeHarmony() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if (harmonyInstance == null) { harmonyInstance = new Harmony("LethalFashion"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Harmony instance created"); try { harmonyInstance.PatchAll(typeof(SuitFashion)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Patch applied successfully. You are now FASHIONABLE."); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Error applying patch: " + ex.Message)); } } } } public class SuitFashion { private static readonly MethodInfo unlockItem; private static bool isHost; static SuitFashion() { unlockItem = typeof(StartOfRound).GetMethod("SpawnUnlockable", BindingFlags.Instance | BindingFlags.NonPublic); if (unlockItem == null) { Plugin.Log.LogError((object)"SpawnUnlockable method not found in StartOfRound. Please check game/plugin version."); } } public static void SpawnUnlockableDelegate(StartOfRound instance, int ID) { if (unlockItem == null) { Plugin.Log.LogError((object)"Cannot invoke SpawnUnlockable - method reference is null. Please check game/plugin version."); } else if (!instance.SpawnedShipUnlockables.ContainsKey(ID)) { try { unlockItem.Invoke(instance, new object[1] { ID }); } catch (Exception ex) { Plugin.Log.LogError((object)("Error invoking SpawnUnlockable: " + ex.Message)); } } } public static void PositionSuitsOnRack(StartOfRound startOfRoundInstance) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) UnlockableSuit[] array = Object.FindObjectsOfType<UnlockableSuit>(); for (int i = 0; i < array.Length; i++) { UnlockableSuit val = array[i]; AutoParentToShip component = ((Component)val).gameObject.GetComponent<AutoParentToShip>(); if ((Object)(object)component != (Object)null) { component.overrideOffset = true; component.positionOffset = new Vector3(-2.45f, 2.75f, -8.41f) + startOfRoundInstance.rightmostSuitPosition.forward * 0.18f * (float)i; component.rotationOffset = new Vector3(0f, 90f, 0f); } } } [HarmonyPatch(typeof(StartOfRound), "Start")] [HarmonyPostfix] public static void StartOfRoundSuitPatch(StartOfRound __instance) { if (!isHost) { return; } int[] array = new int[3] { 1, 2, 3 }; int[] array2 = array; foreach (int num in array2) { if (num >= 0 && num < __instance.unlockablesList.unlockables.Count) { UnlockableItem val = __instance.unlockablesList.unlockables[num]; if (val != null) { val.alreadyUnlocked = true; val.hasBeenUnlockedByPlayer = true; val.inStorage = false; SpawnUnlockableDelegate(__instance, num); } } } PositionSuitsOnRack(__instance); } [HarmonyPatch(typeof(StartOfRound), "ResetShip")] [HarmonyPostfix] public static void ResetShipSuitPatch(StartOfRound __instance) { if (isHost) { StartOfRoundSuitPatch(__instance); } } [HarmonyPatch(typeof(RoundManager), "Start")] [HarmonyPrefix] private static void SetIsHost() { isHost = ((NetworkBehaviour)RoundManager.Instance).NetworkManager.IsHost; } } public static class PluginInfo { public const string PLUGIN_GUID = "LethalFashion"; public const string PLUGIN_NAME = "LethalFashion"; public const string PLUGIN_VERSION = "1.0.4"; } }
BepInEx/plugins/LethalLib/LethalLib.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using DunGen; using DunGen.Graph; using LethalLib.Extras; using LethalLib.Modules; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using On; using Unity.Netcode; using UnityEngine; using UnityEngine.Audio; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalLib")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Mod for Lethal Company")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+7c7b4f966a6195fee029a3973eece88a0d72f551")] [assembly: AssemblyProduct("LethalLib")] [assembly: AssemblyTitle("LethalLib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] internal class <Module> { static <Module>() { } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 LethalLib { [BepInPlugin("evaisa.lethallib", "LethalLib", "0.10.1")] public class Plugin : BaseUnityPlugin { public const string ModGUID = "evaisa.lethallib"; public const string ModName = "LethalLib"; public const string ModVersion = "0.10.1"; public static AssetBundle MainAssets; public static ManualLogSource logger; public static ConfigFile config; private void Awake() { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) config = ((BaseUnityPlugin)this).Config; logger = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogInfo((object)"LethalLib loaded!!"); new ILHook((MethodBase)typeof(StackTrace).GetMethod("AddFrames", BindingFlags.Instance | BindingFlags.NonPublic), new Manipulator(IlHook)); Enemies.Init(); Items.Init(); Unlockables.Init(); MapObjects.Init(); Dungeon.Init(); Weathers.Init(); Player.Init(); Utilities.Init(); NetworkPrefabs.Init(); } private void IlHook(ILContext il) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction x) => ILPatternMatchingExt.MatchCallvirt(x, (MethodBase)typeof(StackFrame).GetMethod("GetFileLineNumber", BindingFlags.Instance | BindingFlags.Public)) }); val.RemoveRange(2); val.EmitDelegate<Func<StackFrame, string>>((Func<StackFrame, string>)GetLineOrIL); } private static string GetLineOrIL(StackFrame instance) { int fileLineNumber = instance.GetFileLineNumber(); if (fileLineNumber == -1 || fileLineNumber == 0) { return "IL_" + instance.GetILOffset().ToString("X4"); } return fileLineNumber.ToString(); } } } namespace LethalLib.Modules { public class ContentLoader { public class CustomContent { private string id = ""; public string ID => id; public CustomContent(string id) { this.id = id; } } public class CustomItem : CustomContent { public Action<Item> registryCallback = delegate { }; public string contentPath = ""; internal Item item; public Item Item => item; public CustomItem(string id, string contentPath, Action<Item> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } } } public class ShopItem : CustomItem { public int initPrice = 0; public string buyNode1Path = null; public string buyNode2Path = null; public string itemInfoPath = null; public void RemoveFromShop() { Items.RemoveShopItem(base.Item); } public void SetPrice(int price) { Items.UpdateShopItemPrice(base.Item, price); } public ShopItem(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, Action<Item> registryCallback = null) : base(id, contentPath, registryCallback) { initPrice = price; this.buyNode1Path = buyNode1Path; this.buyNode2Path = buyNode2Path; this.itemInfoPath = itemInfoPath; } } public class ScrapItem : CustomItem { private int rarity = 0; public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None; public string[] levelOverrides = null; public int Rarity => rarity; public void RemoveFromLevels(Levels.LevelTypes levelFlags) { Items.RemoveScrapFromLevels(base.Item, levelFlags); } public ScrapItem(string id, string contentPath, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Action<Item> registryCallback = null) : base(id, contentPath, registryCallback) { this.rarity = rarity; LevelTypes = levelFlags; this.levelOverrides = levelOverrides; } } public class Unlockable : CustomContent { public Action<UnlockableItem> registryCallback = delegate { }; internal UnlockableItem unlockable; public string contentPath = ""; public int initPrice = 0; public string buyNode1Path = null; public string buyNode2Path = null; public string itemInfoPath = null; public StoreType storeType = StoreType.None; public UnlockableItem UnlockableItem => unlockable; public void RemoveFromShop() { Unlockables.DisableUnlockable(UnlockableItem); } public void SetPrice(int price) { Unlockables.UpdateUnlockablePrice(UnlockableItem, price); } public Unlockable(string id, string contentPath, int price = 0, string buyNode1Path = null, string buyNode2Path = null, string itemInfoPath = null, StoreType storeType = StoreType.None, Action<UnlockableItem> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } initPrice = price; this.buyNode1Path = buyNode1Path; this.buyNode2Path = buyNode2Path; this.itemInfoPath = itemInfoPath; this.storeType = storeType; } } public class CustomEnemy : CustomContent { public Action<EnemyType> registryCallback = delegate { }; public string contentPath = ""; internal EnemyType enemy; public string infoNodePath = null; public string infoKeywordPath = null; public int rarity = 0; public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None; public string[] levelOverrides = null; public Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1); public EnemyType Enemy => enemy; public void RemoveFromLevels(Levels.LevelTypes levelFlags) { Enemies.RemoveEnemyFromLevels(Enemy, levelFlags); } public CustomEnemy(string id, string contentPath, int rarity = 0, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, Enemies.SpawnType spawnType = (Enemies.SpawnType)(-1), string[] levelOverrides = null, string infoNodePath = null, string infoKeywordPath = null, Action<EnemyType> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } this.infoNodePath = infoNodePath; this.infoKeywordPath = infoKeywordPath; this.rarity = rarity; LevelTypes = levelFlags; this.levelOverrides = levelOverrides; this.spawnType = spawnType; } } public class MapHazard : CustomContent { public Action<SpawnableMapObjectDef> registryCallback = delegate { }; public string contentPath = ""; internal SpawnableMapObjectDef hazard; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None; public string[] levelOverrides = null; public SpawnableMapObjectDef Hazard => hazard; public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { MapObjects.RemoveMapObject(Hazard, levelFlags, levelOverrides); } public MapHazard(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableMapObjectDef> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } LevelTypes = levelFlags; this.levelOverrides = levelOverrides; this.spawnRateFunction = spawnRateFunction; } } public class OutsideObject : CustomContent { public Action<SpawnableOutsideObjectDef> registryCallback = delegate { }; public string contentPath = ""; internal SpawnableOutsideObjectDef mapObject; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; public Levels.LevelTypes LevelTypes = Levels.LevelTypes.None; public string[] levelOverrides = null; public SpawnableOutsideObjectDef MapObject => mapObject; public void RemoveFromLevels(Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { MapObjects.RemoveOutsideObject(MapObject, levelFlags, levelOverrides); } public OutsideObject(string id, string contentPath, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, Action<SpawnableOutsideObjectDef> registryCallback = null) : base(id) { this.contentPath = contentPath; if (registryCallback != null) { this.registryCallback = registryCallback; } LevelTypes = levelFlags; this.levelOverrides = levelOverrides; this.spawnRateFunction = spawnRateFunction; } } private Dictionary<string, CustomContent> loadedContent = new Dictionary<string, CustomContent>(); public PluginInfo modInfo; private AssetBundle modBundle; public Action<CustomContent, GameObject> prefabCallback = delegate { }; public Dictionary<string, CustomContent> LoadedContent => loadedContent; public string modName => modInfo.Metadata.Name; public string modVersion => modInfo.Metadata.Version.ToString(); public string modGUID => modInfo.Metadata.GUID; public ContentLoader(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null) { this.modInfo = modInfo; this.modBundle = modBundle; if (prefabCallback != null) { this.prefabCallback = prefabCallback; } } public ContentLoader Create(PluginInfo modInfo, AssetBundle modBundle, Action<CustomContent, GameObject> prefabCallback = null) { return new ContentLoader(modInfo, modBundle, prefabCallback); } public void Register(CustomContent content) { if (loadedContent.ContainsKey(content.ID)) { Debug.LogError((object)("[LethalLib] " + modName + " tried to register content with ID " + content.ID + " but it already exists!")); return; } if (content is CustomItem customItem) { Item val = (customItem.item = modBundle.LoadAsset<Item>(customItem.contentPath)); NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab); Utilities.FixMixerGroups(val.spawnPrefab); prefabCallback(content, val.spawnPrefab); customItem.registryCallback(val); if (content is ShopItem shopItem) { TerminalNode buyNode = null; TerminalNode buyNode2 = null; TerminalNode itemInfo = null; if (shopItem.buyNode1Path != null) { buyNode = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode1Path); } if (shopItem.buyNode2Path != null) { buyNode2 = modBundle.LoadAsset<TerminalNode>(shopItem.buyNode2Path); } if (shopItem.itemInfoPath != null) { itemInfo = modBundle.LoadAsset<TerminalNode>(shopItem.itemInfoPath); } Items.RegisterShopItem(val, buyNode, buyNode2, itemInfo, shopItem.initPrice); } else if (content is ScrapItem scrapItem) { Items.RegisterScrap(val, scrapItem.Rarity, scrapItem.LevelTypes, scrapItem.levelOverrides); } else { Items.RegisterItem(val); } } else if (content is Unlockable unlockable) { UnlockableItemDef unlockableItemDef = modBundle.LoadAsset<UnlockableItemDef>(unlockable.contentPath); if ((Object)(object)unlockableItemDef.unlockable.prefabObject != (Object)null) { NetworkPrefabs.RegisterNetworkPrefab(unlockableItemDef.unlockable.prefabObject); prefabCallback(content, unlockableItemDef.unlockable.prefabObject); Utilities.FixMixerGroups(unlockableItemDef.unlockable.prefabObject); } unlockable.unlockable = unlockableItemDef.unlockable; unlockable.registryCallback(unlockableItemDef.unlockable); TerminalNode buyNode3 = null; TerminalNode buyNode4 = null; TerminalNode itemInfo2 = null; if (unlockable.buyNode1Path != null) { buyNode3 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode1Path); } if (unlockable.buyNode2Path != null) { buyNode4 = modBundle.LoadAsset<TerminalNode>(unlockable.buyNode2Path); } if (unlockable.itemInfoPath != null) { itemInfo2 = modBundle.LoadAsset<TerminalNode>(unlockable.itemInfoPath); } Unlockables.RegisterUnlockable(unlockableItemDef, unlockable.storeType, buyNode3, buyNode4, itemInfo2, unlockable.initPrice); } else if (content is CustomEnemy customEnemy) { EnemyType val2 = modBundle.LoadAsset<EnemyType>(customEnemy.contentPath); NetworkPrefabs.RegisterNetworkPrefab(val2.enemyPrefab); Utilities.FixMixerGroups(val2.enemyPrefab); customEnemy.enemy = val2; prefabCallback(content, val2.enemyPrefab); customEnemy.registryCallback(val2); TerminalNode infoNode = null; TerminalKeyword infoKeyword = null; if (customEnemy.infoNodePath != null) { infoNode = modBundle.LoadAsset<TerminalNode>(customEnemy.infoNodePath); } if (customEnemy.infoKeywordPath != null) { infoKeyword = modBundle.LoadAsset<TerminalKeyword>(customEnemy.infoKeywordPath); } if (customEnemy.spawnType == (Enemies.SpawnType)(-1)) { Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.levelOverrides, infoNode, infoKeyword); } else { Enemies.RegisterEnemy(val2, customEnemy.rarity, customEnemy.LevelTypes, customEnemy.spawnType, customEnemy.levelOverrides, infoNode, infoKeyword); } } else if (content is MapHazard mapHazard) { SpawnableMapObjectDef spawnableMapObjectDef = (mapHazard.hazard = modBundle.LoadAsset<SpawnableMapObjectDef>(mapHazard.contentPath)); NetworkPrefabs.RegisterNetworkPrefab(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn); Utilities.FixMixerGroups(spawnableMapObjectDef.spawnableMapObject.prefabToSpawn); prefabCallback(content, spawnableMapObjectDef.spawnableMapObject.prefabToSpawn); mapHazard.registryCallback(spawnableMapObjectDef); MapObjects.RegisterMapObject(spawnableMapObjectDef, mapHazard.LevelTypes, mapHazard.levelOverrides, mapHazard.spawnRateFunction); } else if (content is OutsideObject outsideObject) { SpawnableOutsideObjectDef spawnableOutsideObjectDef = (outsideObject.mapObject = modBundle.LoadAsset<SpawnableOutsideObjectDef>(outsideObject.contentPath)); NetworkPrefabs.RegisterNetworkPrefab(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn); Utilities.FixMixerGroups(spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn); prefabCallback(content, spawnableOutsideObjectDef.spawnableMapObject.spawnableObject.prefabToSpawn); outsideObject.registryCallback(spawnableOutsideObjectDef); MapObjects.RegisterOutsideObject(spawnableOutsideObjectDef, outsideObject.LevelTypes, outsideObject.levelOverrides, outsideObject.spawnRateFunction); } loadedContent.Add(content.ID, content); } public void RegisterAll(CustomContent[] content) { Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Length} content items!"); foreach (CustomContent content2 in content) { Register(content2); } } public void RegisterAll(List<CustomContent> content) { Plugin.logger.LogInfo((object)$"[LethalLib] {modName} is registering {content.Count} content items!"); foreach (CustomContent item in content) { Register(item); } } } public class Dungeon { public class CustomDungeonArchetype { public DungeonArchetype archeType; public Levels.LevelTypes LevelTypes; public int lineIndex = -1; } public class CustomGraphLine { public GraphLine graphLine; public Levels.LevelTypes LevelTypes; } public class CustomDungeon { public int rarity; public DungeonFlow dungeonFlow; public Levels.LevelTypes LevelTypes; public string[] levelOverrides; public int dungeonIndex = -1; public AudioClip firstTimeDungeonAudio; } [CompilerGenerated] private static class <>O { public static hook_GenerateNewFloor <0>__RoundManager_GenerateNewFloor; public static hook_Start <1>__RoundManager_Start; public static hook_Start <2>__StartOfRound_Start; } public static List<CustomDungeonArchetype> customDungeonArchetypes = new List<CustomDungeonArchetype>(); public static List<CustomGraphLine> customGraphLines = new List<CustomGraphLine>(); public static Dictionary<string, TileSet> extraTileSets = new Dictionary<string, TileSet>(); public static Dictionary<string, GameObjectChance> extraRooms = new Dictionary<string, GameObjectChance>(); public static List<CustomDungeon> customDungeons = new List<CustomDungeon>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown object obj = <>O.<0>__RoundManager_GenerateNewFloor; if (obj == null) { hook_GenerateNewFloor val = RoundManager_GenerateNewFloor; <>O.<0>__RoundManager_GenerateNewFloor = val; obj = (object)val; } RoundManager.GenerateNewFloor += (hook_GenerateNewFloor)obj; object obj2 = <>O.<1>__RoundManager_Start; if (obj2 == null) { hook_Start val2 = RoundManager_Start; <>O.<1>__RoundManager_Start = val2; obj2 = (object)val2; } RoundManager.Start += (hook_Start)obj2; object obj3 = <>O.<2>__StartOfRound_Start; if (obj3 == null) { hook_Start val3 = StartOfRound_Start; <>O.<2>__StartOfRound_Start = val3; obj3 = (object)val3; } StartOfRound.Start += (hook_Start)obj3; } private static void StartOfRound_Start(orig_Start orig, StartOfRound self) { //IL_0152: 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_0168: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Expected O, but got Unknown foreach (CustomDungeon dungeon in customDungeons) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = dungeon.LevelTypes.HasFlag(Levels.LevelTypes.All) || (dungeon.levelOverrides != null && dungeon.levelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag) { Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if ((flag || dungeon.LevelTypes.HasFlag(levelTypes)) && !val.dungeonFlowTypes.Any((IntWithRarity rarityInt) => rarityInt.id == dungeon.dungeonIndex)) { List<IntWithRarity> list = val.dungeonFlowTypes.ToList(); list.Add(new IntWithRarity { id = dungeon.dungeonIndex, rarity = dungeon.rarity }); val.dungeonFlowTypes = list.ToArray(); } } } } Plugin.logger.LogInfo((object)"Added custom dungeons to levels"); orig.Invoke(self); } private static void RoundManager_Start(orig_Start orig, RoundManager self) { foreach (CustomDungeon customDungeon in customDungeons) { if (self.dungeonFlowTypes.Contains(customDungeon.dungeonFlow)) { continue; } List<DungeonFlow> list = self.dungeonFlowTypes.ToList(); list.Add(customDungeon.dungeonFlow); self.dungeonFlowTypes = list.ToArray(); int dungeonIndex = self.dungeonFlowTypes.Length - 1; customDungeon.dungeonIndex = dungeonIndex; List<AudioClip> list2 = self.firstTimeDungeonAudios.ToList(); if (list2.Count != self.dungeonFlowTypes.Length - 1) { while (list2.Count < self.dungeonFlowTypes.Length - 1) { list2.Add(null); } } list2.Add(customDungeon.firstTimeDungeonAudio); self.firstTimeDungeonAudios = list2.ToArray(); } orig.Invoke(self); } private static void RoundManager_GenerateNewFloor(orig_GenerateNewFloor orig, RoundManager self) { string name = ((Object)self.currentLevel).name; if (Enum.IsDefined(typeof(Levels.LevelTypes), name)) { Levels.LevelTypes levelEnum = (Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name); int index = 0; self.dungeonGenerator.Generator.DungeonFlow.Lines.ForEach(delegate(GraphLine line) { foreach (CustomDungeonArchetype customDungeonArchetype in customDungeonArchetypes) { if (customDungeonArchetype.LevelTypes.HasFlag(levelEnum) && !line.DungeonArchetypes.Contains(customDungeonArchetype.archeType) && (customDungeonArchetype.lineIndex == -1 || customDungeonArchetype.lineIndex == index)) { line.DungeonArchetypes.Add(customDungeonArchetype.archeType); Plugin.logger.LogInfo((object)("Added " + ((Object)customDungeonArchetype.archeType).name + " to " + name)); } } foreach (DungeonArchetype dungeonArchetype in line.DungeonArchetypes) { string name2 = ((Object)dungeonArchetype).name; if (extraTileSets.ContainsKey(name2)) { TileSet val4 = extraTileSets[name2]; if (!dungeonArchetype.TileSets.Contains(val4)) { dungeonArchetype.TileSets.Add(val4); Plugin.logger.LogInfo((object)("Added " + ((Object)val4).name + " to " + name)); } } foreach (TileSet tileSet in dungeonArchetype.TileSets) { string name3 = ((Object)tileSet).name; if (extraRooms.ContainsKey(name3)) { GameObjectChance item = extraRooms[name3]; if (!tileSet.TileWeights.Weights.Contains(item)) { tileSet.TileWeights.Weights.Add(item); } } } } index++; }); foreach (CustomGraphLine customGraphLine in customGraphLines) { if (customGraphLine.LevelTypes.HasFlag(levelEnum) && !self.dungeonGenerator.Generator.DungeonFlow.Lines.Contains(customGraphLine.graphLine)) { self.dungeonGenerator.Generator.DungeonFlow.Lines.Add(customGraphLine.graphLine); } } } orig.Invoke(self); NetworkManager val = Object.FindObjectOfType<NetworkManager>(); RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val2 in array2) { for (int j = 0; j < val2.spawnablePrefabs.Count; j++) { string prefabName = ((Object)val2.spawnablePrefabs[j]).name; NetworkPrefab val3 = val.NetworkConfig.Prefabs.m_Prefabs.First((NetworkPrefab x) => ((Object)x.Prefab).name == prefabName); if (val3 != null && (Object)(object)val3.Prefab != (Object)(object)val2.spawnablePrefabs[j]) { val2.spawnablePrefabs[j] = val3.Prefab; } } } } public static void AddArchetype(DungeonArchetype archetype, Levels.LevelTypes levelFlags, int lineIndex = -1) { CustomDungeonArchetype customDungeonArchetype = new CustomDungeonArchetype(); customDungeonArchetype.archeType = archetype; customDungeonArchetype.LevelTypes = levelFlags; customDungeonArchetype.lineIndex = lineIndex; customDungeonArchetypes.Add(customDungeonArchetype); } public static void AddLine(GraphLine line, Levels.LevelTypes levelFlags) { CustomGraphLine customGraphLine = new CustomGraphLine(); customGraphLine.graphLine = line; customGraphLine.LevelTypes = levelFlags; customGraphLines.Add(customGraphLine); } public static void AddLine(DungeonGraphLineDef line, Levels.LevelTypes levelFlags) { AddLine(line.graphLine, levelFlags); } public static void AddTileSet(TileSet set, string archetypeName) { extraTileSets.Add(archetypeName, set); } public static void AddRoom(GameObjectChance room, string tileSetName) { extraRooms.Add(tileSetName, room); } public static void AddRoom(GameObjectChanceDef room, string tileSetName) { AddRoom(room.gameObjectChance, tileSetName); } public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags) { AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, dungeon.firstTimeDungeonAudio); } public static void AddDungeon(DungeonDef dungeon, Levels.LevelTypes levelFlags, string[] levelOverrides) { AddDungeon(dungeon.dungeonFlow, dungeon.rarity, levelFlags, levelOverrides, dungeon.firstTimeDungeonAudio); } public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, AudioClip firstTimeDungeonAudio = null) { customDungeons.Add(new CustomDungeon { dungeonFlow = dungeon, rarity = rarity, LevelTypes = levelFlags, firstTimeDungeonAudio = firstTimeDungeonAudio }); } public static void AddDungeon(DungeonFlow dungeon, int rarity, Levels.LevelTypes levelFlags, string[] levelOverrides = null, AudioClip firstTimeDungeonAudio = null) { customDungeons.Add(new CustomDungeon { dungeonFlow = dungeon, rarity = rarity, LevelTypes = levelFlags, firstTimeDungeonAudio = firstTimeDungeonAudio, levelOverrides = levelOverrides }); } } public class Enemies { public struct EnemyAssetInfo { public EnemyType EnemyAsset; public TerminalKeyword keyword; } public enum SpawnType { Default, Daytime, Outside } public class SpawnableEnemy { public EnemyType enemy; public int rarity; public Levels.LevelTypes spawnLevels; public SpawnType spawnType; public TerminalNode terminalNode; public TerminalKeyword infoKeyword; public string modName; public string[] spawnLevelOverrides; public SpawnableEnemy(EnemyType enemy, int rarity, Levels.LevelTypes spawnLevels, SpawnType spawnType, string[] spawnLevelOverrides = null) { this.enemy = enemy; this.rarity = rarity; this.spawnLevels = spawnLevels; this.spawnType = spawnType; this.spawnLevelOverrides = spawnLevelOverrides; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__RegisterLevelEnemies; public static hook_Start <1>__Terminal_Start; } public static Terminal terminal; public static List<EnemyAssetInfo> enemyAssetInfos = new List<EnemyAssetInfo>(); public static List<SpawnableEnemy> spawnableEnemies = new List<SpawnableEnemy>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown object obj = <>O.<0>__RegisterLevelEnemies; if (obj == null) { hook_Awake val = RegisterLevelEnemies; <>O.<0>__RegisterLevelEnemies = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__Terminal_Start; if (obj2 == null) { hook_Start val2 = Terminal_Start; <>O.<1>__Terminal_Start = val2; obj2 = (object)val2; } Terminal.Start += (hook_Start)obj2; } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Expected O, but got Unknown terminal = self; TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); List<string> list = new List<string>(); foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { if (list.Contains(spawnableEnemy.enemy.enemyName)) { Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added")); continue; } if ((Object)(object)spawnableEnemy.terminalNode == (Object)null) { spawnableEnemy.terminalNode = ScriptableObject.CreateInstance<TerminalNode>(); spawnableEnemy.terminalNode.displayText = spawnableEnemy.enemy.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n"; spawnableEnemy.terminalNode.clearPreviousText = true; spawnableEnemy.terminalNode.maxCharactersToType = 35; spawnableEnemy.terminalNode.creatureName = spawnableEnemy.enemy.enemyName; } if (self.enemyFiles.Any((TerminalNode x) => x.creatureName == spawnableEnemy.terminalNode.creatureName)) { Plugin.logger.LogInfo((object)("Skipping " + spawnableEnemy.enemy.enemyName + " because it was already added")); continue; } TerminalKeyword keyword2 = (((Object)(object)spawnableEnemy.infoKeyword != (Object)null) ? spawnableEnemy.infoKeyword : TerminalUtils.CreateTerminalKeyword(spawnableEnemy.terminalNode.creatureName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val)); keyword2.defaultVerb = val; List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); if (!list2.Any((TerminalKeyword x) => x.word == keyword2.word)) { list2.Add(keyword2); self.terminalNodes.allKeywords = list2.ToArray(); } List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); if (!list3.Any((CompatibleNoun x) => x.noun.word == keyword2.word)) { list3.Add(new CompatibleNoun { noun = keyword2, result = spawnableEnemy.terminalNode }); } val.compatibleNouns = list3.ToArray(); spawnableEnemy.terminalNode.creatureFileID = self.enemyFiles.Count; self.enemyFiles.Add(spawnableEnemy.terminalNode); spawnableEnemy.enemy.enemyPrefab.GetComponentInChildren<ScanNodeProperties>().creatureScanID = spawnableEnemy.terminalNode.creatureFileID; EnemyAssetInfo enemyAssetInfo = default(EnemyAssetInfo); enemyAssetInfo.EnemyAsset = spawnableEnemy.enemy; enemyAssetInfo.keyword = keyword2; EnemyAssetInfo item = enemyAssetInfo; enemyAssetInfos.Add(item); } orig.Invoke(self); } private static void RegisterLevelEnemies(orig_Awake orig, StartOfRound self) { //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown orig.Invoke(self); foreach (SpawnableEnemy spawnableEnemy in spawnableEnemies) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = spawnableEnemy.spawnLevels.HasFlag(Levels.LevelTypes.All) || (spawnableEnemy.spawnLevelOverrides != null && spawnableEnemy.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (!flag && !spawnableEnemy.spawnLevels.HasFlag(levelTypes)) { continue; } SpawnableEnemyWithRarity item2 = new SpawnableEnemyWithRarity { enemyType = spawnableEnemy.enemy, rarity = spawnableEnemy.rarity }; switch (spawnableEnemy.spawnType) { case SpawnType.Default: if (!val.Enemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.Enemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Default]")); } break; case SpawnType.Daytime: if (!val.DaytimeEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.DaytimeEnemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Daytime]")); } break; case SpawnType.Outside: if (!val.OutsideEnemies.Any((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)spawnableEnemy.enemy)) { val.OutsideEnemies.Add(item2); Plugin.logger.LogInfo((object)("Added " + ((Object)spawnableEnemy.enemy).name + " to " + name + " with SpawnType [Outside]")); } break; } } } } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, SpawnType spawnType, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, spawnType, spawnLevelOverrides); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default)); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RegisterEnemy(EnemyType enemy, int rarity, Levels.LevelTypes levelFlags, string[] spawnLevelOverrides = null, TerminalNode infoNode = null, TerminalKeyword infoKeyword = null) { SpawnableEnemy spawnableEnemy = new SpawnableEnemy(enemy, rarity, levelFlags, enemy.isDaytimeEnemy ? SpawnType.Daytime : (enemy.isOutsideEnemy ? SpawnType.Outside : SpawnType.Default), spawnLevelOverrides); spawnableEnemy.terminalNode = infoNode; spawnableEnemy.infoKeyword = infoKeyword; Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; spawnableEnemy.modName = name; spawnableEnemies.Add(spawnableEnemy); } public static void RemoveEnemyFromLevels(EnemyType enemyType, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { List<SpawnableEnemyWithRarity> enemies = val.Enemies; List<SpawnableEnemyWithRarity> daytimeEnemies = val.DaytimeEnemies; List<SpawnableEnemyWithRarity> outsideEnemies = val.OutsideEnemies; enemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType); daytimeEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType); outsideEnemies.RemoveAll((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyType); } } } } public class Items { public struct ItemSaveOrderData { public int itemId; public string itemName; public string assetName; } public struct BuyableItemAssetInfo { public Item itemAsset; public TerminalKeyword keyword; } public class ScrapItem { public Item item; public int rarity; public Levels.LevelTypes spawnLevels; public string[] spawnLevelOverrides; public string modName; public ScrapItem(Item item, int rarity, Levels.LevelTypes spawnLevels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null) { this.item = item; this.rarity = rarity; this.spawnLevels = spawnLevels; this.spawnLevelOverrides = spawnLevelOverrides; } } public class PlainItem { public Item item; public string modName; public PlainItem(Item item) { this.item = item; } } public class ShopItem { public Item item; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public ShopItem(Item item, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = 0) { this.item = item; this.price = price; if ((Object)(object)buyNode1 != (Object)null) { this.buyNode1 = buyNode1; } if ((Object)(object)buyNode2 != (Object)null) { this.buyNode2 = buyNode2; } if ((Object)(object)itemInfo != (Object)null) { this.itemInfo = itemInfo; } } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_Start <1>__StartOfRound_Start; public static hook_Awake <2>__Terminal_Awake; } public static ConfigEntry<bool> useSavedataFix; public static List<Item> LethalLibItemList = new List<Item>(); public static List<BuyableItemAssetInfo> buyableItemAssetInfos = new List<BuyableItemAssetInfo>(); public static Terminal terminal; public static List<ScrapItem> scrapItems = new List<ScrapItem>(); public static List<ShopItem> shopItems = new List<ShopItem>(); public static List<PlainItem> plainItems = new List<PlainItem>(); public static void Init() { //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_003b: Expected O, but got Unknown //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown useSavedataFix = Plugin.config.Bind<bool>("Items", "EnableItemSaveFix", false, "Allow for LethalLib to store/reorder the item list, which should fix issues where items get reshuffled when loading an old save. This is experimental and may cause save corruptions occasionally."); object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__StartOfRound_Start; if (obj2 == null) { hook_Start val2 = StartOfRound_Start; <>O.<1>__StartOfRound_Start = val2; obj2 = (object)val2; } StartOfRound.Start += (hook_Start)obj2; object obj3 = <>O.<2>__Terminal_Awake; if (obj3 == null) { hook_Awake val3 = Terminal_Awake; <>O.<2>__Terminal_Awake = val3; obj3 = (object)val3; } Terminal.Awake += (hook_Awake)obj3; } private static void StartOfRound_Start(orig_Start orig, StartOfRound self) { if (useSavedataFix.Value && ((NetworkBehaviour)self).IsHost) { Plugin.logger.LogInfo((object)"Fixing Item savedata!!"); List<ItemSaveOrderData> itemList = new List<ItemSaveOrderData>(); StartOfRound.Instance.allItemsList.itemsList.ForEach(delegate(Item item) { itemList.Add(new ItemSaveOrderData { itemId = item.itemId, itemName = item.itemName, assetName = ((Object)item).name }); }); if (ES3.KeyExists("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName)) { itemList = ES3.Load<List<ItemSaveOrderData>>("LethalLibAllItemsList", GameNetworkManager.Instance.currentSaveFileName); } List<Item> itemsList = StartOfRound.Instance.allItemsList.itemsList; List<Item> list = new List<Item>(); foreach (ItemSaveOrderData item2 in itemList) { Item val = ((IEnumerable<Item>)itemsList).FirstOrDefault((Func<Item, bool>)((Item x) => x.itemId == item2.itemId && x.itemName == item2.itemName && item2.assetName == ((Object)x).name)); if ((Object)(object)val != (Object)null) { list.Add(val); } else { list.Add(ScriptableObject.CreateInstance<Item>()); } } foreach (Item item3 in itemsList) { if (!list.Contains(item3)) { list.Add(item3); } } StartOfRound.Instance.allItemsList.itemsList = list; ES3.Save<List<ItemSaveOrderData>>("LethalLibAllItemsList", itemList, GameNetworkManager.Instance.currentSaveFileName); } orig.Invoke(self); } private static void Terminal_Awake(orig_Awake orig, Terminal self) { //IL_0304: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Expected O, but got Unknown //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_038b: Expected O, but got Unknown //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03f4: Unknown result type (might be due to invalid IL or missing references) //IL_03fc: Unknown result type (might be due to invalid IL or missing references) //IL_0409: Expected O, but got Unknown //IL_049d: Unknown result type (might be due to invalid IL or missing references) //IL_04a2: Unknown result type (might be due to invalid IL or missing references) //IL_04aa: Unknown result type (might be due to invalid IL or missing references) //IL_04b7: Expected O, but got Unknown terminal = self; List<Item> list = self.buyableItemsList.ToList(); TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); Plugin.logger.LogInfo((object)$"Adding {shopItems.Count} items to terminal"); foreach (ShopItem item in shopItems) { if (list.Any((Item x) => x.itemName == item.item.itemName)) { Plugin.logger.LogInfo((object)("Item " + item.item.itemName + " already exists in terminal, skipping")); continue; } if (item.price == -1) { item.price = item.item.creditsWorth; } else { item.item.creditsWorth = item.price; } list.Add(item.item); string itemName = item.item.itemName; char c = itemName[itemName.Length - 1]; string text = itemName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = itemName.Replace(" ", "-") + "BuyNode2"; val3.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = list.Count - 1; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = itemName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = list.Count - 1; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; TerminalKeyword val5 = TerminalUtils.CreateTerminalKeyword(itemName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(val5); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = val5, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val6 = item.itemInfo; if ((Object)(object)val6 == (Object)null) { val6 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val6).name = itemName.Replace(" ", "-") + "InfoNode"; val6.displayText = "[No information about this object was found.]\n\n"; val6.clearPreviousText = true; val6.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = val5, result = val6 }); val2.compatibleNouns = list4.ToArray(); BuyableItemAssetInfo buyableItemAssetInfo = default(BuyableItemAssetInfo); buyableItemAssetInfo.itemAsset = item.item; buyableItemAssetInfo.keyword = val5; BuyableItemAssetInfo item2 = buyableItemAssetInfo; buyableItemAssetInfos.Add(item2); } self.buyableItemsList = list.ToArray(); orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Expected O, but got Unknown orig.Invoke(self); foreach (ScrapItem scrapItem in scrapItems) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = scrapItem.spawnLevels.HasFlag(Levels.LevelTypes.All) || (scrapItem.spawnLevelOverrides != null && scrapItem.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || scrapItem.spawnLevels.HasFlag(levelTypes)) { SpawnableItemWithRarity item2 = new SpawnableItemWithRarity { spawnableItem = scrapItem.item, rarity = scrapItem.rarity }; if (!val.spawnableScrap.Any((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem.item)) { val.spawnableScrap.Add(item2); } } } } foreach (ScrapItem scrapItem2 in scrapItems) { if (!self.allItemsList.itemsList.Contains(scrapItem2.item)) { if (scrapItem2.modName != "LethalLib") { Plugin.logger.LogInfo((object)(scrapItem2.modName + " registered item: " + scrapItem2.item.itemName)); } else { Plugin.logger.LogInfo((object)("Registered item: " + scrapItem2.item.itemName)); } LethalLibItemList.Add(scrapItem2.item); self.allItemsList.itemsList.Add(scrapItem2.item); } } foreach (ShopItem shopItem in shopItems) { if (!self.allItemsList.itemsList.Contains(shopItem.item)) { if (shopItem.modName != "LethalLib") { Plugin.logger.LogInfo((object)(shopItem.modName + " registered item: " + shopItem.item.itemName)); } else { Plugin.logger.LogInfo((object)("Registered item: " + shopItem.item.itemName)); } LethalLibItemList.Add(shopItem.item); self.allItemsList.itemsList.Add(shopItem.item); } } foreach (PlainItem plainItem in plainItems) { if (!self.allItemsList.itemsList.Contains(plainItem.item)) { if (plainItem.modName != "LethalLib") { Plugin.logger.LogInfo((object)(plainItem.modName + " registered item: " + plainItem.item.itemName)); } else { Plugin.logger.LogInfo((object)("Registered item: " + plainItem.item.itemName)); } LethalLibItemList.Add(plainItem.item); self.allItemsList.itemsList.Add(plainItem.item); } } } public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags) { ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; scrapItem.modName = name; scrapItems.Add(scrapItem); } public static void RegisterScrap(Item spawnableItem, int rarity, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { ScrapItem scrapItem = new ScrapItem(spawnableItem, rarity, levelFlags, levelOverrides); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; scrapItem.modName = name; scrapItems.Add(scrapItem); } public static void RegisterShopItem(Item shopItem, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { ShopItem shopItem2 = new ShopItem(shopItem, buyNode1, buyNode2, itemInfo, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterShopItem(Item shopItem, int price = -1) { ShopItem shopItem2 = new ShopItem(shopItem, null, null, null, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; shopItem2.modName = name; shopItems.Add(shopItem2); } public static void RegisterItem(Item plainItem) { PlainItem plainItem2 = new PlainItem(plainItem); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; plainItem2.modName = name; plainItems.Add(plainItem2); } public static void RemoveScrapFromLevels(Item scrapItem, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { SpawnableItemWithRarity val2 = ((IEnumerable<SpawnableItemWithRarity>)val.spawnableScrap).FirstOrDefault((Func<SpawnableItemWithRarity, bool>)((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)scrapItem)); if (val2 != null) { val.spawnableScrap.Remove(val2); } } } } public static void RemoveShopItem(Item shopItem) { if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } List<Item> list = terminal.buyableItemsList.ToList(); list.RemoveAll((Item x) => (Object)(object)x == (Object)(object)shopItem); terminal.buyableItemsList = list.ToArray(); List<TerminalKeyword> list2 = terminal.terminalNodes.allKeywords.ToList(); TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); TerminalKeyword val2 = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); List<CompatibleNoun> list3 = val2.compatibleNouns.ToList(); List<CompatibleNoun> list4 = val.compatibleNouns.ToList(); if (buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)shopItem)) { BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)shopItem); list2.Remove(asset.keyword); list3.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword); list4.RemoveAll((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword); } terminal.terminalNodes.allKeywords = list2.ToArray(); val2.compatibleNouns = list3.ToArray(); val.compatibleNouns = list4.ToArray(); } public static void UpdateShopItemPrice(Item shopItem, int price) { if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } shopItem.creditsWorth = price; TerminalKeyword val = terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; List<CompatibleNoun> source = val.compatibleNouns.ToList(); if (!buyableItemAssetInfos.Any((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)shopItem)) { return; } BuyableItemAssetInfo asset = buyableItemAssetInfos.First((BuyableItemAssetInfo x) => (Object)(object)x.itemAsset == (Object)(object)shopItem); if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword)) { return; } CompatibleNoun val2 = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword); TerminalNode result2 = val2.result; result2.itemCost = price; if (result2.terminalOptions.Length == 0) { return; } CompatibleNoun[] terminalOptions = result2.terminalOptions; foreach (CompatibleNoun val3 in terminalOptions) { if ((Object)(object)val3.result != (Object)null && val3.result.buyItemIndex != -1) { val3.result.itemCost = price; } } } } public class Levels { [Flags] public enum LevelTypes { None = 1, ExperimentationLevel = 4, AssuranceLevel = 8, VowLevel = 0x10, OffenseLevel = 0x20, MarchLevel = 0x40, RendLevel = 0x80, DineLevel = 0x100, TitanLevel = 0x200, Vanilla = 0x3FC, All = -1 } } public class MapObjects { public class RegisteredMapObject { public SpawnableMapObject mapObject; public SpawnableOutsideObjectWithRarity outsideObject; public Levels.LevelTypes levels; public string[] spawnLevelOverrides; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_SpawnMapObjects <1>__RoundManager_SpawnMapObjects; } public static List<RegisteredMapObject> mapObjects = new List<RegisteredMapObject>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__RoundManager_SpawnMapObjects; if (obj2 == null) { hook_SpawnMapObjects val2 = RoundManager_SpawnMapObjects; <>O.<1>__RoundManager_SpawnMapObjects = val2; obj2 = (object)val2; } RoundManager.SpawnMapObjects += (hook_SpawnMapObjects)obj2; } private static void RoundManager_SpawnMapObjects(orig_SpawnMapObjects orig, RoundManager self) { RandomMapObject[] array = Object.FindObjectsOfType<RandomMapObject>(); RandomMapObject[] array2 = array; foreach (RandomMapObject val in array2) { foreach (RegisteredMapObject mapObject in mapObjects) { if (mapObject.mapObject != null && !val.spawnablePrefabs.Any((GameObject prefab) => (Object)(object)prefab == (Object)(object)mapObject.mapObject.prefabToSpawn)) { val.spawnablePrefabs.Add(mapObject.mapObject.prefabToSpawn); } } } orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); foreach (RegisteredMapObject mapObject in mapObjects) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = mapObject.levels.HasFlag(Levels.LevelTypes.All) || (mapObject.spawnLevelOverrides != null && mapObject.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (!flag && !mapObject.levels.HasFlag(levelTypes)) { continue; } if (mapObject.mapObject != null) { if (!val.spawnableMapObjects.Any((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn)) { List<SpawnableMapObject> list = val.spawnableMapObjects.ToList(); list.RemoveAll((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn == (Object)(object)mapObject.mapObject.prefabToSpawn); val.spawnableMapObjects = list.ToArray(); } SpawnableMapObject mapObject2 = mapObject.mapObject; if (mapObject.spawnRateFunction != null) { mapObject2.numberToSpawn = mapObject.spawnRateFunction(val); } List<SpawnableMapObject> list2 = val.spawnableMapObjects.ToList(); list2.Add(mapObject2); val.spawnableMapObjects = list2.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)mapObject2.prefabToSpawn).name + " to " + name)); } else { if (mapObject.outsideObject == null) { continue; } if (!val.spawnableOutsideObjects.Any((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn)) { List<SpawnableOutsideObjectWithRarity> list3 = val.spawnableOutsideObjects.ToList(); list3.RemoveAll((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn == (Object)(object)mapObject.outsideObject.spawnableObject.prefabToSpawn); val.spawnableOutsideObjects = list3.ToArray(); } SpawnableOutsideObjectWithRarity outsideObject = mapObject.outsideObject; if (mapObject.spawnRateFunction != null) { outsideObject.randomAmount = mapObject.spawnRateFunction(val); } List<SpawnableOutsideObjectWithRarity> list4 = val.spawnableOutsideObjects.ToList(); list4.Add(outsideObject); val.spawnableOutsideObjects = list4.ToArray(); Plugin.logger.LogInfo((object)("Added " + ((Object)outsideObject.spawnableObject.prefabToSpawn).name + " to " + name)); } } } } public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterMapObject(mapObject.spawnableMapObject, levels, spawnRateFunction); } public static void RegisterMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterMapObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction); } public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { mapObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction }); } public static void RegisterMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { mapObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction, spawnLevelOverrides = levelOverrides }); } public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterOutsideObject(mapObject.spawnableMapObject, levels, spawnRateFunction); } public static void RegisterOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { RegisterOutsideObject(mapObject.spawnableMapObject, levels, levelOverrides, spawnRateFunction); } public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { outsideObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction }); } public static void RegisterOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] levelOverrides = null, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null) { mapObjects.Add(new RegisteredMapObject { outsideObject = mapObject, levels = levels, spawnRateFunction = spawnRateFunction, spawnLevelOverrides = levelOverrides }); } public static void RemoveMapObject(SpawnableMapObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { RemoveMapObject(mapObject.spawnableMapObject, levelFlags, levelOverrides); } public static void RemoveMapObject(SpawnableMapObject mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { val.spawnableMapObjects = val.spawnableMapObjects.Where((SpawnableMapObject x) => (Object)(object)x.prefabToSpawn != (Object)(object)mapObject.prefabToSpawn).ToArray(); } } } public static void RemoveOutsideObject(SpawnableOutsideObjectDef mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { RemoveOutsideObject(mapObject.spawnableMapObject, levelFlags, levelOverrides); } public static void RemoveOutsideObject(SpawnableOutsideObjectWithRarity mapObject, Levels.LevelTypes levelFlags, string[] levelOverrides = null) { if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { val.spawnableOutsideObjects = val.spawnableOutsideObjects.Where((SpawnableOutsideObjectWithRarity x) => (Object)(object)x.spawnableObject.prefabToSpawn != (Object)(object)mapObject.spawnableObject.prefabToSpawn).ToArray(); } } } } public class NetworkPrefabs { [CompilerGenerated] private static class <>O { public static hook_Start <0>__GameNetworkManager_Start; } private static List<GameObject> _networkPrefabs = new List<GameObject>(); internal static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown object obj = <>O.<0>__GameNetworkManager_Start; if (obj == null) { hook_Start val = GameNetworkManager_Start; <>O.<0>__GameNetworkManager_Start = val; obj = (object)val; } GameNetworkManager.Start += (hook_Start)obj; } public static void RegisterNetworkPrefab(GameObject prefab) { _networkPrefabs.Add(prefab); } private static void GameNetworkManager_Start(orig_Start orig, GameNetworkManager self) { orig.Invoke(self); foreach (GameObject networkPrefab in _networkPrefabs) { ((Component)self).GetComponent<NetworkManager>().AddNetworkPrefab(networkPrefab); } } } public class Player { [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; } public static Dictionary<string, GameObject> ragdollRefs = new Dictionary<string, GameObject>(); public static Dictionary<string, int> ragdollIndexes = new Dictionary<string, int>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); foreach (KeyValuePair<string, GameObject> ragdollRef in ragdollRefs) { if (!self.playerRagdolls.Contains(ragdollRef.Value)) { self.playerRagdolls.Add(ragdollRef.Value); int value = self.playerRagdolls.Count - 1; if (ragdollIndexes.ContainsKey(ragdollRef.Key)) { ragdollIndexes[ragdollRef.Key] = value; } else { ragdollIndexes.Add(ragdollRef.Key, value); } } } } public static int GetRagdollIndex(string id) { return ragdollIndexes[id]; } public static GameObject GetRagdoll(string id) { return ragdollRefs[id]; } public static void RegisterPlayerRagdoll(string id, GameObject ragdoll) { Plugin.logger.LogInfo((object)("Registering player ragdoll " + id)); ragdollRefs.Add(id, ragdoll); } } public class Shaders { public static void FixShaders(GameObject gameObject) { Renderer[] componentsInChildren = gameObject.GetComponentsInChildren<Renderer>(); foreach (Renderer val in componentsInChildren) { Material[] materials = val.materials; foreach (Material val2 in materials) { if (((Object)val2.shader).name.Contains("Standard")) { val2.shader = Shader.Find("HDRP/Lit"); } } } } } public class TerminalUtils { public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, CompatibleNoun[] compatibleNouns = null, TerminalNode specialKeywordResult = null, TerminalKeyword defaultVerb = null, bool accessTerminalObjects = false) { TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>(); ((Object)val).name = word; val.word = word; val.isVerb = isVerb; val.compatibleNouns = compatibleNouns; val.specialKeywordResult = specialKeywordResult; val.defaultVerb = defaultVerb; val.accessTerminalObjects = accessTerminalObjects; return val; } } public enum StoreType { None, ShipUpgrade, Decor } public class Unlockables { public class RegisteredUnlockable { public UnlockableItem unlockable; public StoreType StoreType; public TerminalNode buyNode1; public TerminalNode buyNode2; public TerminalNode itemInfo; public int price; public string modName; public bool disabled = false; public RegisteredUnlockable(UnlockableItem unlockable, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { this.unlockable = unlockable; this.buyNode1 = buyNode1; this.buyNode2 = buyNode2; this.itemInfo = itemInfo; this.price = price; } } public struct BuyableUnlockableAssetInfo { public UnlockableItem itemAsset; public TerminalKeyword keyword; } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__StartOfRound_Awake; public static hook_Start <1>__Terminal_Start; public static hook_TextPostProcess <2>__Terminal_TextPostProcess; } public static List<RegisteredUnlockable> registeredUnlockables = new List<RegisteredUnlockable>(); public static List<BuyableUnlockableAssetInfo> buyableUnlockableAssetInfos = new List<BuyableUnlockableAssetInfo>(); public static void Init() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown object obj = <>O.<0>__StartOfRound_Awake; if (obj == null) { hook_Awake val = StartOfRound_Awake; <>O.<0>__StartOfRound_Awake = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__Terminal_Start; if (obj2 == null) { hook_Start val2 = Terminal_Start; <>O.<1>__Terminal_Start = val2; obj2 = (object)val2; } Terminal.Start += (hook_Start)obj2; object obj3 = <>O.<2>__Terminal_TextPostProcess; if (obj3 == null) { hook_TextPostProcess val3 = Terminal_TextPostProcess; <>O.<2>__Terminal_TextPostProcess = val3; obj3 = (object)val3; } Terminal.TextPostProcess += (hook_TextPostProcess)obj3; } private static string Terminal_TextPostProcess(orig_TextPostProcess orig, Terminal self, string modifiedDisplayText, TerminalNode node) { if (modifiedDisplayText.Contains("[buyableItemsList]") && modifiedDisplayText.Contains("[unlockablesSelectionList]")) { int num = modifiedDisplayText.IndexOf(":"); foreach (RegisteredUnlockable registeredUnlockable in registeredUnlockables) { if (registeredUnlockable.StoreType == StoreType.ShipUpgrade && !registeredUnlockable.disabled) { string unlockableName = registeredUnlockable.unlockable.unlockableName; int price = registeredUnlockable.price; string value = $"\n* {unlockableName} // Price: ${price}"; modifiedDisplayText = modifiedDisplayText.Insert(num + 1, value); } } } return orig.Invoke(self, modifiedDisplayText, node); } private static void Terminal_Start(orig_Start orig, Terminal self) { //IL_0390: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_03d3: Expected O, but got Unknown //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Expected O, but got Unknown //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04a3: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04bd: Expected O, but got Unknown //IL_0551: Unknown result type (might be due to invalid IL or missing references) //IL_0556: Unknown result type (might be due to invalid IL or missing references) //IL_0563: Unknown result type (might be due to invalid IL or missing references) //IL_0570: Expected O, but got Unknown TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; TerminalKeyword val2 = self.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); List<RegisteredUnlockable> list = registeredUnlockables.FindAll((RegisteredUnlockable unlockable) => unlockable.price != -1).ToList(); Plugin.logger.LogInfo((object)$"Adding {list.Count} items to terminal"); foreach (RegisteredUnlockable item in list) { string unlockableName = item.unlockable.unlockableName; TerminalKeyword keyword3 = TerminalUtils.CreateTerminalKeyword(unlockableName.ToLowerInvariant().Replace(" ", "-"), isVerb: false, null, null, val); if (self.terminalNodes.allKeywords.Any((TerminalKeyword kw) => kw.word == keyword3.word)) { Plugin.logger.LogInfo((object)("Keyword " + keyword3.word + " already registed, skipping.")); continue; } int shipUnlockableID = StartOfRound.Instance.unlockablesList.unlockables.FindIndex((UnlockableItem unlockable) => unlockable.unlockableName == item.unlockable.unlockableName); StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { Debug.Log((object)"STARTOFROUND INSTANCE NOT FOUND"); } if (item.price == -1 && (Object)(object)item.buyNode1 != (Object)null) { item.price = item.buyNode1.itemCost; } char c = unlockableName[unlockableName.Length - 1]; string text = unlockableName; TerminalNode val3 = item.buyNode2; if ((Object)(object)val3 == (Object)null) { val3 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val3).name = unlockableName.Replace(" ", "-") + "BuyNode2"; val3.displayText = "Ordered [variableAmount] " + text + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n"; val3.clearPreviousText = true; val3.maxCharactersToType = 15; } val3.buyItemIndex = -1; val3.shipUnlockableID = shipUnlockableID; val3.buyUnlockable = true; val3.creatureName = unlockableName; val3.isConfirmationNode = false; val3.itemCost = item.price; val3.playSyncedClip = 0; TerminalNode val4 = item.buyNode1; if ((Object)(object)val4 == (Object)null) { val4 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val4).name = unlockableName.Replace(" ", "-") + "BuyNode1"; val4.displayText = "You have requested to order " + text + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n"; val4.clearPreviousText = true; val4.maxCharactersToType = 35; } val4.buyItemIndex = -1; val4.shipUnlockableID = shipUnlockableID; val4.creatureName = unlockableName; val4.isConfirmationNode = true; val4.overrideOptions = true; val4.itemCost = item.price; val4.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "confirm"), result = val3 }, new CompatibleNoun { noun = self.terminalNodes.allKeywords.First((TerminalKeyword keyword2) => keyword2.word == "deny"), result = result } }; if (item.StoreType == StoreType.Decor) { item.unlockable.shopSelectionNode = val4; } else { item.unlockable.shopSelectionNode = null; } List<TerminalKeyword> list2 = self.terminalNodes.allKeywords.ToList(); list2.Add(keyword3); self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list3 = val.compatibleNouns.ToList(); list3.Add(new CompatibleNoun { noun = keyword3, result = val4 }); val.compatibleNouns = list3.ToArray(); TerminalNode val5 = item.itemInfo; if ((Object)(object)val5 == (Object)null) { val5 = ScriptableObject.CreateInstance<TerminalNode>(); ((Object)val5).name = unlockableName.Replace(" ", "-") + "InfoNode"; val5.displayText = "[No information about this object was found.]\n\n"; val5.clearPreviousText = true; val5.maxCharactersToType = 25; } self.terminalNodes.allKeywords = list2.ToArray(); List<CompatibleNoun> list4 = val2.compatibleNouns.ToList(); list4.Add(new CompatibleNoun { noun = keyword3, result = val5 }); val2.compatibleNouns = list4.ToArray(); BuyableUnlockableAssetInfo buyableUnlockableAssetInfo = default(BuyableUnlockableAssetInfo); buyableUnlockableAssetInfo.itemAsset = item.unlockable; buyableUnlockableAssetInfo.keyword = keyword3; BuyableUnlockableAssetInfo item2 = buyableUnlockableAssetInfo; buyableUnlockableAssetInfos.Add(item2); Plugin.logger.LogInfo((object)(item.modName + " registered item: " + item.unlockable.unlockableName)); } orig.Invoke(self); } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { orig.Invoke(self); Plugin.logger.LogInfo((object)$"Adding {registeredUnlockables.Count} unlockables to unlockables list"); foreach (RegisteredUnlockable unlockable in registeredUnlockables) { unlockable.disabled = false; if (self.unlockablesList.unlockables.Any((UnlockableItem x) => x.unlockableName == unlockable.unlockable.unlockableName)) { Plugin.logger.LogInfo((object)("Unlockable " + unlockable.unlockable.unlockableName + " already exists in unlockables list, skipping")); continue; } if ((Object)(object)unlockable.unlockable.prefabObject != (Object)null) { PlaceableShipObject componentInChildren = unlockable.unlockable.prefabObject.GetComponentInChildren<PlaceableShipObject>(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.unlockableID = self.unlockablesList.unlockables.Count; } } self.unlockablesList.unlockables.Add(unlockable.unlockable); } } public static void RegisterUnlockable(UnlockableItemDef unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable.unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItem unlockable, int price = -1, StoreType storeType = StoreType.None) { RegisterUnlockable(unlockable, storeType, null, null, null, price); } public static void RegisterUnlockable(UnlockableItemDef unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisterUnlockable(unlockable.unlockable, storeType, buyNode1, buyNode2, itemInfo, price); } public static void RegisterUnlockable(UnlockableItem unlockable, StoreType storeType = StoreType.None, TerminalNode buyNode1 = null, TerminalNode buyNode2 = null, TerminalNode itemInfo = null, int price = -1) { RegisteredUnlockable registeredUnlockable = new RegisteredUnlockable(unlockable, buyNode1, buyNode2, itemInfo, price); Assembly callingAssembly = Assembly.GetCallingAssembly(); string name = callingAssembly.GetName().Name; registeredUnlockable.modName = name; registeredUnlockable.StoreType = storeType; registeredUnlockables.Add(registeredUnlockable); } public static void DisableUnlockable(UnlockableItemDef unlockable) { DisableUnlockable(unlockable.unlockable); } public static void DisableUnlockable(UnlockableItem unlockable) { RegisteredUnlockable registeredUnlockable = registeredUnlockables.Find((RegisteredUnlockable unlock) => unlock.unlockable == unlockable); if (registeredUnlockable != null) { registeredUnlockable.disabled = true; if ((Object)(object)StartOfRound.Instance != (Object)null) { StartOfRound.Instance.unlockablesList.unlockables.Remove(registeredUnlockable.unlockable); } } } public static void UpdateUnlockablePrice(UnlockableItem shopItem, int price) { if (!((Object)(object)StartOfRound.Instance != (Object)null)) { return; } TerminalKeyword val = Items.terminal.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "buy"); TerminalNode result = val.compatibleNouns[0].result.terminalOptions[1].result; List<CompatibleNoun> source = val.compatibleNouns.ToList(); RegisteredUnlockable registeredUnlockable = registeredUnlockables.Find((RegisteredUnlockable unlock) => unlock.unlockable == shopItem); if (registeredUnlockable != null && registeredUnlockable.price != -1) { registeredUnlockable.price = price; } if (!buyableUnlockableAssetInfos.Any((BuyableUnlockableAssetInfo x) => x.itemAsset == shopItem)) { return; } BuyableUnlockableAssetInfo asset = buyableUnlockableAssetInfos.First((BuyableUnlockableAssetInfo x) => x.itemAsset == shopItem); if (!source.Any((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword)) { return; } CompatibleNoun val2 = source.First((CompatibleNoun noun) => (Object)(object)noun.noun == (Object)(object)asset.keyword); TerminalNode result2 = val2.result; result2.itemCost = price; if (result2.terminalOptions.Length == 0) { return; } CompatibleNoun[] terminalOptions = result2.terminalOptions; foreach (CompatibleNoun val3 in terminalOptions) { if ((Object)(object)val3.result != (Object)null && val3.result.buyItemIndex != -1) { val3.result.itemCost = price; } } } } public class Utilities { [CompilerGenerated] private static class <>O { public static hook_Start <0>__StartOfRound_Start; public static hook_Start <1>__MenuManager_Start; } public static List<GameObject> prefabsToFix = new List<GameObject>(); public static List<GameObject> fixedPrefabs = new List<GameObject>(); public static void Init() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown Plugin.logger.LogInfo((object)"Utilities.Init()"); object obj = <>O.<0>__StartOfRound_Start; if (obj == null) { hook_Start val = StartOfRound_Start; <>O.<0>__StartOfRound_Start = val; obj = (object)val; } StartOfRound.Start += (hook_Start)obj; object obj2 = <>O.<1>__MenuManager_Start; if (obj2 == null) { hook_Start val2 = MenuManager_Start; <>O.<1>__MenuManager_Start = val2; obj2 = (object)val2; } MenuManager.Start += (hook_Start)obj2; } private static void StartOfRound_Start(orig_Start orig, StartOfRound self) { AudioMixer diageticMixer = SoundManager.Instance.diageticMixer; Plugin.logger.LogInfo((object)("Diagetic mixer is " + ((Object)diageticMixer).name)); Plugin.logger.LogInfo((object)$"Found {prefabsToFix.Count} prefabs to fix"); List<GameObject> list = new List<GameObject>(); for (int num = prefabsToFix.Count - 1; num >= 0; num--) { GameObject val = prefabsToFix[num]; AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>(); AudioSource[] array = componentsInChildren; foreach (AudioSource val2 in array) { if (!((Object)(object)val2.outputAudioMixerGroup == (Object)null) && ((Object)val2.outputAudioMixerGroup.audioMixer).name == "Diagetic") { AudioMixerGroup val3 = diageticMixer.FindMatchingGroups(((Object)val2.outputAudioMixerGroup).name)[0]; if ((Object)(object)val3 != (Object)null) { val2.outputAudioMixerGroup = val3; Plugin.logger.LogInfo((object)("Set mixer group for " + ((Object)val2).name + " in " + ((Object)val).name + " to Diagetic:" + ((Object)val3).name)); list.Add(val); } } } } foreach (GameObject item in list) { prefabsToFix.Remove(item); } orig.Invoke(self); } private static void MenuManager_Start(orig_Start orig, MenuManager self) { orig.Invoke(self); if ((Object)(object)((Component)self).GetComponent<AudioSource>() == (Object)null) { return; } AudioMixer audioMixer = ((Component)self).GetComponent<AudioSource>().outputAudioMixerGroup.audioMixer; List<GameObject> list = new List<GameObject>(); for (int num = prefabsToFix.Count - 1; num >= 0; num--) { GameObject val = prefabsToFix[num]; AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>(); AudioSource[] array = componentsInChildren; foreach (AudioSource val2 in array) { if (!((Object)(object)val2.outputAudioMixerGroup == (Object)null) && ((Object)val2.outputAudioMixerGroup.audioMixer).name == "NonDiagetic") { AudioMixerGroup val3 = audioMixer.FindMatchingGroups(((Object)val2.outputAudioMixerGroup).name)[0]; if ((Object)(object)val3 != (Object)null) { val2.outputAudioMixerGroup = val3; Plugin.logger.LogInfo((object)("Set mixer group for " + ((Object)val2).name + " in " + ((Object)val).name + " to NonDiagetic:" + ((Object)val3).name)); list.Add(val); } } } } foreach (GameObject item in list) { prefabsToFix.Remove(item); } } public static void FixMixerGroups(GameObject prefab) { if (!fixedPrefabs.Contains(prefab)) { fixedPrefabs.Add(prefab); prefabsToFix.Add(prefab); } } } public class Weathers { public class CustomWeather { public string name; public int weatherVariable1; public int weatherVariable2; public WeatherEffect weatherEffect; public Levels.LevelTypes levels; public string[] spawnLevelOverrides; public CustomWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0) { this.name = name; this.weatherVariable1 = weatherVariable1; this.weatherVariable2 = weatherVariable2; this.weatherEffect = weatherEffect; this.levels = levels; this.spawnLevelOverrides = spawnLevelOverrides; } } [CompilerGenerated] private static class <>O { public static hook_Awake <0>__TimeOfDay_Awake; public static hook_Awake <1>__StartOfRound_Awake; } public static Dictionary<int, CustomWeather> customWeathers = new Dictionary<int, CustomWeather>(); public static int numCustomWeathers = 0; public static void Init() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown new Hook((MethodBase)typeof(Enum).GetMethod("ToString", new Type[0]), typeof(Weathers).GetMethod("ToStringHook")); object obj = <>O.<0>__TimeOfDay_Awake; if (obj == null) { hook_Awake val = TimeOfDay_Awake; <>O.<0>__TimeOfDay_Awake = val; obj = (object)val; } TimeOfDay.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__StartOfRound_Awake; if (obj2 == null) { hook_Awake val2 = StartOfRound_Awake; <>O.<1>__StartOfRound_Awake = val2; obj2 = (object)val2; } StartOfRound.Awake += (hook_Awake)obj2; } private static void StartOfRound_Awake(orig_Awake orig, StartOfRound self) { //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: 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_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers) { SelectableLevel[] levels = self.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = customWeather.Value.levels.HasFlag(Levels.LevelTypes.All) || (customWeather.Value.spawnLevelOverrides != null && customWeather.Value.spawnLevelOverrides.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant())); if (Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag) { Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); List<RandomWeatherWithVariables> list = val.randomWeathers.ToList(); if (flag || customWeather.Value.levels.HasFlag(levelTypes)) { list.Add(new RandomWeatherWithVariables { weatherType = (LevelWeatherType)customWeather.Key, weatherVariable = customWeather.Value.weatherVariable1, weatherVariable2 = customWeather.Value.weatherVariable2 }); Plugin.logger.LogInfo((object)$"Added weather {customWeather.Value.name} to level {((Object)val).name} at weather index: {customWeather.Key}"); } val.randomWeathers = list.ToArray(); } } } orig.Invoke(self); } private static void TimeOfDay_Awake(orig_Awake orig, TimeOfDay self) { List<WeatherEffect> list = self.effects.ToList(); int num = 0; foreach (KeyValuePair<int, CustomWeather> customWeather in customWeathers) { if (customWeather.Key > num) { num = customWeather.Key; } } while (list.Count <= num) { list.Add(null); } foreach (KeyValuePair<int, CustomWeather> customWeather2 in customWeathers) { list[customWeather2.Key] = customWeather2.Value.weatherEffect; } self.effects = list.ToArray(); orig.Invoke(self); } public static string ToStringHook(Func<Enum, string> orig, Enum self) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected I4, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected I4, but got Unknown if (self.GetType() == typeof(LevelWeatherType) && customWeathers.ContainsKey((int)(LevelWeatherType)(object)self)) { return customWeathers[(int)(LevelWeatherType)(object)self].name; } return orig(self); } public static void RegisterWeather(WeatherDef weather) { RegisterWeather(weather.weatherName, weather.weatherEffect, weather.levels, weather.levelOverrides, weather.weatherVariable1, weather.weatherVariable2); } public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, int weatherVariable1 = 0, int weatherVariable2 = 0) { Array values = Enum.GetValues(typeof(LevelWeatherType)); int num = values.Length - 1; num += numCustomWeathers; numCustomWeathers++; Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}"); customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, null, weatherVariable1, weatherVariable2)); } public static void RegisterWeather(string name, WeatherEffect weatherEffect, Levels.LevelTypes levels = Levels.LevelTypes.None, string[] spawnLevelOverrides = null, int weatherVariable1 = 0, int weatherVariable2 = 0) { Array values = Enum.GetValues(typeof(LevelWeatherType)); int num = values.Length - 1; num += numCustomWeathers; numCustomWeathers++; Plugin.logger.LogInfo((object)$"Registering weather {name} at index {num - 1}"); customWeathers.Add(num, new CustomWeather(name, weatherEffect, levels, spawnLevelOverrides, weatherVariable1, weatherVariable2)); } public static void RemoveWeather(string levelName, Levels.LevelTypes levelFlags = Levels.LevelTypes.None, string[] levelOverrides = null) { foreach (KeyValuePair<int, CustomWeather> entry in customWeathers) { if (!(entry.Value.name == levelName) || !((Object)(object)StartOfRound.Instance != (Object)null)) { continue; } SelectableLevel[] levels = StartOfRound.Instance.levels; foreach (SelectableLevel val in levels) { string name = ((Object)val).name; bool flag = levelFlags.HasFlag(Levels.LevelTypes.All) || (levelOverrides?.Any((string item) => item.ToLowerInvariant() == name.ToLowerInvariant()) ?? false); if (!(Enum.IsDefined(typeof(Levels.LevelTypes), name) || flag)) { continue; } Levels.LevelTypes levelTypes = (flag ? Levels.LevelTypes.All : ((Levels.LevelTypes)Enum.Parse(typeof(Levels.LevelTypes), name))); if (flag || levelFlags.HasFlag(levelTypes)) { List<RandomWeatherWithVariables> list = val.randomWeathers.ToList(); list.RemoveAll((RandomWeatherWithVariables item) => (int)item.weatherType == entry.Key); val.randomWeathers = list.ToArray(); } } } } } } namespace LethalLib.Extras { [CreateAssetMenu(menuName = "ScriptableObjects/DungeonDef")] public class DungeonDef : ScriptableObject { public DungeonFlow dungeonFlow; [Range(0f, 300f)] public int rarity; public AudioClip firstTimeDungeonAudio; } [CreateAssetMenu(menuName = "ScriptableObjects/DungeonGraphLine")] public class DungeonGraphLineDef : ScriptableObject { public GraphLine graphLine; } [CreateAssetMenu(menuName = "ScriptableObjects/GameObjectChance")] public class GameObjectChanceDef : ScriptableObject { public GameObjectChance gameObjectChance; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableMapObject")] public class SpawnableMapObjectDef : ScriptableObject { public SpawnableMapObject spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/SpawnableOutsideObject")] public class SpawnableOutsideObjectDef : ScriptableObject { public SpawnableOutsideObjectWithRarity spawnableMapObject; } [CreateAssetMenu(menuName = "ScriptableObjects/UnlockableItem")] public class UnlockableItemDef : ScriptableObject { public StoreType storeType = StoreType.None; public UnlockableItem unlockable; } [CreateAssetMenu(menuName = "ScriptableObjects/WeatherDef")] public class WeatherDef : ScriptableObject { public string weatherName; public Levels.LevelTypes levels = Levels.LevelTypes.None; public string[] levelOverrides; public int weatherVariable1; public int weatherVariable2; public WeatherEffect weatherEffect; } }
BepInEx/plugins/LethalSDK.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using DunGen; using DunGen.Adapters; using GameNetcodeStuff; using LethalSDK.Component; using LethalSDK.ScriptableObjects; using LethalSDK.Utils; using Unity.Netcode; using UnityEditor; using UnityEngine; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.SceneManagement; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("LethalSDK")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LethalSDK")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4d234a4d-c807-438a-b717-4c6d77706054")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] public class AssetModificationProcessor : AssetPostprocessor { private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (string assetPath in importedAssets) { ProcessAsset(assetPath); } foreach (string assetPath2 in movedAssets) { ProcessAsset(assetPath2); } } private static void ProcessAsset(string assetPath) { if (assetPath.Contains("NavMesh-Environment")) { AssetDatabase.RenameAsset(assetPath, (SelectionLogger.name != string.Empty) ? (SelectionLogger.name + "NavMesh") : "New NavMesh"); } if (assetPath.Contains("New Terrain")) { AssetDatabase.RenameAsset(assetPath, (SelectionLogger.name != string.Empty) ? SelectionLogger.name : "New Terrain"); } if (assetPath.ToLower().StartsWith("assets/mods/") && assetPath.Split(new char[1] { '/' }).Length > 3 && !assetPath.ToLower().EndsWith(".unity") && !assetPath.ToLower().Contains("/scenes")) { AssetImporter atPath = AssetImporter.GetAtPath(assetPath); if ((Object)(object)atPath != (Object)null) { string text2 = (atPath.assetBundleName = ExtractBundleNameFromPath(assetPath)); atPath.assetBundleVariant = "lem"; Debug.Log((object)(assetPath + " asset moved to " + text2 + " asset bundle.")); } if (assetPath != "Assets/Mods/" + assetPath.ToLower().Replace("assets/mods/", string.Empty).RemoveNonAlphanumeric(4)) { AssetDatabase.MoveAsset(assetPath, "Assets/Mods/" + assetPath.ToLower().Replace("assets/mods/", string.Empty).RemoveNonAlphanumeric(4)); } } else { AssetImporter atPath2 = AssetImporter.GetAtPath(assetPath); if ((Object)(object)atPath2 != (Object)null) { atPath2.assetBundleName = null; Debug.Log((object)(assetPath + " asset removed from asset bundle.")); } } } public static string ExtractBundleNameFromPath(string path) { string[] array = path.Split(new char[1] { '/' }); if (array.Length > 3) { return array[2].ToLower(); } return ""; } } [InitializeOnLoad] public class SelectionLogger { public static string name; static SelectionLogger() { Selection.selectionChanged = (Action)Delegate.Combine(Selection.selectionChanged, new Action(OnSelectionChanged)); } private static void OnSelectionChanged() { if ((Object)(object)Selection.activeGameObject != (Object)null) { name = ((Object)GetRootParent(Selection.activeGameObject)).name; } else { name = string.Empty; } } public static GameObject GetRootParent(GameObject obj) { if ((Object)(object)obj != (Object)null && (Object)(object)obj.transform.parent != (Object)null) { return GetRootParent(((Component)obj.transform.parent).gameObject); } return obj; } } [InitializeOnLoad] public class AssetBundleVariantAssigner { static AssetBundleVariantAssigner() { AssignVariantToAssetBundles(); } [InitializeOnLoadMethod] private static void AssignVariantToAssetBundles() { string[] allAssetBundleNames = AssetDatabase.GetAllAssetBundleNames(); string[] array = allAssetBundleNames; foreach (string text in array) { if (!text.Contains(".")) { string[] assetPathsFromAssetBundle = AssetDatabase.GetAssetPathsFromAssetBundle(text); string[] array2 = assetPathsFromAssetBundle; foreach (string text2 in array2) { AssetImporter.GetAtPath(text2).SetAssetBundleNameAndVariant(text, "lem"); } Debug.Log((object)("File extention added to AssetBundle: " + text)); } } AssetDatabase.SaveAssets(); string text3 = "Assets/AssetBundles"; if (!Directory.Exists(text3)) { Debug.LogError((object)("Le dossier n'existe pas : " + text3)); return; } string[] files = Directory.GetFiles(text3); string[] array3 = files; foreach (string text4 in array3) { if (Path.GetExtension(text4) == "" && Path.GetFileName(text4) != "AssetBundles") { string path = text4 + ".meta"; string text5 = text4 + ".manifest"; string path2 = text5 + ".meta"; File.Delete(text4); if (File.Exists(path)) { File.Delete(path); } if (File.Exists(text5)) { File.Delete(text5); } if (File.Exists(path2)) { File.Delete(path2); } Debug.Log((object)("Fichier supprimé : " + text4)); } } AssetDatabase.Refresh(); } } public class CubemapTextureBuilder : EditorWindow { private Texture2D[] textures = (Texture2D[])(object)new Texture2D[6]; private string[] labels = new string[6] { "Right", "Left", "Top", "Bottom", "Front", "Back" }; private TextureFormat[] HDRFormats; private Vector2Int[] placementRects; [MenuItem("LethalSDK/Cubemap Builder", false, 100)] public static void OpenWindow() { EditorWindow.GetWindow<CubemapTextureBuilder>(); } private Texture2D UpscaleTexture(Texture2D original, int targetWidth, int targetHeight) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) RenderTexture val = (RenderTexture.active = RenderTexture.GetTemporary(targetWidth, targetHeight)); Graphics.Blit((Texture)(object)original, val); Texture2D val2 = new Texture2D(targetWidth, targetHeight); val2.ReadPixels(new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), 0, 0); val2.Apply(); RenderTexture.ReleaseTemporary(val); return val2; } private void OnGUI() { //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Expected O, but got Unknown for (int i = 0; i < 6; i++) { ref Texture2D reference = ref textures[i]; Object obj = EditorGUILayout.ObjectField(labels[i], (Object)(object)textures[i], typeof(Texture2D), false, Array.Empty<GUILayoutOption>()); reference = (Texture2D)(object)((obj is Texture2D) ? obj : null); } if (!GUILayout.Button("Build Cubemap", Array.Empty<GUILayoutOption>())) { return; } if (textures.Any((Texture2D t) => (Object)(object)t == (Object)null)) { EditorUtility.DisplayDialog("Cubemap Builder Error", "One or more texture is missing.", "Ok"); return; } int size = ((Texture)textures[0]).width; if (textures.Any((Texture2D t) => ((Texture)t).width != size || ((Texture)t).height != size)) { EditorUtility.DisplayDialog("Cubemap Builder Error", "All the textures need to be the same size and square.", "Ok"); return; } bool flag = HDRFormats.Any((TextureFormat f) => f == textures[0].format); string[] array = textures.Select((Texture2D t) => AssetDatabase.GetAssetPath((Object)(object)t)).ToArray(); string text = EditorUtility.SaveFilePanel("Save Cubemap", Path.GetDirectoryName(array[0]), "Cubemap", flag ? "exr" : "png"); if (!string.IsNullOrEmpty(text)) { bool[] array2 = textures.Select((Texture2D t) => ((Texture)t).isReadable).ToArray(); TextureImporter[] array3 = array.Select(delegate(string p) { AssetImporter atPath2 = AssetImporter.GetAtPath(p); return (TextureImporter)(object)((atPath2 is TextureImporter) ? atPath2 : null); }).ToArray(); TextureImporter[] array4 = array3; foreach (TextureImporter val in array4) { val.isReadable = true; } AssetDatabase.Refresh(); string[] array5 = array; foreach (string text2 in array5) { AssetDatabase.ImportAsset(text2); } Texture2D val2 = new Texture2D(size * 4, size * 3, (TextureFormat)(flag ? 20 : 4), false); for (int l = 0; l < 6; l++) { val2.SetPixels(((Vector2Int)(ref placementRects[l])).x * size, ((Vector2Int)(ref placementRects[l])).y * size, size, size, textures[l].GetPixels(0)); } val2.Apply(false); byte[] bytes = (flag ? ImageConversion.EncodeToEXR(val2) : ImageConversion.EncodeToPNG(val2)); File.WriteAllBytes(text, bytes); Object.Destroy((Object)(object)val2); for (int m = 0; m < 6; m++) { array3[m].isReadable = array2[m]; } text = text.Remove(0, Application.dataPath.Length - 6); AssetDatabase.ImportAsset(text); AssetImporter atPath = AssetImporter.GetAtPath(text); TextureImporter val3 = (TextureImporter)(object)((atPath is TextureImporter) ? atPath : null); val3.textureShape = (TextureImporterShape)2; val3.sRGBTexture = false; val3.generateCubemap = (TextureImporterGenerateCubemap)5; string[] array6 = array; foreach (string text3 in array6) { AssetDatabase.ImportAsset(text3); } AssetDatabase.ImportAsset(text); AssetDatabase.Refresh(); } } public CubemapTextureBuilder() { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) TextureFormat[] array = new TextureFormat[9]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); HDRFormats = (TextureFormat[])(object)array; placementRects = (Vector2Int[])(object)new Vector2Int[6] { new Vector2Int(2, 1), new Vector2Int(0, 1), new Vector2Int(1, 2), new Vector2Int(1, 0), new Vector2Int(1, 1), new Vector2Int(3, 1) }; ((EditorWindow)this)..ctor(); } } public class PlayerShip : MonoBehaviour { public readonly Vector3 shipPosition = new Vector3(-17.5f, 5.75f, -16.55f); private void Start() { Object.Destroy((Object)(object)this); } } [CustomEditor(typeof(PlayerShip))] public class PlayerShipEditor : Editor { public override void OnInspectorGUI() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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) ((Editor)this).OnInspectorGUI(); PlayerShip playerShip = (PlayerShip)(object)((Editor)this).target; if (((Component)playerShip).transform.position != playerShip.shipPosition) { ((Component)playerShip).transform.position = playerShip.shipPosition; } } } namespace LethalSDK.ScriptableObjects { [CreateAssetMenu(fileName = "AssetBank", menuName = "LethalSDK/Asset Bank")] public class AssetBank : ScriptableObject { [Header("Audio Clips")] [SerializeField] private AudioClipInfoPair[] _audioClips = new AudioClipInfoPair[0]; [SerializeField] private PlanetPrefabInfoPair[] _planetPrefabs = new PlanetPrefabInfoPair[0]; [SerializeField] private PrefabInfoPair[] _networkPrefabs = new PrefabInfoPair[0]; [HideInInspector] public string serializedAudioClips; [HideInInspector] public string serializedPlanetPrefabs; [HideInInspector] public string serializedNetworkPrefabs; private void OnValidate() { for (int i = 0; i < _audioClips.Length; i++) { _audioClips[i].AudioClipName = _audioClips[i].AudioClipName.RemoveNonAlphanumeric(1); _audioClips[i].AudioClipPath = _audioClips[i].AudioClipPath.RemoveNonAlphanumeric(4); } for (int j = 0; j < _planetPrefabs.Length; j++) { _planetPrefabs[j].PlanetPrefabName = _planetPrefabs[j].PlanetPrefabName.RemoveNonAlphanumeric(1); _planetPrefabs[j].PlanetPrefabPath = _planetPrefabs[j].PlanetPrefabPath.RemoveNonAlphanumeric(4); } for (int k = 0; k < _networkPrefabs.Length; k++) { _networkPrefabs[k].PrefabName = _networkPrefabs[k].PrefabName.RemoveNonAlphanumeric(1); _networkPrefabs[k].PrefabPath = _networkPrefabs[k].PrefabPath.RemoveNonAlphanumeric(4); } serializedAudioClips = string.Join(";", _audioClips.Select((AudioClipInfoPair p) => ((p.AudioClipName.Length != 0) ? p.AudioClipName : (((Object)(object)p.AudioClip != (Object)null) ? ((Object)p.AudioClip).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.AudioClip))); serializedPlanetPrefabs = string.Join(";", _planetPrefabs.Select((PlanetPrefabInfoPair p) => ((p.PlanetPrefabName.Length != 0) ? p.PlanetPrefabName : (((Object)(object)p.PlanetPrefab != (Object)null) ? ((Object)p.PlanetPrefab).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.PlanetPrefab))); serializedNetworkPrefabs = string.Join(";", _networkPrefabs.Select((PrefabInfoPair p) => ((p.PrefabName.Length != 0) ? p.PrefabName : (((Object)(object)p.Prefab != (Object)null) ? ((Object)p.Prefab).name : "")) + "," + AssetDatabase.GetAssetPath((Object)(object)p.Prefab))); } public AudioClipInfoPair[] AudioClips() { if (serializedAudioClips != null) { return (from s in serializedAudioClips.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new AudioClipInfoPair(split[0], split[1])).ToArray(); } return new AudioClipInfoPair[0]; } public bool HaveAudioClip(string audioClipName) { if (serializedAudioClips != null) { return AudioClips().Any((AudioClipInfoPair a) => a.AudioClipName == audioClipName); } return false; } public string AudioClipPath(string audioClipName) { if (serializedAudioClips != null) { return AudioClips().First((AudioClipInfoPair c) => c.AudioClipName == audioClipName).AudioClipPath; } return string.Empty; } public Dictionary<string, string> AudioClipsDictionary() { if (serializedAudioClips != null) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); AudioClipInfoPair[] audioClips = _audioClips; for (int i = 0; i < audioClips.Length; i++) { AudioClipInfoPair audioClipInfoPair = audioClips[i]; dictionary.Add(audioClipInfoPair.AudioClipName, audioClipInfoPair.AudioClipPath); } return dictionary; } return new Dictionary<string, string>(); } public PlanetPrefabInfoPair[] PlanetPrefabs() { if (serializedPlanetPrefabs != null) { return (from s in serializedPlanetPrefabs.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new PlanetPrefabInfoPair(split[0], split[1])).ToArray(); } return new PlanetPrefabInfoPair[0]; } public bool HavePlanetPrefabs(string planetPrefabName) { if (serializedPlanetPrefabs != null) { return PlanetPrefabs().Any((PlanetPrefabInfoPair a) => a.PlanetPrefabName == planetPrefabName); } return false; } public string PlanetPrefabsPath(string planetPrefabName) { if (serializedPlanetPrefabs != null) { return PlanetPrefabs().First((PlanetPrefabInfoPair c) => c.PlanetPrefabName == planetPrefabName).PlanetPrefabPath; } return string.Empty; } public Dictionary<string, string> PlanetPrefabsDictionary() { if (serializedPlanetPrefabs != null) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); PlanetPrefabInfoPair[] planetPrefabs = _planetPrefabs; for (int i = 0; i < planetPrefabs.Length; i++) { PlanetPrefabInfoPair planetPrefabInfoPair = planetPrefabs[i]; dictionary.Add(planetPrefabInfoPair.PlanetPrefabName, planetPrefabInfoPair.PlanetPrefabPath); } return dictionary; } return new Dictionary<string, string>(); } public PrefabInfoPair[] NetworkPrefabs() { if (serializedNetworkPrefabs != null) { return (from s in serializedNetworkPrefabs.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new PrefabInfoPair(split[0], split[1])).ToArray(); } return new PrefabInfoPair[0]; } public bool HaveNetworkPrefabs(string networkPrefabName) { if (serializedNetworkPrefabs != null) { return NetworkPrefabs().Any((PrefabInfoPair a) => a.PrefabName == networkPrefabName); } return false; } public string NetworkPrefabsPath(string networkPrefabName) { if (serializedNetworkPrefabs != null) { return NetworkPrefabs().First((PrefabInfoPair c) => c.PrefabName == networkPrefabName).PrefabPath; } return string.Empty; } public Dictionary<string, string> NetworkPrefabsDictionary() { if (serializedNetworkPrefabs != null) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); PrefabInfoPair[] networkPrefabs = _networkPrefabs; for (int i = 0; i < networkPrefabs.Length; i++) { PrefabInfoPair prefabInfoPair = networkPrefabs[i]; dictionary.Add(prefabInfoPair.PrefabName, prefabInfoPair.PrefabPath); } return dictionary; } return new Dictionary<string, string>(); } } [CreateAssetMenu(fileName = "ModManifest", menuName = "LethalSDK/Mod Manifest")] public class ModManifest : ScriptableObject { public string modName = "New Mod"; [Space] [SerializeField] private SerializableVersion version = new SerializableVersion(0, 0, 0, 0); [HideInInspector] public string serializedVersion; [Space] public string author = "Author"; [Space] [TextArea(5, 15)] public string description = "Mod Description"; [Space] [Header("Content")] public Scrap[] scraps = new Scrap[0]; public Moon[] moons = new Moon[0]; [Space] public AssetBank assetBank; private void OnValidate() { serializedVersion = version.ToString(); } public SerializableVersion GetVersion() { int[] array = ((serializedVersion != null) ? serializedVersion.Split(new char[1] { '.' }).Select(int.Parse).ToArray() : new int[4]); return new SerializableVersion(array[0], array[1], array[2], array[3]); } } [CreateAssetMenu(fileName = "New Moon", menuName = "LethalSDK/Moon")] public class Moon : ScriptableObject { public string MoonName = "NewMoon"; public string[] RequiredBundles; public string[] IncompatibleBundles; public bool IsEnabled = true; public bool IsHidden = false; public bool IsLocked = false; [Header("Info")] public string OrbitPrefabName = "Moon1"; public bool SpawnEnemiesAndScrap = true; public string PlanetName = "New Moon"; public GameObject MainPrefab; [TextArea(5, 15)] public string PlanetDescription; public VideoClip PlanetVideo; public string RiskLevel = "X"; [Range(0f, 16f)] public float TimeToArrive = 1f; [Header("Time")] [Range(0.1f, 5f)] public float DaySpeedMultiplier = 1f; public bool PlanetHasTime = true; [SerializeField] private RandomWeatherPair[] _RandomWeatherTypes = new RandomWeatherPair[6] { new RandomWeatherPair(LevelWeatherType.None, 0, 0), new RandomWeatherPair(LevelWeatherType.Rainy, 0, 0), new RandomWeatherPair(LevelWeatherType.Stormy, 1, 0), new RandomWeatherPair(LevelWeatherType.Foggy, 1, 0), new RandomWeatherPair(LevelWeatherType.Flooded, -4, 5), new RandomWeatherPair(LevelWeatherType.Eclipsed, 1, 0) }; public bool OverwriteWeather = false; public LevelWeatherType OverwriteWeatherType = LevelWeatherType.None; [Header("Route")] public string RouteWord = "newmoon"; public int RoutePrice; public string BoughtComment = "Please enjoy your flight."; [Header("Dungeon")] [Range(1f, 5f)] public float FactorySizeMultiplier = 1f; public int FireExitsAmountOverwrite = 1; [SerializeField] private DungeonFlowPair[] _DungeonFlowTypes = new DungeonFlowPair[2] { new DungeonFlowPair(0, 300), new DungeonFlowPair(1, 1) }; [SerializeField] private SpawnableScrapPair[] _SpawnableScrap = new SpawnableScrapPair[19] { new SpawnableScrapPair("Cog1", 80), new SpawnableScrapPair("EnginePart1", 90), new SpawnableScrapPair("FishTestProp", 12), new SpawnableScrapPair("MetalSheet", 88), new SpawnableScrapPair("FlashLaserPointer", 4), new SpawnableScrapPair("BigBolt", 80), new SpawnableScrapPair("BottleBin", 19), new SpawnableScrapPair("Ring", 3), new SpawnableScrapPair("SteeringWheel", 32), new SpawnableScrapPair("MoldPan", 5), new SpawnableScrapPair("EggBeater", 10), new SpawnableScrapPair("PickleJar", 10), new SpawnableScrapPair("DustPan", 32), new SpawnableScrapPair("Airhorn", 3), new SpawnableScrapPair("ClownHorn", 3), new SpawnableScrapPair("CashRegister", 3), new SpawnableScrapPair("Candy", 2), new SpawnableScrapPair("GoldBar", 1), new SpawnableScrapPair("YieldSign", 6) }; [Range(0f, 100f)] public int MinScrap = 8; [Range(0f, 100f)] public int MaxScrap = 12; public string LevelAmbienceClips = "Level1TypeAmbience"; [Range(0f, 30f)] public int MaxEnemyPowerCount = 4; [SerializeField] private SpawnableEnemiesPair[] _Enemies = new SpawnableEnemiesPair[8] { new SpawnableEnemiesPair("Centipede", 51), new SpawnableEnemiesPair("SandSpider", 58), new SpawnableEnemiesPair("HoarderBug", 28), new SpawnableEnemiesPair("Flowerman", 13), new SpawnableEnemiesPair("Crawler", 16), new SpawnableEnemiesPair("Blob", 31), new SpawnableEnemiesPair("DressGirl", 1), new SpawnableEnemiesPair("Puffer", 28) }; public AnimationCurve EnemySpawnChanceThroughoutDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0015411376953125,\"value\":-3.0,\"inSlope\":19.556997299194337,\"outSlope\":19.556997299194337,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.12297855317592621},{\"serializedVersion\":\"3\",\"time\":0.4575331211090088,\"value\":4.796203136444092,\"inSlope\":24.479534149169923,\"outSlope\":24.479534149169923,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.396077424287796,\"outWeight\":0.35472238063812258},{\"serializedVersion\":\"3\",\"time\":0.7593884468078613,\"value\":4.973001480102539,\"inSlope\":2.6163148880004885,\"outSlope\":2.6163148880004885,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.2901076376438141,\"outWeight\":0.5360636115074158},{\"serializedVersion\":\"3\",\"time\":1.0,\"value\":15.0,\"inSlope\":35.604026794433597,\"outSlope\":35.604026794433597,\"tangentMode\":0,\"weightedMode\":1,\"inWeight\":0.04912583902478218,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}"); [Range(0f, 30f)] public float SpawnProbabilityRange = 4f; [Header("Outside")] [SerializeField] private SpawnableMapObjectPair[] _SpawnableMapObjects = new SpawnableMapObjectPair[2] { new SpawnableMapObjectPair("Landmine", spawnFacingAwayFromWall: false, CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":-0.003082275390625,\"value\":0.0,\"inSlope\":0.23179344832897187,\"outSlope\":0.23179344832897187,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27936428785324099},{\"serializedVersion\":\"3\",\"time\":0.8171924352645874,\"value\":1.7483322620391846,\"inSlope\":7.064207077026367,\"outSlope\":7.064207077026367,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.2631833553314209,\"outWeight\":0.6898177862167358},{\"serializedVersion\":\"3\",\"time\":1.0002186298370362,\"value\":11.760997772216797,\"inSlope\":968.80810546875,\"outSlope\":968.80810546875,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.029036391526460649,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")), new SpawnableMapObjectPair("TurretContainer", spawnFacingAwayFromWall: true, CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.354617178440094,\"outSlope\":0.354617178440094,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9190289974212647,\"value\":1.0005745887756348,\"inSlope\":Infinity,\"outSlope\":1.7338485717773438,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.6534967422485352},{\"serializedVersion\":\"3\",\"time\":1.0038425922393799,\"value\":7.198680877685547,\"inSlope\":529.4945068359375,\"outSlope\":529.4945068359375,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.14589552581310273,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")) }; [SerializeField] private SpawnableOutsideObjectPair[] _SpawnableOutsideObjects = new SpawnableOutsideObjectPair[7] { new SpawnableOutsideObjectPair("LargeRock1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.7571572661399841,\"value\":0.6448163986206055,\"inSlope\":2.974250078201294,\"outSlope\":2.974250078201294,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.3333333432674408},{\"serializedVersion\":\"3\",\"time\":0.9995536804199219,\"value\":5.883961200714111,\"inSlope\":65.30631256103516,\"outSlope\":65.30631256103516,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.12097536772489548,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")), new SpawnableOutsideObjectPair("LargeRock2", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.7562879920005798,\"value\":1.2308543920516968,\"inSlope\":5.111926555633545,\"outSlope\":5.111926555633545,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.21955738961696626},{\"serializedVersion\":\"3\",\"time\":1.0010795593261719,\"value\":7.59307336807251,\"inSlope\":92.0470199584961,\"outSlope\":92.0470199584961,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.05033162236213684,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")), new SpawnableOutsideObjectPair("LargeRock3", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9964686632156372,\"value\":2.0009398460388185,\"inSlope\":6.82940673828125,\"outSlope\":6.82940673828125,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.06891261041164398,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")), new SpawnableOutsideObjectPair("LargeRock4", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0},{\"serializedVersion\":\"3\",\"time\":0.9635604619979858,\"value\":2.153383493423462,\"inSlope\":6.251225471496582,\"outSlope\":6.251225471496582,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.07428120821714401,\"outWeight\":0.3333333432674408},{\"serializedVersion\":\"3\",\"time\":0.9995394349098206,\"value\":5.0,\"inSlope\":15.746581077575684,\"outSlope\":15.746581077575684,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.06317413598299027,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")), new SpawnableOutsideObjectPair("TreeLeafless1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.776531994342804,\"value\":6.162014007568359,\"inSlope\":30.075166702270509,\"outSlope\":30.075166702270509,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.15920747816562653,\"outWeight\":0.5323987007141113},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":38.093849182128909,\"inSlope\":1448.839111328125,\"outSlope\":1448.839111328125,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0620061457157135,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")), new SpawnableOutsideObjectPair("SmallGreyRocks1", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.802714467048645,\"value\":1.5478605031967164,\"inSlope\":9.096116065979004,\"outSlope\":9.096116065979004,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.15920747816562653,\"outWeight\":0.58766108751297},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":14.584033966064454,\"inSlope\":1244.9173583984375,\"outSlope\":1244.9173583984375,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.054620321840047839,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")), new SpawnableOutsideObjectPair("GiantPumpkin", CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":0.0,\"inSlope\":1.6912956237792969,\"outSlope\":1.6912956237792969,\"tangentMode\":0,\"weightedMode\":2,\"inWeight\":0.0,\"outWeight\":0.27726083993911745},{\"serializedVersion\":\"3\",\"time\":0.8832725882530212,\"value\":0.5284063816070557,\"inSlope\":3.2962090969085695,\"outSlope\":29.38977813720703,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.19772815704345704,\"outWeight\":0.8989489078521729},{\"serializedVersion\":\"3\",\"time\":0.972209095954895,\"value\":6.7684478759765629,\"inSlope\":140.27394104003907,\"outSlope\":140.27394104003907,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.39466607570648196,\"outWeight\":0.47049039602279665},{\"serializedVersion\":\"3\",\"time\":1.0002281665802003,\"value\":23.0,\"inSlope\":579.3037109375,\"outSlope\":14.8782377243042,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.648808479309082,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}")) }; [Range(0f, 30f)] public int MaxOutsideEnemyPowerCount = 8; [Range(0f, 30f)] public int MaxDaytimeEnemyPowerCount = 5; [SerializeField] private SpawnableEnemiesPair[] _OutsideEnemies = new SpawnableEnemiesPair[3] { new SpawnableEnemiesPair("MouthDog", 75), new SpawnableEnemiesPair("ForestGiant", 0), new SpawnableEnemiesPair("SandWorm", 56) }; [SerializeField] private SpawnableEnemiesPair[] _DaytimeEnemies = new SpawnableEnemiesPair[3] { new SpawnableEnemiesPair("RedLocustBees", 22), new SpawnableEnemiesPair("Doublewing", 74), new SpawnableEnemiesPair("DocileLocustBees", 52) }; public AnimationCurve OutsideEnemySpawnChanceThroughDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":-7.736962288618088e-7,\"value\":-2.996999979019165,\"inSlope\":Infinity,\"outSlope\":0.5040292143821716,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.0,\"outWeight\":0.08937685936689377},{\"serializedVersion\":\"3\",\"time\":0.7105481624603272,\"value\":-0.6555822491645813,\"inSlope\":9.172262191772461,\"outSlope\":9.172262191772461,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.3333333432674408,\"outWeight\":0.7196550369262695},{\"serializedVersion\":\"3\",\"time\":1.0052626132965088,\"value\":5.359400749206543,\"inSlope\":216.42247009277345,\"outSlope\":11.374387741088868,\"tangentMode\":0,\"weightedMode\":3,\"inWeight\":0.044637180864810947,\"outWeight\":0.48315444588661196}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}"); public AnimationCurve DaytimeEnemySpawnChanceThroughDay = CurveContainer.DeserializeCurve("{\"curve\":{\"serializedVersion\":\"2\",\"m_Curve\":[{\"serializedVersion\":\"3\",\"time\":0.0,\"value\":2.2706568241119386,\"inSlope\":-7.500085353851318,\"outSlope\":-7.500085353851318,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.3333333432674408,\"outWeight\":0.20650266110897065},{\"serializedVersion\":\"3\",\"time\":0.38507816195487978,\"value\":-0.0064108967781066898,\"inSlope\":-2.7670974731445314,\"outSlope\":-2.7670974731445314,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.28388944268226626,\"outWeight\":0.30659767985343935},{\"serializedVersion\":\"3\",\"time\":0.6767024993896484,\"value\":-7.021658420562744,\"inSlope\":-27.286888122558595,\"outSlope\":-27.286888122558595,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.10391546785831452,\"outWeight\":0.12503522634506226},{\"serializedVersion\":\"3\",\"time\":0.9998173117637634,\"value\":-14.818100929260254,\"inSlope\":0.0,\"outSlope\":0.0,\"tangentMode\":0,\"weightedMode\":0,\"inWeight\":0.0,\"outWeight\":0.0}],\"m_PreInfinity\":2,\"m_PostInfinity\":2,\"m_RotationOrder\":4}}"); [Range(0f, 30f)] public float DaytimeEnemiesProbabilityRange = 5f; public bool LevelIncludesSnowFootprints = false; [HideInInspector] public string serializedRandomWeatherTypes; [HideInInspector] public string serializedDungeonFlowTypes; [HideInInspector] public string serializedSpawnableScrap; [HideInInspector] public string serializedEnemies; [HideInInspector] public string serializedOutsideEnemies; [HideInInspector] public string serializedDaytimeEnemies; [HideInInspector] public string serializedSpawnableMapObjects; [HideInInspector] public string serializedSpawnableOutsideObjects; private void OnValidate() { RequiredBundles = RequiredBundles.RemoveNonAlphanumeric(1); IncompatibleBundles = IncompatibleBundles.RemoveNonAlphanumeric(1); MoonName = MoonName.RemoveNonAlphanumeric(1); OrbitPrefabName = OrbitPrefabName.RemoveNonAlphanumeric(1); RiskLevel = RiskLevel.RemoveNonAlphanumeric(); RouteWord = RouteWord.RemoveNonAlphanumeric(2); BoughtComment = BoughtComment.RemoveNonAlphanumeric(); LevelAmbienceClips = LevelAmbienceClips.RemoveNonAlphanumeric(1); TimeToArrive = Mathf.Clamp(TimeToArrive, 0f, 16f); DaySpeedMultiplier = Mathf.Clamp(DaySpeedMultiplier, 0.1f, 5f); RoutePrice = Mathf.Clamp(RoutePrice, 0, int.MaxValue); FactorySizeMultiplier = Mathf.Clamp(FactorySizeMultiplier, 1f, 5f); FireExitsAmountOverwrite = Mathf.Clamp(FireExitsAmountOverwrite, 0, 20); MinScrap = Mathf.Clamp(MinScrap, 0, MaxScrap); MaxScrap = Mathf.Clamp(MaxScrap, MinScrap, 100); MaxEnemyPowerCount = Mathf.Clamp(MaxEnemyPowerCount, 0, 30); MaxOutsideEnemyPowerCount = Mathf.Clamp(MaxOutsideEnemyPowerCount, 0, 30); MaxDaytimeEnemyPowerCount = Mathf.Clamp(MaxDaytimeEnemyPowerCount, 0, 30); SpawnProbabilityRange = Mathf.Clamp(SpawnProbabilityRange, 0f, 30f); DaytimeEnemiesProbabilityRange = Mathf.Clamp(DaytimeEnemiesProbabilityRange, 0f, 30f); for (int i = 0; i < _SpawnableScrap.Length; i++) { _SpawnableScrap[i].ObjectName = _SpawnableScrap[i].ObjectName.RemoveNonAlphanumeric(1); } for (int j = 0; j < _Enemies.Length; j++) { _Enemies[j].EnemyName = _Enemies[j].EnemyName.RemoveNonAlphanumeric(1); } for (int k = 0; k < _SpawnableMapObjects.Length; k++) { _SpawnableMapObjects[k].ObjectName = _SpawnableMapObjects[k].ObjectName.RemoveNonAlphanumeric(1); } for (int l = 0; l < _SpawnableOutsideObjects.Length; l++) { _SpawnableOutsideObjects[l].ObjectName = _SpawnableOutsideObjects[l].ObjectName.RemoveNonAlphanumeric(1); } for (int m = 0; m < _OutsideEnemies.Length; m++) { _OutsideEnemies[m].EnemyName = _OutsideEnemies[m].EnemyName.RemoveNonAlphanumeric(1); } for (int n = 0; n < _DaytimeEnemies.Length; n++) { _DaytimeEnemies[n].EnemyName = _DaytimeEnemies[n].EnemyName.RemoveNonAlphanumeric(1); } serializedRandomWeatherTypes = string.Join(";", _RandomWeatherTypes.Select((RandomWeatherPair p) => $"{(int)p.Weather},{p.WeatherVariable1},{p.WeatherVariable2}")); serializedDungeonFlowTypes = string.Join(";", _DungeonFlowTypes.Select((DungeonFlowPair p) => $"{p.ID},{p.Rarity}")); serializedSpawnableScrap = string.Join(";", _SpawnableScrap.Select((SpawnableScrapPair p) => $"{p.ObjectName},{p.SpawnWeight}")); serializedEnemies = string.Join(";", _Enemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}")); serializedOutsideEnemies = string.Join(";", _OutsideEnemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}")); serializedDaytimeEnemies = string.Join(";", _DaytimeEnemies.Select((SpawnableEnemiesPair p) => $"{p.EnemyName},{p.SpawnWeight}")); serializedSpawnableMapObjects = string.Join(";", _SpawnableMapObjects.Select((SpawnableMapObjectPair p) => $"{p.ObjectName}|{p.SpawnFacingAwayFromWall}|{CurveContainer.SerializeCurve(p.SpawnRate)}")); serializedSpawnableOutsideObjects = string.Join(";", _SpawnableOutsideObjects.Select((SpawnableOutsideObjectPair p) => p.ObjectName + "|" + CurveContainer.SerializeCurve(p.SpawnRate))); } public RandomWeatherPair[] RandomWeatherTypes() { return (from s in serializedRandomWeatherTypes.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 3 select new RandomWeatherPair((LevelWeatherType)int.Parse(split[0]), int.Parse(split[1]), int.Parse(split[2]))).ToArray(); } public DungeonFlowPair[] DungeonFlowTypes() { return (from s in serializedDungeonFlowTypes.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new DungeonFlowPair(int.Parse(split[0]), int.Parse(split[1]))).ToArray(); } public SpawnableScrapPair[] SpawnableScrap() { return (from s in serializedSpawnableScrap.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new SpawnableScrapPair(split[0], int.Parse(split[1]))).ToArray(); } public SpawnableEnemiesPair[] Enemies() { return (from s in serializedEnemies.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray(); } public SpawnableEnemiesPair[] OutsideEnemies() { return (from s in serializedOutsideEnemies.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray(); } public SpawnableEnemiesPair[] DaytimeEnemies() { return (from s in serializedDaytimeEnemies.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new SpawnableEnemiesPair(split[0], int.Parse(split[1]))).ToArray(); } public SpawnableMapObjectPair[] SpawnableMapObjects() { return (from s in serializedSpawnableMapObjects.Split(new char[1] { ';' }) select s.Split(new char[1] { '|' }) into split where split.Length == 3 select new SpawnableMapObjectPair(split[0], bool.Parse(split[1]), CurveContainer.DeserializeCurve(split[2]))).ToArray(); } public SpawnableOutsideObjectPair[] SpawnableOutsideObjects() { return (from s in serializedSpawnableOutsideObjects.Split(new char[1] { ';' }) select s.Split(new char[1] { '|' }) into split where split.Length == 2 select new SpawnableOutsideObjectPair(split[0], CurveContainer.DeserializeCurve(split[1]))).ToArray(); } } [CreateAssetMenu(fileName = "New Scrap", menuName = "LethalSDK/Scrap")] public class Scrap : ScriptableObject { public string[] RequiredBundles; public string[] IncompatibleBundles; [Header("Base")] public string itemName = string.Empty; public int minValue = 0; public int maxValue = 0; public bool twoHanded = false; public bool twoHandedAnimation = false; public bool requiresBattery = false; public bool isConductiveMetal = false; public int weight = 0; public GameObject prefab; [Header("Sounds")] public string grabSFX = string.Empty; public string dropSFX = string.Empty; [Header("Offsets")] public float verticalOffset = 0f; public Vector3 restingRotation = Vector3.zero; public Vector3 positionOffset = Vector3.zero; public Vector3 rotationOffset = Vector3.zero; [Header("Variants")] public Mesh[] meshVariants = (Mesh[])(object)new Mesh[0]; public Material[] materialVariants = (Material[])(object)new Material[0]; [Header("Spawn rate")] public bool useGlobalSpawnWeight = true; [Range(0f, 100f)] public int globalSpawnWeight = 10; [SerializeField] private ScrapSpawnChancePerScene[] _perPlanetSpawnWeight = new ScrapSpawnChancePerScene[8] { new ScrapSpawnChancePerScene("41 Experimentation", 10), new ScrapSpawnChancePerScene("220 Assurance", 10), new ScrapSpawnChancePerScene("56 Vow", 10), new ScrapSpawnChancePerScene("21 Offense", 10), new ScrapSpawnChancePerScene("61 March", 10), new ScrapSpawnChancePerScene("85 Rend", 10), new ScrapSpawnChancePerScene("7 Dine", 10), new ScrapSpawnChancePerScene("8 Titan", 10) }; [HideInInspector] public string serializedData; private void OnValidate() { RequiredBundles = RequiredBundles.RemoveNonAlphanumeric(1); IncompatibleBundles = IncompatibleBundles.RemoveNonAlphanumeric(1); itemName = itemName.RemoveNonAlphanumeric(1); grabSFX = grabSFX.RemoveNonAlphanumeric(1); dropSFX = dropSFX.RemoveNonAlphanumeric(1); for (int i = 0; i < _perPlanetSpawnWeight.Length; i++) { _perPlanetSpawnWeight[i].SceneName = _perPlanetSpawnWeight[i].SceneName.RemoveNonAlphanumeric(1); } serializedData = string.Join(";", _perPlanetSpawnWeight.Select((ScrapSpawnChancePerScene p) => $"{p.SceneName},{p.SpawnWeight}")); } public ScrapSpawnChancePerScene[] perPlanetSpawnWeight() { return (from s in serializedData.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new ScrapSpawnChancePerScene(split[0], int.Parse(split[1]))).ToArray(); } } } namespace LethalSDK.Utils { public static class AssetGatherDialog { public static Dictionary<string, AudioClip> audioClips = new Dictionary<string, AudioClip>(); public static Dictionary<string, (AudioMixer, AudioMixerGroup[])> audioMixers = new Dictionary<string, (AudioMixer, AudioMixerGroup[])>(); public static Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>(); } [Serializable] public class SerializableVersion { public int Major = 1; public int Minor = 0; public int Build = 0; public int Revision = 0; public SerializableVersion(int major, int minor, int build, int revision) { Major = major; Minor = minor; Build = build; Revision = revision; } public Version ToVersion() { return new Version(Major, Minor, Build, Revision); } public override string ToString() { return $"{Major}.{Minor}.{Build}.{Revision}"; } } [Serializable] public class CurveContainer { public AnimationCurve curve; public static string SerializeCurve(AnimationCurve curve) { CurveContainer curveContainer = new CurveContainer { curve = curve }; return JsonUtility.ToJson((object)curveContainer); } public static AnimationCurve DeserializeCurve(string json) { CurveContainer curveContainer = JsonUtility.FromJson<CurveContainer>(json); return curveContainer.curve; } } [Serializable] public struct StringIntPair { public string _string; public int _int; public StringIntPair(string _string, int _int) { this._string = _string.RemoveNonAlphanumeric(1); this._int = Mathf.Clamp(_int, 0, 100); } } [Serializable] public struct StringStringPair { public string _string1; public string _string2; public StringStringPair(string _string1, string _string2) { this._string1 = _string1.RemoveNonAlphanumeric(1); this._string2 = _string2.RemoveNonAlphanumeric(1); } } [Serializable] public struct IntIntPair { public int _int1; public int _int2; public IntIntPair(int _int1, int _int2) { this._int1 = _int1; this._int2 = _int2; } } [Serializable] public struct DungeonFlowPair { public int ID; [Range(0f, 300f)] public int Rarity; public DungeonFlowPair(int id, int rarity) { ID = id; Rarity = Mathf.Clamp(rarity, 0, 300); } } [Serializable] public struct SpawnableScrapPair { public string ObjectName; [Range(0f, 100f)] public int SpawnWeight; public SpawnableScrapPair(string objectName, int spawnWeight) { ObjectName = objectName.RemoveNonAlphanumeric(1); SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100); } } [Serializable] public struct SpawnableMapObjectPair { public string ObjectName; public bool SpawnFacingAwayFromWall; public AnimationCurve SpawnRate; public SpawnableMapObjectPair(string objectName, bool spawnFacingAwayFromWall, AnimationCurve spawnRate) { ObjectName = objectName.RemoveNonAlphanumeric(1); SpawnFacingAwayFromWall = spawnFacingAwayFromWall; SpawnRate = spawnRate; } } [Serializable] public struct SpawnableOutsideObjectPair { public string ObjectName; public AnimationCurve SpawnRate; public SpawnableOutsideObjectPair(string objectName, AnimationCurve spawnRate) { ObjectName = objectName.RemoveNonAlphanumeric(1); SpawnRate = spawnRate; } } [Serializable] public struct SpawnableEnemiesPair { public string EnemyName; [Range(0f, 100f)] public int SpawnWeight; public SpawnableEnemiesPair(string enemyName, int spawnWeight) { EnemyName = enemyName.RemoveNonAlphanumeric(1); SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100); } } [Serializable] public struct ScrapSpawnChancePerScene { public string SceneName; [Range(0f, 100f)] public int SpawnWeight; public ScrapSpawnChancePerScene(string sceneName, int spawnWeight) { SceneName = sceneName.RemoveNonAlphanumeric(1); SpawnWeight = Mathf.Clamp(spawnWeight, 0, 100); } } [Serializable] public struct ScrapInfoPair { public string ScrapPath; public Scrap Scrap; public ScrapInfoPair(string scrapPath, Scrap scrap) { ScrapPath = scrapPath.RemoveNonAlphanumeric(4); Scrap = scrap; } } [Serializable] public struct AudioClipInfoPair { public string AudioClipName; [HideInInspector] public string AudioClipPath; [SerializeField] public AudioClip AudioClip; public AudioClipInfoPair(string audioClipName, string audioClipPath) { AudioClipName = audioClipName.RemoveNonAlphanumeric(1); AudioClipPath = audioClipPath.RemoveNonAlphanumeric(4); AudioClip = null; } } [Serializable] public struct PlanetPrefabInfoPair { public string PlanetPrefabName; [HideInInspector] public string PlanetPrefabPath; [SerializeField] public GameObject PlanetPrefab; public PlanetPrefabInfoPair(string planetPrefabName, string planetPrefabPath) { PlanetPrefabName = planetPrefabName.RemoveNonAlphanumeric(1); PlanetPrefabPath = planetPrefabPath.RemoveNonAlphanumeric(4); PlanetPrefab = null; } } [Serializable] public struct PrefabInfoPair { public string PrefabName; [HideInInspector] public string PrefabPath; [SerializeField] public GameObject Prefab; public PrefabInfoPair(string prefabName, string prefabPath) { PrefabName = prefabName.RemoveNonAlphanumeric(1); PrefabPath = prefabPath.RemoveNonAlphanumeric(4); Prefab = null; } } [Serializable] public struct RandomWeatherPair { public LevelWeatherType Weather; [Tooltip("Thunder Frequency, Flooding speed or minimum initial enemies in eclipses")] public int WeatherVariable1; [Tooltip("Flooding offset when Weather is Flooded")] public int WeatherVariable2; public RandomWeatherPair(LevelWeatherType weather, int weatherVariable1, int weatherVariable2) { Weather = weather; WeatherVariable1 = weatherVariable1; WeatherVariable2 = weatherVariable2; } } public enum LevelWeatherType { None = -1, DustClouds, Rainy, Stormy, Foggy, Flooded, Eclipsed } public class SpawnPrefab { private static SpawnPrefab _instance; public GameObject waterSurface; public static SpawnPrefab Instance { get { if (_instance == null) { _instance = new SpawnPrefab(); } return _instance; } } } public static class TypeExtensions { public enum removeType { Normal, Serializable, Keyword, Path, SerializablePath } public static readonly Dictionary<removeType, string> regexes = new Dictionary<removeType, string> { { removeType.Normal, "[^a-zA-Z0-9 ,.!?_-]" }, { removeType.Serializable, "[^a-zA-Z0-9 .!_-]" }, { removeType.Keyword, "[^a-zA-Z0-9._-]" }, { removeType.Path, "[^a-zA-Z0-9 ,.!_/-]" }, { removeType.SerializablePath, "[^a-zA-Z0-9 .!_/-]" } }; public static string RemoveNonAlphanumeric(this string input) { if (input != null) { return Regex.Replace(input, regexes[removeType.Normal], string.Empty); } return string.Empty; } public static string[] RemoveNonAlphanumeric(this string[] input) { if (input != null) { for (int i = 0; i < input.Length; i++) { input[i] = Regex.Replace(input[i], regexes[removeType.Normal], string.Empty); } return input; } return new string[0]; } public static string RemoveNonAlphanumeric(this string input, removeType removeType = removeType.Normal) { if (input != null) { return Regex.Replace(input, regexes[removeType], string.Empty); } return string.Empty; } public static string[] RemoveNonAlphanumeric(this string[] input, removeType removeType = removeType.Normal) { if (input != null) { for (int i = 0; i < input.Length; i++) { input[i] = Regex.Replace(input[i], regexes[removeType], string.Empty); } return input; } return new string[0]; } public static string RemoveNonAlphanumeric(this string input, int removeType = 0) { if (input != null) { return Regex.Replace(input, regexes[(removeType)removeType], string.Empty); } return string.Empty; } public static string[] RemoveNonAlphanumeric(this string[] input, int removeType = 0) { if (input != null) { for (int i = 0; i < input.Length; i++) { input[i] = Regex.Replace(input[i], regexes[(removeType)removeType], string.Empty); } return input; } return new string[0]; } } } namespace LethalSDK.Editor { internal class CopyrightsWindow : EditorWindow { private Vector2 scrollPosition; private readonly Dictionary<string, string> assetAuthorList = new Dictionary<string, string> { { "Drop Ship assets, Sun cycle animations, ScrapItem sprite, ScavengerSuit Textures/Arms Mesh and MonitorWall mesh", "Zeekerss" }, { "SDK Scripts, Sun Texture, CrossButton Sprite (Inspired of vanilla), OldSeaPort planet prefab texture", "HolographicWings" }, { "Old Sea Port asset package", "VIVID Arts" }, { "Survival Game Tools asset package", "cookiepopworks.com" } }; [MenuItem("LethalSDK/Copyrights", false, 999)] public static void ShowWindow() { EditorWindow.GetWindow<CopyrightsWindow>("Copyrights"); } private void OnGUI() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("List of Copyrights", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>()); scrollPosition = GUILayout.BeginScrollView(scrollPosition, Array.Empty<GUILayoutOption>()); EditorGUILayout.Space(5f); foreach (KeyValuePair<string, string> assetAuthor in assetAuthorList) { GUILayout.Label("Asset: " + assetAuthor.Key + " - By: " + assetAuthor.Value, EditorStyles.wordWrappedLabel, Array.Empty<GUILayoutOption>()); EditorGUILayout.Space(2f); } EditorGUILayout.Space(5f); GUILayout.Label("This SDK do not embed any Vanilla script.", Array.Empty<GUILayoutOption>()); GUILayout.EndScrollView(); } } public class EditorChecker : Editor { public override void OnInspectorGUI() { ((Editor)this).DrawDefaultInspector(); } } [CustomEditor(typeof(ModManifest))] public class ModManifestEditor : EditorChecker { public override void OnInspectorGUI() { ModManifest modManifest = (ModManifest)(object)((Editor)this).target; if (modManifest.serializedVersion == "0.0.0.0") { EditorGUILayout.HelpBox("Please define a version to your mod and don't forget to increment it at each update.", (MessageType)2); } if (modManifest.modName == null || modManifest.modName.Length == 0) { EditorGUILayout.HelpBox("Your mod need a name.", (MessageType)3); } IEnumerable<string> enumerable = from e in modManifest.scraps.Where((Scrap e) => (Object)(object)e != (Object)null).ToList() group e by e.itemName into g where g.Count() > 1 select g.Key; if (enumerable.Any()) { string text = string.Empty; foreach (string item in enumerable) { text = text + item + ","; } text = text.Remove(text.Length - 1); EditorGUILayout.HelpBox("You are trying to register two times or more the same Scraps. Duplicated Scraps are: " + text, (MessageType)2); } IEnumerable<string> enumerable2 = from e in modManifest.moons.Where((Moon e) => (Object)(object)e != (Object)null).ToList() group e by e.MoonName into g where g.Count() > 1 select g.Key; if (enumerable2.Any()) { string text2 = string.Empty; foreach (string item2 in enumerable2) { text2 = text2 + item2 + ","; } text2 = text2.Remove(text2.Length - 1); EditorGUILayout.HelpBox("You are trying to register two times or more the same Moons. Duplicated Moons are: " + text2, (MessageType)2); } string text3 = string.Empty; Scrap[] scraps = modManifest.scraps; foreach (Scrap scrap in scraps) { if ((Object)(object)scrap != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest))) { text3 = text3 + ((Object)scrap).name + ","; } } Moon[] moons = modManifest.moons; foreach (Moon moon in moons) { if ((Object)(object)moon != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest))) { text3 = text3 + ((Object)moon).name + ","; } } if (text3 != null && text3.Length > 0) { text3 = text3.Remove(text3.Length - 1); EditorGUILayout.HelpBox("You try to register a Scrap or a Moon from another mod folder. " + text3, (MessageType)2); } if ((Object)(object)modManifest.assetBank != (Object)null && AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest.assetBank)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)modManifest))) { EditorGUILayout.HelpBox("You try to register an AssetBank from another mod folder.", (MessageType)2); } base.OnInspectorGUI(); } } [CustomEditor(typeof(AssetBank))] public class AssetBankEditor : EditorChecker { public override void OnInspectorGUI() { AssetBank assetBank = (AssetBank)(object)((Editor)this).target; IEnumerable<string> enumerable = from e in (from e in assetBank.AudioClips() where e.AudioClipName != null && e.AudioClipName.Length > 0 select e).ToList() group e by e.AudioClipName into g where g.Count() > 1 select g.Key; if (enumerable.Any()) { string text = string.Empty; foreach (string item in enumerable) { text = text + item + ","; } text = text.Remove(text.Length - 1); EditorGUILayout.HelpBox("You are trying to register two times or more the same Audio Clip. Duplicated Clips are: " + text, (MessageType)2); } IEnumerable<string> enumerable2 = from e in (from e in assetBank.PlanetPrefabs() where e.PlanetPrefabName != null && e.PlanetPrefabName.Length > 0 select e).ToList() group e by e.PlanetPrefabName into g where g.Count() > 1 select g.Key; if (enumerable2.Any()) { string text2 = string.Empty; foreach (string item2 in enumerable2) { text2 = text2 + item2 + ","; } text2 = text2.Remove(text2.Length - 1); EditorGUILayout.HelpBox("You are trying to register two times or more the same Planet Prefabs. Duplicated Planet Prefabs are: " + text2, (MessageType)2); } string text3 = string.Empty; AudioClipInfoPair[] array = assetBank.AudioClips(); for (int i = 0; i < array.Length; i++) { AudioClipInfoPair audioClipInfoPair = array[i]; if (audioClipInfoPair.AudioClipName != null && audioClipInfoPair.AudioClipName.Length > 0 && AssetModificationProcessor.ExtractBundleNameFromPath(audioClipInfoPair.AudioClipPath) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)assetBank))) { text3 = text3 + audioClipInfoPair.AudioClipName + ","; } } PlanetPrefabInfoPair[] array2 = assetBank.PlanetPrefabs(); for (int j = 0; j < array2.Length; j++) { PlanetPrefabInfoPair planetPrefabInfoPair = array2[j]; if (planetPrefabInfoPair.PlanetPrefabName != null && planetPrefabInfoPair.PlanetPrefabName.Length > 0 && AssetModificationProcessor.ExtractBundleNameFromPath(planetPrefabInfoPair.PlanetPrefabPath) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)assetBank))) { text3 = text3 + planetPrefabInfoPair.PlanetPrefabName + ","; } } if (text3 != null && text3.Length > 0) { text3 = text3.Remove(text3.Length - 1); EditorGUILayout.HelpBox("You try to register an Audio Clip or a Planet Prefab from another mod folder. " + text3, (MessageType)2); } base.OnInspectorGUI(); } } [CustomEditor(typeof(SI_DungeonGenerator))] public class SI_DungeonGeneratorEditor : EditorChecker { public override void OnInspectorGUI() { SI_DungeonGenerator sI_DungeonGenerator = (SI_DungeonGenerator)(object)((Editor)this).target; string assetPath = AssetDatabase.GetAssetPath((Object)(object)sI_DungeonGenerator.DungeonRoot); if (assetPath != null && assetPath.Length > 0) { EditorGUILayout.HelpBox("Dungeon Root must be in the scene.", (MessageType)3); } base.OnInspectorGUI(); } } [CustomEditor(typeof(SI_ScanNode))] public class SI_ScanNodeEditor : EditorChecker { public override void OnInspectorGUI() { SI_ScanNode sI_ScanNode = (SI_ScanNode)(object)((Editor)this).target; if (sI_ScanNode.MinRange > sI_ScanNode.MaxRange) { EditorGUILayout.HelpBox("Min Range must be smaller than Max Ranger.", (MessageType)3); } if (sI_ScanNode.CreatureScanID < -1) { EditorGUILayout.HelpBox("Creature Scan ID can't be less than -1.", (MessageType)2); } base.OnInspectorGUI(); } } [CustomEditor(typeof(SI_AnimatedSun))] public class SI_AnimatedSunEditor : EditorChecker { public override void OnInspectorGUI() { SI_AnimatedSun sI_AnimatedSun = (SI_AnimatedSun)(object)((Editor)this).target; if ((Object)(object)sI_AnimatedSun.directLight == (Object)null || (Object)(object)sI_AnimatedSun.indirectLight == (Object)null) { EditorGUILayout.HelpBox("A direct and an indirect light must be defined.", (MessageType)2); } if ((Object)(object)((Component)sI_AnimatedSun.directLight).transform.parent != (Object)(object)((Component)sI_AnimatedSun).transform || (Object)(object)((Component)sI_AnimatedSun.indirectLight).transform.parent != (Object)(object)((Component)sI_AnimatedSun).transform) { EditorGUILayout.HelpBox("Direct and an indirect light must be a child of the AnimatedSun in the hierarchy.", (MessageType)2); } base.OnInspectorGUI(); } } [CustomEditor(typeof(SI_EntranceTeleport))] public class SI_EntranceTeleportEditor : EditorChecker { public override void OnInspectorGUI() { SI_EntranceTeleport sI_EntranceTeleport = (SI_EntranceTeleport)(object)((Editor)this).target; IEnumerable<int> enumerable = from e in Object.FindObjectsOfType<SI_EntranceTeleport>().ToList() group e by e.EntranceID into g where g.Count() > 1 select g.Key; if (enumerable.Any()) { string text = string.Empty; foreach (int item in enumerable) { text += $"{item},"; } text = text.Remove(text.Length - 1); EditorGUILayout.HelpBox("Two entrances or more have same Entrance ID. Duplicated entrances are: " + text, (MessageType)2); } if ((Object)(object)sI_EntranceTeleport.EntrancePoint == (Object)null) { EditorGUILayout.HelpBox("An entrance point must be defined.", (MessageType)3); } if (sI_EntranceTeleport.AudioReverbPreset < 0) { EditorGUILayout.HelpBox("Audio Reverb Preset can't be negative.", (MessageType)3); } base.OnInspectorGUI(); } } [CustomEditor(typeof(Scrap))] public class ScrapEditor : EditorChecker { public override void OnInspectorGUI() { Scrap scrap = (Scrap)(object)((Editor)this).target; if ((Object)(object)scrap.prefab == (Object)null) { EditorGUILayout.HelpBox("You must add a Prefab to your Scrap.", (MessageType)1); } else { if ((Object)(object)scrap.prefab.GetComponent<NetworkObject>() == (Object)null) { EditorGUILayout.HelpBox("The Prefab must have a NetworkObject.", (MessageType)3); } if ((Object)(object)scrap.prefab.transform.Find("ScanNode") == (Object)null) { EditorGUILayout.HelpBox("The Prefab don't have a ScanNode.", (MessageType)2); } if (AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap.prefab)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)scrap))) { EditorGUILayout.HelpBox("The Prefab must come from the same mod folder as your Scrap.", (MessageType)2); } } if (scrap.itemName == null || scrap.itemName.Length == 0) { EditorGUILayout.HelpBox("Your scrap must have a Name.", (MessageType)3); } if (!scrap.useGlobalSpawnWeight && !scrap.perPlanetSpawnWeight().Any((ScrapSpawnChancePerScene w) => w.SceneName != null && w.SceneName.Length > 0)) { EditorGUILayout.HelpBox("Your scrap use Per Planet Spawn Weight but no planet are defined.", (MessageType)2); } base.OnInspectorGUI(); } } [CustomEditor(typeof(Moon))] public class MoonEditor : EditorChecker { public override void OnInspectorGUI() { Moon moon = (Moon)(object)((Editor)this).target; if (moon.MoonName == null || moon.MoonName.Length == 0) { EditorGUILayout.HelpBox("Your moon must have a Name.", (MessageType)3); } if (moon.PlanetName == null || moon.PlanetName.Length == 0) { EditorGUILayout.HelpBox("Your moon must have a Planet Name.", (MessageType)3); } if (moon.RouteWord == null || moon.RouteWord.Length < 3) { EditorGUILayout.HelpBox("Your moon route word must be at least 3 characters long.", (MessageType)3); } if ((Object)(object)moon.MainPrefab == (Object)null) { EditorGUILayout.HelpBox("You must add a Main Prefab to your Scrap.", (MessageType)1); } else if (AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon.MainPrefab)) != AssetModificationProcessor.ExtractBundleNameFromPath(AssetDatabase.GetAssetPath((Object)(object)moon))) { EditorGUILayout.HelpBox("The Main Prefab must come from the same mod folder as your Moon.", (MessageType)2); } base.OnInspectorGUI(); } } [CustomEditor(typeof(SI_DoorLock))] public class SI_DoorLockEditor : EditorChecker { public override void OnInspectorGUI() { SI_DoorLock sI_DoorLock = (SI_DoorLock)(object)((Editor)this).target; EditorGUILayout.HelpBox("DoorLock is not implemented yet.", (MessageType)1); base.OnInspectorGUI(); } } [CustomEditor(typeof(SI_Ladder))] public class SI_LadderEditor : EditorChecker { public override void OnInspectorGUI() { SI_Ladder sI_Ladder = (SI_Ladder)(object)((Editor)this).target; EditorGUILayout.HelpBox("Ladder is experimental.", (MessageType)1); base.OnInspectorGUI(); } } internal class OldAssetsRemover { private static readonly List<string> assetPaths = new List<string> { "Assets/LethalCompanyAssets", "Assets/Mods/LethalExpansion/Audio", "Assets/Mods/LethalExpansion/AudioMixerController", "Assets/Mods/LethalExpansion/Materials/Default.mat", "Assets/Mods/LethalExpansion/Prefabs/Settings", "Assets/Mods/LethalExpansion/Prefabs/EntranceTeleportA.prefab", "Assets/Mods/LethalExpansion/Prefabs/Prefabs.zip", "Assets/Mods/LethalExpansion/Scenes/ItemPlaceTest", "Assets/Mods/LethalExpansion/Sprites/HandIcon.png", "Assets/Mods/LethalExpansion/Sprites/HandIconPoint.png", "Assets/Mods/LethalExpansion/Sprites/HandLadderIcon.png", "Assets/Mods/TemplateMod/Moons/NavMesh-Environment.asset", "Assets/Mods/TemplateMod/Moons/OldSeaPort.asset", "Assets/Mods/TemplateMod/Moons/Sky and Fog Global Volume Profile.asset", "Assets/Mods/TemplateMod/Moons/Sky and Fog Global Volume Profile 1.asset", "Assets/Mods/TemplateMod/AssetBank.asset", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunCompanyLevel.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeB.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeBEclipse.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeBStormy.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeC.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeCEclipse.anim", "Assets/Mods/LethalExpansion/Animations/Sun/TimeOfDaySunTypeCStormy.anim", "Assets/Mods/LethalExpansion/Skybox", "Assets/Mods/LethalExpansion/Sprites/XButton.png", "Assets/Mods/LethalExpansion/Textures/sunTexture1.png", "Assets/Mods/OldSeaPort/Materials/Maple_bark_1.mat", "Assets/Mods/OldSeaPort/Materials/maple_leaves.mat", "Assets/Mods/TemplateMod/AssetBank.asset", "Assets/Mods/OldSeaPort/EffectExamples/Shared/Scripts", "Assets/Mods/OldSeaPort/scenes", "Assets/Mods/OldSeaPort/prefabs/Plane (12).prefab", "Assets/Mods/LethalExpansion/Meshes/labyrinth.fbx", "Assets/Mods/ChristmasVillage/christmas-assets-free/fbx/Materials" }; [InitializeOnLoadMethod] public static void CheckOldAssets() { foreach (string assetPath in assetPaths) { if (AssetDatabase.IsValidFolder(assetPath)) { DeleteFolder(assetPath); } else if ((Object)(object)AssetDatabase.LoadAssetAtPath<GameObject>(assetPath) != (Object)null) { DeleteAsset(assetPath); } } } private static void DeleteFolder(string path) { if (AssetDatabase.DeleteAsset(path)) { Debug.Log((object)("Deleted folder at: " + path)); } else { Debug.LogError((object)("Failed to delete folder at: " + path)); } } private static void DeleteAsset(string path) { if (AssetDatabase.DeleteAsset(path)) { Debug.Log((object)("Deleted asset at: " + path)); } else { Debug.LogError((object)("Failed to delete asset at: " + path)); } } } public class VersionChecker : Editor { [InitializeOnLoadMethod] public static void CheckVersion() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown UnityWebRequest www = UnityWebRequest.Get("https://raw.githubusercontent.com/HolographicWings/LethalSDK-Unity-Project/main/last.txt"); UnityWebRequestAsyncOperation operation = www.SendWebRequest(); CallbackFunction callback = null; callback = (CallbackFunction)delegate { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown if (((AsyncOperation)operation).isDone) { EditorApplication.update = (CallbackFunction)Delegate.Remove((Delegate?)(object)EditorApplication.update, (Delegate?)(object)callback); OnRequestComplete(www); } }; EditorApplication.update = (CallbackFunction)Delegate.Combine((Delegate?)(object)EditorApplication.update, (Delegate?)(object)callback); } private static void OnRequestComplete(UnityWebRequest www) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 if ((int)www.result == 2 || (int)www.result == 3) { Debug.LogError((object)("Error when getting last version number: " + www.error)); } else { CompareVersions(www.downloadHandler.text); } } private static void CompareVersions(string onlineVersion) { if (Version.Parse(PlayerSettings.bundleVersion) < Version.Parse(onlineVersion) && EditorUtility.DisplayDialogComplex("Warning", "The SDK is not up to date: " + onlineVersion, "Update", "Ignore", "") == 0) { Application.OpenURL("https://thunderstore.io/c/lethal-company/p/HolographicWings/LethalSDK/"); } } } internal class LethalSDKCategory : EditorWindow { [MenuItem("LethalSDK/Lethal SDK v1.3.0", false, 0)] public static void ShowWindow() { } } public class Lethal_AssetBundleBuilderWindow : EditorWindow { private enum compressionOption { NormalCompression, FastCompression, Uncompressed } private static string assetBundleDirectoryKey = "LethalSDK_AssetBundleBuilderWindow_assetBundleDirectory"; private static string compressionModeKey = "LethalSDK_AssetBundleBuilderWindow_compressionMode"; private static string _64BitsModeKey = "LethalSDK_AssetBundleBuilderWindow_64BitsMode"; private string assetBundleDirectory = string.Empty; private compressionOption compressionMode = compressionOption.NormalCompression; private bool _64BitsMode; [MenuItem("LethalSDK/AssetBundle Builder", false, 100)] public static void ShowWindow() { //IL_0017: 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) Lethal_AssetBundleBuilderWindow window = EditorWindow.GetWindow<Lethal_AssetBundleBuilderWindow>("AssetBundle Builder"); ((EditorWindow)window).minSize = new Vector2(295f, 133f); ((EditorWindow)window).maxSize = new Vector2(295f, 133f); window.LoadPreferences(); } private void OnGUI() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Expected O, but got Unknown GUILayout.Label("Base Settings", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); EditorGUILayout.LabelField(new GUIContent("Output Path", "The directory where the asset bundles will be saved."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(84f) }); assetBundleDirectory = EditorGUILayout.TextField(assetBundleDirectory, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.EndHorizontal(); EditorGUILayout.Space(5f); GUILayout.Label("Options", EditorStyles.boldLabel, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); EditorGUILayout.LabelField(new GUIContent("Compression Mode", "Select the compression option for the asset bundle. Faster the compression is, faster the assets will load and less CPU it will use, but the Bundle will be bigger."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(145f) }); compressionMode = (compressionOption)(object)EditorGUILayout.EnumPopup((Enum)compressionMode, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); EditorGUILayout.LabelField(new GUIContent("64 Bits Asset Bundle (Not recommended)", "Better performances but incompatible with 32 bits computers."), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(270f) }); _64BitsMode = EditorGUILayout.Toggle(_64BitsMode, Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); EditorGUILayout.Space(5f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Build AssetBundles", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) })) { BuildAssetBundles(); } if (GUILayout.Button("Reset", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(45f) })) { ClearPreferences(); } GUILayout.EndHorizontal(); } private void ClearPreferences() { EditorPrefs.DeleteKey(assetBundleDirectoryKey); EditorPrefs.DeleteKey(compressionModeKey); EditorPrefs.DeleteKey(_64BitsModeKey); LoadPreferences(); } private void BuildAssetBundles() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_004f: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) if (!Directory.Exists(assetBundleDirectory)) { Directory.CreateDirectory(assetBundleDirectory); } BuildAssetBundleOptions val = (BuildAssetBundleOptions)0; val = (BuildAssetBundleOptions)(compressionMode switch { compressionOption.NormalCompression => 0, compressionOption.FastCompression => 256, compressionOption.Uncompressed => 1, _ => 0, }); BuildTarget val2 = (BuildTarget)(_64BitsMode ? 19 : 5); try { if (assetBundleDirectory != null || assetBundleDirectory.Length != 0) { AssetBundleManifest val3 = BuildPipeline.BuildAssetBundles(assetBundleDirectory, val, val2); if ((Object)(object)val3 != (Object)null) { Debug.Log((object)"AssetBundles built successfully."); } else { Debug.LogError((object)"Cannot build AssetBundles."); } } else { Debug.LogError((object)"AssetBundles path cannot be blank."); } } catch (Exception ex) { Debug.LogError((object)ex.Message); } } private void OnLostFocus() { SavePreferences(); } private void OnDisable() { SavePreferences(); } private void LoadPreferences() { assetBundleDirectory = EditorPrefs.GetString(assetBundleDirectoryKey, "Assets/AssetBundles"); compressionMode = (compressionOption)EditorPrefs.GetInt(compressionModeKey, 0); _64BitsMode = EditorPrefs.GetBool(_64BitsModeKey, false); } private void SavePreferences() { EditorPrefs.SetString(assetBundleDirectoryKey, assetBundleDirectory); EditorPrefs.SetInt(compressionModeKey, (int)compressionMode); EditorPrefs.SetBool(_64BitsModeKey, _64BitsMode); } } } namespace LethalSDK.Component { [AddComponentMenu("LethalSDK/DamagePlayer")] public class SI_DamagePlayer : MonoBehaviour { public bool kill = false; public bool dontSpawnBody = false; public SI_CauseOfDeath causeOfDeath = SI_CauseOfDeath.Gravity; public int damages = 25; public int numberIterations = 1; public int iterationCooldown = 1000; public int warmupCooldown = 0; public UnityEvent postEvent = new UnityEvent(); public void Trigger(object player) { if (kill) { ((MonoBehaviour)this).StartCoroutine(Kill(player)); } else { ((MonoBehaviour)this).StartCoroutine(Damage(player)); } } public IEnumerator Kill(object player) { yield return (object)new WaitForSeconds((float)warmupCooldown / 1000f); ((PlayerControllerB)((player is PlayerControllerB) ? player : null)).KillPlayer(Vector3.zero, !dontSpawnBody, (CauseOfDeath)causeOfDeath, 0); postEvent.Invoke(); } public IEnumerator Damage(object player) { yield return (object)new WaitForSeconds((float)warmupCooldown / 1000f); int iteration = 0; while (iteration < numberIterations || numberIterations == -1) { ((PlayerControllerB)((player is PlayerControllerB) ? player : null)).DamagePlayer(damages, true, true, (CauseOfDeath)causeOfDeath, 0, false, Vector3.zero); postEvent.Invoke(); iteration++; yield return (object)new WaitForSeconds((float)iterationCooldown / 1000f); } } public void StopCounter(object player) { ((MonoBehaviour)this).StopAllCoroutines(); } } [AddComponentMenu("LethalSDK/SoundYDistance")] public class SI_SoundYDistance : MonoBehaviour { public AudioSource audioSource; public int maxDistance = 50; public void Awake() { if ((Object)(object)audioSource == (Object)null) { audioSource = ((Component)this).gameObject.GetComponent<AudioSource>(); if ((Object)(object)audioSource == (Object)null) { audioSource = ((Component)this).gameObject.AddComponent<AudioSource>(); } } } public void Update() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)RoundManager.Instance != (Object)null && (Object)(object)StartOfRound.Instance != (Object)null) { audioSource.volume = 1f - Mathf.Abs(((Component)this).transform.position.y - ((Component)RoundManager.Instance.playersManager.allPlayerScripts[StartOfRound.Instance.ClientPlayerList[((NetworkBehaviour)StartOfRound.Instance).NetworkManager.LocalClientId]].gameplayCamera).transform.position.y) / (float)maxDistance; } } } [AddComponentMenu("LethalSDK/AudioOutputInterface")] public class SI_AudioOutputInterface : MonoBehaviour { public AudioSource audioSource; public string mixerName = "Diagetic"; public string mixerGroupName = "Master"; public void Awake() { if ((Object)(object)audioSource == (Object)null) { audioSource = ((Component)this).gameObject.GetComponent<AudioSource>(); if ((Object)(object)audioSource == (Object)null) { audioSource = ((Component)this).gameObject.AddComponent<AudioSource>(); } } if (mixerName != null && mixerName.Length > 0 && mixerGroupName != null && mixerGroupName.Length > 0) { audioSource.outputAudioMixerGroup = AssetGatherDialog.audioMixers[mixerName].Item2.First((AudioMixerGroup g) => ((Object)g).name == mixerGroupName); } Object.Destroy((Object)(object)this); } } [AddComponentMenu("LethalSDK/NetworkPrefabInstancier")] public class SI_NetworkPrefabInstancier : MonoBehaviour { public GameObject prefab; public GameObject instance; public void Awake() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)prefab != (Object)null) { NetworkObject component = prefab.GetComponent<NetworkObject>(); if ((Object)(object)component != (Object)null && (Object)(object)component.NetworkManager != (Object)null && component.NetworkManager.IsHost) { instance = Object.Instantiate<GameObject>(prefab, ((Component)this).transform.position, ((Component)this).transform.rotation, ((Component)this).transform.parent); instance.GetComponent<NetworkObject>().Spawn(false); } } ((Component)this).gameObject.SetActive(false); } public void OnDestroy() { if ((Object)(object)instance != (Object)null) { NetworkObject component = prefab.GetComponent<NetworkObject>(); if ((Object)(object)component != (Object)null && (Object)(object)component.NetworkManager != (Object)null && component.NetworkManager.IsHost) { instance.GetComponent<NetworkObject>().Despawn(true); Object.Destroy((Object)(object)instance); } } } } public class ScriptImporter : MonoBehaviour { public virtual void Awake() { Object.Destroy((Object)(object)this); } } [AddComponentMenu("LethalSDK/MatchLocalPlayerPosition")] public class SI_MatchLocalPlayerPosition : ScriptImporter { public override void Awake() { ((Component)this).gameObject.AddComponent<MatchLocalPlayerPosition>(); base.Awake(); } } [AddComponentMenu("LethalSDK/AnimatedSun")] public class SI_AnimatedSun : ScriptImporter { public Light indirectLight; public Light directLight; public override void Awake() { animatedSun val = ((Component)this).gameObject.AddComponent<animatedSun>(); val.indirectLight = indirectLight; val.directLight = directLight; base.Awake(); } } [AddComponentMenu("LethalSDK/ScanNode")] public class SI_ScanNode : ScriptImporter { public int MaxRange; public int MinRange; public bool RequiresLineOfSight; public string HeaderText; public string SubText; public int ScrapValue; public int CreatureScanID; public NodeType NodeType; public override void Awake() { ScanNodeProperties val = ((Component)this).gameObject.AddComponent<ScanNodeProperties>(); val.minRange = MinRange; val.maxRange = MaxRange; val.requiresLineOfSight = RequiresLineOfSight; val.headerText = HeaderText; val.subText = SubText; val.scrapValue = ScrapValue; val.creatureScanID = CreatureScanID; val.nodeType = (int)NodeType; base.Awake(); } } public enum NodeType { Information = 0, Danger = 0, Ressource = 0 } [AddComponentMenu("LethalSDK/AudioReverbPresets")] public class SI_AudioReverbPresets : ScriptImporter { public GameObject[] presets; public override void Awake() { } public void Update() { int num = 0; GameObject[] array = presets; foreach (GameObject val in array) { if ((Object)(object)val.GetComponent<SI_AudioReverbTrigger>() != (Object)null) { num++; } } if (num != 0) { return; } List<AudioReverbTrigger> list = new List<AudioReverbTrigger>(); GameObject[] array2 = presets; foreach (GameObject val2 in array2) { if ((Object)(object)val2.GetComponent<AudioReverbTrigger>() != (Object)null) { list.Add(val2.GetComponent<AudioReverbTrigger>()); } } AudioReverbPresets val3 = ((Component)this).gameObject.AddComponent<AudioReverbPresets>(); val3.audioPresets = list.ToArray(); Object.Destroy((Object)(object)this); } } [AddComponentMenu("LethalSDK/AudioReverbTrigger")] public class SI_AudioReverbTrigger : ScriptImporter { [Header("Reverb Preset")] public bool ChangeDryLevel = false; [Range(-10000f, 0f)] public float DryLevel = 0f; public bool ChangeHighFreq = false; [Range(-10000f, 0f)] public float HighFreq = -270f; public bool ChangeLowFreq = false; [Range(-10000f, 0f)] public float LowFreq = -244f; public bool ChangeDecayTime = false; [Range(0f, 35f)] public float DecayTime = 1.4f; public bool ChangeRoom = false; [Range(-10000f, 0f)] public float Room = -600f; [Header("MISC")] public bool ElevatorTriggerForProps = false; public bool SetInElevatorTrigger = false; public bool IsShipRoom = false; public bool ToggleLocalFog = false; public float FogEnabledAmount = 10f; [Header("Weather and effects")] public bool SetInsideAtmosphere = false; public bool InsideLighting = false; public int WeatherEffect = -1; public bool EffectEnabled = true; public bool DisableAllWeather = false; public bool EnableCurrentLevelWeather = true; public override void Awake() { AudioReverbTrigger val = ((Component)this).gameObject.AddComponent<AudioReverbTrigger>(); ReverbPreset val2 = ScriptableObject.CreateInstance<ReverbPreset>(); val2.changeDryLevel = ChangeDryLevel; val2.dryLevel = DryLevel; val2.changeHighFreq = ChangeHighFreq; val2.highFreq = HighFreq; val2.changeLowFreq = ChangeLowFreq; val2.lowFreq = LowFreq; val2.changeDecayTime = ChangeDecayTime; val2.decayTime = DecayTime; val2.changeRoom = ChangeRoom; val2.room = Room; val.reverbPreset = val2; val.usePreset = -1; val.audioChanges = (switchToAudio[])(object)new switchToAudio[0]; val.elevatorTriggerForProps = ElevatorTriggerForProps; val.setInElevatorTrigger = SetInElevatorTrigger; val.isShipRoom = IsShipRoom; val.toggleLocalFog = ToggleLocalFog; val.fogEnabledAmount = FogEnabledAmount; val.setInsideAtmosphere = SetInsideAtmosphere; val.insideLighting = InsideLighting; val.weatherEffect = WeatherEffect; val.effectEnabled = EffectEnabled; val.disableAllWeather = DisableAllWeather; val.enableCurrentLevelWeather = EnableCurrentLevelWeather; base.Awake(); } } [AddComponentMenu("LethalSDK/DungeonGenerator")] public class SI_DungeonGenerator : ScriptImporter { public GameObject DungeonRoot; public override void Awake() { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) if (((Component)this).tag != "DungeonGenerator") { ((Component)this).tag = "DungeonGenerator"; } RuntimeDungeon val = ((Component)this).gameObject.AddComponent<RuntimeDungeon>(); val.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0]; val.Generator.LengthMultiplier = 0.8f; val.Generator.PauseBetweenRooms = 0.2f; val.GenerateOnStart = false; if ((Object)(object)DungeonRoot != (Object)null) { _ = DungeonRoot.scene; if (false) { DungeonRoot = new GameObject(); ((Object)DungeonRoot).name = "DungeonRoot"; DungeonRoot.transform.position = new Vector3(0f, -200f, 0f); } } val.Root = DungeonRoot; val.Generator.DungeonFlow = RoundManager.Instance.dungeonFlowTypes[0]; UnityNavMeshAdapter val2 = ((Component)this).gameObject.AddComponent<UnityNavMeshAdapter>(); val2.BakeMode = (RuntimeNavMeshBakeMode)3; val2.LayerMask = LayerMask.op_Implicit(35072); base.Awake(); } } [AddComponentMenu("LethalSDK/EntranceTeleport")] public class SI_EntranceTeleport : ScriptImporter { public int EntranceID = 0; public Transform EntrancePoint; public int AudioReverbPreset = -1; public AudioClip[] DoorAudios = (AudioClip[])(object)new AudioClip[0]; public override void Awake() { //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Expected O, but got Unknown //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Expected O, but got Unknown //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Expected O, but got Unknown //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Expected O, but got Unknown //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Expected O, but got Unknown AudioSource val = ((Component)this).gameObject.AddComponent<AudioSource>(); val.outputAudioMixerGroup = AssetGatherDialog.audioMixers["Diagetic"].Item2.First((AudioMixerGroup g) => ((Object)g).name == "Master"); val.playOnAwake = false; val.spatialBlend = 1f; EntranceTeleport entranceTeleport = ((Component)this).gameObject.AddComponent<EntranceTeleport>(); entranceTeleport.isEntranceToBuilding = true; entranceTeleport.entrancePoint = EntrancePoint; entranceTeleport.entranceId = EntranceID; entranceTeleport.audioReverbPreset = AudioReverbPreset; entranceTeleport.entrancePointAudio = val; entranceTeleport.doorAudios = DoorAudios; InteractTrigger val2 = ((Component)this).gameObject.AddComponent<InteractTrigger>(); val2.hoverIcon = (AssetGatherDialog.sprites.ContainsKey("HandIcon") ? AssetGatherDialog.sprites["HandIcon"] : AssetGatherDialog.sprites.First().Value); val2.hoverTip = "Enter : [LMB]"; val2.disabledHoverTip = string.Empty; val2.holdTip = string.Empty; val2.animationString = string.Empty; val2.interactable = true; val2.oneHandedItemAllowed = true; val2.twoHandedItemAllowed = true; val2.holdInteraction = true; val2.timeToHold = 1.5f; val2.timeToHoldSpeedMultiplier = 1f; val2.holdingInteractEvent = new InteractEventFloat(); val2.onInteract = new InteractEvent(); val2.onInteractEarly = new InteractEvent(); val2.onStopInteract = new InteractEvent(); val2.onCancelAnimation = new InteractEvent(); ((UnityEvent<PlayerControllerB>)(object)val2.onInteract).AddListener((UnityAction<PlayerControllerB>)delegate { entranceTeleport.TeleportPlayer(); }); base.Awake(); } } [AddComponentMenu("LethalSDK/DoorLock")] public class SI_DoorLock : ScriptImporter { public override void Awake() { base.Awake(); } } [AddComponentMenu("LethalSDK/WaterSurface")] public class SI_WaterSurface : ScriptImporter { private GameObject obj; public int soundMaxDistance = 50; public override void Awake() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) obj = Object.Instantiate<GameObject>(SpawnPrefab.Instance.waterSurface); SceneManager.MoveGameObjectToScene(obj, ((Component)this).gameObject.scene); obj.transform.parent = ((Component)this).transform; obj.transform.localPosition = Vector3.zero; Transform val = obj.transform.Find("Water"); ((Component)val).GetComponent<MeshFilter>().sharedMesh = ((Component)this).GetComponent<MeshFilter>().sharedMesh; val.position = ((Component)this).transform.position; val.rotation = ((Component)this).transform.rotation; val.localScale = ((Component)this).transform.localScale; SI_SoundYDistance sI_SoundYDistance = ((Component)val).gameObject.AddComponent<SI_SoundYDistance>(); sI_SoundYDistance.audioSource = ((Component)obj.transform.Find("WaterAudio")).GetComponent<AudioSource>(); sI_SoundYDistance.maxDistance = soundMaxDistance; obj.SetActive(true); base.Awake(); } } [AddComponentMenu("LethalSDK/Ladder")] public class SI_Ladder : ScriptImporter { public Transform BottomPosition; public Transform TopPosition; public Transform HorizontalPosition; public Transform PlayerNodePosition; public bool UseRaycastToGetTopPosition = false; public override void Awake() { //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected O, but got Unknown //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Expected O, but got Unknown InteractTrigger val = ((Component)this).gameObject.AddComponent<InteractTrigger>(); val.hoverIcon = (AssetGatherDialog.sprites.ContainsKey("HandLadderIcon") ? AssetGatherDialog.sprites["HandLadderIcon"] : AssetGatherDialog.sprites.First().Value); val.hoverTip = "Climb : [LMB]"; val.disabledHoverTip = string.Empty; val.holdTip = string.Empty; val.animationString = string.Empty; val.specialCharacterAnimation = true; val.animationWaitTime = 0.5f; val.animationString = "SA_PullLever"; val.isLadder = true; val.lockPlayerPosition = true; val.playerPositionNode = BottomPosition; val.bottomOfLadderPosition = BottomPosition; val.bottomOfLadderPosition = BottomPosition; val.topOfLadderPosition = TopPosition; val.ladderHorizontalPosition = HorizontalPosition; val.ladderPlayerPositionNode = PlayerNodePosition; val.useRaycastToGetTopPosition = UseRaycastToGetTopPosition; val.holdingInteractEvent = new InteractEventFloat(); val.onCancelAnimation = new InteractEvent(); val.onInteract = new InteractEvent(); val.onInteractEarly = new InteractEvent(); val.onStopInteract = new InteractEvent(); base.Awake(); } } [AddComponentMenu("LethalSDK/ItemDropship")] public class SI_ItemDropship : ScriptImporter { public Animator ShipAnimator; public Transform[] ItemSpawnPositions; public GameObject OpenTriggerObject; public GameObject KillTriggerObject; public AudioClip ShipThrusterCloseSound; public AudioClip ShipLandSound; public AudioClip ShipOpenDoorsSound; public override void Awake() { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Expected O, but got Unknown ItemDropship ItemDropship = ((Component)this).gameObject.AddComponent<ItemDropship>(); ItemDropship.shipAnimator = ShipAnimator; ItemDropship.itemSpawnPositions = ItemSpawnPositions; PlayAudioAnimationEvent val = ((Component)this).gameObject.AddComponent<PlayAudioAnimationEvent>(); val.audioToPlay = ((Component)this).GetComponent<AudioSource>(); val.audioClip = ShipLandSound; val.audioClip2 = ShipOpenDoorsSound; InteractTrigger val2 = OpenTriggerObject.AddComponent<InteractTrigger>(); val2.hoverIcon = (AssetGatherDialog.sprites.ContainsKey("HandIcon") ? AssetGatherDialog.sprites["HandIcon"] : AssetGatherDialog.sprites.First().Value); val2.hoverTip = "Open : [LMB]"; val2.disabledHoverTip = string.Empty; val2.holdTip = string.Empty; val2.animationString = string.Empty; val2.twoHandedItemAllowed = true; val2.onInteract = new InteractEvent(); ((UnityEvent<PlayerControllerB>)(object)val2.onInteract).AddListener((UnityAction<PlayerControllerB>)delegate { ItemDropship.TryOpeningShip(); }); ItemDropship.triggerScript = val2; if ((Object)(object)((Component)ItemDropship).transform.Find("Music") != (Object)null) { ((Component)((Component)ItemDropship).transform.Find("Music")).gameObject.AddComponent<OccludeAudio>(); if ((Object)(object)((Component)this).transform.Find("ThrusterContainer/Thruster") != (Object)null) { facePlayerOnAxis val3 = ((Component)((Component)this).transform.Find("ThrusterContainer/Thruster")).gameObject.AddComponent<facePlayerOnAxis>(); val3.turnAxis = ((Component)this).transform.Find("ThrusterContainer/flameAxis"); } } KillLocalPlayer KillLocalPlayerScript = KillTriggerObject.AddComponent<KillLocalPlayer>(); InteractTrigger val4 = KillTriggerObject.AddComponent<InteractTrigger>(); val4.hoverTip = string.Empty; val4.disabledHoverTip = string.Empty; val4.holdTip = string.Empty; val4.animationString = string.Empty; val4.touchTrigger = true; val4.triggerOnce = true; val4.onInteract = new InteractEvent(); ((UnityEvent<PlayerControllerB>)(object)val4.onInteract).AddListener((UnityAction<PlayerControllerB>)delegate(PlayerControllerB player) { KillLocalPlayerScript.KillPlayer(player); }); base.Awake(); } } [AddComponentMenu("LethalSDK/InteractTrigger")] public class SI_InteractTrigger : ScriptImporter { [Header("Aesthetics")] public string hoverIcon = "HandIcon"; public string hoverTip = "Interact"; public string disabledHoverIcon = string.Empty; public string disabledHoverTip = string.Empty; [Header("Interaction")] public bool interactable = true; public bool oneHandedItemAllowed = true; public bool twoHandedItemAllowed = false; public bool holdInteraction = false; public float timeToHold = 0.5f; public float timeToHoldSpeedMultiplier = 1f; public string holdTip = string.Empty; public UnityEvent<float> holdingInteractEvent = new UnityEvent<float>(); public bool touchTrigger = false; public bool triggerOnce = false; [Header("Misc")] public bool interactCooldown = true; public float cooldownTime = 1f; public bool disableTriggerMesh = true; public bool RandomChanceTrigger = false; public int randomChancePercentage = 0; [Header("Events")] public UnityEvent<object> onInteract = new UnityEvent<object>(); public UnityEvent<object> onInteractEarly = new UnityEvent<object>(); public UnityEvent<object> onStopInteract = new UnityEvent<object>(); public UnityEvent<object> onCancelAnimation = new UnityEvent<object>(); [Header("Special Animation")] public bool specialCharacterAnimation = false; public bool stopAnimationManually = false; public string stopAnimationString = "SA_stopAnimation"; public bool hidePlayerItem = false; public bool isPlayingSpecialAnimation = false; public float animationWaitTime = 2f; public string animationString = string.Empty; public bool lockPlayerPosition = false; public Transform playerPositionNode; [Header("Ladders")] public bool isLadder = false; public Transform topOfLadderPosition; public bool useRaycastToGetTopPosition = false; public Transform bottomOfLadderPosition; public Transform ladderHorizontalPosition; public Transform ladderPlayerPositionNode; public override void Awake() { //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Expected O, but got Unknown //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Expected O, but got Unknown //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Expected O, but got Unknown //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown InteractTrigger val = ((Component)this).gameObject.AddComponent<InteractTrigger>(); if (hoverIcon != null && hoverIcon.Length > 0) { val.hoverIcon = null; } else { val.hoverIcon = (AssetGatherDialog.sprites.ContainsKey(hoverIcon) ? AssetGatherDialog.sprites[hoverIcon] : AssetGatherDialog.sprites.First().Value); } val.hoverTip = hoverTip; if (disabledHoverIcon != null && disabledHoverIcon.Length > 0) { val.disabledHoverIcon = null; } else { val.disabledHoverIcon = (Asset
BepInEx/plugins/LethalThings/LethalThings.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using LethalLib.Extras; using LethalLib.Modules; using LethalThings.Extensions; using LethalThings.MonoBehaviours; using LethalThings.Patches; using Microsoft.CodeAnalysis; using MonoMod.RuntimeDetour; using On; using On.GameNetcodeStuff; using TMPro; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.Utilities; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LethalThings")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Mod for Lethal Company")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+86ae65aa973bc30ae45609c9c37649bfb7da4c59")] [assembly: AssemblyProduct("LethalThings")] [assembly: AssemblyTitle("LethalThings")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<Vector3>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<Vector3>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<HackingTool.HackState>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals<HackingTool.HackState>(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 LethalLib.Modules { public class SaveData { [CompilerGenerated] private static class <>O { public static hook_ResetSavedGameValues <0>__GameNetworkManager_ResetSavedGameValues; public static hook_SaveItemsInShip <1>__GameNetworkManager_SaveItemsInShip; public static hook_LoadShipGrabbableItems <2>__StartOfRound_LoadShipGrabbableItems; } public static List<string> saveKeys = new List<string>(); public static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //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_003b: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown object obj = <>O.<0>__GameNetworkManager_ResetSavedGameValues; if (obj == null) { hook_ResetSavedGameValues val = GameNetworkManager_ResetSavedGameValues; <>O.<0>__GameNetworkManager_ResetSavedGameValues = val; obj = (object)val; } GameNetworkManager.ResetSavedGameValues += (hook_ResetSavedGameValues)obj; object obj2 = <>O.<1>__GameNetworkManager_SaveItemsInShip; if (obj2 == null) { hook_SaveItemsInShip val2 = GameNetworkManager_SaveItemsInShip; <>O.<1>__GameNetworkManager_SaveItemsInShip = val2; obj2 = (object)val2; } GameNetworkManager.SaveItemsInShip += (hook_SaveItemsInShip)obj2; object obj3 = <>O.<2>__StartOfRound_LoadShipGrabbableItems; if (obj3 == null) { hook_LoadShipGrabbableItems val3 = StartOfRound_LoadShipGrabbableItems; <>O.<2>__StartOfRound_LoadShipGrabbableItems = val3; obj3 = (object)val3; } StartOfRound.LoadShipGrabbableItems += (hook_LoadShipGrabbableItems)obj3; } private static void StartOfRound_LoadShipGrabbableItems(orig_LoadShipGrabbableItems orig, StartOfRound self) { orig.Invoke(self); SaveableObject[] array = Object.FindObjectsOfType<SaveableObject>(); SaveableNetworkBehaviour[] array2 = Object.FindObjectsOfType<SaveableNetworkBehaviour>(); SaveableObject[] array3 = array; for (int i = 0; i < array3.Length; i++) { array3[i].LoadObjectData(); } SaveableNetworkBehaviour[] array4 = array2; for (int i = 0; i < array4.Length; i++) { array4[i].LoadObjectData(); } if (ES3.KeyExists("LethalLibItemSaveKeys", GameNetworkManager.Instance.currentSaveFileName)) { saveKeys = ES3.Load<List<string>>("LethalLibItemSaveKeys", GameNetworkManager.Instance.currentSaveFileName); } } private static void GameNetworkManager_SaveItemsInShip(orig_SaveItemsInShip orig, GameNetworkManager self) { orig.Invoke(self); SaveableObject[] array = Object.FindObjectsOfType<SaveableObject>(); SaveableNetworkBehaviour[] array2 = Object.FindObjectsOfType<SaveableNetworkBehaviour>(); SaveableObject[] array3 = array; for (int i = 0; i < array3.Length; i++) { array3[i].SaveObjectData(); } SaveableNetworkBehaviour[] array4 = array2; for (int i = 0; i < array4.Length; i++) { array4[i].SaveObjectData(); } ES3.Save<List<string>>("LethalLibItemSaveKeys", saveKeys, GameNetworkManager.Instance.currentSaveFileName); } private static void GameNetworkManager_ResetSavedGameValues(orig_ResetSavedGameValues orig, GameNetworkManager self) { orig.Invoke(self); foreach (string saveKey in saveKeys) { ES3.DeleteKey(saveKey, GameNetworkManager.Instance.currentSaveFileName); } saveKeys.Clear(); } public static void SaveObjectData<T>(string key, T data, int objectId) { List<T> list = new List<T>(); if (ES3.KeyExists("LethalThingsSave_" + key, GameNetworkManager.Instance.currentSaveFileName)) { list = ES3.Load<List<T>>("LethalThingsSave_" + key, GameNetworkManager.Instance.currentSaveFileName); } List<int> list2 = new List<int>(); if (ES3.KeyExists("LethalThingsSave_objectIds_" + key, GameNetworkManager.Instance.currentSaveFileName)) { list2 = ES3.Load<List<int>>("LethalThingsSave_objectIds_" + key, GameNetworkManager.Instance.currentSaveFileName); } list.Add(data); list2.Add(objectId); if (!saveKeys.Contains("LethalThingsSave_" + key)) { saveKeys.Add("LethalThingsSave_" + key); } if (!saveKeys.Contains("LethalThingsSave_objectIds_" + key)) { saveKeys.Add("LethalThingsSave_objectIds_" + key); } ES3.Save<List<T>>("LethalThingsSave_" + key, list, GameNetworkManager.Instance.currentSaveFileName); ES3.Save<List<int>>("LethalThingsSave_objectIds_" + key, list2, GameNetworkManager.Instance.currentSaveFileName); } public static T LoadObjectData<T>(string key, int objectId) { List<T> list = new List<T>(); if (ES3.KeyExists("LethalThingsSave_" + key, GameNetworkManager.Instance.currentSaveFileName)) { list = ES3.Load<List<T>>("LethalThingsSave_" + key, GameNetworkManager.Instance.currentSaveFileName); } List<int> list2 = new List<int>(); if (ES3.KeyExists("LethalThingsSave_objectIds_" + key, GameNetworkManager.Instance.currentSaveFileName)) { list2 = ES3.Load<List<int>>("LethalThingsSave_objectIds_" + key, GameNetworkManager.Instance.currentSaveFileName); } if (!saveKeys.Contains("LethalThingsSave_" + key)) { saveKeys.Add("LethalThingsSave_" + key); } if (!saveKeys.Contains("LethalThingsSave_objectIds_" + key)) { saveKeys.Add("LethalThingsSave_objectIds_" + key); } if (list2.Contains(objectId)) { int index = list2.IndexOf(objectId); return list[index]; } return default(T); } } } namespace LethalThings { public class Config { public static ConfigEntry<int> arsonSpawnWeight; public static ConfigEntry<int> dirtyArsonSpawnWeight; public static ConfigEntry<int> toimariSpawnWeight; public static ConfigEntry<int> hamisSpawnWeight; public static ConfigEntry<int> cookieSpawnWeight; public static ConfigEntry<int> maxwellSpawnWeight; public static ConfigEntry<float> evilMaxwellChance; public static ConfigEntry<bool> maxwellPlayMusicDefault; public static ConfigEntry<int> glizzySpawnChance; public static ConfigEntry<int> revolverSpawnChance; public static ConfigEntry<int> gremlinSodaSpawnChance; public static ConfigEntry<bool> toyHammerEnabled; public static ConfigEntry<int> toyHammerPrice; public static ConfigEntry<bool> pouchyBeltEnabled; public static ConfigEntry<int> pouchyBeltPrice; public static ConfigEntry<bool> remoteRadarEnabled; public static ConfigEntry<int> remoteRadarPrice; public static ConfigEntry<bool> rocketLauncherEnabled; public static ConfigEntry<int> rocketLauncherPrice; public static ConfigEntry<bool> hackingToolEnabled; public static ConfigEntry<int> hackingToolPrice; public static ConfigEntry<bool> flareGunEnabled; public static ConfigEntry<int> flareGunPrice; public static ConfigEntry<int> flareGunAmmoPrice; public static ConfigEntry<int> boombaSpawnWeight; public static ConfigEntry<bool> rugsEnabled; public static ConfigEntry<int> smallRugPrice; public static ConfigEntry<int> largeRugPrice; public static ConfigEntry<bool> fatalitiesSignEnabled; public static ConfigEntry<int> fatalitiesSignPrice; public static ConfigEntry<bool> dartBoardEnabled; public static ConfigEntry<int> dartBoardPrice; public static ConfigEntry<bool> teleporterTrapsEnabled; public static ConfigEntry<bool> enableItemChargerElectrocution; public static ConfigEntry<int> itemChargerElectrocutionDamage; public static ConfigEntry<bool> disableOverlappingModContent; public static ConfigFile VolumeConfig; public static ConfigEntry<string> version; public static void Load() { //IL_04ae: Unknown result type (might be due to invalid IL or missing references) //IL_04b8: Expected O, but got Unknown arsonSpawnWeight = Plugin.config.Bind<int>("Scrap", "Arson", 5, "How much does Arson spawn, higher = more common"); dirtyArsonSpawnWeight = Plugin.config.Bind<int>("Scrap", "DirtyArson", 5, "How much does Arson (Dirty) spawn, higher = more common"); toimariSpawnWeight = Plugin.config.Bind<int>("Scrap", "Toimari", 10, "How much does Toimari spawn, higher = more common"); hamisSpawnWeight = Plugin.config.Bind<int>("Scrap", "Hamis", 10, "How much does Hamis spawn, higher = more common"); cookieSpawnWeight = Plugin.config.Bind<int>("Scrap", "Cookie", 10, "How much does Cookie spawn, higher = more common"); maxwellSpawnWeight = Plugin.config.Bind<int>("Scrap", "Maxwell", 3, "How much does Maxwell spawn, higher = more common"); evilMaxwellChance = Plugin.config.Bind<float>("Scrap", "MaxwellEvilChance", 10f, "Chance for maxwell to be evil, percentage."); maxwellPlayMusicDefault = Plugin.config.Bind<bool>("Scrap", "MaxwellPlayMusicDefault", true, "Does Maxwell play music by default?"); glizzySpawnChance = Plugin.config.Bind<int>("Scrap", "GlizzySpawnChance", 5, "How much do glizzies spawn, higher = more common"); revolverSpawnChance = Plugin.config.Bind<int>("Scrap", "Revolver", 10, "How much do revolvers spawn, higher = more common"); gremlinSodaSpawnChance = Plugin.config.Bind<int>("Scrap", "GremlinEnergyDrink", 10, "How much does Gremlin Energy Drink spawn, higher = more common"); toyHammerEnabled = Plugin.config.Bind<bool>("Items", "ToyHammer", true, "Is Toy Hammer enabled?"); toyHammerPrice = Plugin.config.Bind<int>("Items", "ToyHammerPrice", 15, "How much does Toy Hammer cost?"); pouchyBeltEnabled = Plugin.config.Bind<bool>("Items", "PouchyBelt", true, "Is Pouchy Belt enabled?"); pouchyBeltPrice = Plugin.config.Bind<int>("Items", "PouchyBeltPrice", 290, "How much does Pouchy Belt cost?"); remoteRadarEnabled = Plugin.config.Bind<bool>("Items", "RemoteRadar", true, "Is Remote Radar enabled?"); remoteRadarPrice = Plugin.config.Bind<int>("Items", "RemoteRadarPrice", 150, "How much does Remote Radar cost?"); rocketLauncherEnabled = Plugin.config.Bind<bool>("Items", "RocketLauncher", true, "Is Rocket Launcher enabled?"); rocketLauncherPrice = Plugin.config.Bind<int>("Items", "RocketLauncherPrice", 300, "How much does Rocket Launcher cost?"); hackingToolEnabled = Plugin.config.Bind<bool>("Items", "HackingTool", true, "Is Hacking Tool enabled?"); hackingToolPrice = Plugin.config.Bind<int>("Items", "HackingToolPrice", 120, "How much does Hacking Tool cost?"); flareGunEnabled = Plugin.config.Bind<bool>("Items", "FlareGun", true, "Is Flare Gun enabled?"); flareGunPrice = Plugin.config.Bind<int>("Items", "FlareGunPrice", 100, "How much does Flare Gun cost?"); flareGunAmmoPrice = Plugin.config.Bind<int>("Items", "FlareGunAmmoPrice", 20, "How much does Flare Gun ammo cost?"); boombaSpawnWeight = Plugin.config.Bind<int>("Enemies", "Boomba", 20, "How much does Boomba spawn, higher = more common"); rugsEnabled = Plugin.config.Bind<bool>("Decor", "Rugs", true, "Are rugs enabled?"); smallRugPrice = Plugin.config.Bind<int>("Decor", "SmallRugPrice", 80, "How much does a small rug cost?"); largeRugPrice = Plugin.config.Bind<int>("Decor", "LargeRugPrice", 110, "How much does a large rug cost?"); fatalitiesSignEnabled = Plugin.config.Bind<bool>("Decor", "FatalitiesSign", true, "Is Fatalities Sign enabled?"); fatalitiesSignPrice = Plugin.config.Bind<int>("Decor", "FatalitiesSignPrice", 100, "How much does Fatalities Sign cost?"); dartBoardEnabled = Plugin.config.Bind<bool>("Decor", "DartBoard", true, "Is Dart Board enabled?"); dartBoardPrice = Plugin.config.Bind<int>("Decor", "DartBoardPrice", 120, "How much does Dart Board cost?"); teleporterTrapsEnabled = Plugin.config.Bind<bool>("Traps", "TeleporterTraps", true, "Are teleporter traps enabled?"); enableItemChargerElectrocution = Plugin.config.Bind<bool>("Misc", "EnableItemChargerElectrocution", true, "Do players get electrocuted when stuffing conductive objects in the item charger."); itemChargerElectrocutionDamage = Plugin.config.Bind<int>("Misc", "ItemChargerElectrocutionDamage", 20, "How much damage does the item charger electrocution do."); disableOverlappingModContent = Plugin.config.Bind<bool>("Misc", "DisableOverlappingModContent", true, "Disable content from other mods which exists in this one (e.g. maxwell)."); version = Plugin.config.Bind<string>("Misc", "Version", "1.0.0", "Version of the mod config."); VolumeConfig = new ConfigFile(Paths.ConfigPath + "\\LethalThings.AudioVolume.cfg", true); } } public class Content { public class CustomItem { public string name = ""; public string itemPath = ""; public string infoPath = ""; public Action<Item> itemAction = delegate { }; public bool enabled = true; public CustomItem(string name, string itemPath, string infoPath, Action<Item> action = null) { this.name = name; this.itemPath = itemPath; this.infoPath = infoPath; if (action != null) { itemAction = action; } } public static CustomItem Add(string name, string itemPath, string infoPath = null, Action<Item> action = null) { return new CustomItem(name, itemPath, infoPath, action); } } public class CustomUnlockable { public string name = ""; public string unlockablePath = ""; public string infoPath = ""; public Action<UnlockableItem> unlockableAction = delegate { }; public bool enabled = true; public int unlockCost = -1; public CustomUnlockable(string name, string unlockablePath, string infoPath, Action<UnlockableItem> action = null, int unlockCost = -1) { this.name = name; this.unlockablePath = unlockablePath; this.infoPath = infoPath; if (action != null) { unlockableAction = action; } this.unlockCost = unlockCost; } public static CustomUnlockable Add(string name, string unlockablePath, string infoPath = null, Action<UnlockableItem> action = null, int unlockCost = -1, bool enabled = true) { return new CustomUnlockable(name, unlockablePath, infoPath, action, unlockCost) { enabled = enabled }; } } public class CustomShopItem : CustomItem { public int itemPrice; public CustomShopItem(string name, string itemPath, string infoPath = null, int itemPrice = 0, Action<Item> action = null) : base(name, itemPath, infoPath, action) { this.itemPrice = itemPrice; } public static CustomShopItem Add(string name, string itemPath, string infoPath = null, int itemPrice = 0, Action<Item> action = null, bool enabled = true) { return new CustomShopItem(name, itemPath, infoPath, itemPrice, action) { enabled = enabled }; } } public class CustomScrap : CustomItem { public LevelTypes levelType = (LevelTypes)510; public int rarity; public CustomScrap(string name, string itemPath, LevelTypes levelType, int rarity, Action<Item> action = null) : base(name, itemPath, null, action) { //IL_0006: 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_0018: Unknown result type (might be due to invalid IL or missing references) this.levelType = levelType; this.rarity = rarity; } public static CustomScrap Add(string name, string itemPath, LevelTypes levelType, int rarity, Action<Item> action = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return new CustomScrap(name, itemPath, levelType, rarity, action); } } public class CustomPlainItem : CustomItem { public CustomPlainItem(string name, string itemPath, Action<Item> action = null) : base(name, itemPath, null, action) { } public static CustomPlainItem Add(string name, string itemPath, Action<Item> action = null) { return new CustomPlainItem(name, itemPath, action); } } public class CustomEnemy { public string name; public string enemyPath; public int rarity; public LevelTypes levelFlags; public SpawnType spawnType; public string infoKeyword; public string infoNode; public bool enabled = true; public CustomEnemy(string name, string enemyPath, int rarity, LevelTypes levelFlags, SpawnType spawnType, string infoKeyword, string infoNode) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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) this.name = name; this.enemyPath = enemyPath; this.rarity = rarity; this.levelFlags = levelFlags; this.spawnType = spawnType; this.infoKeyword = infoKeyword; this.infoNode = infoNode; } public static CustomEnemy Add(string name, string enemyPath, int rarity, LevelTypes levelFlags, SpawnType spawnType, string infoKeyword, string infoNode, bool enabled = true) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) return new CustomEnemy(name, enemyPath, rarity, levelFlags, spawnType, infoKeyword, infoNode) { enabled = enabled }; } } public class CustomMapObject { public string name; public string objectPath; public LevelTypes levelFlags; public Func<SelectableLevel, AnimationCurve> spawnRateFunction; public bool enabled = true; public CustomMapObject(string name, string objectPath, LevelTypes levelFlags, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, bool enabled = false) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) this.name = name; this.objectPath = objectPath; this.levelFlags = levelFlags; this.spawnRateFunction = spawnRateFunction; this.enabled = enabled; } public static CustomMapObject Add(string name, string objectPath, LevelTypes levelFlags, Func<SelectableLevel, AnimationCurve> spawnRateFunction = null, bool enabled = false) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return new CustomMapObject(name, objectPath, levelFlags, spawnRateFunction, enabled); } } public static AssetBundle MainAssets; public static Dictionary<string, GameObject> Prefabs = new Dictionary<string, GameObject>(); public static GameObject devMenuPrefab; public static List<CustomUnlockable> customUnlockables; public static List<CustomItem> customItems; public static List<CustomEnemy> customEnemies; public static List<CustomMapObject> customMapObjects; public static GameObject ConfigManagerPrefab; public static void TryLoadAssets() { if ((Object)(object)MainAssets == (Object)null) { MainAssets = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "lethalthings")); Plugin.logger.LogInfo((object)"Loaded asset bundle"); } } public static void Load() { //IL_0583: Unknown result type (might be due to invalid IL or missing references) //IL_070f: Unknown result type (might be due to invalid IL or missing references) //IL_0716: Unknown result type (might be due to invalid IL or missing references) //IL_07a5: Unknown result type (might be due to invalid IL or missing references) TryLoadAssets(); customItems = new List<CustomItem> { CustomScrap.Add("Arson", "Assets/Custom/LethalThings/Scrap/Arson/ArsonPlush.asset", (LevelTypes)510, Config.arsonSpawnWeight.Value), CustomScrap.Add("Cookie", "Assets/Custom/LethalThings/Scrap/Cookie/CookieFumo.asset", (LevelTypes)510, Config.cookieSpawnWeight.Value), CustomScrap.Add("Bilka", "Assets/Custom/LethalThings/Scrap/Toimari/ToimariPlush.asset", (LevelTypes)510, Config.toimariSpawnWeight.Value), CustomScrap.Add("Hamis", "Assets/Custom/LethalThings/Scrap/Hamis/HamisPlush.asset", (LevelTypes)510, Config.hamisSpawnWeight.Value), CustomScrap.Add("ArsonDirty", "Assets/Custom/LethalThings/Scrap/Arson/ArsonPlushDirty.asset", (LevelTypes)510, Config.dirtyArsonSpawnWeight.Value), CustomScrap.Add("Maxwell", "Assets/Custom/LethalThings/Scrap/Maxwell/Dingus.asset", (LevelTypes)510, Config.maxwellSpawnWeight.Value), CustomScrap.Add("Glizzy", "Assets/Custom/LethalThings/Scrap/glizzy/glizzy.asset", (LevelTypes)510, Config.glizzySpawnChance.Value), CustomScrap.Add("Revolver", "Assets/Custom/LethalThings/Scrap/Flaggun/Toygun.asset", (LevelTypes)510, Config.revolverSpawnChance.Value), CustomShopItem.Add("RocketLauncher", "Assets/Custom/LethalThings/Items/RocketLauncher/RocketLauncher.asset", "Assets/Custom/LethalThings/Items/RocketLauncher/RocketLauncherInfo.asset", Config.rocketLauncherPrice.Value, delegate(Item item) { NetworkPrefabs.RegisterNetworkPrefab(item.spawnPrefab.GetComponent<RocketLauncher>().missilePrefab); }, Config.rocketLauncherEnabled.Value), CustomShopItem.Add("Flaregun", "Assets/Custom/LethalThings/Items/Flaregun/Flaregun.asset", "Assets/Custom/LethalThings/Items/Flaregun/FlaregunInfo.asset", Config.flareGunPrice.Value, delegate(Item item) { NetworkPrefabs.RegisterNetworkPrefab(item.spawnPrefab.GetComponent<ProjectileWeapon>().projectilePrefab); }, Config.flareGunEnabled.Value), CustomShopItem.Add("FlaregunAmmo", "Assets/Custom/LethalThings/Items/Flaregun/FlaregunAmmo.asset", "Assets/Custom/LethalThings/Items/Flaregun/FlaregunAmmoInfo.asset", Config.flareGunAmmoPrice.Value, null, Config.flareGunEnabled.Value), CustomShopItem.Add("ToyHammer", "Assets/Custom/LethalThings/Items/ToyHammer/ToyHammer.asset", "Assets/Custom/LethalThings/Items/ToyHammer/ToyHammerInfo.asset", Config.toyHammerPrice.Value, null, Config.toyHammerEnabled.Value), CustomShopItem.Add("RemoteRadar", "Assets/Custom/LethalThings/Items/Radar/HandheldRadar.asset", "Assets/Custom/LethalThings/Items/Radar/HandheldRadarInfo.asset", Config.remoteRadarPrice.Value, null, Config.remoteRadarEnabled.Value), CustomShopItem.Add("PouchyBelt", "Assets/Custom/LethalThings/Items/Pouch/Pouch.asset", "Assets/Custom/LethalThings/Items/Pouch/PouchInfo.asset", Config.pouchyBeltPrice.Value, null, Config.pouchyBeltEnabled.Value), CustomShopItem.Add("HackingTool", "Assets/Custom/LethalThings/Items/HackingTool/HackingTool.asset", "Assets/Custom/LethalThings/Items/HackingTool/HackingToolInfo.asset", Config.hackingToolPrice.Value, null, Config.hackingToolEnabled.Value), CustomPlainItem.Add("Dart", "Assets/Custom/LethalThings/Unlockables/dartboard/Dart.asset"), CustomScrap.Add("GremlinEnergy", "Assets/Custom/LethalThings/Scrap/GremlinEnergy/GremlinEnergy.asset", (LevelTypes)510, Config.gremlinSodaSpawnChance.Value) }; customEnemies = new List<CustomEnemy> { CustomEnemy.Add("Boomba", "Assets/Custom/LethalThings/Enemies/Roomba/Boomba.asset", Config.boombaSpawnWeight.Value, (LevelTypes)510, (SpawnType)0, null, "Assets/Custom/LethalThings/Enemies/Roomba/BoombaFile.asset") }; customUnlockables = new List<CustomUnlockable> { CustomUnlockable.Add("SmallRug", "Assets/Custom/LethalThings/Unlockables/Rug/SmallRug.asset", "Assets/Custom/LethalThings/Unlockables/Rug/RugInfo.asset", null, Config.smallRugPrice.Value, Config.rugsEnabled.Value), CustomUnlockable.Add("LargeRug", "Assets/Custom/LethalThings/Unlockables/Rug/LargeRug.asset", "Assets/Custom/LethalThings/Unlockables/Rug/RugInfo.asset", null, Config.largeRugPrice.Value, Config.rugsEnabled.Value), CustomUnlockable.Add("FatalitiesSign", "Assets/Custom/LethalThings/Unlockables/Sign/Sign.asset", "Assets/Custom/LethalThings/Unlockables/Sign/SignInfo.asset", null, Config.fatalitiesSignPrice.Value, Config.fatalitiesSignEnabled.Value), CustomUnlockable.Add("Dartboard", "Assets/Custom/LethalThings/Unlockables/dartboard/Dartboard.asset", "Assets/Custom/LethalThings/Unlockables/dartboard/DartboardInfo.asset", null, Config.dartBoardPrice.Value, Config.dartBoardEnabled.Value) }; customMapObjects = new List<CustomMapObject> { CustomMapObject.Add("TeleporterTrap", "Assets/Custom/LethalThings/hazards/TeleporterTrap/TeleporterTrap.asset", (LevelTypes)510, (SelectableLevel level) => new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, 0f), new Keyframe(1f, 4f) }), Config.teleporterTrapsEnabled.Value) }; foreach (CustomItem customItem in customItems) { if (customItem.enabled) { Item val = MainAssets.LoadAsset<Item>(customItem.itemPath); if ((Object)(object)val.spawnPrefab.GetComponent<NetworkTransform>() == (Object)null && (Object)(object)val.spawnPrefab.GetComponent<CustomNetworkTransform>() == (Object)null) { NetworkTransform obj = val.spawnPrefab.AddComponent<NetworkTransform>(); obj.SlerpPosition = false; obj.Interpolate = false; obj.SyncPositionX = false; obj.SyncPositionY = false; obj.SyncPositionZ = false; obj.SyncScaleX = false; obj.SyncScaleY = false; obj.SyncScaleZ = false; obj.UseHalfFloatPrecision = true; } Prefabs.Add(customItem.name, val.spawnPrefab); NetworkPrefabs.RegisterNetworkPrefab(val.spawnPrefab); customItem.itemAction(val); if (customItem is CustomShopItem) { TerminalNode val2 = MainAssets.LoadAsset<TerminalNode>(customItem.infoPath); Plugin.logger.LogInfo((object)$"Registering shop item {customItem.name} with price {((CustomShopItem)customItem).itemPrice}"); Items.RegisterShopItem(val, (TerminalNode)null, (TerminalNode)null, val2, ((CustomShopItem)customItem).itemPrice); } else if (customItem is CustomScrap) { Items.RegisterScrap(val, ((CustomScrap)customItem).rarity, ((CustomScrap)customItem).levelType); } else if (customItem is CustomPlainItem) { Items.RegisterItem(val); } } } foreach (CustomUnlockable customUnlockable in customUnlockables) { if (customUnlockable.enabled) { UnlockableItem unlockable = MainAssets.LoadAsset<UnlockableItemDef>(customUnlockable.unlockablePath).unlockable; if ((Object)(object)unlockable.prefabObject != (Object)null) { NetworkPrefabs.RegisterNetworkPrefab(unlockable.prefabObject); } Prefabs.Add(customUnlockable.name, unlockable.prefabObject); TerminalNode val3 = null; if (customUnlockable.infoPath != null) { val3 = MainAssets.LoadAsset<TerminalNode>(customUnlockable.infoPath); } Unlockables.RegisterUnlockable(unlockable, (StoreType)2, (TerminalNode)null, (TerminalNode)null, val3, customUnlockable.unlockCost); } } foreach (CustomEnemy customEnemy in customEnemies) { if (customEnemy.enabled) { EnemyType val4 = MainAssets.LoadAsset<EnemyType>(customEnemy.enemyPath); TerminalNode val5 = MainAssets.LoadAsset<TerminalNode>(customEnemy.infoNode); TerminalKeyword val6 = null; if (customEnemy.infoKeyword != null) { val6 = MainAssets.LoadAsset<TerminalKeyword>(customEnemy.infoKeyword); } NetworkPrefabs.RegisterNetworkPrefab(val4.enemyPrefab); Prefabs.Add(customEnemy.name, val4.enemyPrefab); Enemies.RegisterEnemy(val4, customEnemy.rarity, customEnemy.levelFlags, customEnemy.spawnType, val5, val6); } } foreach (CustomMapObject customMapObject in customMapObjects) { if (customMapObject.enabled) { SpawnableMapObjectDef val7 = MainAssets.LoadAsset<SpawnableMapObjectDef>(customMapObject.objectPath); NetworkPrefabs.RegisterNetworkPrefab(val7.spawnableMapObject.prefabToSpawn); Prefabs.Add(customMapObject.name, val7.spawnableMapObject.prefabToSpawn); MapObjects.RegisterMapObject(val7, customMapObject.levelFlags, customMapObject.spawnRateFunction); } } foreach (KeyValuePair<string, GameObject> prefab in Prefabs) { GameObject value = prefab.Value; string key = prefab.Key; AudioSource[] componentsInChildren = value.GetComponentsInChildren<AudioSource>(); if (componentsInChildren.Length != 0) { ConfigEntry<float> val8 = Config.VolumeConfig.Bind<float>("Volume", key ?? "", 100f, "Audio volume for " + key + " (0 - 100)"); AudioSource[] array = componentsInChildren; foreach (AudioSource obj2 in array) { obj2.volume *= val8.Value / 100f; } } } GameObject obj3 = MainAssets.LoadAsset<GameObject>("Assets/Custom/LethalThings/DevMenu.prefab"); NetworkPrefabs.RegisterNetworkPrefab(obj3); devMenuPrefab = obj3; try { foreach (Type loadableType in Assembly.GetExecutingAssembly().GetLoadableTypes()) { MethodInfo[] methods = loadableType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0) { methodInfo.Invoke(null, null); } } } } catch (Exception) { } Plugin.logger.LogInfo((object)"Custom content loaded!"); } } public static class InputCompat { public static InputActionAsset Asset; public static bool Enabled => Chainloader.PluginInfos.ContainsKey("com.rune580.LethalCompanyInputUtils"); public static InputAction LTUtilityBeltQuick1 => Keybinds.Instance.LTUtilityBeltQuick1; public static InputAction LTUtilityBeltQuick2 => Keybinds.Instance.LTUtilityBeltQuick2; public static InputAction LTUtilityBeltQuick3 => Keybinds.Instance.LTUtilityBeltQuick3; public static InputAction LTUtilityBeltQuick4 => Keybinds.Instance.LTUtilityBeltQuick4; public static void Init() { Keybinds.Instance = new Keybinds(); Asset = Keybinds.Instance.GetAsset(); } } public class Keybinds : LcInputActions { public static Keybinds Instance; [InputAction("", Name = "[LT] Utility Belt Quick 1")] public InputAction LTUtilityBeltQuick1 { get; set; } [InputAction("", Name = "[LT] Utility Belt Quick 2")] public InputAction LTUtilityBeltQuick2 { get; set; } [InputAction("", Name = "[LT] Utility Belt Quick 3")] public InputAction LTUtilityBeltQuick3 { get; set; } [InputAction("", Name = "[LT] Utility Belt Quick 4")] public InputAction LTUtilityBeltQuick4 { get; set; } public InputActionAsset GetAsset() { return ((LcInputActions)this).Asset; } } public class Dingus : SaveableObject { public AudioSource noiseAudio; public AudioSource noiseAudioFar; public AudioSource musicAudio; public AudioSource musicAudioFar; [Space(3f)] public AudioClip[] noiseSFX; public AudioClip[] noiseSFXFar; public AudioClip evilNoise; [Space(3f)] public float noiseRange; public float maxLoudness; public float minLoudness; public float minPitch; public float maxPitch; private Random noisemakerRandom; public Animator triggerAnimator; private int timesPlayedWithoutTurningOff; private RoundManager roundManager; private float noiseInterval = 1f; public Animator danceAnimator; public bool wasLoadedFromSave; public bool exploding; private NetworkVariable<bool> isEvil = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public GameObject evilObject; public NetworkVariable<bool> isPlayingMusic = new NetworkVariable<bool>(Config.maxwellPlayMusicDefault.Value, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)1); public NetworkVariable<bool> isPipebomb = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public override void SaveObjectData() { SaveData.SaveObjectData("dingusBeEvil", isEvil.Value, uniqueId); } public override void LoadObjectData() { if (((NetworkBehaviour)this).IsHost) { bool flag = SaveData.LoadObjectData<bool>("dingusBeEvil", uniqueId); if (flag) { isEvil.Value = flag; } } } public override void Start() { ((GrabbableObject)this).Start(); roundManager = Object.FindObjectOfType<RoundManager>(); noisemakerRandom = new Random(StartOfRound.Instance.randomMapSeed + 85); Debug.Log((object)"Making the dingus dance"); } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); if (((NetworkBehaviour)this).IsOwner) { isPlayingMusic.Value = Config.maxwellPlayMusicDefault.Value; } if (((NetworkBehaviour)this).IsHost) { isEvil.Value = Random.Range(0f, 100f) <= Config.evilMaxwellChance.Value; } } public override void ItemActivate(bool used, bool buttonDown = true) { //IL_0117: Unknown result type (might be due to invalid IL or missing references) ((GrabbableObject)this).ItemActivate(used, buttonDown); if (!((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)) { int num = noisemakerRandom.Next(0, noiseSFX.Length); float num2 = (float)noisemakerRandom.Next((int)(minLoudness * 100f), (int)(maxLoudness * 100f)) / 100f; float pitch = (float)noisemakerRandom.Next((int)(minPitch * 100f), (int)(maxPitch * 100f)) / 100f; noiseAudio.pitch = pitch; noiseAudio.PlayOneShot(noiseSFX[num], num2); if ((Object)(object)noiseAudioFar != (Object)null) { noiseAudioFar.pitch = pitch; noiseAudioFar.PlayOneShot(noiseSFXFar[num], num2); } if ((Object)(object)triggerAnimator != (Object)null) { triggerAnimator.SetTrigger("playAnim"); } WalkieTalkie.TransmitOneShotAudio(noiseAudio, noiseSFX[num], num2); RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, noiseRange, num2, 0, ((GrabbableObject)this).isInElevator && StartOfRound.Instance.hangarDoorsClosed, 0); } } public override void DiscardItem() { if ((Object)(object)((GrabbableObject)this).playerHeldBy != (Object)null) { ((GrabbableObject)this).playerHeldBy.equippedUsableItemQE = false; } ((GrabbableObject)this).isBeingUsed = false; ((GrabbableObject)this).DiscardItem(); } public override void EquipItem() { ((GrabbableObject)this).EquipItem(); ((GrabbableObject)this).playerHeldBy.equippedUsableItemQE = true; danceAnimator.Play("dingusIdle"); Debug.Log((object)"Making the dingus idle"); } public override void ItemInteractLeftRight(bool right) { ((GrabbableObject)this).ItemInteractLeftRight(right); if (!right && ((NetworkBehaviour)this).IsOwner) { isPlayingMusic.Value = !isPlayingMusic.Value; } } public override void InteractItem() { ((GrabbableObject)this).InteractItem(); if (isEvil.Value && !exploding && !isPipebomb.Value) { EvilMaxwellServerRpc(); } } public void EvilMaxwellTruly() { danceAnimator.Play("dingusIdle"); if (musicAudio.isPlaying) { musicAudio.Pause(); musicAudioFar.Pause(); } ((MonoBehaviour)this).StartCoroutine(evilMaxwellMoment()); } [ServerRpc(RequireOwnership = false)] public void EvilMaxwellServerRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(88404199u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 88404199u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { isPipebomb.Value = true; EvilMaxwellClientRpc(); } } } [ClientRpc] public void EvilMaxwellClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1120322383u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1120322383u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { EvilMaxwellTruly(); exploding = true; if (((NetworkBehaviour)this).IsOwner) { isPlayingMusic.Value = false; } timesPlayedWithoutTurningOff = 0; danceAnimator.Play("dingusIdle"); if (musicAudio.isPlaying) { musicAudio.Pause(); musicAudioFar.Pause(); } Plugin.logger.LogInfo((object)"Evil maxwell moment"); } } public IEnumerator evilMaxwellMoment() { yield return (object)new WaitForSeconds(1f); noiseAudio.PlayOneShot(evilNoise, 1f); evilObject.SetActive(true); ((Renderer)((GrabbableObject)this).mainObjectRenderer).enabled = false; if ((Object)(object)noiseAudioFar != (Object)null) { noiseAudioFar.PlayOneShot(evilNoise, 1f); } if ((Object)(object)triggerAnimator != (Object)null) { triggerAnimator.SetTrigger("playAnim"); } WalkieTalkie.TransmitOneShotAudio(noiseAudio, evilNoise, 1f); RoundManager.Instance.PlayAudibleNoise(((Component)this).transform.position, noiseRange, 1f, 0, ((GrabbableObject)this).isInElevator && StartOfRound.Instance.hangarDoorsClosed, 0); yield return (object)new WaitForSeconds(1.5f); Utilities.CreateExplosion(((Component)this).transform.position, spawnExplosionEffect: true, 100, 0f, 6.4f, 6, (CauseOfDeath)3); Rigidbody[] componentsInChildren = evilObject.GetComponentsInChildren<Rigidbody>(); foreach (Rigidbody obj in componentsInChildren) { obj.isKinematic = false; obj.AddExplosionForce(1000f, evilObject.transform.position, 100f); } yield return (object)new WaitForSeconds(2f); if (((NetworkBehaviour)this).IsServer) { ((Component)this).GetComponent<NetworkObject>().Despawn(true); } } public override void Update() { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) ((GrabbableObject)this).Update(); if (isEvil.Value) { ((GrabbableObject)this).grabbable = false; ((GrabbableObject)this).grabbableToEnemies = false; } if (isPlayingMusic.Value && !exploding) { if (!musicAudio.isPlaying) { musicAudio.Play(); musicAudioFar.Play(); } if (!((GrabbableObject)this).isHeld) { danceAnimator.Play("dingusDance"); } else { danceAnimator.Play("dingusIdle"); } if (noiseInterval <= 0f) { noiseInterval = 1f; timesPlayedWithoutTurningOff++; roundManager.PlayAudibleNoise(((Component)this).transform.position, 16f, 0.9f, timesPlayedWithoutTurningOff, false, 5); } else { noiseInterval -= Time.deltaTime; } } else { timesPlayedWithoutTurningOff = 0; danceAnimator.Play("dingusIdle"); if (musicAudio.isPlaying) { musicAudio.Pause(); musicAudioFar.Pause(); } } } protected override void __initializeVariables() { if (isEvil == null) { throw new Exception("Dingus.isEvil cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)isEvil).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)isEvil, "isEvil"); ((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)isEvil); if (isPlayingMusic == null) { throw new Exception("Dingus.isPlayingMusic cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)isPlayingMusic).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)isPlayingMusic, "isPlayingMusic"); ((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)isPlayingMusic); if (isPipebomb == null) { throw new Exception("Dingus.isPipebomb cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)isPipebomb).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)isPipebomb, "isPipebomb"); ((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)isPipebomb); base.__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_Dingus() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(88404199u, new RpcReceiveHandler(__rpc_handler_88404199)); NetworkManager.__rpc_func_table.Add(1120322383u, new RpcReceiveHandler(__rpc_handler_1120322383)); } private static void __rpc_handler_88404199(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)1; ((Dingus)(object)target).EvilMaxwellServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1120322383(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)2; ((Dingus)(object)target).EvilMaxwellClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "Dingus"; } } public class Missile : NetworkBehaviour { public int damage = 50; public float maxDistance = 10f; public float minDistance; public float gravity = 2.4f; public float flightDelay = 0.5f; public float flightForce = 150f; public float flightTime = 2f; public float autoDestroyTime = 3f; private float timeAlive; public float LobForce = 100f; public ParticleSystem particleSystem; private void OnCollisionEnter(Collision collision) { if (((NetworkBehaviour)this).IsHost) { Boom(); BoomClientRpc(); } else { BoomServerRpc(); } } private void Start() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) ((Component)this).GetComponent<Rigidbody>().useGravity = false; if (((NetworkBehaviour)this).IsHost) { ((Component)this).GetComponent<Rigidbody>().AddForce(((Component)this).transform.forward * LobForce, (ForceMode)1); } } [ClientRpc] public void BoomClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3331368301u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3331368301u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Boom(); } } } [ServerRpc] public void BoomServerRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Invalid comparison between Unknown and I4 //IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: 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_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(452316787u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 452316787u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Boom(); BoomClientRpc(); } } public void CreateExplosion() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB attacker = ((IEnumerable<PlayerControllerB>)StartOfRound.Instance.allPlayerScripts).FirstOrDefault((Func<PlayerControllerB, bool>)((PlayerControllerB x) => ((NetworkBehaviour)x).OwnerClientId == ((NetworkBehaviour)this).OwnerClientId)); Utilities.CreateExplosion(((Component)this).transform.position, spawnExplosionEffect: true, damage, minDistance, maxDistance, 10, (CauseOfDeath)3, attacker); } public void Boom() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)particleSystem == (Object)null) { Debug.LogError((object)"No particle system set on missile, destruction time!!"); CreateExplosion(); if (((NetworkBehaviour)this).IsHost) { Object.Destroy((Object)(object)((Component)this).gameObject); } return; } particleSystem.Stop(true, (ParticleSystemStopBehavior)1); ((Component)particleSystem).transform.SetParent((Transform)null); ((Component)particleSystem).transform.localScale = Vector3.one; GameObject gameObject = ((Component)particleSystem).gameObject; MainModule main = particleSystem.main; float duration = ((MainModule)(ref main)).duration; main = particleSystem.main; MinMaxCurve startLifetime = ((MainModule)(ref main)).startLifetime; Object.Destroy((Object)(object)gameObject, duration + ((MinMaxCurve)(ref startLifetime)).constant); CreateExplosion(); if (((NetworkBehaviour)this).IsHost) { Object.Destroy((Object)(object)((Component)this).gameObject); } } private void FixedUpdate() { //IL_001d: 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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsHost) { return; } ((Component)this).GetComponent<Rigidbody>().useGravity = false; ((Component)this).GetComponent<Rigidbody>().AddForce(Vector3.down * gravity); if (timeAlive <= flightTime && timeAlive >= flightDelay) { ((Component)this).GetComponent<Rigidbody>().AddForce(((Component)this).transform.forward * flightForce); } timeAlive += Time.fixedDeltaTime; if (timeAlive > autoDestroyTime) { if (((NetworkBehaviour)this).IsHost) { Boom(); BoomClientRpc(); } else { BoomServerRpc(); } } else { Debug.Log((object)("Time alive: " + timeAlive + " / " + autoDestroyTime)); } } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_Missile() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(3331368301u, new RpcReceiveHandler(__rpc_handler_3331368301)); NetworkManager.__rpc_func_table.Add(452316787u, new RpcReceiveHandler(__rpc_handler_452316787)); } private static void __rpc_handler_3331368301(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0029: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { target.__rpc_exec_stage = (__RpcExecStage)2; ((Missile)(object)target).BoomClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_452316787(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_008c: 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_0055: Invalid comparison between Unknown and I4 NetworkManager networkManager = target.NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } } else { target.__rpc_exec_stage = (__RpcExecStage)1; ((Missile)(object)target).BoomServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "Missile"; } } public class PouchyBelt : GrabbableObject { [CompilerGenerated] private static class <>O { public static hook_SetHoverTipAndCurrentInteractTrigger <0>__PlayerControllerB_SetHoverTipAndCurrentInteractTrigger; public static hook_BeginGrabObject <1>__PlayerControllerB_BeginGrabObject; } public Transform beltCosmetic; public Vector3 beltCosmeticPositionOffset = new Vector3(0f, 0f, 0f); public Vector3 beltCosmeticRotationOffset = new Vector3(0f, 0f, 0f); public int beltCapacity = 3; private PlayerControllerB previousPlayerHeldBy; public List<int> slotIndexes = new List<int>(); public static void Initialize() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //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_003b: Expected O, but got Unknown object obj = <>O.<0>__PlayerControllerB_SetHoverTipAndCurrentInteractTrigger; if (obj == null) { hook_SetHoverTipAndCurrentInteractTrigger val = PlayerControllerB_SetHoverTipAndCurrentInteractTrigger; <>O.<0>__PlayerControllerB_SetHoverTipAndCurrentInteractTrigger = val; obj = (object)val; } PlayerControllerB.SetHoverTipAndCurrentInteractTrigger += (hook_SetHoverTipAndCurrentInteractTrigger)obj; object obj2 = <>O.<1>__PlayerControllerB_BeginGrabObject; if (obj2 == null) { hook_BeginGrabObject val2 = PlayerControllerB_BeginGrabObject; <>O.<1>__PlayerControllerB_BeginGrabObject = val2; obj2 = (object)val2; } PlayerControllerB.BeginGrabObject += (hook_BeginGrabObject)obj2; } public void Awake() { if (InputCompat.Enabled) { InputCompat.LTUtilityBeltQuick1.started += InputReceived; InputCompat.LTUtilityBeltQuick2.started += InputReceived; InputCompat.LTUtilityBeltQuick3.started += InputReceived; InputCompat.LTUtilityBeltQuick4.started += InputReceived; } } private static void PlayerControllerB_BeginGrabObject(orig_BeginGrabObject orig, PlayerControllerB self) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) self.interactRay = new Ray(((Component)self.gameplayCamera).transform.position, ((Component)self.gameplayCamera).transform.forward); if (!Physics.Raycast(self.interactRay, ref self.hit, self.grabDistance, self.interactableObjectsMask) || ((Component)((RaycastHit)(ref self.hit)).collider).gameObject.layer == 8 || !(((Component)((RaycastHit)(ref self.hit)).collider).tag == "PhysicsProp") || self.twoHanded || self.sinkingValue > 0.73f) { return; } self.currentlyGrabbingObject = ((Component)((Component)((RaycastHit)(ref self.hit)).collider).transform).gameObject.GetComponent<GrabbableObject>(); if ((!GameNetworkManager.Instance.gameHasStarted && !self.currentlyGrabbingObject.itemProperties.canBeGrabbedBeforeGameStart && ((Object)(object)StartOfRound.Instance.testRoom == (Object)null || !StartOfRound.Instance.testRoom.activeSelf)) || (Object)(object)self.currentlyGrabbingObject == (Object)null || self.inSpecialInteractAnimation || self.currentlyGrabbingObject.isHeld || self.currentlyGrabbingObject.isPocketed) { return; } NetworkObject networkObject = ((NetworkBehaviour)self.currentlyGrabbingObject).NetworkObject; if (!((Object)(object)networkObject == (Object)null) && networkObject.IsSpawned) { if (self.currentlyGrabbingObject is PouchyBelt && self.ItemSlots.Any((GrabbableObject x) => (Object)(object)x != (Object)null && x is PouchyBelt)) { self.currentlyGrabbingObject.grabbable = false; } orig.Invoke(self); if (self.currentlyGrabbingObject is PouchyBelt) { self.currentlyGrabbingObject.grabbable = true; } } } private static void PlayerControllerB_SetHoverTipAndCurrentInteractTrigger(orig_SetHoverTipAndCurrentInteractTrigger orig, PlayerControllerB self) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) orig.Invoke(self); if (!Physics.Raycast(self.interactRay, ref self.hit, self.grabDistance, self.interactableObjectsMask) || ((Component)((RaycastHit)(ref self.hit)).collider).gameObject.layer == 8 || !(((Component)((RaycastHit)(ref self.hit)).collider).tag == "PhysicsProp")) { return; } if (self.FirstEmptyItemSlot() == -1) { ((TMP_Text)self.cursorTip).text = "Inventory full!"; } else if (((Component)((RaycastHit)(ref self.hit)).collider).gameObject.GetComponent<GrabbableObject>() is PouchyBelt) { if (self.ItemSlots.Any((GrabbableObject x) => (Object)(object)x != (Object)null && x is PouchyBelt)) { ((TMP_Text)self.cursorTip).text = "(Cannot hold more than 1 belt)"; } else { ((TMP_Text)self.cursorTip).text = "Pick up belt"; } } } public void InputReceived(CallbackContext context) { if (((NetworkBehaviour)this).IsOwner && (Object)(object)base.playerHeldBy != (Object)null && ((CallbackContext)(ref context)).started) { int num = -1; if (((CallbackContext)(ref context)).action == InputCompat.LTUtilityBeltQuick1) { num = 0; } else if (((CallbackContext)(ref context)).action == InputCompat.LTUtilityBeltQuick2) { num = 1; } else if (((CallbackContext)(ref context)).action == InputCompat.LTUtilityBeltQuick3) { num = 2; } else if (((CallbackContext)(ref context)).action == InputCompat.LTUtilityBeltQuick4) { num = 3; } if (num != -1 && num < slotIndexes.Count) { base.playerHeldBy.SwitchItemSlots(slotIndexes[num]); Plugin.logger.LogInfo((object)$"Switched to slot: {slotIndexes[num]}"); } } } public override void LateUpdate() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) ((GrabbableObject)this).LateUpdate(); if ((Object)(object)previousPlayerHeldBy != (Object)null) { ((Component)beltCosmetic).gameObject.SetActive(true); beltCosmetic.SetParent((Transform)null); ((Renderer)((Component)beltCosmetic).GetComponent<MeshRenderer>()).enabled = true; if (((NetworkBehaviour)this).IsOwner) { ((Renderer)((Component)beltCosmetic).GetComponent<MeshRenderer>()).enabled = false; } Transform parent = previousPlayerHeldBy.lowerSpine.parent; beltCosmetic.position = parent.position + beltCosmeticPositionOffset; Quaternion rotation = parent.rotation; Quaternion rotation2 = Quaternion.Euler(((Quaternion)(ref rotation)).eulerAngles + beltCosmeticRotationOffset); beltCosmetic.rotation = rotation2; ((Renderer)base.mainObjectRenderer).enabled = false; ((Component)this).gameObject.SetActive(true); } else { ((Component)beltCosmetic).gameObject.SetActive(false); ((Renderer)base.mainObjectRenderer).enabled = true; beltCosmetic.SetParent(((Component)this).transform); } } public void UpdateHUD(bool add) { //IL_007d: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: 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_016b: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) slotIndexes.Clear(); HUDManager instance = HUDManager.Instance; if (add) { int num = 0; GrabbableObject[] itemSlots = GameNetworkManager.Instance.localPlayerController.ItemSlots; for (int i = 0; i < itemSlots.Length; i++) { if (itemSlots[i] is PouchyBelt) { num++; } } Image val = instance.itemSlotIconFrames[0]; Image val2 = instance.itemSlotIcons[0]; int num2 = instance.itemSlotIconFrames.Length; ((Component)val).GetComponentInParent<CanvasScaler>(); ((Component)val).GetComponentInParent<AspectRatioFitter>(); float x2 = ((Graphic)val).rectTransform.sizeDelta.x; float y = ((Graphic)val).rectTransform.sizeDelta.y; float num3 = ((Graphic)val).rectTransform.anchoredPosition.y + 1.125f * y * (float)num; Vector3 localEulerAngles = ((Transform)((Graphic)val).rectTransform).localEulerAngles; Vector3 localEulerAngles2 = ((Transform)((Graphic)val2).rectTransform).localEulerAngles; List<Image> list = instance.itemSlotIconFrames.ToList(); List<Image> list2 = instance.itemSlotIcons.ToList(); int num4 = list.FindLastIndex((Image x) => Regex.IsMatch(((Object)((Component)x).gameObject).name.ToLowerInvariant(), "\\bslot\\d\\b")); _ = beltCapacity; _ = beltCapacity; Debug.Log((object)$"Adding {beltCapacity} item slots! Surely this will go well.."); Debug.Log((object)$"Adding after index: {num4}"); for (int j = 0; j < beltCapacity; j++) { float num5 = 0f - ((Component)((Transform)((Graphic)val).rectTransform).parent).GetComponent<RectTransform>().sizeDelta.x / 2f - 3f + (float)j * x2 + (float)j * 15f; Image val3 = Object.Instantiate<Image>(list[0], ((Component)val).transform.parent); ((Object)val3).name = $"Slot{num2 + j}[LethalThingsBelt]"; ((Graphic)val3).rectTransform.anchoredPosition = new Vector2(num5, num3); ((Transform)((Graphic)val3).rectTransform).eulerAngles = localEulerAngles; Image component = ((Component)((Component)val3).transform.GetChild(0)).GetComponent<Image>(); ((Object)component).name = "icon"; ((Behaviour)component).enabled = false; ((Transform)((Graphic)component).rectTransform).eulerAngles = localEulerAngles2; ((Transform)((Graphic)component).rectTransform).Rotate(new Vector3(0f, 0f, -90f)); int num6 = num4 + j + 1; list.Insert(num6, val3); list2.Insert(num6, component); slotIndexes.Add(num6); ((Component)val3).transform.SetSiblingIndex(num6); } instance.itemSlotIconFrames = list.ToArray(); instance.itemSlotIcons = list2.ToArray(); Debug.Log((object)$"Added {beltCapacity} item slots!"); return; } List<Image> list3 = instance.itemSlotIconFrames.ToList(); List<Image> list4 = instance.itemSlotIcons.ToList(); int count = list3.Count; int num7 = 0; for (int num8 = count - 1; num8 >= 0; num8--) { if (((Object)list3[num8]).name.Contains("[LethalThingsBelt]")) { num7++; Image obj = list3[num8]; list3.RemoveAt(num8); list4.RemoveAt(num8); Object.Destroy((Object)(object)((Component)obj).gameObject); if (num7 >= beltCapacity) { break; } } } instance.itemSlotIconFrames = list3.ToArray(); instance.itemSlotIcons = list4.ToArray(); Debug.Log((object)$"Removed {beltCapacity} item slots!"); } public void AddItemSlots() { if ((Object)(object)base.playerHeldBy != (Object)null) { List<GrabbableObject> list = base.playerHeldBy.ItemSlots.ToList(); base.playerHeldBy.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[list.Count + beltCapacity]; for (int i = 0; i < list.Count; i++) { base.playerHeldBy.ItemSlots[i] = list[i]; } if ((Object)(object)base.playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController) { UpdateHUD(add: true); } } } public void RemoveItemSlots() { if (!((Object)(object)base.playerHeldBy != (Object)null)) { return; } int num = base.playerHeldBy.ItemSlots.Length - beltCapacity; int currentItemSlot = base.playerHeldBy.currentItemSlot; for (int i = 0; i < beltCapacity; i++) { GrabbableObject val = base.playerHeldBy.ItemSlots[num + i]; if ((Object)(object)val != (Object)null) { base.playerHeldBy.DropItem(val, num + i); } } int currentItemSlot2 = base.playerHeldBy.currentItemSlot; currentItemSlot2 = ((currentItemSlot < base.playerHeldBy.ItemSlots.Length) ? currentItemSlot : 0); List<GrabbableObject> list = base.playerHeldBy.ItemSlots.ToList(); base.playerHeldBy.ItemSlots = (GrabbableObject[])(object)new GrabbableObject[list.Count - beltCapacity]; for (int j = 0; j < base.playerHeldBy.ItemSlots.Length; j++) { base.playerHeldBy.ItemSlots[j] = list[j]; } if ((Object)(object)base.playerHeldBy == (Object)(object)GameNetworkManager.Instance.localPlayerController) { UpdateHUD(add: false); } base.playerHeldBy.SwitchItemSlots(currentItemSlot2); } public override void DiscardItem() { RemoveItemSlots(); previousPlayerHeldBy = null; ((GrabbableObject)this).DiscardItem(); } public override void OnNetworkDespawn() { RemoveItemSlots(); previousPlayerHeldBy = null; ((NetworkBehaviour)this).OnNetworkDespawn(); } public void GrabItemOnClient() { ((GrabbableObject)this).GrabItemOnClient(); } public override void OnDestroy() { if (InputCompat.Enabled) { InputCompat.LTUtilityBeltQuick1.started -= InputReceived; InputCompat.LTUtilityBeltQuick2.started -= InputReceived; InputCompat.LTUtilityBeltQuick3.started -= InputReceived; InputCompat.LTUtilityBeltQuick4.started -= InputReceived; } ((NetworkBehaviour)this).OnDestroy(); } public override void EquipItem() { ((GrabbableObject)this).EquipItem(); if ((Object)(object)base.playerHeldBy != (Object)null) { if ((Object)(object)base.playerHeldBy != (Object)(object)previousPlayerHeldBy) { AddItemSlots(); } previousPlayerHeldBy = base.playerHeldBy; } } protected override void __initializeVariables() { ((GrabbableObject)this).__initializeVariables(); } protected internal override string __getTypeName() { return "PouchyBelt"; } } public class PowerOutletStun : NetworkBehaviour { private Coroutine electrocutionCoroutine; public AudioSource strikeAudio; public ParticleSystem strikeParticle; private NetworkVariable<int> damage = new NetworkVariable<int>(20, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public void Electrocute(ItemCharger socket) { Debug.Log((object)"Attempting electrocution"); if (electrocutionCoroutine != null) { ((MonoBehaviour)this).StopCoroutine(electrocutionCoroutine); } electrocutionCoroutine = ((MonoBehaviour)this).StartCoroutine(electrocutionDelayed(socket)); } public void Awake() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) StormyWeather val = Object.FindObjectOfType<StormyWeather>(true); GameObject gameObject = ((Component)val.targetedStrikeAudio).gameObject; strikeAudio = Object.Instantiate<GameObject>(gameObject, ((Component)this).transform).GetComponent<AudioSource>(); ((Component)strikeAudio).transform.localPosition = Vector3.zero; ((Component)strikeAudio).gameObject.SetActive(true); strikeParticle = Object.Instantiate<GameObject>(((Component)val.explosionEffectParticle).gameObject, ((Component)this).transform).GetComponent<ParticleSystem>(); ((Component)strikeParticle).transform.localPosition = Vector3.zero; ((Component)strikeParticle).gameObject.SetActive(true); if (((NetworkBehaviour)this).IsHost) { damage.Value = Config.itemChargerElectrocutionDamage.Value; } } private IEnumerator electrocutionDelayed(ItemCharger socket) { Debug.Log((object)"Electrocution started"); socket.zapAudio.Play(); yield return (object)new WaitForSeconds(0.75f); socket.chargeStationAnimator.SetTrigger("zap"); Debug.Log((object)"Electrocution finished"); if (((NetworkBehaviour)this).NetworkObject.IsOwner && !((NetworkBehaviour)this).NetworkObject.IsOwnedByServer) { Debug.Log((object)"Sending stun to server!!"); ElectrocutedServerRpc(((Component)this).transform.position); } else if (((NetworkBehaviour)this).NetworkObject.IsOwner && ((NetworkBehaviour)this).NetworkObject.IsOwnedByServer) { Debug.Log((object)"Sending stun to clients!!"); ElectrocutedClientRpc(((Component)this).transform.position); Electrocuted(((Component)this).transform.position); } } [ClientRpc] private void ElectrocutedClientRpc(Vector3 position) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(328188188u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref position); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 328188188u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Debug.Log((object)"Stun received!!"); Electrocuted(position); } } } private void Electrocuted(Vector3 position) { //IL_0006: 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) StormyWeather obj = Object.FindObjectOfType<StormyWeather>(true); Utilities.CreateExplosion(position, spawnExplosionEffect: false, Config.itemChargerElectrocutionDamage.Value, 0f, 5f, 3, (CauseOfDeath)11); strikeParticle.Play(); obj.PlayThunderEffects(position, strikeAudio); } [ServerRpc] private void ElectrocutedServerRpc(Vector3 position) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Invalid comparison between Unknown and I4 //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: 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_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2844681185u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref position); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2844681185u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ElectrocutedClientRpc(position); } } protected override void __initializeVariables() { if (damage == null) { throw new Exception("PowerOutletStun.damage cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)damage).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)damage, "damage"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)damage); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_PowerOutletStun() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(328188188u, new RpcReceiveHandler(__rpc_handler_328188188)); NetworkManager.__rpc_func_table.Add(2844681185u, new RpcReceiveHandler(__rpc_handler_2844681185)); } private static void __rpc_handler_328188188(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { Vector3 position = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref position); target.__rpc_exec_stage = (__RpcExecStage)2; ((PowerOutletStun)(object)target).ElectrocutedClientRpc(position); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2844681185(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: 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_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009d: 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_0055: Invalid comparison between Unknown and I4 NetworkManager networkManager = target.NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if (rpcParams.Server.Receive.SenderClientId != target.OwnerClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } } else { Vector3 position = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref position); target.__rpc_exec_stage = (__RpcExecStage)1; ((PowerOutletStun)(object)target).ElectrocutedServerRpc(position); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "PowerOutletStun"; } } public class ProjectileWeapon : SaveableObject { public AudioSource mainAudio; public AudioClip[] activateClips; public AudioClip[] noAmmoSounds; public AudioClip[] reloadSounds; public Transform aimDirection; public int maxAmmo = 4; private NetworkVariable<int> currentAmmo = new NetworkVariable<int>(4, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public GameObject projectilePrefab; public float LobForce = 100f; private float timeSinceLastShot; private PlayerControllerB previousPlayerHeldBy; public Animator Animator; public ParticleSystem particleSystem; public Item ammoItem; public int ammoSlotToUse = -1; public override void SaveObjectData() { SaveData.SaveObjectData("projectileWeaponAmmoData", currentAmmo.Value, uniqueId); } public override void LoadObjectData() { if (((NetworkBehaviour)this).IsHost) { currentAmmo.Value = SaveData.LoadObjectData<int>("projectileWeaponAmmoData", uniqueId); } } public static void Init() { } private static bool GrabbableObject_UseItemBatteries(orig_UseItemBatteries orig, GrabbableObject self) { if (self is ProjectileWeapon) { return true; } return orig.Invoke(self); } public override void Start() { ((GrabbableObject)this).Start(); } public override void OnDestroy() { ((NetworkBehaviour)this).OnDestroy(); } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); if (((NetworkBehaviour)this).IsServer) { currentAmmo.Value = maxAmmo; } } public override void ItemActivate(bool used, bool buttonDown = true) { //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_0085: 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) ((GrabbableObject)this).ItemActivate(used, buttonDown); if (currentAmmo.Value > 0) { if (((NetworkBehaviour)this).IsHost) { NetworkVariable<int> obj = currentAmmo; int value = obj.Value; obj.Value = value - 1; } PlayRandomAudio(mainAudio, activateClips); Animator.Play("fire"); particleSystem.Play(); timeSinceLastShot = 0f; if (((NetworkBehaviour)this).IsOwner) { if (((NetworkBehaviour)this).IsHost) { ProjectileSpawner(aimDirection.position, aimDirection.rotation); } else { SpawnProjectileServerRpc(aimDirection.position, aimDirection.rotation); } } } else { PlayRandomAudio(mainAudio, noAmmoSounds); } } private bool ReloadedGun() { int num = FindAmmoInInventory(); if (num == -1) { return false; } ammoSlotToUse = num; return true; } private int FindAmmoInInventory() { for (int i = 0; i < ((GrabbableObject)this).playerHeldBy.ItemSlots.Length; i++) { if (!((Object)(object)((GrabbableObject)this).playerHeldBy.ItemSlots[i] == (Object)null) && ((GrabbableObject)this).playerHeldBy.ItemSlots[i].itemProperties.itemId == ammoItem.itemId) { return i; } } return -1; } [ServerRpc] private void FixWeightServerRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Invalid comparison between Unknown and I4 //IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: 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_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(43845628u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 43845628u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { FixWeightClientRpc(); } } [ClientRpc] private void FixWeightClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(948021082u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 948021082u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && (Object)(object)((GrabbableObject)this).playerHeldBy != (Object)null) { PlayerControllerB playerHeldBy = ((GrabbableObject)this).playerHeldBy; playerHeldBy.carryWeight -= Mathf.Clamp(ammoItem.weight - 1f, 0f, 10f); } } } public override void ItemInteractLeftRight(bool right) { ((GrabbableObject)this).ItemInteractLeftRight(right); if (right || !((NetworkBehaviour)this).IsOwner) { return; } if (ReloadedGun()) { if (currentAmmo.Value > 0) { HUDManager.Instance.DisplayTip("Item already loaded.", "You can reload once you use up all the ammo.", false, false, "LC_Tip1"); return; } ReloadAmmoServerRpc(); DestroyItemInSlotAndSync(ammoSlotToUse); ammoSlotToUse = -1; } else { HUDManager.Instance.DisplayTip("No ammo found.", "Buy " + ammoItem.itemName + " from the Terminal to reload.", false, false, "LC_Tip1"); } } [ServerRpc] private void ReloadAmmoServerRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Invalid comparison between Unknown and I4 //IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: 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_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1064596822u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1064596822u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { currentAmmo.Value = maxAmmo; ReloadAmmoSoundClientRpc(); } } [ClientRpc] private void ReloadAmmoSoundClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3520251861u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3520251861u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { PlayRandomAudio(mainAudio, reloadSounds); Animator.Play("reload"); } } } [ServerRpc] private void SpawnProjectileServerRpc(Vector3 aimPosition, Quaternion aimRotation) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Invalid comparison between Unknown and I4 //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: 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_00b3: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(681922146u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref aimPosition); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref aimRotation); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 681922146u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ProjectileSpawner(aimPosition, aimRotation); } } private void ProjectileSpawner(Vector3 aimPosition, Quaternion aimRotation) { //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_002a: 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) GameObject obj = Object.Instantiate<GameObject>(projectilePrefab, aimPosition, aimRotation); obj.GetComponent<NetworkObject>().SpawnWithOwnership(((NetworkBehaviour)this).OwnerClientId, false); obj.GetComponent<Rigidbody>().AddForce(aimDirection.forward * LobForce, (ForceMode)1); } private void PlayRandomAudio(AudioSource audioSource, AudioClip[] audioClips) { if (audioClips.Length != 0) { audioSource.PlayOneShot(audioClips[Random.Range(0, audioClips.Length)]); } } public override void Update() { ((GrabbableObject)this).Update(); timeSinceLastShot += Time.deltaTime; } private void OnEnable() { } private void OnDisable() { } public override void PocketItem() { ((GrabbableObject)this).PocketItem(); if ((Object)(object)((GrabbableObject)this).playerHeldBy != (Object)null) { ((GrabbableObject)this).playerHeldBy.equippedUsableItemQE = false; } } public override void DiscardItem() { ((GrabbableObject)this).DiscardItem(); if ((Object)(object)((GrabbableObject)this).playerHeldBy != (Object)null) { ((GrabbableObject)this).playerHeldBy.equippedUsableItemQE = false; } } public override void EquipItem() { ((GrabbableObject)this).EquipItem(); ((GrabbableObject)this).playerHeldBy.equippedUsableItemQE = true; } public void DestroyItemInSlotAndSync(int itemSlot) { if (((NetworkBehaviour)this).IsOwner) { if (itemSlot >= ((GrabbableObject)this).playerHeldBy.ItemSlots.Length || (Object)(object)((GrabbableObject)this).playerHeldBy.ItemSlots[itemSlot] == (Object)null) { Debug.LogError((object)$"Destroy item in slot called for a slot (slot {itemSlot}) which is empty or incorrect"); } DestroyItemInSlotServerRpc(itemSlot); } } [ServerRpc] public void DestroyItemInSlotServerRpc(int itemSlot) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Invalid comparison between Unknown and I4 //IL_00a5: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: 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_0084: Invalid comparison between Unknown and I4 NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).OwnerClientId != networkManager.LocalClientId) { if ((int)networkManager.LogLevel <= 1) { Debug.LogError((object)"Only the owner can invoke a ServerRpc that requires ownership!"); } return; } ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(3656085789u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, itemSlot); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3656085789u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { DestroyItemInSlotClientRpc(itemSlot); } } [ClientRpc] public void DestroyItemInSlotClientRpc(int itemSlot) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(314723133u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, itemSlot); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 314723133u, val, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { DestroyItemInSlot(itemSlot); } } } public void DestroyItemInSlot(int itemSlot) { if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || (Object)(object)NetworkManager.Singleton == (Object)null || NetworkManager.Singleton.ShutdownInProgress) { return; } GrabbableObject val = ((GrabbableObject)this).playerHeldBy.ItemSlots[itemSlot]; if ((Object)(object)val == (Object)null || (Object)(object)val.itemProperties == (Object)null) { Plugin.logger.LogError((object)"Item properties are null, cannot destroy item in slot"); return; } PlayerControllerB playerHeldBy = ((GrabbableObject)this).playerHeldBy; playerHeldBy.carryWeight -= Mathf.Clamp(val.itemProperties.weight - 1f, 0f, 10f); if (((GrabbableObject)this).playerHeldBy.currentItemSlot == itemSlot) { ((GrabbableObject)this).playerHeldBy.isHoldingObject = false; ((GrabbableObject)this).playerHeldBy.twoHanded = false; if (((NetworkBehaviour)((GrabbableObject)this).playerHeldBy).IsOwner) { ((GrabbableObject)this).playerHeldBy.playerBodyAnimator.SetBool("cancelHolding", true); ((GrabbableObject)this).playerHeldBy.playerBod
BepInEx/plugins/Linkoid.Dissonance.LagFix.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using Dissonance; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Linkoid.Dissonance.LagFix")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Linkoid.Dissonance.LagFix")] [assembly: AssemblyCopyright("Copyright © linkoid 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("07f63a54-331c-49fa-870c-ee582bb74fd3")] [assembly: AssemblyFileVersion("1.0")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.8746.28325")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 Linkoid.Dissonance.LagFix { [BepInPlugin("Linkoid.Dissonance.LagFix", "Dissonance Lag Fix", "1.0")] public sealed class DissonanceLagFixPlugin : BaseUnityPlugin { private void Awake() { Logs.SetLogLevel((LogCategory)1, (LogLevel)4); } } public static class PluginInfo { internal const string GUID = "Linkoid.Dissonance.LagFix"; internal const string NAME = "Dissonance Lag Fix"; internal const string VERSION = "1.0"; public static readonly string Guid = "Linkoid.Dissonance.LagFix"; public static readonly string Name = "Dissonance Lag Fix"; public static readonly string Version = "1.0"; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
BepInEx/plugins/LockDoorsMod.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")] [assembly: AssemblyCompany("LockDoorsMod")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("LockDoorsMod")] [assembly: AssemblyTitle("LockDoorsMod")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 LockDoorsMod { [HarmonyPatch(typeof(HUDManager))] public class Broadcaster { public static Action<string, string> GetString = delegate { }; public static void BroadcastString(string data, string signature) { HUDManager.Instance.AddTextToChatOnServer("<size=0>ENZDATA/" + data + "/" + signature + "/" + GameNetworkManager.Instance.localPlayerController.playerClientId + "/</size>", -1); } [HarmonyPatch(typeof(HUDManager), "AddChatMessage")] [HarmonyPostfix] internal static void AddChatMessagePatch(string chatMessage, string nameOfUserWhoTyped = "") { string[] array = chatMessage.Split(new char[1] { '/' }); if (chatMessage.StartsWith("<size=0>ENZDATA") && !(GameNetworkManager.Instance.localPlayerController.playerClientId.ToString() == array[3])) { GetString(array[1], array[2]); } } } public static class LDMPluginInfo { public const string PLUGIN_GUID = "ENZDS.LockDoorsMod"; public const string PLUGIN_NAME = "Lock Doors Mod"; public const string PLUGIN_VERSION = "1.1.0"; } public static class LDMLogger { public static readonly ManualLogSource logger = Logger.CreateLogSource("LockDoorsMod"); } [JsonObject] internal class LockDoorData { [JsonProperty] public ulong networkObjectId { get; set; } [JsonProperty] public ulong clientId { get; set; } } [HarmonyPatch(typeof(DoorLock))] public class DoorLockPatch { [HarmonyPatch("Awake")] [HarmonyPrefix] private static void Awake() { Broadcaster.GetString = (Action<string, string>)Delegate.Combine(Broadcaster.GetString, new Action<string, string>(CloseDoorReceived)); } private static void CloseDoorReceived(string data, string signature) { LockDoorData lockDoorData = JsonConvert.DeserializeObject<LockDoorData>(data); LDMLogger.logger.LogInfo((object)("[BROADCAST_RECEIVE] Got message \n data: " + data + " \n signature: " + signature)); if (signature == "lock_door") { GameObject val = FindObjectById(Convert.ToUInt64(lockDoorData.networkObjectId)); DoorLock componentInChildren = val.GetComponentInChildren<DoorLock>(); LDMLogger.logger.LogInfo((object)$"[BROADCAST_RECEIVE] found object with id {lockDoorData.networkObjectId}: {val} \n {componentInChildren} \n doorLockNID: {((NetworkBehaviour)componentInChildren).NetworkObjectId}"); componentInChildren.LockDoor(30f); } } [HarmonyPatch("LockDoor")] [HarmonyPrefix] private static bool LockDoorPatch(ref DoorLock __instance, ref bool ___isDoorOpened, ref bool ___isLocked, ref AudioSource ___doorLockSFX, ref AudioClip ___unlockSFX) { if (___isDoorOpened | ___isLocked) { LDMLogger.logger.LogInfo((object)"The door is opened or locked. Can't lock it"); return false; } AudioSource val = ___doorLockSFX; val.PlayOneShot(___unlockSFX); return true; } public static void LockDoorPatchSyncWithServer(ulong networkObjectId) { LockDoorData lockDoorData = new LockDoorData { networkObjectId = networkObjectId, clientId = GameNetworkManager.Instance.localPlayerController.playerClientId }; LDMLogger.logger.LogInfo((object)"[BROADCAST] Locking the door"); Broadcaster.BroadcastString(JsonConvert.SerializeObject((object)lockDoorData, (Formatting)0), "lock_door"); } private static GameObject FindObjectById(ulong networkId) { return (networkId == 0L) ? null : ((Component)NetworkManager.Singleton.SpawnManager.SpawnedObjects[networkId]).gameObject; } } [HarmonyPatch(typeof(KeyItem))] internal class KeyItemPatch { [HarmonyPatch("ItemActivate")] [HarmonyPrefix] private static bool ItemActivatePatch(ref KeyItem __instance, bool used, bool buttonDown = true) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy; bool isOwner = ((NetworkBehaviour)__instance).IsOwner; RaycastHit val = default(RaycastHit); if ((Object)(object)playerHeldBy == (Object)null || !isOwner || !Physics.Raycast(new Ray(((Component)playerHeldBy.gameplayCamera).transform.position, ((Component)playerHeldBy.gameplayCamera).transform.forward), ref val, 3f, 2816)) { return false; } DoorLock component = ((Component)((RaycastHit)(ref val)).transform).GetComponent<DoorLock>(); if ((Object)(object)component == (Object)null || component.isPickingLock) { return false; } if ((bool)typeof(DoorLock).GetField("isDoorOpened", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(component)) { LDMLogger.logger.LogInfo((object)"The door is opened"); return false; } if (!component.isLocked) { component.LockDoor(30f); DoorLockPatch.LockDoorPatchSyncWithServer(((NetworkBehaviour)component).NetworkObjectId); } else { component.UnlockDoorSyncWithServer(); } ((GrabbableObject)__instance).playerHeldBy.DespawnHeldObject(); return false; } } [BepInPlugin("ENZDS.LockDoorsMod", "Lock Doors Mod", "1.1.0")] public class LockingKeyModBase : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("ENZDS.LockDoorsMod"); private static LockingKeyModBase instance; private void Awake() { if (instance == null) { instance = this; } LDMLogger.logger.LogInfo((object)"Lock Doors 1.1.0 :)"); harmony.PatchAll(); } } public static class PluginInfo { public const string PLUGIN_GUID = "LockDoorsMod"; public const string PLUGIN_NAME = "LockDoorsMod"; public const string PLUGIN_VERSION = "1.0.0"; } }
BepInEx/plugins/MaskedEnemyRework.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using MaskedEnemyRework.Patches; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyCompany("MaskedEnemyRework")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0")] [assembly: AssemblyProduct("MaskedEnemyRework")] [assembly: AssemblyTitle("MaskedEnemyRework")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.1.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 MaskedEnemyRework { [BepInPlugin("MaskedEnemyRework", "MaskedEnemyRework", "2.1.0")] public class Plugin : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("MaskedEnemyRework"); private static Plugin Instance; internal ManualLogSource logger; private ConfigEntry<bool> RemoveMasksConfig; private ConfigEntry<bool> RemoveZombieArmsConfig; private ConfigEntry<bool> UseSpawnRarityConfig; private ConfigEntry<int> SpawnRarityConfig; private ConfigEntry<bool> CanSpawnOutsideConfig; private ConfigEntry<int> MaxSpawnCountConfig; private ConfigEntry<bool> ZombieApocalypeModeConfig; private ConfigEntry<bool> UseVanillaSpawnsConfig; private ConfigEntry<int> ZombieApocalypeRandomChanceConfig; private ConfigEntry<float> InsideEnemySpawnCurveConfig; private ConfigEntry<float> MiddayInsideEnemySpawnCurveConfig; private ConfigEntry<float> StartOutsideEnemySpawnCurveConfig; private ConfigEntry<float> MidOutsideEnemySpawnCurveConfig; private ConfigEntry<float> EndOutsideEnemySpawnCurveConfig; public static bool RemoveMasks; public static bool RemoveZombieArms; public static bool UseSpawnRarity; public static int SpawnRarity; public static bool CanSpawnOutside; public static int MaxSpawnCount; public static bool ZombieApocalypseMode; public static bool UseVanillaSpawns; public static int RandomChanceZombieApocalypse; public static float InsideEnemySpawnCurve; public static float MiddayInsideEnemySpawnCurve; public static float StartOutsideEnemySpawnCurve; public static float MidOutsideEnemySpawnCurve; public static float EndOutsideEnemySpawnCurve; public static int PlayerCount; public static SpawnableEnemyWithRarity maskedPrefab; public static SpawnableEnemyWithRarity flowerPrefab; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } RemoveMasksConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Remove Mask From Masked Enemy", true, "Whether or not the Masked Enemy has a mask on."); RemoveZombieArmsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Remove Zombie Arms", true, "Remove the animation where the Masked raise arms like a zombie."); UseVanillaSpawnsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Use Vanilla Spawns", false, "Ignores anything else in this mod. Only uses the above settings from this config. Will not spawn on all moons. will ignore EVERYTHING in the config below this point."); UseSpawnRarityConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawns", "Use Spawn Rarity", false, "Use custom spawn rate from config. If this is false, the masked spawns at the same rate as the Bracken. If true, will spawn at whatever rarity is given in Spawn Rarity config option"); SpawnRarityConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Spawns", "Spawn Rarity", 15, "The rarity for the Masked Enemy to spawn. The higher the number, the more likely to spawn. Can go to 1000000000, any higher will break. Use Spawn Rarity must be set to True"); CanSpawnOutsideConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawns", "Allow Masked To Spawn Outside", false, "Whether the Masked Enemy can spawn outside the building"); MaxSpawnCountConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Spawns", "Max Number of Masked", 2, "Max Number of possible masked to spawn in one level"); ZombieApocalypeModeConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Zombie Apocalypse Mode", "Zombie Apocalype Mode", false, "Only spawns Masked! Make sure to crank up the Max Spawn Count in this config! Would also recommend bringing a gun (mod), a shovel works fine too though.... This mode does not play nice with other mods that affect spawn rates. Disable those before playing for best results"); ZombieApocalypeRandomChanceConfig = ((BaseUnityPlugin)this).Config.Bind<int>("Zombie Apocalypse Mode", "Random Zombie Apocalype Mode", -1, "[Must Be Whole Number] The percent chance from 1 to 100 that a day could contain a zombie apocalypse. Put at -1 to never have the chance arise and don't have Only Spawn Masked turned on"); InsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "StartOfDay Inside Masked Spawn Curve", 0.1f, "Spawn curve for masked inside, start of the day. Crank this way up for immediate action. More info in the readme"); MiddayInsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "Midday Inside Masked Spawn Curve", 500f, "Spawn curve for masked inside, midday."); StartOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "StartOfDay Masked Outside Spawn Curve", -30f, "Spawn curve for outside masked, start of the day."); MidOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "Midday Outside Masked Spawn Curve", -30f, "Spawn curve for outside masked, midday."); EndOutsideEnemySpawnCurveConfig = ((BaseUnityPlugin)this).Config.Bind<float>("Zombie Apocalypse Mode", "EOD Outside Masked Spawn Curve", 10f, "Spawn curve for outside masked, end of day"); RemoveMasks = RemoveMasksConfig.Value; UseVanillaSpawns = UseVanillaSpawnsConfig.Value; RemoveZombieArms = RemoveZombieArmsConfig.Value; UseSpawnRarity = UseSpawnRarityConfig.Value; CanSpawnOutside = CanSpawnOutsideConfig.Value; MaxSpawnCount = MaxSpawnCountConfig.Value; SpawnRarity = SpawnRarityConfig.Value; ZombieApocalypseMode = ZombieApocalypeModeConfig.Value; InsideEnemySpawnCurve = InsideEnemySpawnCurveConfig.Value; MiddayInsideEnemySpawnCurve = MiddayInsideEnemySpawnCurveConfig.Value; StartOutsideEnemySpawnCurve = StartOutsideEnemySpawnCurveConfig.Value; MidOutsideEnemySpawnCurve = MaxSpawnCountConfig.Value; EndOutsideEnemySpawnCurve = EndOutsideEnemySpawnCurveConfig.Value; RandomChanceZombieApocalypse = ZombieApocalypeRandomChanceConfig.Value; logger = Logger.CreateLogSource("MaskedEnemyRework"); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MaskedEnemyRework is loaded! Woohoo!"); harmony.PatchAll(typeof(Plugin)); harmony.PatchAll(typeof(GetMaskedPrefabForLaterUse)); harmony.PatchAll(typeof(MaskedVisualRework)); harmony.PatchAll(typeof(MaskedSpawnSettings)); harmony.PatchAll(typeof(RemoveZombieArms)); } } public static class PluginInfo { public const string PLUGIN_GUID = "MaskedEnemyRework"; public const string PLUGIN_NAME = "MaskedEnemyRework"; public const string PLUGIN_VERSION = "2.1.0"; } } namespace MaskedEnemyRework.Patches { [HarmonyPatch(typeof(Terminal))] internal class GetMaskedPrefabForLaterUse { [HarmonyPatch("Start")] [HarmonyPostfix] private static void SavesPrefabForLaterUse(ref SelectableLevel[] ___moonsCatalogueList) { ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework"); SelectableLevel[] array = ___moonsCatalogueList; foreach (SelectableLevel val2 in array) { foreach (SpawnableEnemyWithRarity enemy in val2.Enemies) { if (enemy.enemyType.enemyName == "Masked") { val.LogInfo((object)"Found Masked!"); Plugin.maskedPrefab = enemy; } else if (enemy.enemyType.enemyName == "Flowerman") { Plugin.flowerPrefab = enemy; val.LogInfo((object)"Found Flowerman!"); } } } } } [HarmonyPatch(typeof(RoundManager))] internal class MaskedSpawnSettings { [HarmonyPatch("BeginEnemySpawning")] [HarmonyPrefix] private static void UpdateSpawnRates(ref SelectableLevel ___currentLevel) { //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Expected O, but got Unknown //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Expected O, but got Unknown //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Expected O, but got Unknown if (Plugin.UseVanillaSpawns) { return; } ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework"); val.LogInfo((object)"Starting Round Manager"); SpawnableEnemyWithRarity maskedPrefab = Plugin.maskedPrefab; SpawnableEnemyWithRarity val2 = Plugin.flowerPrefab; SelectableLevel obj = ___currentLevel; obj.maxEnemyPowerCount += maskedPrefab.enemyType.MaxCount; SelectableLevel obj2 = ___currentLevel; obj2.maxDaytimeEnemyPowerCount += maskedPrefab.enemyType.MaxCount; SelectableLevel obj3 = ___currentLevel; obj3.maxOutsideEnemyPowerCount += maskedPrefab.enemyType.MaxCount; List<SpawnableEnemyWithRarity> enemies = ___currentLevel.Enemies; for (int i = 0; i < ___currentLevel.Enemies.Count; i++) { SpawnableEnemyWithRarity val3 = ___currentLevel.Enemies[i]; if (val3.enemyType.enemyName == "Masked") { enemies.Remove(val3); } if (val3.enemyType.enemyName == "Flowerman") { val2 = val3; } } ___currentLevel.Enemies = enemies; maskedPrefab.enemyType.PowerLevel = 1; maskedPrefab.enemyType.probabilityCurve = val2.enemyType.probabilityCurve; if (Plugin.UseSpawnRarity) { maskedPrefab.rarity = Plugin.SpawnRarity; } else { maskedPrefab.rarity = val2.rarity; } maskedPrefab.enemyType.MaxCount = Plugin.MaxSpawnCount; maskedPrefab.enemyType.isOutsideEnemy = Plugin.CanSpawnOutside; int num = 0; num = ((StartOfRound.Instance.randomMapSeed.ToString().Length >= 3) ? int.Parse(StartOfRound.Instance.randomMapSeed.ToString().Substring(1, 2)) : 0); val.LogInfo((object)("Map seed " + num + " random chance " + Plugin.RandomChanceZombieApocalypse)); num = Mathf.Clamp(num, 0, 100); if (Plugin.ZombieApocalypseMode || (num <= Plugin.RandomChanceZombieApocalypse && Plugin.RandomChanceZombieApocalypse >= 0)) { val.LogInfo((object)"ZOMBIE APOCALYPSE"); ___currentLevel.enemySpawnChanceThroughoutDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, Plugin.InsideEnemySpawnCurve), new Keyframe(0.5f, Plugin.MiddayInsideEnemySpawnCurve) }); ___currentLevel.daytimeEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, 7f), new Keyframe(0.5f, 7f) }); ___currentLevel.outsideEnemySpawnChanceThroughDay = new AnimationCurve((Keyframe[])(object)new Keyframe[3] { new Keyframe(0f, Plugin.StartOutsideEnemySpawnCurve), new Keyframe(20f, Plugin.MidOutsideEnemySpawnCurve), new Keyframe(21f, Plugin.EndOutsideEnemySpawnCurve) }); ___currentLevel.DaytimeEnemies.Clear(); ___currentLevel.OutsideEnemies.Clear(); maskedPrefab.rarity = 1000000000; foreach (SpawnableEnemyWithRarity enemy in ___currentLevel.Enemies) { enemy.rarity = 0; } if (Plugin.CanSpawnOutside) { maskedPrefab.enemyType.isOutsideEnemy = true; ___currentLevel.OutsideEnemies.Add(maskedPrefab); ___currentLevel.DaytimeEnemies.Add(maskedPrefab); } } else { val.LogInfo((object)"no zombies :("); } ___currentLevel.Enemies.Add(maskedPrefab); } } [HarmonyPatch(typeof(MaskedPlayerEnemy))] internal class MaskedVisualRework { [HarmonyPatch("Start")] [HarmonyPostfix] private static void ReformVisuals(ref MaskedPlayerEnemy __instance) { ManualLogSource val = Logger.CreateLogSource("MaskedEnemyRework"); PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; int num = StartOfRound.Instance.ClientPlayerList.Count; if (num == 0) { num = Random.Range(0, 2); val.LogInfo((object)"Player count was zero"); } int num2 = StartOfRound.Instance.randomMapSeed % num; val.LogInfo((object)("player count" + num)); val.LogInfo((object)("player index" + num2)); num2 = Mathf.Clamp(num2, 0, num); PlayerControllerB val2 = allPlayerScripts[num2]; __instance.mimickingPlayer = val2; __instance.SetSuit(val2.currentSuitID); if (Plugin.RemoveMasks) { ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskComedy")).gameObject.SetActive(false); ((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003/spine.004/HeadMaskTragedy")).gameObject.SetActive(false); } } } internal class RemoveZombieArms { [HarmonyPatch(typeof(MaskedPlayerEnemy), "SetHandsOutClientRpc")] [HarmonyPrefix] private static void RemoveArms(ref bool setOut) { if (Plugin.RemoveZombieArms) { setOut = false; } } } }
BepInEx/plugins/MoreCompany.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using MoreCompany.Cosmetics; using MoreCompany.Utils; using Steamworks; using Steamworks.Data; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.Audio; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("MoreCompany")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MoreCompany")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("511a1e5e-0611-49f1-b60f-cec69c668fd8")] [assembly: AssemblyFileVersion("1.7.2")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.7.2.0")] namespace MoreCompany { [HarmonyPatch(typeof(AudioMixer), "SetFloat")] public static class AudioMixerSetFloatPatch { public static bool Prefix(string name, float value) { if (name.StartsWith("PlayerVolume") || name.StartsWith("PlayerPitch")) { string s = name.Replace("PlayerVolume", "").Replace("PlayerPitch", ""); int num = int.Parse(s); PlayerControllerB val = StartOfRound.Instance.allPlayerScripts[num]; AudioSource currentVoiceChatAudioSource = val.currentVoiceChatAudioSource; if ((Object)(object)val != (Object)null && Object.op_Implicit((Object)(object)currentVoiceChatAudioSource)) { if (name.StartsWith("PlayerVolume")) { currentVoiceChatAudioSource.volume = value / 16f; } else if (name.StartsWith("PlayerPitch")) { currentVoiceChatAudioSource.pitch = value; } } return false; } return true; } } [HarmonyPatch(typeof(HUDManager), "AddTextToChatOnServer")] public static class SendChatToServerPatch { public static bool Prefix(HUDManager __instance, string chatMessage, int playerId = -1) { if (((NetworkBehaviour)StartOfRound.Instance).IsHost && chatMessage.StartsWith("/mc") && DebugCommandRegistry.commandEnabled) { string text = chatMessage.Replace("/mc ", ""); DebugCommandRegistry.HandleCommand(text.Split(new char[1] { ' ' })); return false; } if (chatMessage.StartsWith("[morecompanycosmetics]")) { ReflectionUtils.InvokeMethod(__instance, "AddPlayerChatMessageServerRpc", new object[2] { chatMessage, 99 }); return false; } return true; } } [HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageServerRpc")] public static class ServerReceiveMessagePatch { public static string previousDataMessage = ""; public static bool Prefix(HUDManager __instance, ref string chatMessage, int playerId) { NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager; if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening) { return false; } if (chatMessage.StartsWith("[morecompanycosmetics]") && networkManager.IsServer) { previousDataMessage = chatMessage; chatMessage = "[replacewithdata]"; } return true; } } [HarmonyPatch(typeof(PlayerControllerB), "ConnectClientToPlayerObject")] public static class ConnectClientToPlayerObjectPatch { public static void Postfix(PlayerControllerB __instance) { string text = "[morecompanycosmetics]"; text = text + ";" + __instance.playerClientId; foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics) { text = text + ";" + locallySelectedCosmetic; } HUDManager.Instance.AddTextToChatOnServer(text, -1); } } [HarmonyPatch(typeof(HUDManager), "AddChatMessage")] public static class AddChatMessagePatch { public static bool Prefix(HUDManager __instance, string chatMessage, string nameOfUserWhoTyped = "") { if (chatMessage.StartsWith("[replacewithdata]") || chatMessage.StartsWith("[morecompanycosmetics]")) { return false; } return true; } } [HarmonyPatch(typeof(HUDManager), "AddPlayerChatMessageClientRpc")] public static class ClientReceiveMessagePatch { public static bool ignoreSample; public static bool Prefix(HUDManager __instance, ref string chatMessage, int playerId) { NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager; if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening) { return false; } if (networkManager.IsServer) { if (chatMessage.StartsWith("[replacewithdata]")) { chatMessage = ServerReceiveMessagePatch.previousDataMessage; HandleDataMessage(chatMessage); } else if (chatMessage.StartsWith("[morecompanycosmetics]")) { return false; } } else if (chatMessage.StartsWith("[morecompanycosmetics]")) { HandleDataMessage(chatMessage); } return true; } private static void HandleDataMessage(string chatMessage) { //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) if (ignoreSample) { return; } chatMessage = chatMessage.Replace("[morecompanycosmetics]", ""); string[] array = chatMessage.Split(new char[1] { ';' }); string text = array[1]; int num = int.Parse(text); CosmeticApplication component = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[num]).transform.Find("ScavengerModel").Find("metarig")).gameObject.GetComponent<CosmeticApplication>(); if (Object.op_Implicit((Object)(object)component)) { component.ClearCosmetics(); Object.Destroy((Object)(object)component); } CosmeticApplication cosmeticApplication = ((Component)((Component)StartOfRound.Instance.allPlayerScripts[num]).transform.Find("ScavengerModel").Find("metarig")).gameObject.AddComponent<CosmeticApplication>(); cosmeticApplication.ClearCosmetics(); List<string> list = new List<string>(); string[] array2 = array; foreach (string text2 in array2) { if (!(text2 == text)) { list.Add(text2); if (MainClass.showCosmetics) { cosmeticApplication.ApplyCosmetic(text2, startEnabled: true); } } } if (num == StartOfRound.Instance.thisClientPlayerId) { cosmeticApplication.ClearCosmetics(); } foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics) { Transform transform = ((Component)spawnedCosmetic).transform; transform.localScale *= 0.38f; } MainClass.playerIdsAndCosmetics.Remove(num); MainClass.playerIdsAndCosmetics.Add(num, list); if (!GameNetworkManager.Instance.isHostingGame || num == 0) { return; } ignoreSample = true; foreach (KeyValuePair<int, List<string>> playerIdsAndCosmetic in MainClass.playerIdsAndCosmetics) { string text3 = "[morecompanycosmetics]"; text3 = text3 + ";" + playerIdsAndCosmetic.Key; foreach (string item in playerIdsAndCosmetic.Value) { text3 = text3 + ";" + item; } HUDManager.Instance.AddTextToChatOnServer(text3, -1); } ignoreSample = false; } } public class DebugCommandRegistry { public static bool commandEnabled; public static void HandleCommand(string[] args) { //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: 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_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) if (!commandEnabled) { return; } PlayerControllerB localPlayerController = StartOfRound.Instance.localPlayerController; switch (args[0]) { case "money": { int groupCredits = int.Parse(args[1]); Terminal val5 = Resources.FindObjectsOfTypeAll<Terminal>().First(); val5.groupCredits = groupCredits; break; } case "spawnscrap": { string text = ""; for (int i = 1; i < args.Length; i++) { text = text + args[i] + " "; } text = text.Trim(); Vector3 val = ((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f; SpawnableItemWithRarity val2 = null; foreach (SpawnableItemWithRarity item in StartOfRound.Instance.currentLevel.spawnableScrap) { if (item.spawnableItem.itemName.ToLower() == text.ToLower()) { val2 = item; break; } } GameObject val3 = Object.Instantiate<GameObject>(val2.spawnableItem.spawnPrefab, val, Quaternion.identity, (Transform)null); GrabbableObject component = val3.GetComponent<GrabbableObject>(); ((Component)component).transform.rotation = Quaternion.Euler(component.itemProperties.restingRotation); component.fallTime = 0f; NetworkObject component2 = val3.GetComponent<NetworkObject>(); component2.Spawn(false); break; } case "spawnenemy": { string text2 = ""; for (int j = 1; j < args.Length; j++) { text2 = text2 + args[j] + " "; } text2 = text2.Trim(); SpawnableEnemyWithRarity val4 = null; foreach (SpawnableEnemyWithRarity enemy in StartOfRound.Instance.currentLevel.Enemies) { if (enemy.enemyType.enemyName.ToLower() == text2.ToLower()) { val4 = enemy; break; } } RoundManager.Instance.SpawnEnemyGameObject(((Component)localPlayerController).transform.position + ((Component)localPlayerController).transform.forward * 2f, 0f, -1, val4.enemyType); break; } case "listall": MainClass.StaticLogger.LogInfo((object)"Spawnable scrap:"); foreach (SpawnableItemWithRarity item2 in StartOfRound.Instance.currentLevel.spawnableScrap) { MainClass.StaticLogger.LogInfo((object)item2.spawnableItem.itemName); } MainClass.StaticLogger.LogInfo((object)"Spawnable enemies:"); { foreach (SpawnableEnemyWithRarity enemy2 in StartOfRound.Instance.currentLevel.Enemies) { MainClass.StaticLogger.LogInfo((object)enemy2.enemyType.enemyName); } break; } } } } [HarmonyPatch(typeof(ForestGiantAI), "LookForPlayers")] public static class LookForPlayersForestGiantPatch { public static void Prefix(ForestGiantAI __instance) { if (__instance.playerStealthMeters.Length != MainClass.newPlayerCount) { __instance.playerStealthMeters = new float[MainClass.newPlayerCount]; for (int i = 0; i < MainClass.newPlayerCount; i++) { __instance.playerStealthMeters[i] = 0f; } } } } [HarmonyPatch(typeof(SpringManAI), "Update")] public static class SpringManAIUpdatePatch { public static bool Prefix(SpringManAI __instance, ref float ___timeSinceHittingPlayer, ref float ___stopAndGoMinimumInterval, ref bool ___wasOwnerLastFrame, ref bool ___stoppingMovement, ref float ___currentChaseSpeed, ref bool ___hasStopped, ref float ___currentAnimSpeed, ref float ___updateDestinationInterval, ref Vector3 ___tempVelocity, ref float ___targetYRotation, ref float ___setDestinationToPlayerInterval, ref float ___previousYRotation) { //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_014c: 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) UpdateBase((EnemyAI)(object)__instance, ref ___updateDestinationInterval, ref ___tempVelocity, ref ___targetYRotation, ref ___setDestinationToPlayerInterval, ref ___previousYRotation); if (((EnemyAI)__instance).isEnemyDead) { return false; } int currentBehaviourStateIndex = ((EnemyAI)__instance).currentBehaviourStateIndex; if (currentBehaviourStateIndex != 0 && currentBehaviourStateIndex == 1) { if (___timeSinceHittingPlayer >= 0f) { ___timeSinceHittingPlayer -= Time.deltaTime; } if (((NetworkBehaviour)__instance).IsOwner) { if (___stopAndGoMinimumInterval > 0f) { ___stopAndGoMinimumInterval -= Time.deltaTime; } if (!___wasOwnerLastFrame) { ___wasOwnerLastFrame = true; if (!___stoppingMovement && ___timeSinceHittingPlayer < 0.12f) { ((EnemyAI)__instance).agent.speed = ___currentChaseSpeed; } else { ((EnemyAI)__instance).agent.speed = 0f; } } bool flag = false; for (int i = 0; i < MainClass.newPlayerCount; i++) { if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && StartOfRound.Instance.allPlayerScripts[i].HasLineOfSightToPosition(((Component)__instance).transform.position + Vector3.up * 1.6f, 68f, 60, -1f) && Vector3.Distance(((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, ((EnemyAI)__instance).eye.position) > 0.3f) { flag = true; } } if (((EnemyAI)__instance).stunNormalizedTimer > 0f) { flag = true; } if (flag != ___stoppingMovement && ___stopAndGoMinimumInterval <= 0f) { ___stopAndGoMinimumInterval = 0.15f; if (flag) { __instance.SetAnimationStopServerRpc(); } else { __instance.SetAnimationGoServerRpc(); } ___stoppingMovement = flag; } } if (___stoppingMovement) { if (__instance.animStopPoints.canAnimationStop) { if (!___hasStopped) { ___hasStopped = true; __instance.mainCollider.isTrigger = false; if (GameNetworkManager.Instance.localPlayerController.HasLineOfSightToPosition(((Component)__instance).transform.position, 70f, 25, -1f)) { float num = Vector3.Distance(((Component)__instance).transform.position, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position); if (num < 4f) { GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.9f, true); } else if (num < 9f) { GameNetworkManager.Instance.localPlayerController.JumpToFearLevel(0.4f, true); } } if (___currentAnimSpeed > 2f) { RoundManager.PlayRandomClip(((EnemyAI)__instance).creatureVoice, __instance.springNoises, false, 1f, 0); if (__instance.animStopPoints.animationPosition == 1) { ((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoing"); } else { ((EnemyAI)__instance).creatureAnimator.SetTrigger("springBoingPosition2"); } } } ((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", 0f); ___currentAnimSpeed = 0f; if (((NetworkBehaviour)__instance).IsOwner) { ((EnemyAI)__instance).agent.speed = 0f; return false; } } } else { if (___hasStopped) { ___hasStopped = false; __instance.mainCollider.isTrigger = true; } ___currentAnimSpeed = Mathf.Lerp(___currentAnimSpeed, 6f, 5f * Time.deltaTime); ((EnemyAI)__instance).creatureAnimator.SetFloat("walkSpeed", ___currentAnimSpeed); if (((NetworkBehaviour)__instance).IsOwner) { ((EnemyAI)__instance).agent.speed = Mathf.Lerp(((EnemyAI)__instance).agent.speed, ___currentChaseSpeed, 4.5f * Time.deltaTime); } } } return false; } private static void UpdateBase(EnemyAI __instance, ref float updateDestinationInterval, ref Vector3 tempVelocity, ref float targetYRotation, ref float setDestinationToPlayerInterval, ref float previousYRotation) { //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: 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_015d: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Unknown result type (might be due to invalid IL or missing references) //IL_03b3: Unknown result type (might be due to invalid IL or missing references) //IL_03bd: Unknown result type (might be due to invalid IL or missing references) //IL_03c2: Unknown result type (might be due to invalid IL or missing references) //IL_0364: Unknown result type (might be due to invalid IL or missing references) //IL_036e: Unknown result type (might be due to invalid IL or missing references) //IL_0379: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0425: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) if (__instance.enemyType.isDaytimeEnemy && !__instance.daytimeEnemyLeaving) { ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "CheckTimeOfDayToLeave", null); } if (__instance.stunnedIndefinitely <= 0) { if ((double)__instance.stunNormalizedTimer >= 0.0) { __instance.stunNormalizedTimer -= Time.deltaTime / __instance.enemyType.stunTimeMultiplier; } else { __instance.stunnedByPlayer = null; if ((double)__instance.postStunInvincibilityTimer >= 0.0) { __instance.postStunInvincibilityTimer -= Time.deltaTime * 5f; } } } if (!__instance.ventAnimationFinished && (double)__instance.timeSinceSpawn < (double)__instance.exitVentAnimationTime + 0.004999999888241291 * (double)RoundManager.Instance.numberOfEnemiesInScene) { __instance.timeSinceSpawn += Time.deltaTime; if (!((NetworkBehaviour)__instance).IsOwner) { Vector3 serverPosition = __instance.serverPosition; if (__instance.serverPosition != Vector3.zero) { ((Component)__instance).transform.position = __instance.serverPosition; ((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, targetYRotation, ((Component)__instance).transform.eulerAngles.z); } } else if ((double)updateDestinationInterval >= 0.0) { updateDestinationInterval -= Time.deltaTime; } else { __instance.SyncPositionToClients(); updateDestinationInterval = 0.1f; } return; } if (!__instance.ventAnimationFinished) { __instance.ventAnimationFinished = true; if ((Object)(object)__instance.creatureAnimator != (Object)null) { __instance.creatureAnimator.SetBool("inSpawningAnimation", false); } } if (!((NetworkBehaviour)__instance).IsOwner) { if (__instance.currentSearch.inProgress) { __instance.StopSearch(__instance.currentSearch, true); } __instance.SetClientCalculatingAI(false); if (!__instance.inSpecialAnimation) { ((Component)__instance).transform.position = Vector3.SmoothDamp(((Component)__instance).transform.position, __instance.serverPosition, ref tempVelocity, __instance.syncMovementSpeed); ((Component)__instance).transform.eulerAngles = new Vector3(((Component)__instance).transform.eulerAngles.x, Mathf.LerpAngle(((Component)__instance).transform.eulerAngles.y, targetYRotation, 15f * Time.deltaTime), ((Component)__instance).transform.eulerAngles.z); } __instance.timeSinceSpawn += Time.deltaTime; return; } if (__instance.isEnemyDead) { __instance.SetClientCalculatingAI(false); return; } if (!__instance.inSpecialAnimation) { __instance.SetClientCalculatingAI(true); } if (__instance.movingTowardsTargetPlayer && (Object)(object)__instance.targetPlayer != (Object)null) { if ((double)setDestinationToPlayerInterval <= 0.0) { setDestinationToPlayerInterval = 0.25f; __instance.destination = RoundManager.Instance.GetNavMeshPosition(((Component)__instance.targetPlayer).transform.position, RoundManager.Instance.navHit, 2.7f, -1); } else { __instance.destination = new Vector3(((Component)__instance.targetPlayer).transform.position.x, __instance.destination.y, ((Component)__instance.targetPlayer).transform.position.z); setDestinationToPlayerInterval -= Time.deltaTime; } } if (__instance.inSpecialAnimation) { return; } if ((double)updateDestinationInterval >= 0.0) { updateDestinationInterval -= Time.deltaTime; } else { __instance.DoAIInterval(); updateDestinationInterval = __instance.AIIntervalTime; } if (!((double)Mathf.Abs(previousYRotation - ((Component)__instance).transform.eulerAngles.y) <= 6.0)) { previousYRotation = ((Component)__instance).transform.eulerAngles.y; targetYRotation = previousYRotation; if (((NetworkBehaviour)__instance).IsServer) { ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationClientRpc", new object[1] { (short)previousYRotation }); } else { ReflectionUtils.InvokeMethod(__instance, typeof(EnemyAI), "UpdateEnemyRotationServerRpc", new object[1] { (short)previousYRotation }); } } } } [HarmonyPatch(typeof(SpringManAI), "DoAIInterval")] public static class SpringManAIIntervalPatch { public static bool Prefix(SpringManAI __instance) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) if (((EnemyAI)__instance).moveTowardsDestination) { ((EnemyAI)__instance).agent.SetDestination(((EnemyAI)__instance).destination); } ((EnemyAI)__instance).SyncPositionToClients(); if (StartOfRound.Instance.allPlayersDead) { return false; } if (((EnemyAI)__instance).isEnemyDead) { return false; } switch (((EnemyAI)__instance).currentBehaviourStateIndex) { default: return false; case 1: if (__instance.searchForPlayers.inProgress) { ((EnemyAI)__instance).StopSearch(__instance.searchForPlayers, true); } if (((EnemyAI)__instance).TargetClosestPlayer(1.5f, false, 70f)) { PlayerControllerB fieldValue = ReflectionUtils.GetFieldValue<PlayerControllerB>(__instance, "previousTarget"); if ((Object)(object)fieldValue != (Object)(object)((EnemyAI)__instance).targetPlayer) { ReflectionUtils.SetFieldValue(__instance, "previousTarget", ((EnemyAI)__instance).targetPlayer); ((EnemyAI)__instance).ChangeOwnershipOfEnemy(((EnemyAI)__instance).targetPlayer.actualClientId); } ((EnemyAI)__instance).movingTowardsTargetPlayer = true; return false; } ((EnemyAI)__instance).SwitchToBehaviourState(0); ((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId); break; case 0: { if (!((NetworkBehaviour)__instance).IsServer) { ((EnemyAI)__instance).ChangeOwnershipOfEnemy(StartOfRound.Instance.allPlayerScripts[0].actualClientId); return false; } for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (((EnemyAI)__instance).PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false) && !Physics.Linecast(((Component)__instance).transform.position + Vector3.up * 0.5f, ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position, StartOfRound.Instance.collidersAndRoomMaskAndDefault) && Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 30f) { ((EnemyAI)__instance).SwitchToBehaviourState(1); return false; } } if (!__instance.searchForPlayers.inProgress) { ((EnemyAI)__instance).movingTowardsTargetPlayer = false; ((EnemyAI)__instance).StartSearch(((Component)__instance).transform.position, __instance.searchForPlayers); return false; } break; } } return false; } } [HarmonyPatch(typeof(EnemyAI), "GetClosestPlayer")] public static class GetClosestPlayerPatch { public static bool Prefix(EnemyAI __instance, ref PlayerControllerB __result, bool requireLineOfSight = false, bool cannotBeInShip = false, bool cannotBeNearShip = false) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0115: 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB val = null; __instance.mostOptimalDistance = 2000f; for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], cannotBeInShip, false)) { continue; } if (cannotBeNearShip) { if (StartOfRound.Instance.allPlayerScripts[i].isInElevator) { continue; } bool flag = false; for (int j = 0; j < RoundManager.Instance.spawnDenialPoints.Length; j++) { if (Vector3.Distance(RoundManager.Instance.spawnDenialPoints[j].transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < 10f) { flag = true; break; } } if (flag) { continue; } } if (!requireLineOfSight || !Physics.Linecast(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position, 256)) { __instance.tempDist = Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position); if (__instance.tempDist < __instance.mostOptimalDistance) { __instance.mostOptimalDistance = __instance.tempDist; val = StartOfRound.Instance.allPlayerScripts[i]; } } } __result = val; return false; } } [HarmonyPatch(typeof(EnemyAI), "GetAllPlayersInLineOfSight")] public static class GetAllPlayersInLineOfSightPatch { public static bool Prefix(EnemyAI __instance, ref PlayerControllerB[] __result, float width = 45f, int range = 60, Transform eyeObject = null, float proximityCheck = -1f, int layerMask = -1) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) if (layerMask == -1) { layerMask = StartOfRound.Instance.collidersAndRoomMaskAndDefault; } if ((Object)(object)eyeObject == (Object)null) { eyeObject = __instance.eye; } if (__instance.enemyType.isOutsideEnemy && !__instance.enemyType.canSeeThroughFog && (int)TimeOfDay.Instance.currentLevelWeather == 3) { range = Mathf.Clamp(range, 0, 30); } List<PlayerControllerB> list = new List<PlayerControllerB>(MainClass.newPlayerCount); for (int i = 0; i < StartOfRound.Instance.allPlayerScripts.Length; i++) { if (!__instance.PlayerIsTargetable(StartOfRound.Instance.allPlayerScripts[i], false, false)) { continue; } Vector3 position = ((Component)StartOfRound.Instance.allPlayerScripts[i].gameplayCamera).transform.position; if (Vector3.Distance(__instance.eye.position, position) < (float)range && !Physics.Linecast(eyeObject.position, position, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1)) { Vector3 val = position - eyeObject.position; if (Vector3.Angle(eyeObject.forward, val) < width || Vector3.Distance(((Component)__instance).transform.position, ((Component)StartOfRound.Instance.allPlayerScripts[i]).transform.position) < proximityCheck) { list.Add(StartOfRound.Instance.allPlayerScripts[i]); } } } if (list.Count == MainClass.newPlayerCount) { __result = StartOfRound.Instance.allPlayerScripts; return false; } if (list.Count > 0) { __result = list.ToArray(); return false; } __result = null; return false; } } [HarmonyPatch(typeof(DressGirlAI), "ChoosePlayerToHaunt")] public static class DressGirlHauntPatch { public static bool Prefix(DressGirlAI __instance) { ReflectionUtils.SetFieldValue(__instance, "timesChoosingAPlayer", ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") + 1); if (ReflectionUtils.GetFieldValue<int>(__instance, "timesChoosingAPlayer") > 1) { __instance.timer = __instance.hauntInterval - 1f; } __instance.SFXVolumeLerpTo = 0f; ((EnemyAI)__instance).creatureVoice.Stop(); __instance.heartbeatMusic.volume = 0f; if (!ReflectionUtils.GetFieldValue<bool>(__instance, "initializedRandomSeed")) { ReflectionUtils.SetFieldValue(__instance, "ghostGirlRandom", new Random(StartOfRound.Instance.randomMapSeed + 158)); } float num = 0f; float num2 = 0f; int num3 = 0; int num4 = 0; for (int i = 0; i < MainClass.newPlayerCount; i++) { if (StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount > num3) { num3 = StartOfRound.Instance.gameStats.allPlayerStats[i].turnAmount; num4 = i; } if (StartOfRound.Instance.allPlayerScripts[i].insanityLevel > num) { num = StartOfRound.Instance.allPlayerScripts[i].insanityLevel; num2 = i; } } int[] array = new int[MainClass.newPlayerCount]; for (int j = 0; j < MainClass.newPlayerCount; j++) { if (!StartOfRound.Instance.allPlayerScripts[j].isPlayerControlled) { array[j] = 0; continue; } array[j] += 80; if (num2 == (float)j && num > 1f) { array[j] += 50; } if (num4 == j) { array[j] += 30; } if (!StartOfRound.Instance.allPlayerScripts[j].hasBeenCriticallyInjured) { array[j] += 10; } if ((Object)(object)StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer != (Object)null && StartOfRound.Instance.allPlayerScripts[j].currentlyHeldObjectServer.scrapValue > 150) { array[j] += 30; } } __instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[RoundManager.Instance.GetRandomWeightedIndex(array, ReflectionUtils.GetFieldValue<Random>(__instance, "ghostGirlRandom"))]; if (__instance.hauntingPlayer.isPlayerDead) { for (int k = 0; k < StartOfRound.Instance.allPlayerScripts.Length; k++) { if (!StartOfRound.Instance.allPlayerScripts[k].isPlayerDead) { __instance.hauntingPlayer = StartOfRound.Instance.allPlayerScripts[k]; break; } } } Debug.Log((object)$"Little girl: Haunting player with playerClientId: {__instance.hauntingPlayer.playerClientId}; actualClientId: {__instance.hauntingPlayer.actualClientId}"); ((EnemyAI)__instance).ChangeOwnershipOfEnemy(__instance.hauntingPlayer.actualClientId); __instance.hauntingLocalPlayer = (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)(object)__instance.hauntingPlayer; if (ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine") != null) { ((MonoBehaviour)__instance).StopCoroutine(ReflectionUtils.GetFieldValue<Coroutine>(__instance, "switchHauntedPlayerCoroutine")); } ReflectionUtils.SetFieldValue(__instance, "switchHauntedPlayerCoroutine", ((MonoBehaviour)__instance).StartCoroutine(ReflectionUtils.InvokeMethod<IEnumerator>(__instance, "setSwitchingHauntingPlayer", null))); return false; } } [HarmonyPatch(typeof(HUDManager), "AddChatMessage")] public static class HudChatPatch { public static void Prefix(HUDManager __instance, ref string chatMessage, string nameOfUserWhoTyped = "") { if (!(__instance.lastChatMessage == chatMessage)) { StringBuilder stringBuilder = new StringBuilder(chatMessage); for (int i = 0; i < MainClass.newPlayerCount; i++) { string oldValue = $"[playerNum{i}]"; string playerUsername = StartOfRound.Instance.allPlayerScripts[i].playerUsername; stringBuilder.Replace(oldValue, playerUsername); } chatMessage = stringBuilder.ToString(); } } } [HarmonyPatch(typeof(MenuManager), "Awake")] public static class MenuManagerLogoOverridePatch { public static void Postfix(MenuManager __instance) { //IL_0076: 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_00fd: Unknown result type (might be due to invalid IL or missing references) try { GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject; GameObject gameObject2 = ((Component)gameObject.transform.Find("MenuContainer").Find("MainButtons").Find("HeaderImage")).gameObject; Image component = gameObject2.GetComponent<Image>(); MainClass.ReadSettingsFromFile(); component.sprite = Sprite.Create(MainClass.mainLogo, new Rect(0f, 0f, (float)((Texture)MainClass.mainLogo).width, (float)((Texture)MainClass.mainLogo).height), new Vector2(0.5f, 0.5f)); CosmeticRegistry.SpawnCosmeticGUI(); Transform val = gameObject.transform.Find("MenuContainer").Find("LobbyHostSettings").Find("Panel") .Find("LobbyHostOptions") .Find("OptionsNormal"); GameObject val2 = Object.Instantiate<GameObject>(MainClass.crewCountUI, val); RectTransform component2 = val2.GetComponent<RectTransform>(); ((Transform)component2).localPosition = new Vector3(96.9f, -70f, -6.7f); TMP_InputField inputField = ((Component)val2.transform.Find("InputField (TMP)")).GetComponent<TMP_InputField>(); inputField.characterLimit = 3; inputField.text = MainClass.newPlayerCount.ToString(); ((UnityEvent<string>)(object)inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string s) { if (int.TryParse(s, out var result)) { MainClass.newPlayerCount = result; MainClass.newPlayerCount = Mathf.Clamp(MainClass.newPlayerCount, 1, MainClass.maxPlayerCount); inputField.text = MainClass.newPlayerCount.ToString(); MainClass.SaveSettingsToFile(); } else if (s.Length != 0) { inputField.text = MainClass.newPlayerCount.ToString(); inputField.caretPosition = 1; } }); } catch (Exception) { } } } [HarmonyPatch(typeof(QuickMenuManager), "AddUserToPlayerList")] public static class AddUserPlayerListPatch { public static bool Prefix(QuickMenuManager __instance, ulong steamId, string playerName, int playerObjectId) { QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance); MainClass.EnablePlayerObjectsBasedOnConnected(); return false; } } [HarmonyPatch(typeof(QuickMenuManager), "RemoveUserFromPlayerList")] public static class RemoveUserPlayerListPatch { public static bool Prefix(QuickMenuManager __instance) { QuickmenuVisualInjectPatch.PopulateQuickMenu(__instance); return false; } } [HarmonyPatch(typeof(QuickMenuManager), "Update")] public static class QuickMenuUpdatePatch { public static bool Prefix(QuickMenuManager __instance) { return false; } } [HarmonyPatch(typeof(QuickMenuManager), "NonHostPlayerSlotsEnabled")] public static class QuickMenuDisplayPatch { public static bool Prefix(QuickMenuManager __instance, ref bool __result) { __result = true; return false; } } [HarmonyPatch(typeof(QuickMenuManager), "Start")] public static class QuickmenuVisualInjectPatch { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__2_2; internal void <PopulateQuickMenu>b__2_2() { if (!GameNetworkManager.Instance.disableSteam) { } } } public static GameObject quickMenuScrollInstance; public static void Postfix(QuickMenuManager __instance) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) GameObject gameObject = ((Component)__instance.playerListPanel.transform.Find("Image")).gameObject; GameObject val = Object.Instantiate<GameObject>(MainClass.quickMenuScrollParent); val.transform.SetParent(gameObject.transform); RectTransform component = val.GetComponent<RectTransform>(); ((Transform)component).localPosition = new Vector3(0f, -31.2f, 0f); ((Transform)component).localScale = Vector3.one; quickMenuScrollInstance = val; } public static void PopulateQuickMenu(QuickMenuManager __instance) { //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Expected O, but got Unknown //IL_02d8: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Expected O, but got Unknown int childCount = quickMenuScrollInstance.transform.Find("Holder").childCount; List<GameObject> list = new List<GameObject>(); for (int i = 0; i < childCount; i++) { list.Add(((Component)quickMenuScrollInstance.transform.Find("Holder").GetChild(i)).gameObject); } foreach (GameObject item in list) { Object.Destroy((Object)(object)item); } if (!Object.op_Implicit((Object)(object)StartOfRound.Instance)) { return; } for (int j = 0; j < StartOfRound.Instance.allPlayerScripts.Length; j++) { PlayerControllerB playerScript = StartOfRound.Instance.allPlayerScripts[j]; if (!playerScript.isPlayerControlled && !playerScript.isPlayerDead) { continue; } GameObject val = Object.Instantiate<GameObject>(MainClass.playerEntry, quickMenuScrollInstance.transform.Find("Holder")); RectTransform component = val.GetComponent<RectTransform>(); ((Transform)component).localScale = Vector3.one; ((Transform)component).localPosition = new Vector3(0f, 0f - ((Transform)component).localPosition.y, 0f); TextMeshProUGUI component2 = ((Component)val.transform.Find("PlayerNameButton").Find("PName")).GetComponent<TextMeshProUGUI>(); ((TMP_Text)component2).text = playerScript.playerUsername; Slider playerVolume = ((Component)val.transform.Find("PlayerVolumeSlider")).GetComponent<Slider>(); int finalIndex = j; ((UnityEvent<float>)(object)playerVolume.onValueChanged).AddListener((UnityAction<float>)delegate(float f) { if (playerScript.isPlayerControlled || playerScript.isPlayerDead) { float num = f / playerVolume.maxValue + 1f; if (num <= -1f) { SoundManager.Instance.playerVoiceVolumes[finalIndex] = -70f; } else { SoundManager.Instance.playerVoiceVolumes[finalIndex] = num; } } }); if (StartOfRound.Instance.localPlayerController.playerClientId == playerScript.playerClientId) { ((Component)playerVolume).gameObject.SetActive(false); ((Component)val.transform.Find("Text (1)")).gameObject.SetActive(false); } Button component3 = ((Component)val.transform.Find("KickButton")).GetComponent<Button>(); ((UnityEvent)component3.onClick).AddListener((UnityAction)delegate { __instance.KickUserFromServer(finalIndex); }); if (!GameNetworkManager.Instance.isHostingGame) { ((Component)component3).gameObject.SetActive(false); } Button component4 = ((Component)val.transform.Find("ProfileIcon")).GetComponent<Button>(); ButtonClickedEvent onClick = component4.onClick; object obj = <>c.<>9__2_2; if (obj == null) { UnityAction val2 = delegate { if (!GameNetworkManager.Instance.disableSteam) { } }; <>c.<>9__2_2 = val2; obj = (object)val2; } ((UnityEvent)onClick).AddListener((UnityAction)obj); } } } [HarmonyPatch(typeof(HUDManager), "UpdateBoxesSpectateUI")] public static class SpectatorBoxUpdatePatch { public static void Postfix(HUDManager __instance) { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) Dictionary<Animator, PlayerControllerB> fieldValue = ReflectionUtils.GetFieldValue<Dictionary<Animator, PlayerControllerB>>(__instance, "spectatingPlayerBoxes"); int num = -64; int num2 = 0; int num3 = 0; int num4 = -70; int num5 = 230; int num6 = 4; foreach (KeyValuePair<Animator, PlayerControllerB> item in fieldValue) { if (((Component)item.Key).gameObject.activeInHierarchy) { GameObject gameObject = ((Component)item.Key).gameObject; RectTransform component = gameObject.GetComponent<RectTransform>(); int num7 = (int)Math.Floor((double)num3 / (double)num6); int num8 = num3 % num6; int num9 = num8 * num4; int num10 = num7 * num5; component.anchoredPosition = Vector2.op_Implicit(new Vector3((float)(num + num10), (float)(num2 + num9), 0f)); num3++; } } } } [HarmonyPatch(typeof(HUDManager), "FillEndGameStats")] public static class HudFillEndGameFix { public static bool Prefix(HUDManager __instance, EndOfGameStats stats) { //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Invalid comparison between Unknown and I4 int num = 0; int num2 = 0; for (int i = 0; i < __instance.statsUIElements.playerNamesText.Length; i++) { PlayerControllerB val = __instance.playersManager.allPlayerScripts[i]; ((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = ""; ((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = false; ((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = "Notes: \n"; if (val.disconnectedMidGame || val.isPlayerDead || val.isPlayerControlled) { if (val.isPlayerDead) { num++; } else if (val.isPlayerControlled) { num2++; } ((TMP_Text)__instance.statsUIElements.playerNamesText[i]).text = __instance.playersManager.allPlayerScripts[i].playerUsername; ((Behaviour)__instance.statsUIElements.playerStates[i]).enabled = true; if (__instance.playersManager.allPlayerScripts[i].isPlayerDead) { if ((int)__instance.playersManager.allPlayerScripts[i].causeOfDeath == 10) { __instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.missingIcon; } else { __instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.deceasedIcon; } } else { __instance.statsUIElements.playerStates[i].sprite = __instance.statsUIElements.aliveIcon; } for (int j = 0; j < 3 && j < stats.allPlayerStats[i].playerNotes.Count; j++) { TextMeshProUGUI val2 = __instance.statsUIElements.playerNotesText[i]; ((TMP_Text)val2).text = ((TMP_Text)val2).text + "* " + stats.allPlayerStats[i].playerNotes[j] + "\n"; } } else { ((TMP_Text)__instance.statsUIElements.playerNotesText[i]).text = ""; } } ((TMP_Text)__instance.statsUIElements.quotaNumerator).text = RoundManager.Instance.scrapCollectedInLevel.ToString(); ((TMP_Text)__instance.statsUIElements.quotaDenominator).text = RoundManager.Instance.totalScrapValueInLevel.ToString(); if (StartOfRound.Instance.allPlayersDead) { ((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = true; ((TMP_Text)__instance.statsUIElements.gradeLetter).text = "F"; return false; } ((Behaviour)__instance.statsUIElements.allPlayersDeadOverlay).enabled = false; int num3 = 0; float num4 = (float)RoundManager.Instance.scrapCollectedInLevel / RoundManager.Instance.totalScrapValueInLevel; if (num2 == StartOfRound.Instance.connectedPlayersAmount + 1) { num3++; } else if (num > 1) { num3--; } if (num4 >= 0.99f) { num3 += 2; } else if (num4 >= 0.6f) { num3++; } else if (num4 <= 0.25f) { num3--; } switch (num3) { case -1: ((TMP_Text)__instance.statsUIElements.gradeLetter).text = "D"; return false; case 0: ((TMP_Text)__instance.statsUIElements.gradeLetter).text = "C"; return false; case 1: ((TMP_Text)__instance.statsUIElements.gradeLetter).text = "B"; return false; case 2: ((TMP_Text)__instance.statsUIElements.gradeLetter).text = "A"; return false; case 3: ((TMP_Text)__instance.statsUIElements.gradeLetter).text = "S"; return false; default: return false; } } } [HarmonyPatch(typeof(HUDManager), "Start")] public static class HudStartPatch { public static void Postfix(HUDManager __instance) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) EndOfGameStatUIElements statsUIElements = __instance.statsUIElements; GameObject gameObject = ((Component)((Component)statsUIElements.playerNamesText[0]).gameObject.transform.parent).gameObject; GameObject gameObject2 = ((Component)gameObject.transform.parent.parent).gameObject; GameObject gameObject3 = ((Component)gameObject2.transform.Find("BGBoxes")).gameObject; gameObject2.transform.parent.Find("DeathScreen").SetSiblingIndex(3); gameObject3.transform.localScale = new Vector3(2.5f, 1f, 1f); MakePlayerHolder(4, gameObject, statsUIElements, new Vector3(426.9556f, -0.7932f, 0f)); MakePlayerHolder(5, gameObject, statsUIElements, new Vector3(426.9556f, -115.4483f, 0f)); MakePlayerHolder(6, gameObject, statsUIElements, new Vector3(-253.6783f, -115.4483f, 0f)); MakePlayerHolder(7, gameObject, statsUIElements, new Vector3(-253.6783f, -0.7932f, 0f)); for (int i = 8; i < MainClass.newPlayerCount; i++) { MakePlayerHolder(i, gameObject, statsUIElements, new Vector3(10000f, 10000f, 0f)); } } public static void MakePlayerHolder(int index, GameObject original, EndOfGameStatUIElements uiElements, Vector3 localPosition) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) if (index + 1 <= MainClass.newPlayerCount) { GameObject val = Object.Instantiate<GameObject>(original); RectTransform component = val.GetComponent<RectTransform>(); RectTransform component2 = original.GetComponent<RectTransform>(); ((Transform)component).SetParent(((Transform)component2).parent); ((Transform)component).localScale = new Vector3(1f, 1f, 1f); ((Transform)component).localPosition = localPosition; GameObject gameObject = ((Component)val.transform.Find("PlayerName1")).gameObject; GameObject gameObject2 = ((Component)val.transform.Find("Notes")).gameObject; ((Transform)gameObject2.GetComponent<RectTransform>()).localPosition = new Vector3(-95.7222f, 43.3303f, 0f); GameObject gameObject3 = ((Component)val.transform.Find("Symbol")).gameObject; if (index >= uiElements.playerNamesText.Length) { Array.Resize(ref uiElements.playerNamesText, index + 1); Array.Resize(ref uiElements.playerStates, index + 1); Array.Resize(ref uiElements.playerNotesText, index + 1); } uiElements.playerNamesText[index] = gameObject.GetComponent<TextMeshProUGUI>(); uiElements.playerNotesText[index] = gameObject2.GetComponent<TextMeshProUGUI>(); uiElements.playerStates[index] = gameObject3.GetComponent<Image>(); } } } public static class PluginInformation { public const string PLUGIN_NAME = "MoreCompany"; public const string PLUGIN_VERSION = "1.7.2"; public const string PLUGIN_GUID = "me.swipez.melonloader.morecompany"; } [BepInPlugin("me.swipez.melonloader.morecompany", "MoreCompany", "1.7.2")] public class MainClass : BaseUnityPlugin { public static int newPlayerCount = 32; public static int maxPlayerCount = 50; public static bool showCosmetics = true; public static List<PlayerControllerB> notSupposedToExistPlayers = new List<PlayerControllerB>(); public static Texture2D mainLogo; public static GameObject quickMenuScrollParent; public static GameObject playerEntry; public static GameObject crewCountUI; public static GameObject cosmeticGUIInstance; public static GameObject cosmeticButton; public static ManualLogSource StaticLogger; public static Dictionary<int, List<string>> playerIdsAndCosmetics = new Dictionary<int, List<string>>(); public static string cosmeticSavePath = Application.persistentDataPath + "/morecompanycosmetics.txt"; public static string moreCompanySave = Application.persistentDataPath + "/morecompanysave.txt"; public static string dynamicCosmeticsPath = Paths.PluginPath + "/MoreCompanyCosmetics"; private void Awake() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown StaticLogger = ((BaseUnityPlugin)this).Logger; Harmony val = new Harmony("me.swipez.melonloader.morecompany"); try { val.PatchAll(); } catch (Exception ex) { StaticLogger.LogError((object)("Failed to patch: " + ex)); } ManualHarmonyPatches.ManualPatch(val); StaticLogger.LogInfo((object)"Loading MoreCompany..."); StaticLogger.LogInfo((object)("Checking: " + dynamicCosmeticsPath)); if (!Directory.Exists(dynamicCosmeticsPath)) { StaticLogger.LogInfo((object)"Creating cosmetics directory"); Directory.CreateDirectory(dynamicCosmeticsPath); } ReadSettingsFromFile(); ReadCosmeticsFromFile(); StaticLogger.LogInfo((object)"Read settings and cosmetics"); AssetBundle bundle = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.assets", Assembly.GetExecutingAssembly()); AssetBundle val2 = BundleUtilities.LoadBundleFromInternalAssembly("morecompany.cosmetics", Assembly.GetExecutingAssembly()); CosmeticRegistry.LoadCosmeticsFromBundle(val2); val2.Unload(false); SteamFriends.OnGameLobbyJoinRequested += delegate(Lobby lobby, SteamId steamId) { newPlayerCount = ((Lobby)(ref lobby)).MaxMembers; }; SteamMatchmaking.OnLobbyEntered += delegate(Lobby lobby) { newPlayerCount = ((Lobby)(ref lobby)).MaxMembers; }; StaticLogger.LogInfo((object)"Loading USER COSMETICS..."); RecursiveCosmeticLoad(Paths.PluginPath); LoadAssets(bundle); StaticLogger.LogInfo((object)"Loaded MoreCompany FULLY"); } private void RecursiveCosmeticLoad(string directory) { string[] directories = Directory.GetDirectories(directory); foreach (string directory2 in directories) { RecursiveCosmeticLoad(directory2); } string[] files = Directory.GetFiles(directory); foreach (string text in files) { if (text.EndsWith(".cosmetics")) { AssetBundle val = AssetBundle.LoadFromFile(text); CosmeticRegistry.LoadCosmeticsFromBundle(val); val.Unload(false); } } } private void ReadCosmeticsFromFile() { if (File.Exists(cosmeticSavePath)) { string[] array = File.ReadAllLines(cosmeticSavePath); string[] array2 = array; foreach (string item in array2) { CosmeticRegistry.locallySelectedCosmetics.Add(item); } } } public static void WriteCosmeticsToFile() { string text = ""; foreach (string locallySelectedCosmetic in CosmeticRegistry.locallySelectedCosmetics) { text = text + locallySelectedCosmetic + "\n"; } File.WriteAllText(cosmeticSavePath, text); } public static void SaveSettingsToFile() { string text = ""; text = text + newPlayerCount + "\n"; text = text + showCosmetics + "\n"; File.WriteAllText(moreCompanySave, text); } public static void ReadSettingsFromFile() { if (File.Exists(moreCompanySave)) { string[] array = File.ReadAllLines(moreCompanySave); try { newPlayerCount = int.Parse(array[0]); showCosmetics = bool.Parse(array[1]); } catch (Exception) { StaticLogger.LogError((object)"Failed to read settings from file, resetting to default"); newPlayerCount = 32; showCosmetics = true; } } } private static void LoadAssets(AssetBundle bundle) { if (Object.op_Implicit((Object)(object)bundle)) { mainLogo = bundle.LoadPersistentAsset<Texture2D>("assets/morecompanyassets/morecompanytransparentred.png"); quickMenuScrollParent = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/quickmenuoverride.prefab"); playerEntry = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/playerlistslot.prefab"); cosmeticGUIInstance = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/testoverlay.prefab"); cosmeticButton = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/cosmeticinstance.prefab"); crewCountUI = bundle.LoadPersistentAsset<GameObject>("assets/morecompanyassets/crewcountfield.prefab"); bundle.Unload(false); } } public static void ResizePlayerCache(Dictionary<uint, Dictionary<int, NetworkObject>> ScenePlacedObjects) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Expected O, but got Unknown StartOfRound instance = StartOfRound.Instance; if (instance.allPlayerObjects.Length == newPlayerCount) { return; } playerIdsAndCosmetics.Clear(); uint num = 10000u; int num2 = newPlayerCount - instance.allPlayerObjects.Length; int num3 = instance.allPlayerObjects.Length; GameObject val = instance.allPlayerObjects[3]; for (int i = 0; i < num2; i++) { uint num4 = num + (uint)i; GameObject val2 = Object.Instantiate<GameObject>(val); NetworkObject component = val2.GetComponent<NetworkObject>(); ReflectionUtils.SetFieldValue(component, "GlobalObjectIdHash", num4); Scene scene = ((Component)component).gameObject.scene; int handle = ((Scene)(ref scene)).handle; uint num5 = num4; if (!ScenePlacedObjects.ContainsKey(num5)) { ScenePlacedObjects.Add(num5, new Dictionary<int, NetworkObject>()); } if (ScenePlacedObjects[num5].ContainsKey(handle)) { string arg = (((Object)(object)ScenePlacedObjects[num5][handle] != (Object)null) ? ((Object)ScenePlacedObjects[num5][handle]).name : "Null Entry"); throw new Exception(((Object)component).name + " tried to registered with ScenePlacedObjects which already contains " + string.Format("the same {0} value {1} for {2}!", "GlobalObjectIdHash", num5, arg)); } ScenePlacedObjects[num5].Add(handle, component); ((Object)val2).name = $"Player ({4 + i})"; val2.transform.parent = null; PlayerControllerB componentInChildren = val2.GetComponentInChildren<PlayerControllerB>(); notSupposedToExistPlayers.Add(componentInChildren); componentInChildren.playerClientId = (ulong)(4 + i); componentInChildren.isPlayerControlled = false; componentInChildren.isPlayerDead = false; componentInChildren.DropAllHeldItems(false, false); componentInChildren.TeleportPlayer(instance.notSpawnedPosition.position, false, 0f, false, true); UnlockableSuit.SwitchSuitForPlayer(componentInChildren, 0, false); Array.Resize(ref instance.allPlayerObjects, instance.allPlayerObjects.Length + 1); Array.Resize(ref instance.allPlayerScripts, instance.allPlayerScripts.Length + 1); Array.Resize(ref instance.gameStats.allPlayerStats, instance.gameStats.allPlayerStats.Length + 1); Array.Resize(ref instance.playerSpawnPositions, instance.playerSpawnPositions.Length + 1); instance.allPlayerObjects[num3 + i] = val2; instance.gameStats.allPlayerStats[num3 + i] = new PlayerStats(); instance.allPlayerScripts[num3 + i] = componentInChildren; instance.playerSpawnPositions[num3 + i] = instance.playerSpawnPositions[3]; } } public static void EnablePlayerObjectsBasedOnConnected() { int connectedPlayersAmount = StartOfRound.Instance.connectedPlayersAmount; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { for (int j = 0; j < connectedPlayersAmount + 1; j++) { if (!val.isPlayerControlled) { ((Component)val).gameObject.SetActive(false); } else { ((Component)val).gameObject.SetActive(true); } } } } } [HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesServerRpc")] public static class SendNewPlayerValuesServerRpcPatch { public static ulong lastId; public static void Prefix(PlayerControllerB __instance, ulong newPlayerSteamId) { NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager; if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer) { lastId = newPlayerSteamId; } } } [HarmonyPatch(typeof(PlayerControllerB), "SendNewPlayerValuesClientRpc")] public static class SendNewPlayerValuesClientRpcPatch { public static void Prefix(PlayerControllerB __instance, ref ulong[] playerSteamIds) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager; if ((Object)(object)networkManager == (Object)null || !networkManager.IsListening) { return; } if (StartOfRound.Instance.mapScreen.radarTargets.Count != MainClass.newPlayerCount) { List<PlayerControllerB> useless = new List<PlayerControllerB>(); foreach (PlayerControllerB notSupposedToExistPlayer in MainClass.notSupposedToExistPlayers) { if (Object.op_Implicit((Object)(object)notSupposedToExistPlayer)) { StartOfRound.Instance.mapScreen.radarTargets.Add(new TransformAndName(((Component)notSupposedToExistPlayer).transform, notSupposedToExistPlayer.playerUsername, false)); } else { useless.Add(notSupposedToExistPlayer); } } MainClass.notSupposedToExistPlayers.RemoveAll((PlayerControllerB x) => useless.Contains(x)); } if (!networkManager.IsServer) { return; } List<ulong> list = new List<ulong>(); for (int i = 0; i < MainClass.newPlayerCount; i++) { if (i == (int)__instance.playerClientId) { list.Add(SendNewPlayerValuesServerRpcPatch.lastId); } else { list.Add(__instance.playersManager.allPlayerScripts[i].playerSteamId); } } playerSteamIds = list.ToArray(); } } public static class HUDManagerBullshitPatch { public static bool ManualPrefix(HUDManager __instance) { return false; } } [HarmonyPatch(typeof(StartOfRound), "SyncShipUnlockablesClientRpc")] public static class SyncShipUnlockablePatch { public static void Prefix(StartOfRound __instance, ref int[] playerSuitIDs, bool shipLightsOn, Vector3[] placeableObjectPositions, Vector3[] placeableObjectRotations, int[] placeableObjects, int[] storedItems, int[] scrapValues, int[] itemSaveData) { NetworkManager networkManager = ((NetworkBehaviour)__instance).NetworkManager; if (!((Object)(object)networkManager == (Object)null) && networkManager.IsListening && networkManager.IsServer) { int[] array = new int[MainClass.newPlayerCount]; for (int i = 0; i < MainClass.newPlayerCount; i++) { array[i] = __instance.allPlayerScripts[i].currentSuitID; } playerSuitIDs = array; } } } [HarmonyPatch(typeof(NetworkSceneManager), "PopulateScenePlacedObjects")] public static class ScenePlacedObjectsInitPatch { public static void Postfix(ref Dictionary<uint, Dictionary<int, NetworkObject>> ___ScenePlacedObjects) { MainClass.ResizePlayerCache(___ScenePlacedObjects); } } [HarmonyPatch(typeof(GameNetworkManager), "LobbyDataIsJoinable")] public static class LobbyDataJoinablePatch { public static bool Prefix(ref bool __result) { __result = true; return false; } } [HarmonyPatch(typeof(NetworkConnectionManager), "HandleConnectionApproval")] public static class ConnectionApprovalTest { public static void Prefix(ulong ownerClientId, ConnectionApprovalResponse response) { if (Object.op_Implicit((Object)(object)StartOfRound.Instance)) { if (StartOfRound.Instance.connectedPlayersAmount >= MainClass.newPlayerCount) { response.Approved = false; response.Reason = "Server is full"; } else { response.Approved = true; } } } } [HarmonyPatch(typeof(SteamMatchmaking), "CreateLobbyAsync")] public static class LobbyThingPatch { public static void Prefix(ref int maxMembers) { MainClass.ReadSettingsFromFile(); maxMembers = MainClass.newPlayerCount; } } public class ManualHarmonyPatches { public static void ManualPatch(Harmony HarmonyInstance) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(HUDManager), "SyncAllPlayerLevelsServerRpc", new Type[0], (Type[])null), new HarmonyMethod(typeof(HUDManagerBullshitPatch).GetMethod("ManualPrefix")), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } public class MimicPatches { [HarmonyPatch(typeof(MaskedPlayerEnemy), "SetEnemyOutside")] public class MaskedPlayerEnemyOnEnablePatch { public static void Postfix(MaskedPlayerEnemy __instance) { //IL_00d2: 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) if (!((Object)(object)__instance.mimickingPlayer != (Object)null)) { return; } List<string> list = MainClass.playerIdsAndCosmetics[(int)__instance.mimickingPlayer.playerClientId]; Transform val = ((Component)__instance).transform.Find("ScavengerModel").Find("metarig"); CosmeticApplication component = ((Component)val).GetComponent<CosmeticApplication>(); if (Object.op_Implicit((Object)(object)component)) { component.ClearCosmetics(); Object.Destroy((Object)(object)component); } component = ((Component)val).gameObject.AddComponent<CosmeticApplication>(); foreach (string item in list) { component.ApplyCosmetic(item, startEnabled: true); } foreach (CosmeticInstance spawnedCosmetic in component.spawnedCosmetics) { Transform transform = ((Component)spawnedCosmetic).transform; transform.localScale *= 0.38f; } } } } public class ReflectionUtils { public static void InvokeMethod(object obj, string methodName, object[] parameters) { Type type = obj.GetType(); MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); method.Invoke(obj, parameters); } public static void InvokeMethod(object obj, Type forceType, string methodName, object[] parameters) { MethodInfo method = forceType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); method.Invoke(obj, parameters); } public static void SetPropertyValue(object obj, string propertyName, object value) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); property.SetValue(obj, value); } public static T InvokeMethod<T>(object obj, string methodName, object[] parameters) { Type type = obj.GetType(); MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return (T)method.Invoke(obj, parameters); } public static T GetFieldValue<T>(object obj, string fieldName) { Type type = obj.GetType(); FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return (T)field.GetValue(obj); } public static void SetFieldValue(object obj, string fieldName, object value) { Type type = obj.GetType(); FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); field.SetValue(obj, value); } } [HarmonyPatch(typeof(ShipTeleporter), "Awake")] public static class ShipTeleporterAwakePatch { public static void Postfix(ShipTeleporter __instance) { int[] array = new int[MainClass.newPlayerCount]; for (int i = 0; i < MainClass.newPlayerCount; i++) { array[i] = -1; } ReflectionUtils.SetFieldValue(__instance, "playersBeingTeleported", array); } } [HarmonyPatch(typeof(PlayerControllerB), "SpectateNextPlayer")] public static class SpectatePatches { public static bool Prefix(PlayerControllerB __instance) { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) int num = 0; if ((Object)(object)__instance.spectatedPlayerScript != (Object)null) { num = (int)__instance.spectatedPlayerScript.playerClientId; } for (int i = 0; i < MainClass.newPlayerCount; i++) { num = (num + 1) % MainClass.newPlayerCount; if (!__instance.playersManager.allPlayerScripts[num].isPlayerDead && __instance.playersManager.allPlayerScripts[num].isPlayerControlled && (Object)(object)__instance.playersManager.allPlayerScripts[num] != (Object)(object)__instance) { __instance.spectatedPlayerScript = __instance.playersManager.allPlayerScripts[num]; __instance.SetSpectatedPlayerEffects(false); return false; } } if ((Object)(object)__instance.deadBody != (Object)null && ((Component)__instance.deadBody).gameObject.activeSelf) { __instance.spectateCameraPivot.position = __instance.deadBody.bodyParts[0].position; ReflectionUtils.InvokeMethod(__instance, "RaycastSpectateCameraAroundPivot", null); } StartOfRound.Instance.SetPlayerSafeInShip(); return false; } } [HarmonyPatch(typeof(SoundManager), "Start")] public static class SoundManagerStartPatch { public static void Postfix() { int num = MainClass.newPlayerCount - 4; int num2 = 4; for (int i = 0; i < num; i++) { Array.Resize(ref SoundManager.Instance.playerVoicePitches, SoundManager.Instance.playerVoicePitches.Length + 1); Array.Resize(ref SoundManager.Instance.playerVoicePitchTargets, SoundManager.Instance.playerVoicePitchTargets.Length + 1); Array.Resize(ref SoundManager.Instance.playerVoiceVolumes, SoundManager.Instance.playerVoiceVolumes.Length + 1); Array.Resize(ref SoundManager.Instance.playerVoicePitchLerpSpeed, SoundManager.Instance.playerVoicePitchLerpSpeed.Length + 1); Array.Resize(ref SoundManager.Instance.playerVoiceMixers, SoundManager.Instance.playerVoiceMixers.Length + 1); AudioMixerGroup val = ((IEnumerable<AudioMixerGroup>)Resources.FindObjectsOfTypeAll<AudioMixerGroup>()).FirstOrDefault((Func<AudioMixerGroup, bool>)((AudioMixerGroup x) => ((Object)x).name.Contains("Voice"))); SoundManager.Instance.playerVoicePitches[num2 + i] = 1f; SoundManager.Instance.playerVoicePitchTargets[num2 + i] = 1f; SoundManager.Instance.playerVoiceVolumes[num2 + i] = 0.5f; SoundManager.Instance.playerVoicePitchLerpSpeed[num2 + i] = 3f; SoundManager.Instance.playerVoiceMixers[num2 + i] = val; } } } [HarmonyPatch(typeof(StartOfRound), "GetPlayerSpawnPosition")] public static class SpawnPositionClampPatch { public static void Prefix(ref int playerNum, bool simpleTeleport = false) { if (playerNum > 3) { playerNum = 3; } } } [HarmonyPatch(typeof(StartOfRound), "OnClientConnect")] public static class OnClientConnectedPatch { public static bool Prefix(StartOfRound __instance, ulong clientId) { if (!((NetworkBehaviour)__instance).IsServer) { return false; } Debug.Log((object)"player connected"); Debug.Log((object)$"connected players #: {__instance.connectedPlayersAmount}"); try { List<int> list = __instance.ClientPlayerList.Values.ToList(); Debug.Log((object)$"Connecting new player on host; clientId: {clientId}"); int num = 0; for (int i = 1; i < MainClass.newPlayerCount; i++) { if (!list.Contains(i)) { num = i; break; } } __instance.allPlayerScripts[num].actualClientId = clientId; __instance.allPlayerObjects[num].GetComponent<NetworkObject>().ChangeOwnership(clientId); Debug.Log((object)$"New player assigned object id: {__instance.allPlayerObjects[num]}"); List<ulong> list2 = new List<ulong>(); for (int j = 0; j < __instance.allPlayerObjects.Length; j++) { NetworkObject component = __instance.allPlayerObjects[j].GetComponent<NetworkObject>(); if (!component.IsOwnedByServer) { list2.Add(component.OwnerClientId); } else if (j == 0) { list2.Add(NetworkManager.Singleton.LocalClientId); } else { list2.Add(999uL); } } int groupCredits = Object.FindObjectOfType<Terminal>().groupCredits; int profitQuota = TimeOfDay.Instance.profitQuota; int quotaFulfilled = TimeOfDay.Instance.quotaFulfilled; int num2 = (int)TimeOfDay.Instance.timeUntilDeadline; ReflectionUtils.InvokeMethod(__instance, "OnPlayerConnectedClientRpc", new object[10] { clientId, __instance.connectedPlayersAmount, list2.ToArray(), num, groupCredits, __instance.currentLevelID, profitQuota, num2, quotaFulfilled, __instance.randomMapSeed }); __instance.ClientPlayerList.Add(clientId, num); Debug.Log((object)$"client id connecting: {clientId} ; their corresponding player object id: {num}"); } catch (Exception arg) { Debug.LogError((object)$"Error occured in OnClientConnected! Shutting server down. clientId: {clientId}. Error: {arg}"); GameNetworkManager.Instance.disconnectionReasonMessage = "Error occured when a player attempted to join the server! Restart the application and please report the glitch!"; GameNetworkManager.Instance.Disconnect(); } return false; } } [HarmonyPatch(typeof(SteamLobbyManager), "LoadServerList")] public static class LoadServerListPatch { public static bool Prefix(SteamLobbyManager __instance) { OverrideMethod(__instance); return false; } private static async void OverrideMethod(SteamLobbyManager __instance) { if (GameNetworkManager.Instance.waitingForLobbyDataRefresh) { return; } ReflectionUtils.SetFieldValue(__instance, "refreshServerListTimer", 0f); ((TMP_Text)__instance.serverListBlankText).text = "Loading server list..."; ReflectionUtils.GetFieldValue<Lobby[]>(__instance, "currentLobbyList"); LobbySlot[] array = Object.FindObjectsOfType<LobbySlot>(); for (int i = 0; i < array.Length; i++) { Object.Destroy((Object)(object)((Component)array[i]).gameObject); } LobbyQuery val; switch (__instance.sortByDistanceSetting) { case 0: val = SteamMatchmaking.LobbyList; ((LobbyQuery)(ref val)).FilterDistanceClose(); break; case 1: val = SteamMatchmaking.LobbyList; ((LobbyQuery)(ref val)).FilterDistanceFar(); break; case 2: val = SteamMatchmaking.LobbyList; ((LobbyQuery)(ref val)).FilterDistanceWorldwide(); break; } Debug.Log((object)"Requested server list"); GameNetworkManager.Instance.waitingForLobbyDataRefresh = true; Lobby[] currentLobbyList; switch (__instance.sortByDistanceSetting) { case 0: val = SteamMatchmaking.LobbyList; val = ((LobbyQuery)(ref val)).FilterDistanceClose(); val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1); val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString()); currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync(); break; case 1: val = SteamMatchmaking.LobbyList; val = ((LobbyQuery)(ref val)).FilterDistanceFar(); val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1); val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString()); currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync(); break; default: val = SteamMatchmaking.LobbyList; val = ((LobbyQuery)(ref val)).FilterDistanceWorldwide(); val = ((LobbyQuery)(ref val)).WithSlotsAvailable(1); val = ((LobbyQuery)(ref val)).WithKeyValue("vers", GameNetworkManager.Instance.gameVersionNum.ToString()); currentLobbyList = await ((LobbyQuery)(ref val)).RequestAsync(); break; } GameNetworkManager.Instance.waitingForLobbyDataRefresh = false; if (currentLobbyList != null) { Debug.Log((object)"Got lobby list!"); ReflectionUtils.InvokeMethod(__instance, "DebugLogServerList", null); if (currentLobbyList.Length == 0) { ((TMP_Text)__instance.serverListBlankText).text = "No available servers to join."; } else { ((TMP_Text)__instance.serverListBlankText).text = ""; } ReflectionUtils.SetFieldValue(__instance, "lobbySlotPositionOffset", 0f); for (int j = 0; j < currentLobbyList.Length; j++) { Friend[] array2 = SteamFriends.GetBlocked().ToArray(); if (array2 != null) { for (int k = 0; k < array2.Length; k++) { Debug.Log((object)$"blocked user: {((Friend)(ref array2[k])).Name}; id: {array2[k].Id}"); if (((Lobby)(ref currentLobbyList[j])).IsOwnedBy(array2[k].Id)) { Debug.Log((object)("Hiding lobby by blocked user: " + ((Friend)(ref array2[k])).Name)); } } } else { Debug.Log((object)"Blocked users list is null"); } GameObject gameObject = Object.Instantiate<GameObject>(__instance.LobbySlotPrefab, __instance.levelListContainer); gameObject.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, 0f + ReflectionUtils.GetFieldValue<float>(__instance, "lobbySlotPositionOffset")); ReflectionUtils.SetFieldValue(__instance, "lobbySlotPositionOffset", ReflectionUtils.GetFieldValue<float>(__instance, "lobbySlotPositionOffset") - 42f); LobbySlot componentInChildren = gameObject.GetComponentInChildren<LobbySlot>(); ((TMP_Text)componentInChildren.LobbyName).text = ((Lobby)(ref currentLobbyList[j])).GetData("name"); ((TMP_Text)componentInChildren.playerCount).text = $"{((Lobby)(ref currentLobbyList[j])).MemberCount} / {((Lobby)(ref currentLobbyList[j])).MaxMembers}"; componentInChildren.lobbyId = ((Lobby)(ref currentLobbyList[j])).Id; componentInChildren.thisLobby = currentLobbyList[j]; ReflectionUtils.SetFieldValue(__instance, "currentLobbyList", currentLobbyList); } } else { Debug.Log((object)"Lobby list is null after request."); ((TMP_Text)__instance.serverListBlankText).text = "No available servers to join."; } } } [HarmonyPatch(typeof(GameNetworkManager), "Awake")] public static class GameNetworkAwakePatch { public static int originalVersion; public static void Postfix(GameNetworkManager __instance) { originalVersion = __instance.gameVersionNum; if (!AssemblyChecker.HasAssemblyLoaded("lc_api")) { __instance.gameVersionNum = 9999; } } } [HarmonyPatch(typeof(MenuManager), "Awake")] public static class MenuManagerVersionDisplayPatch { public static void Postfix(MenuManager __instance) { if ((Object)(object)GameNetworkManager.Instance != (Object)null && (Object)(object)__instance.versionNumberText != (Object)null) { ((TMP_Text)__instance.versionNumberText).text = $"v{GameNetworkAwakePatch.originalVersion} (MC)"; } } } } namespace MoreCompany.Utils { public class AssemblyChecker { public static bool HasAssemblyLoaded(string name) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); Assembly[] array = assemblies; foreach (Assembly assembly in array) { if (assembly.GetName().Name.ToLower().Equals(name)) { return true; } } return false; } } public class BundleUtilities { public static byte[] GetResourceBytes(string filename, Assembly assembly) { string[] manifestResourceNames = assembly.GetManifestResourceNames(); foreach (string text in manifestResourceNames) { if (!text.Contains(filename)) { continue; } using Stream stream = assembly.GetManifestResourceStream(text); if (stream == null) { return null; } byte[] array = new byte[stream.Length]; stream.Read(array, 0, array.Length); return array; } return null; } public static AssetBundle LoadBundleFromInternalAssembly(string filename, Assembly assembly) { return AssetBundle.LoadFromMemory(GetResourceBytes(filename, assembly)); } } public static class AssetBundleExtension { public static T LoadPersistentAsset<T>(this AssetBundle bundle, string name) where T : Object { Object val = bundle.LoadAsset(name); if (val != (Object)null) { val.hideFlags = (HideFlags)32; return (T)(object)val; } return default(T); } } } namespace MoreCompany.Cosmetics { public class CosmeticApplication : MonoBehaviour { public Transform head; public Transform hip; public Transform lowerArmRight; public Transform shinLeft; public Transform shinRight; public Transform chest; public List<CosmeticInstance> spawnedCosmetics = new List<CosmeticInstance>(); public void Awake() { head = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002") .Find("spine.003") .Find("spine.004"); chest = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002") .Find("spine.003"); lowerArmRight = ((Component)this).transform.Find("spine").Find("spine.001").Find("spine.002") .Find("spine.003") .Find("shoulder.R") .Find("arm.R_upper") .Find("arm.R_lower"); hip = ((Component)this).transform.Find("spine"); shinLeft = ((Component)this).transform.Find("spine").Find("thigh.L").Find("shin.L"); shinRight = ((Component)this).transform.Find("spine").Find("thigh.R").Find("shin.R"); RefreshAllCosmeticPositions(); } private void OnDisable() { foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { ((Component)spawnedCosmetic).gameObject.SetActive(false); } } private void OnEnable() { foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { ((Component)spawnedCosmetic).gameObject.SetActive(true); } } public void ClearCosmetics() { foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { Object.Destroy((Object)(object)((Component)spawnedCosmetic).gameObject); } spawnedCosmetics.Clear(); } public void ApplyCosmetic(string cosmeticId, bool startEnabled) { if (CosmeticRegistry.cosmeticInstances.ContainsKey(cosmeticId)) { CosmeticInstance cosmeticInstance = CosmeticRegistry.cosmeticInstances[cosmeticId]; GameObject val = Object.Instantiate<GameObject>(((Component)cosmeticInstance).gameObject); val.SetActive(startEnabled); CosmeticInstance component = val.GetComponent<CosmeticInstance>(); spawnedCosmetics.Add(component); if (startEnabled) { ParentCosmetic(component); } } } public void RefreshAllCosmeticPositions() { foreach (CosmeticInstance spawnedCosmetic in spawnedCosmetics) { ParentCosmetic(spawnedCosmetic); } } private void ParentCosmetic(CosmeticInstance cosmeticInstance) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) Transform val = null; switch (cosmeticInstance.cosmeticType) { case CosmeticType.HAT: val = head; break; case CosmeticType.R_LOWER_ARM: val = lowerArmRight; break; case CosmeticType.HIP: val = hip; break; case CosmeticType.L_SHIN: val = shinLeft; break; case CosmeticType.R_SHIN: val = shinRight; break; case CosmeticType.CHEST: val = chest; break; } ((Component)cosmeticInstance).transform.position = val.position; ((Component)cosmeticInstance).transform.rotation = val.rotation; ((Component)cosmeticInstance).transform.parent = val; } } public class CosmeticInstance : MonoBehaviour { public CosmeticType cosmeticType; public string cosmeticId; public Texture2D icon; } public class CosmeticGeneric { public virtual string gameObjectPath { get; } public virtual string cosmeticId { get; } public virtual string textureIconPath { get; } public CosmeticType cosmeticType { get; } public void LoadFromBundle(AssetBundle bundle) { GameObject val = bundle.LoadPersistentAsset<GameObject>(gameObjectPath); Texture2D icon = bundle.LoadPersistentAsset<Texture2D>(textureIconPath); CosmeticInstance cosmeticInstance = val.AddComponent<CosmeticInstance>(); cosmeticInstance.cosmeticId = cosmeticId; cosmeticInstance.icon = icon; cosmeticInstance.cosmeticType = cosmeticType; MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + cosmeticId + " from bundle: " + ((Object)bundle).name)); CosmeticRegistry.cosmeticInstances.Add(cosmeticId, cosmeticInstance); } } public enum CosmeticType { HAT, WRIST, CHEST, R_LOWER_ARM, HIP, L_SHIN, R_SHIN } public class CosmeticRegistry { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__8_0; public static UnityAction <>9__8_1; internal void <SpawnCosmeticGUI>b__8_0() { MainClass.showCosmetics = true; MainClass.SaveSettingsToFile(); } internal void <SpawnCosmeticGUI>b__8_1() { MainClass.showCosmetics = false; MainClass.SaveSettingsToFile(); } } public static Dictionary<string, CosmeticInstance> cosmeticInstances = new Dictionary<string, CosmeticInstance>(); public static GameObject cosmeticGUI; private static GameObject displayGuy; private static CosmeticApplication cosmeticApplication; public static List<string> locallySelectedCosmetics = new List<string>(); public const float COSMETIC_PLAYER_SCALE_MULT = 0.38f; public static void LoadCosmeticsFromBundle(AssetBundle bundle) { string[] allAssetNames = bundle.GetAllAssetNames(); foreach (string text in allAssetNames) { if (text.EndsWith(".prefab")) { GameObject val = bundle.LoadPersistentAsset<GameObject>(text); CosmeticInstance component = val.GetComponent<CosmeticInstance>(); if (!((Object)(object)component == (Object)null)) { MainClass.StaticLogger.LogInfo((object)("Loaded cosmetic: " + component.cosmeticId + " from bundle")); cosmeticInstances.Add(component.cosmeticId, component); } } } } public static void LoadCosmeticsFromAssembly(Assembly assembly, AssetBundle bundle) { Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.IsSubclassOf(typeof(CosmeticGeneric))) { CosmeticGeneric cosmeticGeneric = (CosmeticGeneric)type.GetConstructor(new Type[0]).Invoke(new object[0]); cosmeticGeneric.LoadFromBundle(bundle); } } } public static void SpawnCosmeticGUI() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Expected O, but got Unknown cosmeticGUI = Object.Instantiate<GameObject>(MainClass.cosmeticGUIInstance); ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale")).transform.localScale = new Vector3(2f, 2f, 2f); displayGuy = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen") .Find("ObjectHolder") .Find("ScavengerModel") .Find("metarig")).gameObject; cosmeticApplication = displayGuy.AddComponent<CosmeticApplication>(); GameObject gameObject = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen") .Find("EnableButton")).gameObject; ButtonClickedEvent onClick = gameObject.GetComponent<Button>().onClick; object obj = <>c.<>9__8_0; if (obj == null) { UnityAction val = delegate { MainClass.showCosmetics = true; MainClass.SaveSettingsToFile(); }; <>c.<>9__8_0 = val; obj = (object)val; } ((UnityEvent)onClick).AddListener((UnityAction)obj); GameObject gameObject2 = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen") .Find("DisableButton")).gameObject; ButtonClickedEvent onClick2 = gameObject2.GetComponent<Button>().onClick; object obj2 = <>c.<>9__8_1; if (obj2 == null) { UnityAction val2 = delegate { MainClass.showCosmetics = false; MainClass.SaveSettingsToFile(); }; <>c.<>9__8_1 = val2; obj2 = (object)val2; } ((UnityEvent)onClick2).AddListener((UnityAction)obj2); if (MainClass.showCosmetics) { gameObject.SetActive(false); gameObject2.SetActive(true); } else { gameObject.SetActive(true); gameObject2.SetActive(false); } PopulateCosmetics(); UpdateCosmeticsOnDisplayGuy(startEnabled: false); } public static void PopulateCosmetics() { //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0214: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown GameObject gameObject = ((Component)cosmeticGUI.transform.Find("Canvas").Find("GlobalScale").Find("CosmeticsScreen") .Find("CosmeticsHolder") .Find("Content")).gameObject; List<Transform> list = new List<Transform>(); for (int i = 0; i < gameObject.transform.childCount; i++) { list.Add(gameObject.transform.GetChild(i)); } foreach (Transform item in list) { Object.Destroy((Object)(object)((Component)item).gameObject); } foreach (KeyValuePair<string, CosmeticInstance> cosmeticInstance in cosmeticInstances) { GameObject val = Object.Instantiate<GameObject>(MainClass.cosmeticButton, gameObject.transform); val.transform.localScale = Vector3.one; GameObject disabledOverlay = ((Component)val.transform.Find("Deselected")).gameObject; disabledOverlay.SetActive(true); GameObject enabledOverlay = ((Component)val.transform.Find("Selected")).gameObject; enabledOverlay.SetActive(true); if (IsEquipped(cosmeticInstance.Value.cosmeticId)) { enabledOverlay.SetActive(true); disabledOverlay.SetActive(false); } else { enabledOverlay.SetActive(false); disabledOverlay.SetActive(true); } RawImage component = ((Component)val.transform.Find("Icon")).GetComponent<RawImage>(); component.texture = (Texture)(object)cosmeticInstance.Value.icon; Button component2 = val.GetComponent<Button>(); ((UnityEvent)component2.onClick).AddListener((UnityAction)delegate { ToggleCosmetic(cosmeticInstance.Value.cosmeticId); if (IsEquipped(cosmeticInstance.Value.cosmeticId)) { enabledOverlay.SetActive(true); disabledOverlay.SetActive(false); } else { enabledOverlay.SetActive(false); disabledOverlay.SetActive(true); } MainClass.WriteCosmeticsToFile(); UpdateCosmeticsOnDisplayGuy(startEnabled: true); }); } } private static Color HexToColor(string hex) { //IL_0003: 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_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) Color result = default(Color); ColorUtility.TryParseHtmlString(hex, ref result); return result; } public static void UpdateCosmeticsOnDisplayGuy(bool startEnabled) { cosmeticApplication.ClearCosmetics(); foreach (string locallySelectedCosmetic in locallySelectedCosmetics) { cosmeticApplication.ApplyCosmetic(locallySelectedCosmetic, startEnabled); } foreach (CosmeticInstance spawnedCosmetic in cosmeticApplication.spawnedCosmetics) { RecursiveLayerChange(((Component)spawnedCosmetic).transform, 5); } } private static void RecursiveLayerChange(Transform transform, int layer) { ((Component)transform).gameObject.layer = layer; for (int i = 0; i < transform.childCount; i++) { RecursiveLayerChange(transform.GetChild(i), layer); } } public static bool IsEquipped(string cosmeticId) { return locallySelectedCosmetics.Contains(cosmeticId); } public static void ToggleCosmetic(string cosmeticId) { if (locallySelectedCosmetics.Contains(cosmeticId)) { locallySelectedCosmetics.Remove(cosmeticId); } else { locallySelectedCosmetics.Add(cosmeticId); } } } } namespace MoreCompany.Behaviors { public class SpinDragger : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerUpHandler { public float speed = 1f; private Vector2 lastMousePosition; private bool dragging = false; private Vector3 rotationalVelocity = Vector3.zero; public float dragSpeed = 1f; public float airDrag = 0.99f; public GameObject target; private void Update() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_004f: 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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) if (dragging) { Vector3 val = Vector2.op_Implicit(((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue() - lastMousePosition); rotationalVelocity += new Vector3(0f, 0f - val.x, 0f) * dragSpeed; lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue(); } rotationalVelocity *= airDrag; target.transform.Rotate(rotationalVelocity * Time.deltaTime * speed, (Space)0); } public void OnPointerDown(PointerEventData eventData) { //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) lastMousePosition = ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue(); dragging = true; } public void OnPointerUp(PointerEventData eventData) { dragging = false; } } }
BepInEx/plugins/MoreEmotes1.2.2.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using MoreEmotes.Patch; using Tools; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.Utilities; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("FuckYouMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FuckYouMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("5ecc2bf2-af12-4e83-a6f1-cf2eacbf3060")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace Tools { public class Reflection { public static object GetInstanceField(Type type, object instance, string fieldName) { BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; FieldInfo field = type.GetField(fieldName, bindingAttr); return field.GetValue(instance); } public static object CallMethod(object instance, string methodName, params object[] args) { MethodInfo method = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic); if (method != null) { return method.Invoke(instance, args); } return null; } } } namespace MoreEmotes { [BepInPlugin("MoreEmotes", "MoreEmotes-Sligili", "1.2.2")] public class FuckYouModInitialization : BaseUnityPlugin { private Harmony _harmony; private ConfigEntry<string> config_KeyWheel; private ConfigEntry<bool> config_InventoryCheck; private ConfigEntry<string> config_KeyEmote3; private ConfigEntry<string> config_KeyEmote4; private ConfigEntry<string> config_KeyEmote5; private ConfigEntry<string> config_KeyEmote6; private ConfigEntry<string> config_KeyEmote7; private ConfigEntry<string> config_KeyEmote8; private void Awake() { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown ((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded"); EmotePatch.animationsBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle")); EmotePatch.animatorBundle = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle")); EmotePatch.local = EmotePatch.animatorBundle.LoadAsset<RuntimeAnimatorController>("Assets/MoreEmotes/NEWmetarig.controller"); EmotePatch.others = EmotePatch.animatorBundle.LoadAsset<RuntimeAnimatorController>("Assets/MoreEmotes/NEWmetarigOtherPlayers.controller"); CustomAudioAnimationEvent.claps[0] = EmotePatch.animationsBundle.LoadAsset<AudioClip>("Assets/MoreEmotes/SingleClapEmote1.wav"); CustomAudioAnimationEvent.claps[1] = EmotePatch.animationsBundle.LoadAsset<AudioClip>("Assets/MoreEmotes/SingleClapEmote2.wav"); ConfigFile(); IncompatibilityAids(); _harmony = new Harmony("MoreEmotes"); _harmony.PatchAll(typeof(EmotePatch)); } private void IncompatibilityAids() { foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos) { BepInPlugin metadata = pluginInfo.Value.Metadata; if (metadata.GUID.Equals("com.malco.lethalcompany.moreshipupgrades") || metadata.GUID.Equals("Stoneman.LethalProgression")) { EmotePatch.IncompatibleStuff = true; break; } } } private void ConfigFile() { EmotePatch.keybinds = new string[9]; config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null); EmotePatch.wheelKeybind = config_KeyWheel.Value; config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap"); EmotePatch.InvCheck = config_InventoryCheck.Value; config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null); EmotePatch.keybinds[2] = config_KeyEmote3.Value.Replace(" ", ""); config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null); EmotePatch.keybinds[5] = config_KeyEmote4.Value.Replace(" ", ""); config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null); EmotePatch.keybinds[4] = config_KeyEmote5.Value.Replace(" ", ""); config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null); EmotePatch.keybinds[3] = config_KeyEmote6.Value.Replace(" ", ""); config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null); EmotePatch.keybinds[6] = config_KeyEmote7.Value.Replace(" ", ""); config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null); EmotePatch.keybinds[7] = config_KeyEmote8.Value.Replace(" ", ""); } } public static class PluginInfo { public const string Guid = "MoreEmotes"; public const string Name = "MoreEmotes-Sligili"; public const string Ver = "1.2.2"; } } namespace MoreEmotes.Patch { internal class EmotePatch { public static AssetBundle animationsBundle; public static AssetBundle animatorBundle; public static string[] keybinds; public static string wheelKeybind; private static CallbackContext context; public static RuntimeAnimatorController local; public static RuntimeAnimatorController others; private static int currentEmoteID; private static float svMovSpeed; public static bool IncompatibleStuff; public static bool InvCheck; public static bool emoteWheelIsOpened; public static GameObject wheel; public static GameObject rebindmenu; public static GameObject btn; private static SelectionWheel selectionWheel; [HarmonyPatch(typeof(MenuManager), "Start")] [HarmonyPostfix] private static void MenuStart(MenuManager __instance) { GameObject val = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesPanel.prefab"); GameObject val2 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesButton.prefab"); GameObject gameObject = ((Component)((Component)__instance).transform.parent).gameObject; GameObject gameObject2 = ((Component)((Component)gameObject.transform.Find("MenuContainer")).transform.Find("SettingsPanel")).gameObject; if ((Object)(object)btn != (Object)null) { Object.Destroy((Object)(object)btn.gameObject); } btn = Object.Instantiate<GameObject>(val2, gameObject2.transform); btn.transform.SetSiblingIndex(7); if ((Object)(object)rebindmenu != (Object)null) { Object.Destroy((Object)(object)rebindmenu.gameObject); } rebindmenu = Object.Instantiate<GameObject>(val, gameObject2.transform); RebindBtn.defaultKeys = keybinds; BasicToggle.configValueInv = InvCheck; if ((Object)(object)gameObject2.GetComponent<SetupEverything>() == (Object)null) { gameObject2.AddComponent<SetupEverything>(); } SetupEverything.configValue = InvCheck; } [HarmonyPatch(typeof(PlayerControllerB), "Start")] [HarmonyPostfix] private static void StartPostfix(PlayerControllerB __instance) { GameObject gameObject = ((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject; CustomAudioAnimationEvent customAudioAnimationEvent = gameObject.AddComponent<CustomAudioAnimationEvent>(); svMovSpeed = __instance.movementSpeed; customAudioAnimationEvent.player = __instance; if (Object.FindObjectsOfType(typeof(SelectionWheel)).Length == 0) { GameObject val = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab"); GameObject gameObject2 = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject; GameObject val2 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesPanel.prefab"); GameObject val3 = animationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesButton.prefab"); GameObject gameObject3 = ((Component)((Component)gameObject2.transform.Find("QuickMenu")).transform.Find("SettingsPanel")).gameObject; if ((Object)(object)btn != (Object)null) { Object.Destroy((Object)(object)btn.gameObject); } btn = Object.Instantiate<GameObject>(val3, gameObject3.transform); btn.transform.SetSiblingIndex(7); if ((Object)(object)rebindmenu != (Object)null) { Object.Destroy((Object)(object)rebindmenu.gameObject); } rebindmenu = Object.Instantiate<GameObject>(val2, gameObject3.transform); RebindBtn.defaultKeys = keybinds; BasicToggle.configValueInv = InvCheck; if ((Object)(object)wheel != (Object)null) { Object.Destroy((Object)(object)wheel.gameObject); } wheel = Object.Instantiate<GameObject>(val, gameObject2.transform); selectionWheel = wheel.AddComponent<SelectionWheel>(); SelectionWheel.emotes_Keybinds = new string[keybinds.Length + 1]; SelectionWheel.emotes_Keybinds = keybinds; if ((Object)(object)gameObject3.GetComponent<SetupEverything>() == (Object)null) { gameObject3.AddComponent<SetupEverything>(); } SetupEverything.configValue = InvCheck; } } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] private static void UpdatePostfix(PlayerControllerB __instance) { //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner) { __instance.playerBodyAnimator.runtimeAnimatorController = others; return; } if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local) { __instance.playerBodyAnimator.runtimeAnimatorController = local; } if (__instance.performingEmote) { currentEmoteID = __instance.playerBodyAnimator.GetInteger("emoteNumber"); } if (!IncompatibleStuff) { bool flag = (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && currentEmoteID == 6 && __instance.performingEmote; __instance.movementSpeed = (flag ? (svMovSpeed / 2f) : svMovSpeed); } if (!PlayerPrefs.HasKey("InvCheck")) { PlayerPrefs.SetInt("InvCheck", InvCheck ? 1 : 0); } else { InvCheck = PlayerPrefs.GetInt("InvCheck") == 1; } if (!PlayerPrefs.HasKey("Emote_Wheel")) { PlayerPrefs.SetString("Emote_Wheel", wheelKeybind); } if (InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[PlayerPrefs.GetString("Emote_Wheel")], 0f) && !emoteWheelIsOpened && !__instance.isPlayerDead && !__instance.inTerminalMenu && !__instance.quickMenuManager.isMenuOpen) { emoteWheelIsOpened = true; Cursor.visible = true; Cursor.lockState = (CursorLockMode)2; wheel.SetActive(emoteWheelIsOpened); __instance.disableLookInput = true; } else if ((!InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[PlayerPrefs.GetString("Emote_Wheel")], 0f) && emoteWheelIsOpened) || __instance.quickMenuManager.isMenuOpen) { if (!__instance.quickMenuManager.isMenuOpen || __instance.isPlayerDead) { int selectedEmoteID = selectionWheel.selectedEmoteID; if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !InvCheck) { __instance.PerformEmote(context, selectedEmoteID); } else if (!__instance.isHoldingObject) { __instance.PerformEmote(context, selectedEmoteID); } Cursor.visible = false; Cursor.lockState = (CursorLockMode)1; } if (__instance.isPlayerDead && !__instance.quickMenuManager.isMenuOpen) { Cursor.visible = false; Cursor.lockState = (CursorLockMode)1; } __instance.disableLookInput = false; emoteWheelIsOpened = false; wheel.SetActive(emoteWheelIsOpened); } if (!emoteWheelIsOpened && !__instance.quickMenuManager.isMenuOpen) { EmoteInput(keybinds[2], needsEmptyHands: false, 3, __instance); EmoteInput(keybinds[3], needsEmptyHands: true, 4, __instance); EmoteInput(keybinds[4], needsEmptyHands: true, 5, __instance); EmoteInput(keybinds[5], needsEmptyHands: false, 6, __instance); EmoteInput(keybinds[6], needsEmptyHands: true, 7, __instance); EmoteInput(keybinds[7], needsEmptyHands: true, 8, __instance); } } private static void EmoteInput(string keyBind, bool needsEmptyHands, int emoteID, PlayerControllerB player) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) bool flag = PlayerPrefs.GetInt("InvCheck") == 1; Emotes emotes = (Emotes)emoteID; string text = emotes.ToString(); if (PlayerPrefs.HasKey(text)) { keyBind = PlayerPrefs.GetString(text); } else { PlayerPrefs.SetString(text, keyBind); } if (!keyBind.Equals(string.Empty) && InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keyBind], 0f) && (!player.isHoldingObject || !needsEmptyHands || !flag) && (!player.performingEmote || currentEmoteID != emoteID)) { Debug.Log((object)text); player.PerformEmote(context, emoteID); } } [HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")] [HarmonyPrefix] private static bool prefixCheckConditions(ref bool __result, PlayerControllerB __instance) { bool flag = (bool)Reflection.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping"); if (currentEmoteID == 6) { __result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat; return false; } return true; } [HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")] [HarmonyPrefix] private static void PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance) { if ((emoteID >= 3 || emoteWheelIsOpened || ((CallbackContext)(ref context)).performed) && ((((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject)) || __instance.isTestingPlayer) && (bool)Reflection.CallMethod(__instance, "CheckConditionsForEmote") && !(__instance.timeSinceStartingEmote < 0.5f)) { __instance.timeSinceStartingEmote = 0f; __instance.performingEmote = true; __instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID); __instance.StartPerformingEmoteServerRpc(); } } } public class CustomAudioAnimationEvent : MonoBehaviour { private Animator animator; private AudioSource SoundsSource; public static AudioClip[] claps = (AudioClip[])(object)new AudioClip[2]; public PlayerControllerB player; private void Start() { animator = ((Component)this).GetComponent<Animator>(); SoundsSource = player.movementAudio; } public void PlayClapSound() { //IL_0087: Unknown result type (might be due to invalid IL or missing references) if (player.performingEmote && (!((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || animator.GetInteger("emoteNumber") == 4)) { bool flag = player.isInHangarShipRoom && player.playersManager.hangarDoorsClosed; RoundManager.Instance.PlayAudibleNoise(((Component)player).transform.position, 22f, 0.6f, 0, flag, 6); SoundsSource.pitch = Random.Range(0.59f, 0.79f); SoundsSource.PlayOneShot(claps[Random.Range(0, claps.Length)]); } } public void PlayFootstepSound() { if (player.performingEmote && (!((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled || animator.GetInteger("emoteNumber") == 6 || animator.GetInteger("emoteNumber") == 8) && ((Vector2)(ref player.moveInputVector)).sqrMagnitude == 0f) { player.PlayFootstepLocal(); player.PlayFootstepServer(); } } } public enum Emotes { Dance = 1, Point, Middle_Finger, Clap, Shy, The_Griddy, Twerk, Salute } public class SelectionWheel : MonoBehaviour { public RectTransform selectionBlock; public Text emoteInformation; public Text pageInformation; private int blocksNumber = 8; private int currentBlock = 1; public int pageNumber; public int selectedEmoteID; private float angle; private float pageCooldown = 0.1f; public GameObject[] Pages; private int cuadrante = 0; public string selectedEmoteName; public float wheelMovementOffset = 3.3f; public static string[] emotes_Keybinds; private Vector2 center; private void OnEnable() { //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_01a7: Unknown result type (might be due to invalid IL or missing references) center = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2)); PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>(); emotes_Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0); emotes_Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0); Cursor.visible = true; selectionBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>(); GameObject gameObject = ((Component)((Component)this).gameObject.transform.Find("FunctionalContent")).gameObject; emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>(); Pages = (GameObject[])(object)new GameObject[gameObject.transform.childCount]; pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>(); pageInformation.text = "Page " + Pages.Length + "/" + (pageNumber + 1); for (int i = 0; i < gameObject.transform.childCount; i++) { Pages[i] = ((Component)gameObject.transform.GetChild(i)).gameObject; } Mouse.current.WarpCursorPosition(center); } private void Update() { wheelSelection(); pageSelection(); selectedEmoteID = currentBlock + Mathf.RoundToInt((float)(blocksNumber / 4)) + blocksNumber * pageNumber; displayEmoteInfo(); } private void wheelSelection() { //IL_0002: 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_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) if (!(Vector2.Distance(center, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < wheelMovementOffset)) { bool flag = ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue() > center.x; bool flag2 = ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue() > center.y; cuadrante = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4)); float num = (((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue() - center.y) / (((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue() - center.x); float num2 = 180 * (cuadrante - ((cuadrante <= 2) ? 1 : 2)); angle = Mathf.Atan(num) * (180f / (float)Math.PI) + num2; if (angle == 90f) { angle = 270f; } else if (angle == 270f) { angle = 90f; } float num3 = 360 / blocksNumber; currentBlock = Mathf.RoundToInt((angle - num3 * 1.5f) / num3); ((Transform)selectionBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num3 * (float)currentBlock); } } private void pageSelection() { pageInformation.text = "Page " + Pages.Length + "/" + (pageNumber + 1); if (pageCooldown > 0f) { pageCooldown -= Time.deltaTime; } else if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() != 0f) { GameObject[] pages = Pages; foreach (GameObject val in pages) { val.SetActive(false); } int num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1)); if (pageNumber + 1 > Pages.Length - 1 && num > 0) { pageNumber = 0; } else if (pageNumber - 1 < 0 && num < 0) { pageNumber = Pages.Length - 1; } else { pageNumber += num; } Pages[pageNumber].SetActive(true); pageCooldown = 0.1f; } } private void displayEmoteInfo() { string text = ((selectedEmoteID > emotes_Keybinds.Length) ? "" : emotes_Keybinds[selectedEmoteID - 1]); object obj; if (selectedEmoteID <= Enum.GetValues(typeof(Emotes)).Length) { Emotes emotes = (Emotes)selectedEmoteID; obj = emotes.ToString().Replace("_", " "); } else { obj = "EMPTY"; } string text2 = (string)obj; if (!PlayerPrefs.HasKey(text2.Replace(" ", "_"))) { PlayerPrefs.SetString(text2.Replace(" ", "_"), (selectedEmoteID > emotes_Keybinds.Length) ? "" : emotes_Keybinds[selectedEmoteID - 1]); } else { text = PlayerPrefs.GetString(text2.Replace(" ", "_")); } emoteInformation.text = text2 + "\n[" + text.ToUpper() + "]"; } } public class RebindBtn : MonoBehaviour { public string defaultKey; public static string[] defaultKeys; public string playerPrefs; public GameObject waitingForInput; public Text keyInfo; public Text description; private void Start() { //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text; try { int num = (int)(Emotes)Enum.Parse(typeof(Emotes), text.Replace(" ", "_")); defaultKey = defaultKeys[num - 1]; } catch { defaultKey = "V"; } playerPrefs = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_"); ((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteBtn>(); keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>(); waitingForInput = ((Component)((Component)this).transform.Find("wait")).gameObject; ((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey)); if (!PlayerPrefs.HasKey(playerPrefs)) { PlayerPrefs.SetString(playerPrefs, defaultKey); } SetKeybind(PlayerPrefs.GetString(playerPrefs)); } public void SetKeybind(string key) { PlayerPrefs.SetString(playerPrefs, key); keyInfo.text = key; ((MonoBehaviour)this).StopAllCoroutines(); waitingForInput.SetActive(false); } public void GetKey() { waitingForInput.SetActive(true); ((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key) { SetKeybind(key); })); } private IEnumerator WaitForKey(Action<string> callback) { while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame) { yield return (object)new WaitForEndOfFrame(); Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl) { callback((ctrl.device == Keyboard.current) ? ctrl.name : defaultKey); }); } } } public class DeleteBtn : MonoBehaviour { private RebindBtn rebindBtn; private void Start() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown rebindBtn = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindBtn>(); Button component = ((Component)this).GetComponent<Button>(); ((UnityEvent)component.onClick).AddListener(new UnityAction(deleteKey)); } public void deleteKey() { rebindBtn.SetKeybind(string.Empty); } } public class BasicToggle : MonoBehaviour { private Toggle tog; public static bool configValueInv; public string playerPrefs; private void Start() { tog = ((Component)this).GetComponent<Toggle>(); ((UnityEvent<bool>)(object)tog.onValueChanged).AddListener((UnityAction<bool>)SetNewValue); if (!PlayerPrefs.HasKey(playerPrefs)) { PlayerPrefs.SetInt(playerPrefs, configValueInv ? 1 : 0); } } public void SetNewValue(bool arg) { PlayerPrefs.SetInt(playerPrefs, tog.isOn ? 1 : 0); } } public class ButtonBasic : MonoBehaviour { public GameObject[] alternateActive = (GameObject[])(object)new GameObject[1]; private void Start() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown ((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(onButtonTrigger)); if (((Object)((Component)this).gameObject).name.Equals("BackButton")) { alternateActive[0] = ((Component)((Component)this).transform.parent).gameObject; } if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)")) { alternateActive[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject; } } public void onButtonTrigger() { GameObject[] array = alternateActive; foreach (GameObject val in array) { val.SetActive((!val.activeInHierarchy) ? true : false); } } } public class SetupEverything : MonoBehaviour { private GameObject panel; public static bool configValue; private void Start() { panel = ((Component)((Component)this).transform.Find("MoreEmotesPanel(Clone)")).gameObject; ((Component)panel.transform.Find("Version")).GetComponent<Text>().text = "Sligili - 1.2.2"; if (!PlayerPrefs.HasKey("InvCheck")) { PlayerPrefs.SetInt("InvCheck", configValue ? 1 : 0); } SetupMenuButton(); BackButton(); KeybindButtons(); Others(); } private void SetupMenuButton() { GameObject gameObject = ((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject; gameObject.AddComponent<ButtonBasic>(); } private void BackButton() { GameObject gameObject = ((Component)panel.transform.Find("BackButton")).gameObject; gameObject.AddComponent<ButtonBasic>(); } private void KeybindButtons() { GameObject gameObject = ((Component)panel.transform.Find("KeybindButtons")).gameObject; GameObject[] array = (GameObject[])(object)new GameObject[gameObject.transform.childCount]; for (int i = 0; i < gameObject.transform.childCount; i++) { array[i] = ((Component)gameObject.transform.GetChild(i)).gameObject; } GameObject[] array2 = array; foreach (GameObject val in array2) { ((Component)val.transform.Find("Button")).gameObject.AddComponent<RebindBtn>(); } } private void Others() { GameObject gameObject = ((Component)panel.transform.Find("Inv")).gameObject; gameObject.AddComponent<BasicToggle>(); BasicToggle basicToggle = gameObject.AddComponent<BasicToggle>(); basicToggle.playerPrefs = "InvCheck"; } } }
BepInEx/plugins/MoreItems.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using MoreItems.Patches; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("MoreItems")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("MoreItems")] [assembly: AssemblyTitle("MoreItems")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 MoreItems { [BepInPlugin("MoreItems", "MoreItems", "1.0.0")] public class Plugin : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("MoreItems"); private void Awake() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MoreItems is loaded!"); harmony.PatchAll(typeof(StartOfRoundPatch)); } } public static class PluginInfo { public const string PLUGIN_GUID = "MoreItems"; public const string PLUGIN_NAME = "MoreItems"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace MoreItems.Patches { [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { private const int newMaxItemCapacity = 999; [HarmonyPatch("Awake")] [HarmonyPostfix] private static void IncreaseShipItemCapacity(ref int ___maxShipItemCapacity) { ___maxShipItemCapacity = 999; Logger.CreateLogSource("MoreItems").LogInfo((object)$"Maximum amount of items that can be saved set to {999}."); } } }
BepInEx/plugins/NoPenalty.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using HarmonyLib; using LC_API.ServerAPI; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("NoPenalty")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Increase the max players in Lethal Company")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1")] [assembly: AssemblyProduct("NoPenalty")] [assembly: AssemblyTitle("NoPenalty")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.1.0")] [module: UnverifiableCode] namespace NoPenalty { [BepInPlugin("NoPenalty", "NoPenalty", "1.0.1")] public class Plugin : BaseUnityPlugin { private Harmony harmonymain; private void Awake() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown harmonymain = new Harmony("NoPenalty"); harmonymain.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"NoPenalty has loaded!!!"); } private void OnDestroy() { ModdedServer.SetServerModdedOnly(); } } public static class PluginInfo { public const string PLUGIN_GUID = "NoPenalty"; public const string PLUGIN_NAME = "NoPenalty"; public const string PLUGIN_VERSION = "1.0.1"; } } namespace PermUnlockables.Patches { [HarmonyPatch] internal class PenaltyPatches { [HarmonyPatch(typeof(HUDManager), "ApplyPenalty")] [HarmonyPrefix] public static bool ApplyPenalty() { return false; } [HarmonyPatch(typeof(HUDManager), "Awake")] [HarmonyPostfix] public static void ResizeLists2(ref HUDManager __instance) { ((Component)((TMP_Text)__instance.statsUIElements.penaltyTotal).transform.parent.parent).gameObject.SetActive(false); } } }
BepInEx/plugins/ObjectVolumeController.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using GameNetcodeStuff; using HarmonyLib; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("ObjectVolumeController")] [assembly: AssemblyDescription("Mod made by flipf17")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ObjectVolumeController")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("49ff2710-6c88-48c4-989a-32b79f0ddd6a")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace ObjectVolumeController { [BepInPlugin("FlipMods.ObjectVolumeController", "ObjectVolumeController", "1.0.3")] public class Plugin : BaseUnityPlugin { public static Plugin instance; private Harmony _harmony; public static Key volumeUpKey = (Key)14; public static Key volumeDownKey = (Key)13; public static string volumeHoverTip = "Volume up: [+]\nVolume down: [-]"; public static float volumeIncrement = 0.1f; public static float maxDisplayedVolume = 1.5f; public static float defaultVolume = 1f; private void Awake() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown _harmony = new Harmony("ObjectVolumeController"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"ObjectVolumeController loaded"); instance = this; } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.ObjectVolumeController"; public const string PLUGIN_NAME = "ObjectVolumeController"; public const string PLUGIN_VERSION = "1.0.3"; } } namespace ObjectVolumeController.Patcher { [HarmonyPatch] internal class ChangeVolumePatcher { private static AudioPlayerItemType boomboxItems = new AudioPlayerItemType("Boomboxes", "Grab boombox: [E]"); private static AudioPlayerPlaceableType recordPlayers = new AudioPlayerPlaceableType("Record players", "Record player: [E]"); private static AudioPlayerPlaceableType televisions = new AudioPlayerPlaceableType("Televisions", "Television: [E]"); [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPrefix] public static void GetObjectLookingAt(PlayerControllerB __instance) { boomboxItems.lookingAtDeviceType = false; recordPlayers.lookingAtDeviceType = false; televisions.lookingAtDeviceType = false; if (!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || __instance.inTerminalMenu || __instance.isTypingChat || __instance.isPlayerDead) { return; } InteractTrigger hoveringOverTrigger = __instance.hoveringOverTrigger; object obj; if (hoveringOverTrigger == null) { obj = null; } else { Transform parent = ((Component)hoveringOverTrigger).transform.parent; obj = ((parent != null) ? ((Component)parent).gameObject : null); } GameObject val = (GameObject)obj; if ((Object)(object)val != (Object)null) { if (((Object)val).name.Contains("RecordPlayer")) { recordPlayers.lookingAtDeviceType = true; } else if (((Object)val).name.Contains("Television")) { televisions.lookingAtDeviceType = true; } } if (!recordPlayers.lookingAtDeviceType && !televisions.lookingAtDeviceType) { if ((Object)(object)__instance.cursorTip != (Object)null && ((TMP_Text)__instance.cursorTip).text.Contains(boomboxItems.originalHoverTip)) { boomboxItems.lookingAtDeviceType = true; } else if ((Object)(object)__instance.currentlyHeldObjectServer != (Object)null && __instance.currentlyHeldObjectServer is BoomboxItem) { boomboxItems.lookingAtDeviceType = true; } } } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void GetVolumeInput(PlayerControllerB __instance) { if (!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || __instance.inTerminalMenu || __instance.isTypingChat || __instance.isPlayerDead || (!boomboxItems.lookingAtDeviceType && !recordPlayers.lookingAtDeviceType && !televisions.lookingAtDeviceType)) { return; } float num = 0f; if (((ButtonControl)Keyboard.current.minusKey).wasPressedThisFrame) { num = 0f - Plugin.volumeIncrement; } if (((ButtonControl)Keyboard.current.equalsKey).wasPressedThisFrame) { num = Plugin.volumeIncrement; } if (num != 0f) { Plugin.Log("AdjustVolume: " + num); AudioPlayerTypeBase audioPlayerTypeBase = null; if (boomboxItems.lookingAtDeviceType) { audioPlayerTypeBase = boomboxItems; } else if (recordPlayers.lookingAtDeviceType) { audioPlayerTypeBase = recordPlayers; } else if (televisions.lookingAtDeviceType) { audioPlayerTypeBase = televisions; } if (audioPlayerTypeBase != null) { audioPlayerTypeBase.currentVolume = Mathf.Clamp(audioPlayerTypeBase.currentVolume + num, 0f, Plugin.maxDisplayedVolume); audioPlayerTypeBase.UpdateVolumes(); audioPlayerTypeBase.UpdateTooltips(); Plugin.Log($"[{audioPlayerTypeBase.name}] Updating volume to: {audioPlayerTypeBase.currentVolume}%"); } } } [HarmonyPatch(typeof(BoomboxItem), "Start")] [HarmonyPostfix] public static void SetBoomboxHoverTip(BoomboxItem __instance) { boomboxItems.audioSources.Add(__instance.boomboxAudio); boomboxItems.items.Add((GrabbableObject)(object)__instance); ((GrabbableObject)__instance).itemProperties.canBeGrabbedBeforeGameStart = true; if (boomboxItems.defaultVolume == 0f) { boomboxItems.defaultVolume = __instance.boomboxAudio.volume; Plugin.Log("Boombox volume: " + boomboxItems.defaultVolume); } if (boomboxItems.controlTooltips == null) { boomboxItems.controlTooltips = new List<string>(((GrabbableObject)__instance).itemProperties.toolTips); boomboxItems.controlTooltips.Add(""); } boomboxItems.UpdateTooltips(); boomboxItems.UpdateVolumes(); } [HarmonyPatch(typeof(AutoParentToShip), "Awake")] [HarmonyPostfix] public static void SetRecordPlayerHoverTip(AutoParentToShip __instance) { if (((Object)__instance).name.Contains("RecordPlayerContainer")) { AudioSource val = ((Component)__instance).GetComponentInChildren<AnimatedObjectTrigger>()?.thisAudioSource; if ((Object)(object)val != (Object)null) { recordPlayers.audioSources.Add(val); } InteractTrigger componentInChildren = ((Component)__instance).GetComponentInChildren<InteractTrigger>(); if (recordPlayers.defaultVolume == 0f) { recordPlayers.defaultVolume = val.volume; Plugin.Log("RecordPlayer Volume: " + recordPlayers.defaultVolume); } if ((Object)(object)componentInChildren == (Object)null) { Plugin.Log("Record player trigger missing!"); return; } recordPlayers.triggers.Add(componentInChildren); recordPlayers.UpdateTooltips(); recordPlayers.UpdateVolumes(); } } [HarmonyPatch(typeof(TVScript), "__initializeVariables")] [HarmonyPostfix] public static void SetTelevisionHoverTip(TVScript __instance) { televisions.audioSources.Add(__instance.tvSFX); Transform parent = ((Component)__instance).transform.parent; InteractTrigger val = ((parent != null) ? ((Component)parent).GetComponentInChildren<InteractTrigger>() : null); if (televisions.defaultVolume == 0f) { televisions.defaultVolume = __instance.tvSFX.volume; Plugin.Log("Television volume: " + televisions.defaultVolume); } if ((Object)(object)val == (Object)null) { Plugin.Log("Television trigger missing!"); return; } televisions.triggers.Add(val); televisions.UpdateTooltips(); televisions.UpdateVolumes(); } } internal abstract class AudioPlayerTypeBase { public string name; public List<AudioSource> audioSources; public string originalHoverTip; public float defaultVolume; public float currentVolume; public bool lookingAtDeviceType; public Type objectType; public AudioPlayerTypeBase(string name, string originalHoverTip = "", float defaultVolume = 0f) { this.name = name; audioSources = new List<AudioSource>(); this.originalHoverTip = originalHoverTip; this.defaultVolume = defaultVolume; currentVolume = Plugin.defaultVolume; lookingAtDeviceType = false; } public void UpdateVolumes() { for (int i = 0; i < audioSources.Count; i++) { if ((Object)(object)audioSources[i] != (Object)null) { audioSources[i].volume = currentVolume / Plugin.maxDisplayedVolume; } } } public abstract void UpdateTooltips(); } internal class AudioPlayerItemType : AudioPlayerTypeBase { public List<GrabbableObject> items; public List<string> controlTooltips; public AudioPlayerItemType(string name, string originalHoverTip = "", float defaultVolume = 0f) : base(name, originalHoverTip, defaultVolume) { items = new List<GrabbableObject>(); } public override void UpdateTooltips() { for (int i = 0; i < items.Count; i++) { if ((Object)(object)items[i] != (Object)null) { items[i].customGrabTooltip = $"{originalHoverTip}\n{Mathf.RoundToInt(currentVolume * 10f) * 10}% volume\n{Plugin.volumeHoverTip}"; controlTooltips[controlTooltips.Count - 1] = items[i].customGrabTooltip.Replace(originalHoverTip + "\n", ""); items[i].itemProperties.toolTips = controlTooltips.ToArray(); } } PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if ((Object)(object)localPlayerController != (Object)null && (Object)(object)localPlayerController.currentlyHeldObjectServer != (Object)null && items.Contains(localPlayerController.currentlyHeldObjectServer)) { localPlayerController.currentlyHeldObjectServer.EquipItem(); } } } internal class AudioPlayerPlaceableType : AudioPlayerTypeBase { public List<InteractTrigger> triggers; public AudioPlayerPlaceableType(string name, string originalHoverTip = "", float defaultVolume = 0f) : base(name, originalHoverTip, defaultVolume) { triggers = new List<InteractTrigger>(); } public override void UpdateTooltips() { for (int i = 0; i < triggers.Count; i++) { if ((Object)(object)triggers[i] != (Object)null) { triggers[i].hoverTip = $"{originalHoverTip}\n{Mathf.RoundToInt(currentVolume * 10f) * 10}% volume\n{Plugin.volumeHoverTip}"; } } } } }
BepInEx/plugins/OctolarFirstMod.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using OctolarFirstMod.Patches; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("OctolarFirstMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OctolarFirstMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("a761e7d0-2e73-4d38-b7ad-3010bdcd4702")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] namespace OctolarFirstMod { [BepInPlugin("Octolar.Healthstation", "Health Station mod", "1.0.0.1")] public class OctolarFirstMod : BaseUnityPlugin { private const string modGUID = "Octolar.Healthstation"; private const string modName = "Health Station mod"; private const string modVersion = "1.0.0.1"; private readonly Harmony harmony = new Harmony("Octolar.Healthstation"); private static OctolarFirstMod Instance; internal ManualLogSource mls; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } mls = Logger.CreateLogSource("Octolar.Healthstation"); mls.LogInfo((object)"Octolar HealthStation mod is now active"); harmony.PatchAll(typeof(OctolarFirstMod)); harmony.PatchAll(typeof(ItemChargerPatch)); } } } namespace OctolarFirstMod.Patches { [HarmonyPatch(typeof(PlayerControllerB))] [HarmonyPatch(typeof(ItemCharger))] internal class ItemChargerPatch { [HarmonyPatch("ChargeItem")] [HarmonyPostfix] private static void ChargerHealsPatch() { //IL_0014: 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) GameNetworkManager.Instance.localPlayerController.DamagePlayer(-100, false, true, (CauseOfDeath)0, 0, false, default(Vector3)); if (GameNetworkManager.Instance.localPlayerController.health >= 10 && GameNetworkManager.Instance.localPlayerController.criticallyInjured) { GameNetworkManager.Instance.localPlayerController.MakeCriticallyInjured(false); } } } }
BepInEx/plugins/patchers/BepInEx.MonoMod.HookGenPatcher/BepInEx.MonoMod.HookGenPatcher.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using BepInEx.Configuration; using BepInEx.Logging; using Mono.Cecil; using MonoMod; using MonoMod.RuntimeDetour.HookGen; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Bepinex.Monomod.HookGenPatcher")] [assembly: AssemblyDescription("Runtime HookGen for BepInEx")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HarbingerOfMe")] [assembly: AssemblyProduct("Bepinex.Monomod.HookGenPatcher")] [assembly: AssemblyCopyright("HarbingerOfMe-2022")] [assembly: AssemblyTrademark("MIT")] [assembly: ComVisible(false)] [assembly: Guid("12032e45-9577-4195-8f4f-a729911b2f08")] [assembly: AssemblyFileVersion("1.2.1.0")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("1.2.1.0")] namespace BepInEx.MonoMod.HookGenPatcher; public static class HookGenPatcher { internal static ManualLogSource Logger = Logger.CreateLogSource("HookGenPatcher"); private const string CONFIG_FILE_NAME = "HookGenPatcher.cfg"; private static readonly ConfigFile Config = new ConfigFile(Path.Combine(Paths.ConfigPath, "HookGenPatcher.cfg"), true); private const char EntrySeparator = ','; private static readonly ConfigEntry<string> AssemblyNamesToHookGenPatch = Config.Bind<string>("General", "MMHOOKAssemblyNames", "Assembly-CSharp.dll", $"Assembly names to make mmhooks for, separate entries with : {','} "); private static readonly ConfigEntry<bool> preciseHash = Config.Bind<bool>("General", "Preciser filehashing", false, "Hash file using contents instead of size. Minor perfomance impact."); private static bool skipHashing => !preciseHash.Value; public static IEnumerable<string> TargetDLLs { get; } = new string[0]; public static void Initialize() { //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Expected O, but got Unknown //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Expected O, but got Unknown //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Expected O, but got Unknown //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Expected O, but got Unknown string[] array = AssemblyNamesToHookGenPatch.Value.Split(new char[1] { ',' }); string text = Path.Combine(Paths.PluginPath, "MMHOOK"); string[] array2 = array; foreach (string text2 in array2) { string text3 = "MMHOOK_" + text2; string text4 = Path.Combine(Paths.ManagedPath, text2); string text5 = Path.Combine(text, text3); bool flag = true; string[] files = Directory.GetFiles(Paths.PluginPath, text3, SearchOption.AllDirectories); foreach (string text6 in files) { if (Path.GetFileName(text6).Equals(text3)) { text5 = text6; Logger.LogInfo((object)"Previous MMHOOK location found. Using that location to save instead."); flag = false; break; } } if (flag) { Directory.CreateDirectory(text); } FileInfo fileInfo = new FileInfo(text4); long length = fileInfo.Length; long num = 0L; if (File.Exists(text5)) { try { AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text5); try { if (val.MainModule.GetType("BepHookGen.size" + length) != null) { if (skipHashing) { Logger.LogInfo((object)"Already ran for this version, reusing that file."); continue; } num = fileInfo.makeHash(); if (val.MainModule.GetType("BepHookGen.content" + num) != null) { Logger.LogInfo((object)"Already ran for this version, reusing that file."); continue; } } } finally { ((IDisposable)val)?.Dispose(); } } catch (BadImageFormatException) { Logger.LogWarning((object)("Failed to read " + Path.GetFileName(text5) + ", probably corrupted, remaking one.")); } } Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1"); Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0"); MonoModder val2 = new MonoModder { InputPath = text4, OutputPath = text5, ReadingMode = (ReadingMode)2 }; try { IAssemblyResolver assemblyResolver = val2.AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(Paths.BepInExAssemblyDirectory); } val2.Read(); val2.MapDependencies(); if (File.Exists(text5)) { Logger.LogDebug((object)("Clearing " + text5)); File.Delete(text5); } Logger.LogInfo((object)"Starting HookGenerator"); HookGenerator val3 = new HookGenerator(val2, Path.GetFileName(text5)); ModuleDefinition outputModule = val3.OutputModule; try { val3.Generate(); outputModule.Types.Add(new TypeDefinition("BepHookGen", "size" + length, (TypeAttributes)1, outputModule.TypeSystem.Object)); if (!skipHashing) { outputModule.Types.Add(new TypeDefinition("BepHookGen", "content" + ((num == 0L) ? fileInfo.makeHash() : num), (TypeAttributes)1, outputModule.TypeSystem.Object)); } outputModule.Write(text5); } finally { ((IDisposable)outputModule)?.Dispose(); } Logger.LogInfo((object)"Done."); } finally { ((IDisposable)val2)?.Dispose(); } } } public static void Patch(AssemblyDefinition _) { } private static long makeHash(this FileInfo fileInfo) { FileStream inputStream = fileInfo.OpenRead(); byte[] value = null; using (MD5 mD = new MD5CryptoServiceProvider()) { value = mD.ComputeHash(inputStream); } long num = BitConverter.ToInt64(value, 0); if (num == 0L) { return 1L; } return num; } }
BepInEx/plugins/patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.dll
Decompiled a year ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Mdb; using Mono.Cecil.Pdb; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.InlineRT; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("General purpose .NET assembly modding \"basework\". This package contains the core IL patcher and relinker.")] [assembly: AssemblyFileVersion("21.8.5.1")] [assembly: AssemblyInformationalVersion("21.08.05.01")] [assembly: AssemblyProduct("MonoMod")] [assembly: AssemblyTitle("MonoMod")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.8.5.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { [MonoMod__SafeToCopy__] public class MonoModAdded : Attribute { } [MonoMod__SafeToCopy__] public class MonoModConstructor : Attribute { } [MonoMod__SafeToCopy__] public class MonoModCustomAttributeAttribute : Attribute { public MonoModCustomAttributeAttribute(string h) { } } [MonoMod__SafeToCopy__] public class MonoModCustomMethodAttributeAttribute : Attribute { public MonoModCustomMethodAttributeAttribute(string h) { } } [MonoMod__SafeToCopy__] public class MonoModEnumReplace : Attribute { } [MonoMod__SafeToCopy__] public class MonoModForceCall : Attribute { } [MonoMod__SafeToCopy__] public class MonoModForceCallvirt : Attribute { } [MonoMod__SafeToCopy__] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [Obsolete("Use MonoModLinkFrom or RuntimeDetour / HookGen instead.")] public class MonoModHook : Attribute { public string FindableID; public Type Type; public MonoModHook(string findableID) { FindableID = findableID; } public MonoModHook(Type type) { Type = type; FindableID = type.FullName; } } [MonoMod__SafeToCopy__] public class MonoModIfFlag : Attribute { public MonoModIfFlag(string key) { } public MonoModIfFlag(string key, bool fallback) { } } [MonoMod__SafeToCopy__] public class MonoModIgnore : Attribute { } [MonoMod__SafeToCopy__] [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class MonoModLinkFrom : Attribute { public string FindableID; public Type Type; public MonoModLinkFrom(string findableID) { FindableID = findableID; } public MonoModLinkFrom(Type type) { Type = type; FindableID = type.FullName; } } [MonoMod__SafeToCopy__] public class MonoModLinkTo : Attribute { public MonoModLinkTo(string t) { } public MonoModLinkTo(Type t) { } public MonoModLinkTo(string t, string n) { } public MonoModLinkTo(Type t, string n) { } } [MonoMod__SafeToCopy__] public class MonoModNoNew : Attribute { } [MonoMod__SafeToCopy__] public class MonoModOnPlatform : Attribute { public MonoModOnPlatform(params Platform[] p) { } } [MonoMod__SafeToCopy__] public class MonoModOriginal : Attribute { } [MonoMod__SafeToCopy__] public class MonoModOriginalName : Attribute { public MonoModOriginalName(string n) { } } [MonoMod__SafeToCopy__] public class MonoModPatch : Attribute { public MonoModPatch(string name) { } } [MonoMod__SafeToCopy__] public class MonoModPublic : Attribute { } [MonoMod__SafeToCopy__] public class MonoModRemove : Attribute { } [MonoMod__SafeToCopy__] public class MonoModReplace : Attribute { } [MonoMod__SafeToCopy__] public class MonoModTargetModule : Attribute { public MonoModTargetModule(string name) { } } [MonoMod__SafeToCopy__] internal class MonoMod__SafeToCopy__ : Attribute { } public delegate bool MethodParser(MonoModder modder, MethodBody body, Instruction instr, ref int instri); public delegate void MethodRewriter(MonoModder modder, MethodDefinition method); public delegate void MethodBodyRewriter(MonoModder modder, MethodBody body, Instruction instr, int instri); public delegate ModuleDefinition MissingDependencyResolver(MonoModder modder, ModuleDefinition main, string name, string fullName); public delegate void PostProcessor(MonoModder modder); public delegate void ModReadEventHandler(MonoModder modder, ModuleDefinition mod); public class RelinkMapEntry { public string Type; public string FindableID; public RelinkMapEntry() { } public RelinkMapEntry(string type, string findableID) { Type = type; FindableID = findableID; } } public enum DebugSymbolFormat { Auto, MDB, PDB } public class MonoModder : IDisposable { public static readonly bool IsMono = (object)Type.GetType("Mono.Runtime") != null; public static readonly Version Version = typeof(MonoModder).Assembly.GetName().Version; public Dictionary<string, object> SharedData = new Dictionary<string, object>(); public Dictionary<string, object> RelinkMap = new Dictionary<string, object>(); public Dictionary<string, ModuleDefinition> RelinkModuleMap = new Dictionary<string, ModuleDefinition>(); public HashSet<string> SkipList = new HashSet<string>(EqualityComparer<string>.Default); public Dictionary<string, IMetadataTokenProvider> RelinkMapCache = new Dictionary<string, IMetadataTokenProvider>(); public Dictionary<string, TypeReference> RelinkModuleMapCache = new Dictionary<string, TypeReference>(); public Dictionary<string, OpCode> ForceCallMap = new Dictionary<string, OpCode>(); public ModReadEventHandler OnReadMod; public PostProcessor PostProcessors; public Dictionary<string, Action<object, object[]>> CustomAttributeHandlers = new Dictionary<string, Action<object, object[]>> { { "MonoMod.MonoModPublic", delegate { } } }; public Dictionary<string, Action<object, object[]>> CustomMethodAttributeHandlers = new Dictionary<string, Action<object, object[]>>(); public MissingDependencyResolver MissingDependencyResolver; public MethodParser MethodParser; public MethodRewriter MethodRewriter; public MethodBodyRewriter MethodBodyRewriter; public Stream Input; public string InputPath; public Stream Output; public string OutputPath; public List<string> DependencyDirs = new List<string>(); public ModuleDefinition Module; public Dictionary<ModuleDefinition, List<ModuleDefinition>> DependencyMap = new Dictionary<ModuleDefinition, List<ModuleDefinition>>(); public Dictionary<string, ModuleDefinition> DependencyCache = new Dictionary<string, ModuleDefinition>(); public Func<ICustomAttributeProvider, TypeReference, bool> ShouldCleanupAttrib; public bool LogVerboseEnabled; public bool CleanupEnabled; public bool PublicEverything; public List<ModuleReference> Mods = new List<ModuleReference>(); public bool Strict; public bool MissingDependencyThrow; public bool RemovePatchReferences; public bool PreventInline; public bool? UpgradeMSCORLIB; public ReadingMode ReadingMode = (ReadingMode)1; public DebugSymbolFormat DebugSymbolOutputFormat; public int CurrentRID; protected IAssemblyResolver _assemblyResolver; protected ReaderParameters _readerParameters; protected WriterParameters _writerParameters; public bool GACEnabled; private string[] _GACPathsNone = new string[0]; protected string[] _GACPaths; protected MethodDefinition _mmOriginalCtor; protected MethodDefinition _mmOriginalNameCtor; protected MethodDefinition _mmAddedCtor; protected MethodDefinition _mmPatchCtor; public virtual IAssemblyResolver AssemblyResolver { get { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown if (_assemblyResolver == null) { DefaultAssemblyResolver val = new DefaultAssemblyResolver(); foreach (string dependencyDir in DependencyDirs) { ((BaseAssemblyResolver)val).AddSearchDirectory(dependencyDir); } _assemblyResolver = (IAssemblyResolver)(object)val; } return _assemblyResolver; } set { _assemblyResolver = value; } } public virtual ReaderParameters ReaderParameters { get { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if (_readerParameters == null) { _readerParameters = new ReaderParameters(ReadingMode) { AssemblyResolver = AssemblyResolver, ReadSymbols = true }; } return _readerParameters; } set { _readerParameters = value; } } public virtual WriterParameters WriterParameters { get { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0067: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown if (_writerParameters == null) { bool flag = DebugSymbolOutputFormat == DebugSymbolFormat.PDB; bool flag2 = DebugSymbolOutputFormat == DebugSymbolFormat.MDB; if (DebugSymbolOutputFormat == DebugSymbolFormat.Auto) { if ((PlatformHelper.Current & 0x25) == 37) { flag = true; } else { flag2 = true; } } WriterParameters val = new WriterParameters { WriteSymbols = true }; object symbolWriterProvider; if (!flag) { if (!flag2) { symbolWriterProvider = null; } else { ISymbolWriterProvider val2 = (ISymbolWriterProvider)new MdbWriterProvider(); symbolWriterProvider = val2; } } else { ISymbolWriterProvider val2 = (ISymbolWriterProvider)new NativePdbWriterProvider(); symbolWriterProvider = val2; } val.SymbolWriterProvider = (ISymbolWriterProvider)symbolWriterProvider; _writerParameters = val; } return _writerParameters; } set { _writerParameters = value; } } public string[] GACPaths { get { if (!GACEnabled) { return _GACPathsNone; } if (_GACPaths != null) { return _GACPaths; } if (!IsMono) { string environmentVariable = Environment.GetEnvironmentVariable("windir"); if (string.IsNullOrEmpty(environmentVariable)) { return _GACPaths = _GACPathsNone; } environmentVariable = Path.Combine(environmentVariable, "Microsoft.NET"); environmentVariable = Path.Combine(environmentVariable, "assembly"); _GACPaths = new string[3] { Path.Combine(environmentVariable, "GAC_32"), Path.Combine(environmentVariable, "GAC_64"), Path.Combine(environmentVariable, "GAC_MSIL") }; } else { List<string> list = new List<string>(); string text = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(object).Module.FullyQualifiedName)), "gac"); if (Directory.Exists(text)) { list.Add(text); } string environmentVariable2 = Environment.GetEnvironmentVariable("MONO_GAC_PREFIX"); if (!string.IsNullOrEmpty(environmentVariable2)) { string[] array = environmentVariable2.Split(new char[1] { Path.PathSeparator }); foreach (string text2 in array) { if (!string.IsNullOrEmpty(text2)) { string path = text2; path = Path.Combine(path, "lib"); path = Path.Combine(path, "mono"); path = Path.Combine(path, "gac"); if (Directory.Exists(path) && !list.Contains(path)) { list.Add(path); } } } } _GACPaths = list.ToArray(); } return _GACPaths; } set { GACEnabled = true; _GACPaths = value; } } public MonoModder() { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) MethodParser = DefaultParser; MissingDependencyResolver = DefaultMissingDependencyResolver; PostProcessors = (PostProcessor)Delegate.Combine(PostProcessors, new PostProcessor(DefaultPostProcessor)); string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DEPDIRS"); if (!string.IsNullOrEmpty(environmentVariable)) { foreach (string item in from dir in environmentVariable.Split(new char[1] { Path.PathSeparator }) select dir.Trim()) { IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(item); } DependencyDirs.Add(item); } } LogVerboseEnabled = Environment.GetEnvironmentVariable("MONOMOD_LOG_VERBOSE") == "1"; CleanupEnabled = Environment.GetEnvironmentVariable("MONOMOD_CLEANUP") != "0"; PublicEverything = Environment.GetEnvironmentVariable("MONOMOD_PUBLIC_EVERYTHING") == "1"; PreventInline = Environment.GetEnvironmentVariable("MONOMOD_PREVENTINLINE") == "1"; Strict = Environment.GetEnvironmentVariable("MONOMOD_STRICT") == "1"; MissingDependencyThrow = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") != "0"; RemovePatchReferences = Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_REMOVE_PATCH") != "0"; string environmentVariable2 = Environment.GetEnvironmentVariable("MONOMOD_DEBUG_FORMAT"); if (environmentVariable2 != null) { environmentVariable2 = environmentVariable2.ToLowerInvariant(); if (environmentVariable2 == "pdb") { DebugSymbolOutputFormat = DebugSymbolFormat.PDB; } else if (environmentVariable2 == "mdb") { DebugSymbolOutputFormat = DebugSymbolFormat.MDB; } } string environmentVariable3 = Environment.GetEnvironmentVariable("MONOMOD_MSCORLIB_UPGRADE"); UpgradeMSCORLIB = (string.IsNullOrEmpty(environmentVariable3) ? null : new bool?(environmentVariable3 != "0")); GACEnabled = Environment.GetEnvironmentVariable("MONOMOD_GAC_ENABLED") != "0"; MonoModRulesManager.Register(this); } public virtual void ClearCaches(bool all = false, bool shareable = false, bool moduleSpecific = false) { if (all || shareable) { foreach (KeyValuePair<string, ModuleDefinition> item in DependencyCache) { item.Value.Dispose(); } DependencyCache.Clear(); } if (all || moduleSpecific) { RelinkMapCache.Clear(); RelinkModuleMapCache.Clear(); } } public virtual void Dispose() { //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) ClearCaches(all: true); ModuleDefinition module = Module; if (module != null) { module.Dispose(); } Module = null; ((IDisposable)AssemblyResolver)?.Dispose(); AssemblyResolver = null; foreach (ModuleDefinition mod in Mods) { if ((int)mod != 0) { mod.Dispose(); } } foreach (List<ModuleDefinition> value in DependencyMap.Values) { foreach (ModuleDefinition item in value) { if (item != null) { item.Dispose(); } } } DependencyMap.Clear(); Input?.Dispose(); Output?.Dispose(); } public virtual void Log(object value) { Log(value.ToString()); } public virtual void Log(string text) { Console.Write("[MonoMod] "); Console.WriteLine(text); } public virtual void LogVerbose(object value) { if (LogVerboseEnabled) { Log(value); } } public virtual void LogVerbose(string text) { if (LogVerboseEnabled) { Log(text); } } private static ModuleDefinition _ReadModule(Stream input, ReaderParameters args) { if (args.ReadSymbols) { try { return ModuleDefinition.ReadModule(input, args); } catch { args.ReadSymbols = false; input.Seek(0L, SeekOrigin.Begin); } } return ModuleDefinition.ReadModule(input, args); } private static ModuleDefinition _ReadModule(string input, ReaderParameters args) { if (args.ReadSymbols) { try { return ModuleDefinition.ReadModule(input, args); } catch { args.ReadSymbols = false; } } return ModuleDefinition.ReadModule(input, args); } public virtual void Read() { if (Module != null) { return; } if (Input != null) { Log("Reading input stream into module."); Module = _ReadModule(Input, GenReaderParameters(mainModule: true)); } else if (InputPath != null) { Log("Reading input file into module."); IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(Path.GetDirectoryName(InputPath)); } DependencyDirs.Add(Path.GetDirectoryName(InputPath)); Module = _ReadModule(InputPath, GenReaderParameters(mainModule: true, InputPath)); } string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_MODS"); if (string.IsNullOrEmpty(environmentVariable)) { return; } foreach (string item in from path in environmentVariable.Split(new char[1] { Path.PathSeparator }) select path.Trim()) { ReadMod(item); } } public virtual void MapDependencies() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown foreach (ModuleDefinition mod in Mods) { ModuleDefinition main = mod; MapDependencies(main); } MapDependencies(Module); } public virtual void MapDependencies(ModuleDefinition main) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (DependencyMap.ContainsKey(main)) { return; } DependencyMap[main] = new List<ModuleDefinition>(); Enumerator<AssemblyNameReference> enumerator = main.AssemblyReferences.GetEnumerator(); try { while (enumerator.MoveNext()) { AssemblyNameReference current = enumerator.Current; MapDependency(main, current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void MapDependency(ModuleDefinition main, AssemblyNameReference depRef) { MapDependency(main, depRef.Name, depRef.FullName, depRef); } public virtual void MapDependency(ModuleDefinition main, string name, string fullName = null, AssemblyNameReference depRef = null) { if (!DependencyMap.TryGetValue(main, out var value)) { value = (DependencyMap[main] = new List<ModuleDefinition>()); } if (fullName != null && (DependencyCache.TryGetValue(fullName, out var value2) || DependencyCache.TryGetValue(fullName + " [RT:" + main.RuntimeVersion + "]", out value2))) { LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) from cache"); value.Add(value2); MapDependencies(value2); return; } if (DependencyCache.TryGetValue(name, out value2) || DependencyCache.TryGetValue(name + " [RT:" + main.RuntimeVersion + "]", out value2)) { LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " (" + name + ") from cache"); value.Add(value2); MapDependencies(value2); return; } string text = Path.GetExtension(name).ToLowerInvariant(); bool flag = text == "pdb" || text == "mdb"; string text2 = null; foreach (string dependencyDir in DependencyDirs) { text2 = Path.Combine(dependencyDir, name + ".dll"); if (!File.Exists(text2)) { text2 = Path.Combine(dependencyDir, name + ".exe"); } if (!File.Exists(text2) && !flag) { text2 = Path.Combine(dependencyDir, name); } if (File.Exists(text2)) { break; } text2 = null; } if (text2 == null && depRef != null) { try { AssemblyDefinition obj = AssemblyResolver.Resolve(depRef); value2 = ((obj != null) ? obj.MainModule : null); } catch { } if (value2 != null) { text2 = value2.FileName; } } if (text2 == null) { string[] gACPaths = GACPaths; for (int i = 0; i < gACPaths.Length; i++) { text2 = Path.Combine(gACPaths[i], name); if (Directory.Exists(text2)) { string[] directories = Directory.GetDirectories(text2); int num = 0; int num2 = 0; for (int j = 0; j < directories.Length; j++) { string text3 = directories[j]; if (text3.StartsWith(text2)) { text3 = text3.Substring(text2.Length + 1); } Match match = Regex.Match(text3, "\\d+"); if (match.Success) { int num3 = int.Parse(match.Value); if (num3 > num) { num = num3; num2 = j; } } } text2 = Path.Combine(directories[num2], name + ".dll"); break; } text2 = null; } } if (text2 == null) { try { AssemblyDefinition obj3 = AssemblyResolver.Resolve(AssemblyNameReference.Parse(fullName ?? name)); value2 = ((obj3 != null) ? obj3.MainModule : null); } catch { } if (value2 != null) { text2 = value2.FileName; } } if (value2 == null) { if (text2 != null && File.Exists(text2)) { value2 = _ReadModule(text2, GenReaderParameters(mainModule: false, text2)); } else if ((value2 = MissingDependencyResolver?.Invoke(this, main, name, fullName)) == null) { return; } } LogVerbose("[MapDependency] " + ((ModuleReference)main).Name + " -> " + ((ModuleReference)value2).Name + " ((" + fullName + "), (" + name + ")) loaded"); value.Add(value2); if (fullName == null) { fullName = value2.Assembly.FullName; } DependencyCache[fullName] = value2; DependencyCache[name] = value2; MapDependencies(value2); } public virtual ModuleDefinition DefaultMissingDependencyResolver(MonoModder mod, ModuleDefinition main, string name, string fullName) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (MissingDependencyThrow && Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW") == "0") { Log("[MissingDependencyResolver] [WARNING] Use MMILRT.Modder.MissingDependencyThrow instead of setting the env var MONOMOD_DEPENDENCY_MISSING_THROW"); MissingDependencyThrow = false; } if (MissingDependencyThrow || Strict) { throw new RelinkTargetNotFoundException("MonoMod cannot map dependency " + ((ModuleReference)main).Name + " -> ((" + fullName + "), (" + name + ")) - not found", (IMetadataTokenProvider)(object)main, (IMetadataTokenProvider)null); } return null; } public virtual void Write(Stream output = null, string outputPath = null) { output = output ?? Output; outputPath = outputPath ?? OutputPath; PatchRefsInType(PatchWasHere()); if (output != null) { Log("[Write] Writing modded module into output stream."); Module.Write(output, WriterParameters); } else { Log("[Write] Writing modded module into output file."); Module.Write(outputPath, WriterParameters); } } public virtual ReaderParameters GenReaderParameters(bool mainModule, string path = null) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown ReaderParameters readerParameters = ReaderParameters; ReaderParameters val = new ReaderParameters(readerParameters.ReadingMode); val.AssemblyResolver = readerParameters.AssemblyResolver; val.MetadataResolver = readerParameters.MetadataResolver; val.InMemory = readerParameters.InMemory; val.MetadataImporterProvider = readerParameters.MetadataImporterProvider; val.ReflectionImporterProvider = readerParameters.ReflectionImporterProvider; val.ThrowIfSymbolsAreNotMatching = readerParameters.ThrowIfSymbolsAreNotMatching; val.ApplyWindowsRuntimeProjections = readerParameters.ApplyWindowsRuntimeProjections; val.SymbolStream = readerParameters.SymbolStream; val.SymbolReaderProvider = readerParameters.SymbolReaderProvider; val.ReadSymbols = readerParameters.ReadSymbols; if (path != null && !File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb"))) { val.ReadSymbols = false; } return val; } public virtual void ReadMod(string path) { if (Directory.Exists(path)) { Log("[ReadMod] Loading mod dir: " + path); string text = ((ModuleReference)Module).Name.Substring(0, ((ModuleReference)Module).Name.Length - 3); string value = text.Replace(" ", ""); if (!DependencyDirs.Contains(path)) { IAssemblyResolver assemblyResolver = AssemblyResolver; IAssemblyResolver obj = ((assemblyResolver is BaseAssemblyResolver) ? assemblyResolver : null); if (obj != null) { ((BaseAssemblyResolver)obj).AddSearchDirectory(path); } DependencyDirs.Add(path); } string[] files = Directory.GetFiles(path); foreach (string text2 in files) { if ((Path.GetFileName(text2).StartsWith(text) || Path.GetFileName(text2).StartsWith(value)) && text2.ToLower().EndsWith(".mm.dll")) { ReadMod(text2); } } return; } Log("[ReadMod] Loading mod: " + path); ModuleDefinition val = _ReadModule(path, GenReaderParameters(mainModule: false, path)); string directoryName = Path.GetDirectoryName(path); if (!DependencyDirs.Contains(directoryName)) { IAssemblyResolver assemblyResolver2 = AssemblyResolver; IAssemblyResolver obj2 = ((assemblyResolver2 is BaseAssemblyResolver) ? assemblyResolver2 : null); if (obj2 != null) { ((BaseAssemblyResolver)obj2).AddSearchDirectory(directoryName); } DependencyDirs.Add(directoryName); } Mods.Add((ModuleReference)(object)val); OnReadMod?.Invoke(this, val); } public virtual void ReadMod(Stream stream) { Log($"[ReadMod] Loading mod: stream#{(uint)stream.GetHashCode()}"); ModuleDefinition val = _ReadModule(stream, GenReaderParameters(mainModule: false)); Mods.Add((ModuleReference)(object)val); OnReadMod?.Invoke(this, val); } public virtual void ParseRules(ModuleDefinition mod) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) TypeDefinition type = mod.GetType("MonoMod.MonoModRules"); Type rulesTypeMMILRT = null; if (type != null) { rulesTypeMMILRT = this.ExecuteRules(type); mod.Types.Remove(type); } Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; ParseRulesInType(current, rulesTypeMMILRT); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void ParseRulesInType(TypeDefinition type, Type rulesTypeMMILRT = null) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) Extensions.GetPatchFullName((MemberReference)(object)type); if (!MatchingConditionals((ICustomAttributeProvider)(object)type, Module)) { return; } CustomAttribute customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomAttributeAttribute"); CustomAttributeArgument val; if (customAttribute != null) { val = customAttribute.ConstructorArguments[0]; MethodInfo method2 = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value); CustomAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { method2.Invoke(self, args); }; } customAttribute = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModCustomMethodAttributeAttribute"); if (customAttribute != null) { val = customAttribute.ConstructorArguments[0]; MethodInfo method = rulesTypeMMILRT.GetMethod((string)((CustomAttributeArgument)(ref val)).Value); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 2 && Extensions.IsCompatible(parameters[0].ParameterType, typeof(ILContext))) { CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown ILContext il = new ILContext((MethodDefinition)args[0]); il.Invoke((Manipulator)delegate { method.Invoke(self, new object[2] { il, args[1] }); }); if (il.IsReadOnly) { il.Dispose(); } }; } else { CustomMethodAttributeHandlers[((MemberReference)type).FullName] = delegate(object self, object[] args) { method.Invoke(self, args); }; } } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)type, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)type, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)type).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)type, val2); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) { return; } Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current, val2); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCall")) { ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Call; } else if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)current, "MonoMod.MonoModForceCallvirt")) { ForceCallMap[Extensions.GetID((MethodReference)(object)current, (string)null, (string)null, true, false)] = OpCodes.Callvirt; } } } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<FieldDefinition> enumerator2 = type.Fields.GetEnumerator(); try { while (enumerator2.MoveNext()) { FieldDefinition current2 = enumerator2.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current2, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current2, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current2, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current2, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current2).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current2, val2); } } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<PropertyDefinition> enumerator3 = type.Properties.GetEnumerator(); try { while (enumerator3.MoveNext()) { PropertyDefinition current3 = enumerator3.Current; if (MatchingConditionals((ICustomAttributeProvider)(object)current3, Module)) { for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModHook"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModHook")) { ParseLinkFrom((MemberReference)(object)current3, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkFrom"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkFrom")) { ParseLinkFrom((MemberReference)(object)current3, val2); } for (CustomAttribute val2 = Extensions.GetCustomAttribute((ICustomAttributeProvider)(object)current3, "MonoMod.MonoModLinkTo"); val2 != null; val2 = ((ICustomAttributeProvider)(object)current3).GetNextCustomAttribute("MonoMod.MonoModLinkTo")) { ParseLinkTo((MemberReference)(object)current3, val2); } } } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<TypeDefinition> enumerator4 = type.NestedTypes.GetEnumerator(); try { while (enumerator4.MoveNext()) { TypeDefinition current4 = enumerator4.Current; ParseRulesInType(current4, rulesTypeMMILRT); } } finally { ((IDisposable)enumerator4).Dispose(); } } public virtual void ParseLinkFrom(MemberReference target, CustomAttribute hook) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_003c: 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_005a: Expected O, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = hook.ConstructorArguments[0]; string key = (string)((CustomAttributeArgument)(ref val)).Value; object value; if (target is TypeReference) { value = Extensions.GetPatchFullName((MemberReference)(TypeReference)target); } else if (target is MethodReference) { value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(MethodReference)target).DeclaringType), Extensions.GetID((MethodReference)target, (string)null, (string)null, false, false)); } else if (target is FieldReference) { value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(FieldReference)target).DeclaringType), ((MemberReference)(FieldReference)target).Name); } else { if (!(target is PropertyReference)) { return; } value = new RelinkMapEntry(Extensions.GetPatchFullName((MemberReference)(object)((MemberReference)(PropertyReference)target).DeclaringType), ((MemberReference)(PropertyReference)target).Name); } RelinkMap[key] = value; } public virtual void ParseLinkTo(MemberReference from, CustomAttribute hook) { //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_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) MemberReference obj = ((from is MethodReference) ? from : null); string key = ((obj != null) ? Extensions.GetID((MethodReference)(object)obj, (string)null, (string)null, true, false) : null) ?? Extensions.GetPatchFullName(from); CustomAttributeArgument val; if (hook.ConstructorArguments.Count == 1) { Dictionary<string, object> relinkMap = RelinkMap; val = hook.ConstructorArguments[0]; relinkMap[key] = (string)((CustomAttributeArgument)(ref val)).Value; } else { Dictionary<string, object> relinkMap2 = RelinkMap; val = hook.ConstructorArguments[0]; string type = (string)((CustomAttributeArgument)(ref val)).Value; val = hook.ConstructorArguments[1]; relinkMap2[key] = new RelinkMapEntry(type, (string)((CustomAttributeArgument)(ref val)).Value); } } public virtual void RunCustomAttributeHandlers(ICustomAttributeProvider cap) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown if (!cap.HasCustomAttributes) { return; } CustomAttribute[] array = cap.CustomAttributes.ToArray(); foreach (CustomAttribute val in array) { if (CustomAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out var value)) { value?.Invoke(null, new object[2] { cap, val }); } if (cap is MethodReference && CustomMethodAttributeHandlers.TryGetValue(((MemberReference)val.AttributeType).FullName, out value)) { value?.Invoke(null, new object[2] { (object)(MethodDefinition)cap, val }); } } } public virtual void AutoPatch() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown Log("[AutoPatch] Parsing rules in loaded mods"); foreach (ModuleDefinition mod4 in Mods) { ModuleDefinition mod = mod4; ParseRules(mod); } Log("[AutoPatch] PrePatch pass"); foreach (ModuleDefinition mod5 in Mods) { ModuleDefinition mod2 = mod5; PrePatchModule(mod2); } Log("[AutoPatch] Patch pass"); foreach (ModuleDefinition mod6 in Mods) { ModuleDefinition mod3 = mod6; PatchModule(mod3); } Log("[AutoPatch] PatchRefs pass"); PatchRefs(); if (PostProcessors != null) { Delegate[] invocationList = PostProcessors.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { Log($"[PostProcessor] PostProcessor pass #{i + 1}"); ((PostProcessor)invocationList[i])?.Invoke(this); } } } public virtual IMetadataTokenProvider Relinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) try { return PostRelinker(MainRelinker(mtp, context) ?? mtp, context) ?? throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context); } catch (Exception ex) { throw new RelinkFailedException((string)null, ex, mtp, (IMetadataTokenProvider)(object)context); } } public virtual IMetadataTokenProvider MainRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) TypeReference val = (TypeReference)(object)((mtp is TypeReference) ? mtp : null); if (val != null) { if (((MemberReference)val).Module == Module) { return (IMetadataTokenProvider)(object)val; } if (((MemberReference)val).Module != null && !Mods.Contains((ModuleReference)(object)((MemberReference)val).Module)) { return (IMetadataTokenProvider)(object)Module.ImportReference(val); } val = (TypeReference)(((object)Extensions.SafeResolve(val)) ?? ((object)val)); TypeReference val2 = FindTypeDeep(Extensions.GetPatchFullName((MemberReference)(object)val)); if (val2 == null) { if (RelinkMap.ContainsKey(((MemberReference)val).FullName)) { return null; } throw new RelinkTargetNotFoundException(mtp, (IMetadataTokenProvider)(object)context); } return (IMetadataTokenProvider)(object)Module.ImportReference(val2); } if (mtp is FieldReference || mtp is MethodReference || mtp is PropertyReference || mtp is EventReference) { return Extensions.ImportReference(Module, mtp); } throw new InvalidOperationException($"MonoMod default relinker can't handle metadata token providers of the type {((object)mtp).GetType()}"); } public virtual IMetadataTokenProvider PostRelinker(IMetadataTokenProvider mtp, IGenericParameterProvider context) { return ResolveRelinkTarget(mtp) ?? mtp; } public virtual IMetadataTokenProvider ResolveRelinkTarget(IMetadataTokenProvider mtp, bool relink = true, bool relinkModule = true) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_004b: 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_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Expected O, but got Unknown //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Expected O, but got Unknown //IL_023c: Expected O, but got Unknown //IL_02d2: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Expected O, but got Unknown //IL_0193: Unknown result type (might be due to invalid IL or missing references) string text = null; string text2; if (mtp is TypeReference) { text2 = ((MemberReference)(TypeReference)mtp).FullName; } else if (mtp is MethodReference) { text2 = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, false); text = Extensions.GetID((MethodReference)mtp, (string)null, (string)null, true, true); } else if (mtp is FieldReference) { text2 = ((MemberReference)(FieldReference)mtp).FullName; } else { if (!(mtp is PropertyReference)) { return null; } text2 = ((MemberReference)(PropertyReference)mtp).FullName; } if (RelinkMapCache.TryGetValue(text2, out var value)) { return value; } if (relink && (RelinkMap.TryGetValue(text2, out var value2) || (text != null && RelinkMap.TryGetValue(text, out value2)))) { if (value2 is IMetadataTokenProvider) { return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2); } if (value2 is RelinkMapEntry) { string type = ((RelinkMapEntry)value2).Type; string findableID = ((RelinkMapEntry)value2).FindableID; TypeReference obj = FindTypeDeep(type); TypeDefinition val2 = ((obj != null) ? Extensions.SafeResolve(obj) : null); if (val2 == null) { return RelinkMapCache[text2] = ResolveRelinkTarget(mtp, relink: false, relinkModule); } value2 = Extensions.FindMethod(val2, findableID, true) ?? ((object)Extensions.FindField(val2, findableID)) ?? ((object)(Extensions.FindProperty(val2, findableID) ?? null)); if (value2 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} ({1}, {2}) (remap: {3})", "MonoMod relinker failed finding", type, findableID, mtp), mtp, (IMetadataTokenProvider)null); } return null; } return RelinkMapCache[text2] = Extensions.ImportReference(Module, (IMetadataTokenProvider)value2); } if (value2 is string && mtp is TypeReference) { IMetadataTokenProvider val5 = (IMetadataTokenProvider)(object)FindTypeDeep((string)value2); if (val5 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", value2, mtp), mtp, (IMetadataTokenProvider)null); } return null; } value2 = Extensions.ImportReference(Module, ResolveRelinkTarget(val5, relink: false, relinkModule) ?? val5); } if (value2 is IMetadataTokenProvider) { Dictionary<string, IMetadataTokenProvider> relinkMapCache = RelinkMapCache; string key = text2; IMetadataTokenProvider val6 = (IMetadataTokenProvider)value2; IMetadataTokenProvider result = val6; relinkMapCache[key] = val6; return result; } throw new InvalidOperationException($"MonoMod doesn't support RelinkMap value of type {value2.GetType()} (remap: {mtp})"); } if (relinkModule && mtp is TypeReference) { if (RelinkModuleMapCache.TryGetValue(text2, out var value3)) { return (IMetadataTokenProvider)(object)value3; } value3 = (TypeReference)mtp; if (RelinkModuleMap.TryGetValue(value3.Scope.Name, out var value4)) { TypeReference type2 = (TypeReference)(object)value4.GetType(((MemberReference)value3).FullName); if (type2 == null) { if (Strict) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (remap: {2})", "MonoMod relinker failed finding", ((MemberReference)value3).FullName, mtp), mtp, (IMetadataTokenProvider)null); } return null; } return (IMetadataTokenProvider)(object)(RelinkModuleMapCache[text2] = Module.ImportReference(type2)); } return (IMetadataTokenProvider)(object)Module.ImportReference(value3); } return null; } public virtual bool DefaultParser(MonoModder mod, MethodBody body, Instruction instr, ref int instri) { return true; } public virtual TypeReference FindType(string name) { return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, false); } public virtual TypeReference FindType(string name, bool runtimeName) { return FindType(Module, name, new Stack<ModuleDefinition>()) ?? Module.GetType(name, runtimeName); } protected virtual TypeReference FindType(ModuleDefinition main, string fullName, Stack<ModuleDefinition> crawled) { TypeReference type; if ((type = main.GetType(fullName, false)) != null) { return type; } if (fullName.StartsWith("<PrivateImplementationDetails>/")) { return null; } if (crawled.Contains(main)) { return null; } crawled.Push(main); foreach (ModuleDefinition item in DependencyMap[main]) { if ((!RemovePatchReferences || !((AssemblyNameReference)item.Assembly.Name).Name.EndsWith(".mm")) && (type = FindType(item, fullName, crawled)) != null) { return type; } } return null; } public virtual TypeReference FindTypeDeep(string name) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown TypeReference val = FindType(name, runtimeName: false); if (val != null) { return val; } Stack<ModuleDefinition> crawled = new Stack<ModuleDefinition>(); val = null; foreach (ModuleDefinition mod in Mods) { ModuleDefinition key = mod; foreach (ModuleDefinition item in DependencyMap[key]) { if ((val = FindType(item, name, crawled)) != null) { IMetadataScope scope = val.Scope; AssemblyNameReference dllRef = (AssemblyNameReference)(object)((scope is AssemblyNameReference) ? scope : null); if (dllRef != null && !((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference n) => n.Name == dllRef.Name)) { Module.AssemblyReferences.Add(dllRef); } return Module.ImportReference(val); } } } return null; } public virtual void PrePatchModule(ModuleDefinition mod) { //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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Expected O, but got Unknown Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PrePatchType(current); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<ModuleReference> enumerator2 = mod.ModuleReferences.GetEnumerator(); try { while (enumerator2.MoveNext()) { ModuleReference current2 = enumerator2.Current; if (!Module.ModuleReferences.Contains(current2)) { Module.ModuleReferences.Add(current2); } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<Resource> enumerator3 = mod.Resources.GetEnumerator(); try { while (enumerator3.MoveNext()) { Resource current3 = enumerator3.Current; if (current3 is EmbeddedResource) { Module.Resources.Add((Resource)new EmbeddedResource(current3.Name.StartsWith(((AssemblyNameReference)mod.Assembly.Name).Name) ? (((AssemblyNameReference)Module.Assembly.Name).Name + current3.Name.Substring(((AssemblyNameReference)mod.Assembly.Name).Name.Length)) : current3.Name, current3.Attributes, ((EmbeddedResource)current3).GetResourceData())); } } } finally { ((IDisposable)enumerator3).Dispose(); } } public virtual void PrePatchType(TypeDefinition type, bool forceAdd = false) { //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: 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_0161: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Expected O, but got Unknown //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Expected O, but got Unknown string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type); if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module) || (((MemberReference)type).FullName == "MonoMod.MonoModRules" && !forceAdd)) { return; } TypeReference val = (forceAdd ? null : Module.GetType(patchFullName, false)); TypeDefinition val2 = ((val != null) ? Extensions.SafeResolve(val) : null); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModReplace") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove")) { if (val2 != null) { if (val2.DeclaringType == null) { Module.Types.Remove(val2); } else { val2.DeclaringType.NestedTypes.Remove(val2); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModRemove")) { return; } } else if (val != null) { PrePatchNested(type); return; } LogVerbose("[PrePatchType] Adding " + patchFullName + " to the target module."); TypeDefinition val3 = new TypeDefinition(((TypeReference)type).Namespace, ((MemberReference)type).Name, type.Attributes, type.BaseType); Enumerator<GenericParameter> enumerator = ((TypeReference)type).GenericParameters.GetEnumerator(); try { while (enumerator.MoveNext()) { GenericParameter current = enumerator.Current; ((TypeReference)val3).GenericParameters.Add(Extensions.Clone(current)); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<InterfaceImplementation> enumerator2 = type.Interfaces.GetEnumerator(); try { while (enumerator2.MoveNext()) { InterfaceImplementation current2 = enumerator2.Current; val3.Interfaces.Add(current2); } } finally { ((IDisposable)enumerator2).Dispose(); } val3.ClassSize = type.ClassSize; if (type.DeclaringType != null) { val3.DeclaringType = Extensions.Relink((TypeReference)(object)type.DeclaringType, new Relinker(Relinker), (IGenericParameterProvider)(object)val3).Resolve(); val3.DeclaringType.NestedTypes.Add(val3); } else { Module.Types.Add(val3); } val3.PackingSize = type.PackingSize; Extensions.AddRange<SecurityDeclaration>(val3.SecurityDeclarations, (IEnumerable<SecurityDeclaration>)type.SecurityDeclarations); val3.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val = (TypeReference)(object)val3; PrePatchNested(type); } protected virtual void PrePatchNested(TypeDefinition type) { for (int i = 0; i < type.NestedTypes.Count; i++) { PrePatchType(type.NestedTypes[i]); } } public virtual void PatchModule(ModuleDefinition mod) { //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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; if ((((TypeReference)current).Namespace == "MonoMod" || ((TypeReference)current).Namespace.StartsWith("MonoMod.")) && ((MemberReference)current.BaseType).FullName == "System.Attribute") { PatchType(current); } } } finally { ((IDisposable)enumerator).Dispose(); } enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current2 = enumerator.Current; if ((!(((TypeReference)current2).Namespace == "MonoMod") && !((TypeReference)current2).Namespace.StartsWith("MonoMod.")) || !(((MemberReference)current2.BaseType).FullName == "System.Attribute")) { PatchType(current2); } } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchType(TypeDefinition type) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)type); TypeReference type2 = Module.GetType(patchFullName, false); if (type2 == null) { return; } TypeDefinition val = ((type2 != null) ? Extensions.SafeResolve(type2) : null); Enumerator<CustomAttribute> enumerator; if ((((TypeReference)type).Namespace != "MonoMod" && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore")) || SkipList.Contains(patchFullName) || !MatchingConditionals((ICustomAttributeProvider)(object)type, Module)) { if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModIgnore") && val != null) { enumerator = type.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } PatchNested(type); return; } if (patchFullName == ((MemberReference)type).FullName) { LogVerbose("[PatchType] Patching type " + patchFullName); } else { LogVerbose("[PatchType] Patching type " + patchFullName + " (prefixed: " + ((MemberReference)type).FullName + ")"); } enumerator = type.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current2 = enumerator.Current; if (!Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)val, ((MemberReference)current2.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current2)); } } } finally { ((IDisposable)enumerator).Dispose(); } HashSet<MethodDefinition> hashSet = new HashSet<MethodDefinition>(); Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { PropertyDefinition current3 = enumerator2.Current; PatchProperty(val, current3, hashSet); } } finally { ((IDisposable)enumerator2).Dispose(); } HashSet<MethodDefinition> hashSet2 = new HashSet<MethodDefinition>(); Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator(); try { while (enumerator3.MoveNext()) { EventDefinition current4 = enumerator3.Current; PatchEvent(val, current4, hashSet2); } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodDefinition current5 = enumerator4.Current; if (!hashSet.Contains(current5) && !hashSet2.Contains(current5)) { PatchMethod(val, current5); } } } finally { ((IDisposable)enumerator4).Dispose(); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)type, "MonoMod.MonoModEnumReplace")) { int num = 0; while (num < val.Fields.Count) { if (((MemberReference)val.Fields[num]).Name == "value__") { num++; } else { val.Fields.RemoveAt(num); } } } Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator(); try { while (enumerator5.MoveNext()) { FieldDefinition current6 = enumerator5.Current; PatchField(val, current6); } } finally { ((IDisposable)enumerator5).Dispose(); } PatchNested(type); } protected virtual void PatchNested(TypeDefinition type) { for (int i = 0; i < type.NestedTypes.Count; i++) { PatchType(type.NestedTypes[i]); } } public virtual void PatchProperty(TypeDefinition targetType, PropertyDefinition prop, HashSet<MethodDefinition> propMethods = null) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Expected O, but got Unknown //IL_022b: Expected O, but got Unknown //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Expected O, but got Unknown //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Expected O, but got Unknown //IL_02b5: Expected O, but got Unknown //IL_0363: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Unknown result type (might be due to invalid IL or missing references) if (!MatchingConditionals((ICustomAttributeProvider)(object)prop, Module)) { return; } ((MemberReference)prop).Name = Extensions.GetPatchName((MemberReference)(object)prop); PropertyDefinition val = Extensions.FindProperty(targetType, ((MemberReference)prop).Name); string text = "<" + ((MemberReference)prop).Name + ">__BackingField"; FieldDefinition val2 = Extensions.FindField(prop.DeclaringType, text); FieldDefinition val3 = Extensions.FindField(targetType, text); Enumerator<CustomAttribute> enumerator; Enumerator<MethodDefinition> enumerator2; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModIgnore")) { if (val != null) { enumerator = prop.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 != null) { val2.DeclaringType.Fields.Remove(val2); } if (prop.GetMethod != null) { propMethods?.Add(prop.GetMethod); } if (prop.SetMethod != null) { propMethods?.Add(prop.SetMethod); } enumerator2 = prop.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current2 = enumerator2.Current; propMethods?.Add(current2); } return; } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModReplace")) { if (val != null) { targetType.Properties.Remove(val); if (val3 != null) { targetType.Fields.Remove(val3); } if (val.GetMethod != null) { targetType.Methods.Remove(val.GetMethod); } if (val.SetMethod != null) { targetType.Methods.Remove(val.SetMethod); } enumerator2 = val.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current3 = enumerator2.Current; targetType.Methods.Remove(current3); } } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)prop, "MonoMod.MonoModRemove")) { return; } } if (val == null) { PropertyDefinition val4 = new PropertyDefinition(((MemberReference)prop).Name, prop.Attributes, ((PropertyReference)prop).PropertyType); val = val4; PropertyDefinition val5 = val4; val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); Enumerator<ParameterDefinition> enumerator3 = ((PropertyReference)prop).Parameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { ParameterDefinition current4 = enumerator3.Current; ((PropertyReference)val5).Parameters.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator3).Dispose(); } val5.DeclaringType = targetType; targetType.Properties.Add(val5); if (val2 != null) { FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType); val3 = val6; FieldDefinition val7 = val6; targetType.Fields.Add(val7); } } enumerator = prop.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current5 = enumerator.Current; val.CustomAttributes.Add(Extensions.Clone(current5)); } } finally { ((IDisposable)enumerator).Dispose(); } MethodDefinition getMethod = prop.GetMethod; MethodDefinition getMethod2; if (getMethod != null && (getMethod2 = PatchMethod(targetType, getMethod)) != null) { val.GetMethod = getMethod2; propMethods?.Add(getMethod); } MethodDefinition setMethod = prop.SetMethod; if (setMethod != null && (getMethod2 = PatchMethod(targetType, setMethod)) != null) { val.SetMethod = getMethod2; propMethods?.Add(setMethod); } enumerator2 = prop.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current6 = enumerator2.Current; if ((getMethod2 = PatchMethod(targetType, current6)) != null) { val.OtherMethods.Add(getMethod2); propMethods?.Add(current6); } } } finally { ((IDisposable)enumerator2).Dispose(); } } public virtual void PatchEvent(TypeDefinition targetType, EventDefinition srcEvent, HashSet<MethodDefinition> propMethods = null) { //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_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Expected O, but got Unknown //IL_0252: Expected O, but got Unknown //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Expected O, but got Unknown //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) ((MemberReference)srcEvent).Name = Extensions.GetPatchName((MemberReference)(object)srcEvent); EventDefinition val = Extensions.FindEvent(targetType, ((MemberReference)srcEvent).Name); string text = "<" + ((MemberReference)srcEvent).Name + ">__BackingField"; FieldDefinition val2 = Extensions.FindField(srcEvent.DeclaringType, text); FieldDefinition val3 = Extensions.FindField(targetType, text); Enumerator<CustomAttribute> enumerator; Enumerator<MethodDefinition> enumerator2; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModIgnore")) { if (val != null) { enumerator = srcEvent.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 != null) { val2.DeclaringType.Fields.Remove(val2); } if (srcEvent.AddMethod != null) { propMethods?.Add(srcEvent.AddMethod); } if (srcEvent.RemoveMethod != null) { propMethods?.Add(srcEvent.RemoveMethod); } if (srcEvent.InvokeMethod != null) { propMethods?.Add(srcEvent.InvokeMethod); } enumerator2 = srcEvent.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current2 = enumerator2.Current; propMethods?.Add(current2); } return; } finally { ((IDisposable)enumerator2).Dispose(); } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModReplace")) { if (val != null) { targetType.Events.Remove(val); if (val3 != null) { targetType.Fields.Remove(val3); } if (val.AddMethod != null) { targetType.Methods.Remove(val.AddMethod); } if (val.RemoveMethod != null) { targetType.Methods.Remove(val.RemoveMethod); } if (val.InvokeMethod != null) { targetType.Methods.Remove(val.InvokeMethod); } if (val.OtherMethods != null) { enumerator2 = val.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current3 = enumerator2.Current; targetType.Methods.Remove(current3); } } finally { ((IDisposable)enumerator2).Dispose(); } } } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)srcEvent, "MonoMod.MonoModRemove")) { return; } } if (val == null) { EventDefinition val4 = new EventDefinition(((MemberReference)srcEvent).Name, srcEvent.Attributes, ((EventReference)srcEvent).EventType); val = val4; EventDefinition val5 = val4; val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val5.DeclaringType = targetType; targetType.Events.Add(val5); if (val2 != null) { FieldDefinition val6 = new FieldDefinition(text, val2.Attributes, ((FieldReference)val2).FieldType); targetType.Fields.Add(val6); } } enumerator = srcEvent.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current4 = enumerator.Current; val.CustomAttributes.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator).Dispose(); } MethodDefinition addMethod = srcEvent.AddMethod; MethodDefinition addMethod2; if (addMethod != null && (addMethod2 = PatchMethod(targetType, addMethod)) != null) { val.AddMethod = addMethod2; propMethods?.Add(addMethod); } MethodDefinition removeMethod = srcEvent.RemoveMethod; if (removeMethod != null && (addMethod2 = PatchMethod(targetType, removeMethod)) != null) { val.RemoveMethod = addMethod2; propMethods?.Add(removeMethod); } MethodDefinition invokeMethod = srcEvent.InvokeMethod; if (invokeMethod != null && (addMethod2 = PatchMethod(targetType, invokeMethod)) != null) { val.InvokeMethod = addMethod2; propMethods?.Add(invokeMethod); } enumerator2 = srcEvent.OtherMethods.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodDefinition current5 = enumerator2.Current; if ((addMethod2 = PatchMethod(targetType, current5)) != null) { val.OtherMethods.Add(addMethod2); propMethods?.Add(current5); } } } finally { ((IDisposable)enumerator2).Dispose(); } } public virtual void PatchField(TypeDefinition targetType, FieldDefinition field) { //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_011b: 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_012c: Expected O, but got Unknown //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)field.DeclaringType); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModNoNew") || SkipList.Contains(patchFullName + "::" + ((MemberReference)field).Name) || !MatchingConditionals((ICustomAttributeProvider)(object)field, Module)) { return; } ((MemberReference)field).Name = Extensions.GetPatchName((MemberReference)(object)field); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModReplace")) { FieldDefinition val = Extensions.FindField(targetType, ((MemberReference)field).Name); if (val != null) { targetType.Fields.Remove(val); } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModRemove")) { return; } } FieldDefinition val2 = Extensions.FindField(targetType, ((MemberReference)field).Name); Enumerator<CustomAttribute> enumerator; if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)field, "MonoMod.MonoModIgnore") && val2 != null) { enumerator = field.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val2.CustomAttributes.Add(Extensions.Clone(current)); } } return; } finally { ((IDisposable)enumerator).Dispose(); } } if (val2 == null) { val2 = new FieldDefinition(((MemberReference)field).Name, field.Attributes, ((FieldReference)field).FieldType); val2.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); val2.InitialValue = field.InitialValue; if (field.HasConstant) { val2.Constant = field.Constant; } targetType.Fields.Add(val2); } enumerator = field.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current2 = enumerator.Current; val2.CustomAttributes.Add(Extensions.Clone(current2)); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual MethodDefinition PatchMethod(TypeDefinition targetType, MethodDefinition method) { //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Expected O, but got Unknown //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_049f: Unknown result type (might be due to invalid IL or missing references) //IL_04b4: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Expected O, but got Unknown //IL_04c3: Unknown result type (might be due to invalid IL or missing references) //IL_04d0: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_0504: Unknown result type (might be due to invalid IL or missing references) //IL_0511: Unknown result type (might be due to invalid IL or missing references) //IL_0564: Unknown result type (might be due to invalid IL or missing references) //IL_0569: Unknown result type (might be due to invalid IL or missing references) //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_0458: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Expected O, but got Unknown //IL_05a8: Unknown result type (might be due to invalid IL or missing references) //IL_05ad: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Unknown result type (might be due to invalid IL or missing references) //IL_069a: Unknown result type (might be due to invalid IL or missing references) //IL_06a1: Expected O, but got Unknown //IL_06be: Unknown result type (might be due to invalid IL or missing references) //IL_05ec: Unknown result type (might be due to invalid IL or missing references) //IL_05f1: Unknown result type (might be due to invalid IL or missing references) //IL_0630: Unknown result type (might be due to invalid IL or missing references) //IL_0635: Unknown result type (might be due to invalid IL or missing references) //IL_0676: Unknown result type (might be due to invalid IL or missing references) //IL_0680: Expected O, but got Unknown if (((MemberReference)method).Name.StartsWith("orig_") || Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginal")) { return null; } if (!AllowedSpecialName(method, targetType) || !MatchingConditionals((ICustomAttributeProvider)(object)method, Module)) { return null; } string patchFullName = Extensions.GetPatchFullName((MemberReference)(object)targetType); if (SkipList.Contains(Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false))) { return null; } ((MemberReference)method).Name = Extensions.GetPatchName((MemberReference)(object)method); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor")) { if (!method.IsSpecialName && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModOriginalName")) { CustomAttribute val = new CustomAttribute(GetMonoModOriginalNameCtor()); val.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)("orig_" + ((MemberReference)method).Name))); method.CustomAttributes.Add(val); } ((MemberReference)method).Name = (method.IsStatic ? ".cctor" : ".ctor"); method.IsSpecialName = true; method.IsRuntimeSpecialName = true; } MethodDefinition val2 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)method, (string)null, patchFullName, true, false), true); MethodDefinition obj = method; string text = patchFullName; MethodDefinition val3 = Extensions.FindMethod(targetType, Extensions.GetID((MethodReference)(object)obj, method.GetOriginalName(), text, true, false), true); if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModIgnore")) { if (val2 != null) { Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current.AttributeType).FullName)) { val2.CustomAttributes.Add(Extensions.Clone(current)); } } } finally { ((IDisposable)enumerator).Dispose(); } } return null; } if (val2 == null && Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModNoNew")) { return null; } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModRemove")) { if (val2 != null) { targetType.Methods.Remove(val2); } return null; } if (Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModReplace")) { if (val2 != null) { val2.CustomAttributes.Clear(); val2.Attributes = method.Attributes; val2.IsPInvokeImpl = method.IsPInvokeImpl; val2.ImplAttributes = method.ImplAttributes; } } else if (val2 != null && val3 == null) { val3 = Extensions.Clone(val2, (MethodDefinition)null); ((MemberReference)val3).Name = method.GetOriginalName(); val3.Attributes = (MethodAttributes)(val2.Attributes & 0xF7FF & 0xEFFF); ((MemberReference)val3).MetadataToken = GetMetadataToken((TokenType)100663296); val3.IsVirtual = false; val3.Overrides.Clear(); Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodReference current2 = enumerator2.Current; val3.Overrides.Add(current2); } } finally { ((IDisposable)enumerator2).Dispose(); } val3.CustomAttributes.Add(new CustomAttribute(GetMonoModOriginalCtor())); MethodDefinition val4 = Extensions.FindMethod(method.DeclaringType, Extensions.GetID((MethodReference)(object)method, method.GetOriginalName(), (string)null, true, false), true); if (val4 != null) { Enumerator<CustomAttribute> enumerator = val4.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current3 = enumerator.Current; if (CustomAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName) || CustomMethodAttributeHandlers.ContainsKey(((MemberReference)current3.AttributeType).FullName)) { val3.CustomAttributes.Add(Extensions.Clone(current3)); } } } finally { ((IDisposable)enumerator).Dispose(); } } targetType.Methods.Add(val3); } if (val3 != null && method.IsConstructor && method.IsStatic && method.HasBody && !Extensions.HasCustomAttribute((ICustomAttributeProvider)(object)method, "MonoMod.MonoModConstructor")) { Collection<Instruction> instructions = method.Body.Instructions; ILProcessor iLProcessor = method.Body.GetILProcessor(); iLProcessor.InsertBefore(instructions[instructions.Count - 1], iLProcessor.Create(OpCodes.Call, (MethodReference)(object)val3)); } if (val2 != null) { val2.Body = Extensions.Clone(method.Body, val2); val2.IsManaged = method.IsManaged; val2.IsIL = method.IsIL; val2.IsNative = method.IsNative; val2.PInvokeInfo = method.PInvokeInfo; val2.IsPreserveSig = method.IsPreserveSig; val2.IsInternalCall = method.IsInternalCall; val2.IsPInvokeImpl = method.IsPInvokeImpl; Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current4 = enumerator.Current; val2.CustomAttributes.Add(Extensions.Clone(current4)); } } finally { ((IDisposable)enumerator).Dispose(); } method = val2; } else { MethodDefinition val5 = new MethodDefinition(((MemberReference)method).Name, method.Attributes, Module.TypeSystem.Void); ((MemberReference)val5).MetadataToken = GetMetadataToken((TokenType)100663296); ((MethodReference)val5).CallingConvention = ((MethodReference)method).CallingConvention; ((MethodReference)val5).ExplicitThis = ((MethodReference)method).ExplicitThis; ((MethodReference)val5).MethodReturnType = ((MethodReference)method).MethodReturnType; val5.Attributes = method.Attributes; val5.ImplAttributes = method.ImplAttributes; val5.SemanticsAttributes = method.SemanticsAttributes; val5.DeclaringType = targetType; ((MethodReference)val5).ReturnType = ((MethodReference)method).ReturnType; val5.Body = Extensions.Clone(method.Body, val5); val5.PInvokeInfo = method.PInvokeInfo; val5.IsPInvokeImpl = method.IsPInvokeImpl; Enumerator<GenericParameter> enumerator3 = ((MethodReference)method).GenericParameters.GetEnumerator(); try { while (enumerator3.MoveNext()) { GenericParameter current5 = enumerator3.Current; ((MethodReference)val5).GenericParameters.Add(Extensions.Clone(current5)); } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<ParameterDefinition> enumerator4 = ((MethodReference)method).Parameters.GetEnumerator(); try { while (enumerator4.MoveNext()) { ParameterDefinition current6 = enumerator4.Current; ((MethodReference)val5).Parameters.Add(Extensions.Clone(current6)); } } finally { ((IDisposable)enumerator4).Dispose(); } Enumerator<CustomAttribute> enumerator = method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current7 = enumerator.Current; val5.CustomAttributes.Add(Extensions.Clone(current7)); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<MethodReference> enumerator2 = method.Overrides.GetEnumerator(); try { while (enumerator2.MoveNext()) { MethodReference current8 = enumerator2.Current; val5.Overrides.Add(current8); } } finally { ((IDisposable)enumerator2).Dispose(); } val5.CustomAttributes.Add(new CustomAttribute(GetMonoModAddedCtor())); targetType.Methods.Add(val5); method = val5; } if (val3 != null) { CustomAttribute val6 = new CustomAttribute(GetMonoModOriginalNameCtor()); val6.ConstructorArguments.Add(new CustomAttributeArgument(Module.TypeSystem.String, (object)((MemberReference)val3).Name)); method.CustomAttributes.Add(val6); } return method; } public virtual void PatchRefs() { //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) if (!UpgradeMSCORLIB.HasValue) { Version fckUnity = new Version(2, 0, 5, 0); UpgradeMSCORLIB = ((IEnumerable<AssemblyNameReference>)Module.AssemblyReferences).Any((AssemblyNameReference x) => x.Version == fckUnity); } if (UpgradeMSCORLIB.Value) { List<AssemblyNameReference> list = new List<AssemblyNameReference>(); for (int i = 0; i < Module.AssemblyReferences.Count; i++) { AssemblyNameReference val = Module.AssemblyReferences[i]; if (val.Name == "mscorlib") { list.Add(val); } } if (list.Count > 1) { AssemblyNameReference val2 = list.OrderByDescending((AssemblyNameReference x) => x.Version).First(); if (DependencyCache.TryGetValue(val2.FullName, out var value)) { for (int j = 0; j < Module.AssemblyReferences.Count; j++) { AssemblyNameReference val3 = Module.AssemblyReferences[j]; if (val3.Name == "mscorlib" && val2.Version > val3.Version) { LogVerbose("[PatchRefs] Removing and relinking duplicate mscorlib: " + val3.Version); RelinkModuleMap[val3.FullName] = value; Module.AssemblyReferences.RemoveAt(j); j--; } } } } } Enumerator<TypeDefinition> enumerator = Module.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PatchRefsInType(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchRefs(ModuleDefinition mod) { //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) Enumerator<TypeDefinition> enumerator = mod.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; PatchRefsInType(current); } } finally { ((IDisposable)enumerator).Dispose(); } } public virtual void PatchRefsInType(TypeDefinition type) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Expected O, but got Unknown //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016e: 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_00dc: Expected O, but got Unknown //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Expected O, but got Unknown //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Expected O, but got Unknown //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Expected O, but got Unknown //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Expected O, but got Unknown //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Expected O, but got Unknown LogVerbose($"[VERBOSE] [PatchRefsInType] Patching refs in {type}"); if (type.BaseType != null) { type.BaseType = Extensions.Relink(type.BaseType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); } for (int i = 0; i < ((TypeReference)type).GenericParameters.Count; i++) { ((TypeReference)type).GenericParameters[i] = Extensions.Relink(((TypeReference)type).GenericParameters[i], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } for (int j = 0; j < type.Interfaces.Count; j++) { InterfaceImplementation obj = type.Interfaces[j]; InterfaceImplementation val = new InterfaceImplementation(Extensions.Relink(obj.InterfaceType, new Relinker(Relinker), (IGenericParameterProvider)(object)type)); Enumerator<CustomAttribute> enumerator = obj.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; val.CustomAttributes.Add(Extensions.Relink(current, new Relinker(Relinker), (IGenericParameterProvider)(object)type)); } } finally { ((IDisposable)enumerator).Dispose(); } type.Interfaces[j] = val; } for (int k = 0; k < type.CustomAttributes.Count; k++) { type.CustomAttributes[k] = Extensions.Relink(type.CustomAttributes[k], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } Enumerator<PropertyDefinition> enumerator2 = type.Properties.GetEnumerator(); try { while (enumerator2.MoveNext()) { PropertyDefinition current2 = enumerator2.Current; ((PropertyReference)current2).PropertyType = Extensions.Relink(((PropertyReference)current2).PropertyType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int l = 0; l < current2.CustomAttributes.Count; l++) { current2.CustomAttributes[l] = Extensions.Relink(current2.CustomAttributes[l], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator2).Dispose(); } Enumerator<EventDefinition> enumerator3 = type.Events.GetEnumerator(); try { while (enumerator3.MoveNext()) { EventDefinition current3 = enumerator3.Current; ((EventReference)current3).EventType = Extensions.Relink(((EventReference)current3).EventType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int m = 0; m < current3.CustomAttributes.Count; m++) { current3.CustomAttributes[m] = Extensions.Relink(current3.CustomAttributes[m], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator3).Dispose(); } Enumerator<MethodDefinition> enumerator4 = type.Methods.GetEnumerator(); try { while (enumerator4.MoveNext()) { MethodDefinition current4 = enumerator4.Current; PatchRefsInMethod(current4); } } finally { ((IDisposable)enumerator4).Dispose(); } Enumerator<FieldDefinition> enumerator5 = type.Fields.GetEnumerator(); try { while (enumerator5.MoveNext()) { FieldDefinition current5 = enumerator5.Current; ((FieldReference)current5).FieldType = Extensions.Relink(((FieldReference)current5).FieldType, new Relinker(Relinker), (IGenericParameterProvider)(object)type); for (int n = 0; n < current5.CustomAttributes.Count; n++) { current5.CustomAttributes[n] = Extensions.Relink(current5.CustomAttributes[n], new Relinker(Relinker), (IGenericParameterProvider)(object)type); } } } finally { ((IDisposable)enumerator5).Dispose(); } for (int num = 0; num < type.NestedTypes.Count; num++) { PatchRefsInType(type.NestedTypes[num]); } } public virtual void PatchRefsInMethod(MethodDefinition method) { //IL_0030: Unknown result t
BepInEx/plugins/patchers/BepInEx.MonoMod.HookGenPatcher/MonoMod.RuntimeDetour.HookGen.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2021 0x0ade")] [assembly: AssemblyDescription("Auto-generate hook helper .dlls, hook arbitrary methods via events: On.Namespace.Type.Method += YourHandlerHere;")] [assembly: AssemblyFileVersion("21.8.5.1")] [assembly: AssemblyInformationalVersion("21.08.05.01")] [assembly: AssemblyProduct("MonoMod.RuntimeDetour.HookGen")] [assembly: AssemblyTitle("MonoMod.RuntimeDetour.HookGen")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("21.8.5.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { internal static class MMDbgLog { public static readonly string Tag; public static TextWriter Writer; public static bool Debugging; static MMDbgLog() { Tag = typeof(MMDbgLog).Assembly.GetName().Name; if (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1" || (Environment.GetEnvironmentVariable("MONOMOD_DBGLOG")?.ToLowerInvariant()?.Contains(Tag.ToLowerInvariant())).GetValueOrDefault()) { Start(); } } public static void WaitForDebugger() { if (!Debugging) { Debugging = true; Debugger.Launch(); Thread.Sleep(6000); Debugger.Break(); } } public static void Start() { if (Writer != null) { return; } string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH"); if (text == "-") { Writer = Console.Out; return; } if (string.IsNullOrEmpty(text)) { text = "mmdbglog.txt"; } text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text)); try { if (File.Exists(text)) { File.Delete(text); } } catch { } try { string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8); } catch { } } public static void Log(string str) { TextWriter writer = Writer; if (writer != null) { writer.WriteLine(str); writer.Flush(); } } public static T Log<T>(string str, T value) { TextWriter writer = Writer; if (writer == null) { return value; } writer.WriteLine(string.Format(str, value)); writer.Flush(); return value; } } } namespace MonoMod.RuntimeDetour.HookGen { public class HookGenerator { private const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes."; private static readonly Regex NameVerifyRegex; private static readonly Dictionary<Type, string> ReflTypeNameMap; private static readonly Dictionary<string, string> TypeNameMap; public MonoModder Modder; public ModuleDefinition OutputModule; public string Namespace; public string NamespaceIL; public bool HookOrig; public bool HookPrivate; public string HookExtName; public ModuleDefinition module_RuntimeDetour; public ModuleDefinition module_Utils; public TypeReference t_MulticastDelegate; public TypeReference t_IAsyncResult; public TypeReference t_AsyncCallback; public TypeReference t_MethodBase; public TypeReference t_RuntimeMethodHandle; public TypeReference t_EditorBrowsableState; public MethodReference m_Object_ctor; public MethodReference m_ObsoleteAttribute_ctor; public MethodReference m_EditorBrowsableAttribute_ctor; public MethodReference m_GetMethodFromHandle; public MethodReference m_Add; public MethodReference m_Remove; public MethodReference m_Modify; public MethodReference m_Unmodify; public TypeReference t_ILManipulator; static HookGenerator() { NameVerifyRegex = new Regex("[^a-zA-Z]"); ReflTypeNameMap = new Dictionary<Type, string> { { typeof(string), "string" }, { typeof(object), "object" }, { typeof(bool), "bool" }, { typeof(byte), "byte" }, { typeof(char), "char" }, { typeof(decimal), "decimal" }, { typeof(double), "double" }, { typeof(short), "short" }, { typeof(int), "int" }, { typeof(long), "long" }, { typeof(sbyte), "sbyte" }, { typeof(float), "float" }, { typeof(ushort), "ushort" }, { typeof(uint), "uint" }, { typeof(ulong), "ulong" }, { typeof(void), "void" } }; TypeNameMap = new Dictionary<string, string>(); foreach (KeyValuePair<Type, string> item in ReflTypeNameMap) { TypeNameMap[item.Key.FullName] = item.Value; } } public HookGenerator(MonoModder modder, string name) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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_003d: 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_0053: Expected O, but got Unknown //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Expected O, but got Unknown //IL_0326: Expected O, but got Unknown Modder = modder; OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters { Architecture = modder.Module.Architecture, AssemblyResolver = modder.Module.AssemblyResolver, Kind = (ModuleKind)0, Runtime = modder.Module.Runtime }); modder.MapDependencies(); Extensions.AddRange<AssemblyNameReference>(OutputModule.AssemblyReferences, (IEnumerable<AssemblyNameReference>)modder.Module.AssemblyReferences); modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]); Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE"); if (string.IsNullOrEmpty(Namespace)) { Namespace = "On"; } NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL"); if (string.IsNullOrEmpty(NamespaceIL)) { NamespaceIL = "IL"; } HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1"; HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1"; modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour", (string)null, (AssemblyNameReference)null); if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour)) { throw new FileNotFoundException("MonoMod.RuntimeDetour not found!"); } modder.MapDependency(modder.Module, "MonoMod.Utils", (string)null, (AssemblyNameReference)null); if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils)) { throw new FileNotFoundException("MonoMod.Utils not found!"); } t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate")); t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult")); t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback")); t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase")); t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle")); t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState")); TypeDefinition type = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager"); t_ILManipulator = OutputModule.ImportReference((TypeReference)(object)module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator")); m_Object_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.Object").Resolve(), "System.Void .ctor()", true)); m_ObsoleteAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ObsoleteAttribute").Resolve(), "System.Void .ctor(System.String,System.Boolean)", true)); m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve(), "System.Void .ctor(System.ComponentModel.EditorBrowsableState)", true)); ModuleDefinition outputModule = OutputModule; MethodReference val = new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase); val.Parameters.Add(new ParameterDefinition(t_RuntimeMethodHandle)); m_GetMethodFromHandle = outputModule.ImportReference(val); m_Add = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Add", true)); m_Remove = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Remove", true)); m_Modify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Modify", true)); m_Unmodify = OutputModule.ImportReference((MethodReference)(object)Extensions.FindMethod(type, "Unmodify", true)); } public void Generate() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) Enumerator<TypeDefinition> enumerator = Modder.Module.Types.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeDefinition current = enumerator.Current; GenerateFor(current, out var hookType, out var hookILType); if (hookType != null && hookILType != null && !((TypeReference)hookType).IsNested) { OutputModule.Types.Add(hookType); OutputModule.Types.Add(hookILType); } } } finally { ((IDisposable)enumerator).Dispose(); } } public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown //IL_0141: 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_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) hookType = (hookILType = null); if (((TypeReference)type).HasGenericParameters || type.IsRuntimeSpecialName || ((MemberReference)type).Name.StartsWith("<") || (!HookPrivate && type.IsNotPublic)) { return; } Modder.LogVerbose("[HookGen] Generating for type " + ((MemberReference)type).FullName); hookType = new TypeDefinition(((TypeReference)type).IsNested ? null : (Namespace + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object); hookILType = new TypeDefinition(((TypeReference)type).IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(((TypeReference)type).Namespace) ? "" : ("." + ((TypeReference)type).Namespace))), ((MemberReference)type).Name, (TypeAttributes)(((!((TypeReference)type).IsNested) ? 1 : 2) | 0x80 | 0x100 | 0), OutputModule.TypeSystem.Object); bool flag = false; Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; flag |= GenerateFor(hookType, hookILType, current); } } finally { ((IDisposable)enumerator).Dispose(); } Enumerator<TypeDefinition> enumerator2 = type.NestedTypes.GetEnumerator(); try { while (enumerator2.MoveNext()) { TypeDefinition current2 = enumerator2.Current; GenerateFor(current2, out var hookType2, out var hookILType2); if (hookType2 != null && hookILType2 != null) { flag = true; hookType.NestedTypes.Add(hookType2); hookILType.NestedTypes.Add(hookILType2); } } } finally { ((IDisposable)enumerator2).Dispose(); } if (!flag) { hookType = (hookILType = null); } } public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method) { //IL_02fa: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Expected O, but got Unknown //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Expected O, but got Unknown //IL_0380: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Expected O, but got Unknown //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_039c: Expected O, but got Unknown //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Expected O, but got Unknown //IL_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03c4: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Expected O, but got Unknown //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_044a: Expected O, but got Unknown //IL_0455: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Expected O, but got Unknown //IL_0463: Unknown result type (might be due to invalid IL or missing references) //IL_046d: Expected O, but got Unknown //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_0487: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Unknown result type (might be due to invalid IL or missing references) //IL_04af: Expected O, but got Unknown //IL_04be: Unknown result type (might be due to invalid IL or missing references) //IL_04ca: Unknown result type (might be due to invalid IL or missing references) //IL_04ea: Unknown result type (might be due to invalid IL or missing references) //IL_04ef: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_0501: Expected O, but got Unknown //IL_0533: Unknown result type (might be due to invalid IL or missing references) //IL_053a: Expected O, but got Unknown //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_0553: Expected O, but got Unknown //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Expected O, but got Unknown //IL_056e: Unknown result type (might be due to invalid IL or missing references) //IL_057b: Unknown result type (might be due to invalid IL or missing references) //IL_058c: Unknown result type (might be due to invalid IL or missing references) //IL_059c: Unknown result type (might be due to invalid IL or missing references) //IL_05a3: Expected O, but got Unknown //IL_05b2: Unknown result type (might be due to invalid IL or missing references) //IL_05be: Unknown result type (might be due to invalid IL or missing references) //IL_05fa: Unknown result type (might be due to invalid IL or missing references) //IL_0601: Expected O, but got Unknown //IL_0610: Unknown result type (might be due to invalid IL or missing references) //IL_061a: Expected O, but got Unknown //IL_061e: Unknown result type (might be due to invalid IL or missing references) //IL_0628: Expected O, but got Unknown //IL_0635: Unknown result type (might be due to invalid IL or missing references) //IL_0642: Unknown result type (might be due to invalid IL or missing references) //IL_0653: Unknown result type (might be due to invalid IL or missing references) //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_066a: Expected O, but got Unknown //IL_0679: Unknown result type (might be due to invalid IL or missing references) //IL_0685: Unknown result type (might be due to invalid IL or missing references) //IL_06a9: Unknown result type (might be due to invalid IL or missing references) //IL_06ae: Unknown result type (might be due to invalid IL or missing references) //IL_06b6: Unknown result type (might be due to invalid IL or missing references) //IL_06c0: Expected O, but got Unknown if (((MethodReference)method).HasGenericParameters || method.IsAbstract || (method.IsSpecialName && !method.IsConstructor)) { return false; } if (!HookOrig && ((MemberReference)method).Name.StartsWith("orig_")) { return false; } if (!HookPrivate && method.IsPrivate) { return false; } string name = GetFriendlyName((MethodReference)(object)method); bool flag = true; if (((MethodReference)method).Parameters.Count == 0) { flag = false; } IEnumerable<MethodDefinition> source = null; if (flag) { source = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name && other != method); if (source.Count() == 0) { flag = false; } } if (flag) { StringBuilder stringBuilder = new StringBuilder(); for (int parami = 0; parami < ((MethodReference)method).Parameters.Count; parami++) { ParameterDefinition param = ((MethodReference)method).Parameters[parami]; if (!TypeNameMap.TryGetValue(((MemberReference)((ParameterReference)param).ParameterType).FullName, out var typeName)) { typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: false); } if (source.Any(delegate(MethodDefinition other) { ParameterDefinition val11 = ((IEnumerable<ParameterDefinition>)((MethodReference)other).Parameters).ElementAtOrDefault(parami); return val11 != null && GetFriendlyName(((ParameterReference)val11).ParameterType, full: false) == typeName && ((ParameterReference)val11).ParameterType.Namespace != ((ParameterReference)param).ParameterType.Namespace; })) { typeName = GetFriendlyName(((ParameterReference)param).ParameterType, full: true); } stringBuilder.Append("_"); stringBuilder.Append(typeName.Replace(".", "").Replace("`", "")); } name += stringBuilder.ToString(); } if (Extensions.FindEvent(hookType, name) != null) { int num = 1; string text; while (Extensions.FindEvent(hookType, text = name + "_" + num) != null) { num++; } name = text; } TypeDefinition val = GenerateDelegateFor(method); ((MemberReference)val).Name = "orig_" + name; val.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never)); hookType.NestedTypes.Add(val); TypeDefinition val2 = GenerateDelegateFor(method); ((MemberReference)val2).Name = "hook_" + name; ((MethodReference)Extensions.FindMethod(val2, "Invoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val)); ((MethodReference)Extensions.FindMethod(val2, "BeginInvoke", true)).Parameters.Insert(0, new ParameterDefinition("orig", (ParameterAttributes)0, (TypeReference)(object)val)); val2.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never)); hookType.NestedTypes.Add(val2); MethodReference val3 = OutputModule.ImportReference((MethodReference)(object)method); MethodDefinition val4 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val4).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2)); val4.Body = new MethodBody(val4); ILProcessor iLProcessor = val4.Body.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldtoken, val3); iLProcessor.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor.Emit(OpCodes.Ldarg_0); GenericInstanceMethod val5 = new GenericInstanceMethod(m_Add); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor.Emit(OpCodes.Ret); hookType.Methods.Add(val4); MethodDefinition val6 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val6).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, (TypeReference)(object)val2)); val6.Body = new MethodBody(val6); ILProcessor iLProcessor2 = val6.Body.GetILProcessor(); iLProcessor2.Emit(OpCodes.Ldtoken, val3); iLProcessor2.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor2.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Remove); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor2.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor2.Emit(OpCodes.Ret); hookType.Methods.Add(val6); EventDefinition val7 = new EventDefinition(name, (EventAttributes)0, (TypeReference)(object)val2) { AddMethod = val4, RemoveMethod = val6 }; hookType.Events.Add(val7); MethodDefinition val8 = new MethodDefinition("add_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val8).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator)); val8.Body = new MethodBody(val8); ILProcessor iLProcessor3 = val8.Body.GetILProcessor(); iLProcessor3.Emit(OpCodes.Ldtoken, val3); iLProcessor3.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor3.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Modify); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor3.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor3.Emit(OpCodes.Ret); hookILType.Methods.Add(val8); MethodDefinition val9 = new MethodDefinition("remove_" + name, (MethodAttributes)2198, OutputModule.TypeSystem.Void); ((MethodReference)val9).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, t_ILManipulator)); val9.Body = new MethodBody(val9); ILProcessor iLProcessor4 = val9.Body.GetILProcessor(); iLProcessor4.Emit(OpCodes.Ldtoken, val3); iLProcessor4.Emit(OpCodes.Call, m_GetMethodFromHandle); iLProcessor4.Emit(OpCodes.Ldarg_0); val5 = new GenericInstanceMethod(m_Unmodify); val5.GenericArguments.Add((TypeReference)(object)val2); iLProcessor4.Emit(OpCodes.Call, (MethodReference)(object)val5); iLProcessor4.Emit(OpCodes.Ret); hookILType.Methods.Add(val9); EventDefinition val10 = new EventDefinition(name, (EventAttributes)0, t_ILManipulator) { AddMethod = val8, RemoveMethod = val9 }; hookILType.Events.Add(val10); return true; } public TypeDefinition GenerateDelegateFor(MethodDefinition method) { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Expected O, but got Unknown //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0174: 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_0184: Expected O, but got Unknown //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Expected O, but got Unknown //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Expected O, but got Unknown //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Expected O, but got Unknown //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Expected O, but got Unknown //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Expected O, but got Unknown //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Expected O, but got Unknown //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Expected O, but got Unknown //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Expected O, but got Unknown //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0344: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_0354: Expected O, but got Unknown //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Expected O, but got Unknown //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_037f: Expected O, but got Unknown string name = GetFriendlyName((MethodReference)(object)method); int num = ((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Where((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name).ToList().IndexOf(method); if (num != 0) { string suffix = num.ToString(); do { name = name + "_" + suffix; } while (((IEnumerable<MethodDefinition>)method.DeclaringType.Methods).Any((MethodDefinition other) => !((MethodReference)other).HasGenericParameters && GetFriendlyName((MethodReference)(object)other) == name + suffix)); } name = "d_" + name; TypeDefinition val = new TypeDefinition((string)null, (string)null, (TypeAttributes)258, t_MulticastDelegate); MethodDefinition val2 = new MethodDefinition(".ctor", (MethodAttributes)6278, OutputModule.TypeSystem.Void) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; ((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object)); ((MethodReference)val2).Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr)); val2.Body = new MethodBody(val2); val.Methods.Add(val2); MethodDefinition val3 = new MethodDefinition("Invoke", (MethodAttributes)454, ImportVisible(((MethodReference)method).ReturnType)) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; if (!method.IsStatic) { TypeReference val4 = ImportVisible((TypeReference)(object)method.DeclaringType); if (((TypeReference)method.DeclaringType).IsValueType) { val4 = (TypeReference)new ByReferenceType(val4); } ((MethodReference)val3).Parameters.Add(new ParameterDefinition("self", (ParameterAttributes)0, val4)); } Enumerator<ParameterDefinition> enumerator = ((MethodReference)method).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current = enumerator.Current; ((MethodReference)val3).Parameters.Add(new ParameterDefinition(((ParameterReference)current).Name, (ParameterAttributes)(current.Attributes & 0xFFEF & 0xEFFF), ImportVisible(((ParameterReference)current).ParameterType))); } } finally { ((IDisposable)enumerator).Dispose(); } val3.Body = new MethodBody(val3); val.Methods.Add(val3); MethodDefinition val5 = new MethodDefinition("BeginInvoke", (MethodAttributes)454, t_IAsyncResult) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; enumerator = ((MethodReference)val3).Parameters.GetEnumerator(); try { while (enumerator.MoveNext()) { ParameterDefinition current2 = enumerator.Current; ((MethodReference)val5).Parameters.Add(new ParameterDefinition(((ParameterReference)current2).Name, current2.Attributes, ((ParameterReference)current2).ParameterType)); } } finally { ((IDisposable)enumerator).Dispose(); } ((MethodReference)val5).Parameters.Add(new ParameterDefinition("callback", (ParameterAttributes)0, t_AsyncCallback)); ((MethodReference)val5).Parameters.Add(new ParameterDefinition((string)null, (ParameterAttributes)0, OutputModule.TypeSystem.Object)); val5.Body = new MethodBody(val5); val.Methods.Add(val5); MethodDefinition val6 = new MethodDefinition("EndInvoke", (MethodAttributes)454, OutputModule.TypeSystem.Object) { ImplAttributes = (MethodImplAttributes)3, HasThis = true }; ((MethodReference)val6).Parameters.Add(new ParameterDefinition("result", (ParameterAttributes)0, t_IAsyncResult)); val6.Body = new MethodBody(val6); val.Methods.Add(val6); return val; } private string GetFriendlyName(MethodReference method) { string text = ((MemberReference)method).Name; if (text.StartsWith(".")) { text = text.Substring(1); } return text.Replace('.', '_'); } private string GetFriendlyName(TypeReference type, bool full) { if (type is TypeSpecification) { StringBuilder stringBuilder = new StringBuilder(); BuildFriendlyName(stringBuilder, type, full); return stringBuilder.ToString(); } if (!full) { return ((MemberReference)type).Name; } return ((MemberReference)type).FullName; } private void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) if (!(type is TypeSpecification)) { builder.Append((full ? ((MemberReference)type).FullName : ((MemberReference)type).Name).Replace("_", "")); return; } if (type.IsByReference) { builder.Append("ref"); } else if (type.IsPointer) { builder.Append("ptr"); } BuildFriendlyName(builder, ((TypeSpecification)type).ElementType, full); if (type.IsArray) { builder.Append("Array"); } } private bool IsPublic(TypeDefinition typeDef) { if (typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic)) { return !typeDef.IsNotPublic; } return false; } private bool HasPublicArgs(GenericInstanceType typeGen) { //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) Enumerator<TypeReference> enumerator = typeGen.GenericArguments.GetEnumerator(); try { while (enumerator.MoveNext()) { TypeReference current = enumerator.Current; if (current.IsGenericParameter) { return false; } GenericInstanceType val = (GenericInstanceType)(object)((current is GenericInstanceType) ? current : null); if (val != null && !HasPublicArgs(val)) { return false; } if (!IsPublic(Extensions.SafeResolve(current))) { return false; } } } finally { ((IDisposable)enumerator).Dispose(); } return true; } private TypeReference ImportVisible(TypeReference typeRef) { for (TypeDefinition val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null); val != null; val = ((typeRef != null) ? Extensions.SafeResolve(typeRef) : null)) { GenericInstanceType val2 = (GenericInstanceType)(object)((typeRef is GenericInstanceType) ? typeRef : null); if (val2 == null || HasPublicArgs(val2)) { TypeDefinition val3 = val; while (true) { if (val3 != null) { if (IsPublic(val3) && (val3 == val || !((TypeReference)val3).HasGenericParameters)) { val3 = val3.DeclaringType; continue; } if (!val.IsEnum) { break; } typeRef = ((FieldReference)Extensions.FindField(val, "value__")).FieldType; } try { return OutputModule.ImportReference(typeRef); } catch { return OutputModule.TypeSystem.Object; } } } typeRef = val.BaseType; } return OutputModule.TypeSystem.Object; } private CustomAttribute GenerateObsolete(string message, bool error) { //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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown CustomAttribute val = new CustomAttribute(m_ObsoleteAttribute_ctor); val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, (object)message)); val.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, (object)error)); return val; } private CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state) { //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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown CustomAttribute val = new CustomAttribute(m_EditorBrowsableAttribute_ctor); val.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, (object)state)); return val; } } internal class Program { private static void Main(string[] args) { //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Expected O, but got Unknown Console.WriteLine("MonoMod.RuntimeDetour.HookGen " + typeof(Program).Assembly.GetName().Version); Console.WriteLine("using MonoMod " + typeof(MonoModder).Assembly.GetName().Version); Console.WriteLine("using MonoMod.RuntimeDetour " + typeof(Detour).Assembly.GetName().Version); if (args.Length == 0) { Console.WriteLine("No valid arguments (assembly path) passed."); if (Debugger.IsAttached) { Console.ReadKey(); } return; } int num = 0; for (int i = 0; i < args.Length; i++) { if (args[i] == "--namespace" && i + 2 < args.Length) { i++; Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE", args[i]); continue; } if (args[i] == "--namespace-il" && i + 2 < args.Length) { i++; Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL", args[i]); continue; } if (args[i] == "--orig") { Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG", "1"); continue; } if (args[i] == "--private") { Environment.SetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE", "1"); continue; } num = i; break; } if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW"))) { Environment.SetEnvironmentVariable("MONOMOD_DEPENDENCY_MISSING_THROW", "0"); } if (num >= args.Length) { Console.WriteLine("No assembly path passed."); if (Debugger.IsAttached) { Console.ReadKey(); } return; } string text = args[num]; string text2 = ((args.Length != 1 && num != args.Length - 1) ? args[^1] : null); text2 = text2 ?? Path.Combine(Path.GetDirectoryName(text), "MMHOOK_" + Path.ChangeExtension(Path.GetFileName(text), "dll")); MonoModder val = new MonoModder { InputPath = text, OutputPath = text2, ReadingMode = (ReadingMode)2 }; try { val.Read(); val.MapDependencies(); if (File.Exists(text2)) { val.Log("[HookGen] Clearing " + text2); File.Delete(text2); } val.Log("[HookGen] Starting HookGenerator"); HookGenerator hookGenerator = new HookGenerator(val, Path.GetFileName(text2)); ModuleDefinition outputModule = hookGenerator.OutputModule; try { hookGenerator.Generate(); outputModule.Write(text2); } finally { ((IDisposable)outputModule)?.Dispose(); } val.Log("[HookGen] Done."); } finally { ((IDisposable)val)?.Dispose(); } if (Debugger.IsAttached) { Console.ReadKey(); } } } }
BepInEx/plugins/PushCompany.dll
Decompiled a year agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using PushCompany.Assets.Scripts; using PushCompany.Properties; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("PushCompany")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Push your fellow crewmates with the interaction key! (E by default)")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: AssemblyInformationalVersion("1.2.0")] [assembly: AssemblyProduct("PushCompany")] [assembly: AssemblyTitle("PushCompany")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 PushCompany { [BepInPlugin("PushCompany", "PushCompany", "1.2.0")] public class PushCompanyBase : BaseUnityPlugin { public static readonly Lazy<PushCompanyBase> Instance = new Lazy<PushCompanyBase>(() => new PushCompanyBase()); public static GameObject pushPrefab; public ManualLogSource mls; private readonly Harmony harmony = new Harmony("PushCompany"); public static ConfigEntry<float> config_PushCooldown; public static ConfigEntry<float> config_PushForce; public static ConfigEntry<float> config_PushRange; public static ConfigEntry<float> config_PushCost; private void Awake() { mls = Logger.CreateLogSource("PushCompany"); ConfigSetup(); LoadBundle(); harmony.PatchAll(typeof(PushCompanyBase)); harmony.PatchAll(typeof(PlayerControllerB_Patches)); harmony.PatchAll(typeof(NetworkHandler)); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } mls.LogInfo((object)"PushCompany has initialized!"); } private void ConfigSetup() { config_PushCooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Push Cooldown", "Value", 0.025f, "How long until the player can push again"); config_PushForce = ((BaseUnityPlugin)this).Config.Bind<float>("Push Force", "Value", 12.5f, "How strong the player pushes."); config_PushRange = ((BaseUnityPlugin)this).Config.Bind<float>("Push Range", "Value", 3f, "The distance the player is able to push."); config_PushCost = ((BaseUnityPlugin)this).Config.Bind<float>("Push Cost", "Value", 0.08f, "The energy cost of each push."); } private void LoadBundle() { AssetBundle val = AssetBundle.LoadFromMemory(Resources.pushcompany); if ((Object)(object)val == (Object)null) { throw new Exception("Failed to load Push Bundle!"); } pushPrefab = val.LoadAsset<GameObject>("Assets/Push.prefab"); if ((Object)(object)pushPrefab == (Object)null) { throw new Exception("Failed to load Push Prefab!"); } pushPrefab.AddComponent<PushComponent>(); } } public static class PluginInfo { public const string PLUGIN_GUID = "PushCompany"; public const string PLUGIN_NAME = "PushCompany"; public const string PLUGIN_VERSION = "1.2.0"; } } namespace PushCompany.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { ResourceManager resourceManager = new ResourceManager("PushCompany.Properties.Resources", typeof(Resources).Assembly); resourceMan = resourceManager; } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] AssetBundles { get { object @object = ResourceManager.GetObject("AssetBundles", resourceCulture); return (byte[])@object; } } internal static byte[] AssetBundles_manifest { get { object @object = ResourceManager.GetObject("AssetBundles.manifest", resourceCulture); return (byte[])@object; } } internal static byte[] AssetBundles1 { get { object @object = ResourceManager.GetObject("AssetBundles1", resourceCulture); return (byte[])@object; } } internal static byte[] AssetBundles2 { get { object @object = ResourceManager.GetObject("AssetBundles2", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany { get { object @object = ResourceManager.GetObject("pushcompany", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany_push { get { object @object = ResourceManager.GetObject("pushcompany.push", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany_push_manifest { get { object @object = ResourceManager.GetObject("pushcompany.push.manifest", resourceCulture); return (byte[])@object; } } internal static byte[] pushcompany_push1 { get { object @object = ResourceManager.GetObject("pushcompany.push1", resourceCulture); return (byte[])@object; } } internal Resources() { } } } namespace PushCompany.Assets.Scripts { [HarmonyPatch] public class NetworkHandler { private static GameObject pushObject; [HarmonyPrefix] [HarmonyPatch(typeof(GameNetworkManager), "Start")] private static void Init() { NetworkManager.Singleton.AddNetworkPrefab(PushCompanyBase.pushPrefab); } [HarmonyPostfix] [HarmonyPatch(typeof(StartOfRound), "Awake")] private static void SpawnNetworkPrefab() { try { if (NetworkManager.Singleton.IsServer) { pushObject = Object.Instantiate<GameObject>(PushCompanyBase.pushPrefab); pushObject.GetComponent<NetworkObject>().Spawn(true); } } catch { PushCompanyBase.Instance.Value.mls.LogError((object)"Failed to instantiate network prefab!"); } } } [HarmonyPatch(typeof(PlayerControllerB))] public static class PlayerControllerB_Patches { private static PushComponent pushComponent; [HarmonyPostfix] [HarmonyPatch(typeof(PlayerControllerB), "Update")] private static void Update(PlayerControllerB __instance) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)__instance).IsOwner) { return; } MovementActions movement = __instance.playerActions.Movement; if (((MovementActions)(ref movement)).Interact.WasPressedThisFrame()) { if ((Object)(object)pushComponent == (Object)null) { pushComponent = Object.FindObjectOfType<PushComponent>(); } if ((Object)(object)pushComponent != (Object)null) { pushComponent.PushServerRpc(((NetworkBehaviour)__instance).NetworkObjectId); } } } } public class PushComponent : NetworkBehaviour { private Dictionary<ulong, float> lastPushTimes = new Dictionary<ulong, float>(); private NetworkVariable<float> PushCooldown = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private NetworkVariable<float> PushRange = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private NetworkVariable<float> PushForce = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private NetworkVariable<float> PushCost = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public override void OnNetworkSpawn() { if (((NetworkBehaviour)this).IsServer) { PushCooldown.Value = PushCompanyBase.config_PushCooldown.Value; PushRange.Value = PushCompanyBase.config_PushRange.Value; PushForce.Value = PushCompanyBase.config_PushForce.Value; PushCost.Value = PushCompanyBase.config_PushCost.Value; } } [ServerRpc(RequireOwnership = false)] public void PushServerRpc(ulong playerId) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0167: 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_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(2433198804u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 2433198804u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } if (lastPushTimes.TryGetValue(playerId, out var value)) { if (Time.time - value < PushCooldown.Value) { return; } } else { lastPushTimes.Add(playerId, 0f); } GameObject playerById = GetPlayerById(playerId); PlayerControllerB component = playerById.GetComponent<PlayerControllerB>(); Camera gameplayCamera = component.gameplayCamera; if (!CanPushPlayer(component)) { return; } int num = 1 << playerById.layer; Vector3 forward = ((Component)gameplayCamera).transform.forward; Vector3 normalized = ((Vector3)(ref forward)).normalized; RaycastHit[] array = Physics.RaycastAll(((Component)gameplayCamera).transform.position, normalized, PushRange.Value, num); RaycastHit[] array2 = array; for (int i = 0; i < array2.Length; i++) { RaycastHit val3 = array2[i]; if ((Object)(object)((Component)((RaycastHit)(ref val3)).transform).gameObject != (Object)(object)playerById) { PlayerControllerB component2 = ((Component)((RaycastHit)(ref val3)).transform).GetComponent<PlayerControllerB>(); if (!component2.inSpecialInteractAnimation) { PushClientRpc(((NetworkBehaviour)component).NetworkObjectId, ((NetworkBehaviour)component2).NetworkObjectId, normalized * PushForce.Value * Time.fixedDeltaTime); lastPushTimes[playerId] = Time.time; } break; } } } [ClientRpc] private void PushClientRpc(ulong pusherId, ulong playerId, Vector3 push) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Invalid comparison between Unknown and I4 //IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3498116674u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, pusherId); BytePacker.WriteValueBitPacked(val2, playerId); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref push); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3498116674u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { GameObject playerById = GetPlayerById(playerId); PlayerControllerB component = playerById.GetComponent<PlayerControllerB>(); ((MonoBehaviour)this).StartCoroutine(SmoothMove(component.thisController, push)); component.movementAudio.PlayOneShot(StartOfRound.Instance.playerJumpSFX); GameObject playerById2 = GetPlayerById(pusherId); PlayerControllerB component2 = playerById2.GetComponent<PlayerControllerB>(); component2.sprintMeter = Mathf.Clamp(component2.sprintMeter - PushCost.Value, 0f, 1f); } } } public IEnumerator SmoothMove(CharacterController controller, Vector3 push) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) float force = PushForce.Value / 12.5f; float smoothTime = ((Vector3)(ref push)).magnitude / force; Vector3 targetPosition = ((Component)controller).transform.position + push; Vector3 val = targetPosition - ((Component)controller).transform.position; Vector3 direction = ((Vector3)(ref val)).normalized; float distance = Vector3.Distance(((Component)controller).transform.position, targetPosition); for (float currentTime = 0f; currentTime < smoothTime; currentTime += Time.fixedDeltaTime) { float currentDistance = distance * Mathf.Min(currentTime, smoothTime) / smoothTime; controller.Move(direction * currentDistance); yield return null; } } private bool CanPushPlayer(PlayerControllerB player) { return !player.quickMenuManager.isMenuOpen && !player.inSpecialInteractAnimation && !player.isTypingChat && !player.isExhausted; } private static GameObject GetPlayerById(ulong playerId) { if (NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(playerId, out var value)) { return ((Component)value).gameObject; } return null; } protected override void __initializeVariables() { if (PushCooldown == null) { throw new Exception("PushComponent.PushCooldown cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushCooldown).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushCooldown, "PushCooldown"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushCooldown); if (PushRange == null) { throw new Exception("PushComponent.PushRange cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushRange).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushRange, "PushRange"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushRange); if (PushForce == null) { throw new Exception("PushComponent.PushForce cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushForce).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushForce, "PushForce"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushForce); if (PushCost == null) { throw new Exception("PushComponent.PushCost cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)PushCost).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)PushCost, "PushCost"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)PushCost); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_PushComponent() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(2433198804u, new RpcReceiveHandler(__rpc_handler_2433198804)); NetworkManager.__rpc_func_table.Add(3498116674u, new RpcReceiveHandler(__rpc_handler_3498116674)); } private static void __rpc_handler_2433198804(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong playerId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); target.__rpc_exec_stage = (__RpcExecStage)1; ((PushComponent)(object)target).PushServerRpc(playerId); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3498116674(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0050: 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_0072: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ulong pusherId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref pusherId); ulong playerId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); Vector3 push = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref push); target.__rpc_exec_stage = (__RpcExecStage)2; ((PushComponent)(object)target).PushClientRpc(pusherId, playerId, push); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "PushComponent"; } } }
BepInEx/plugins/QuickRestart.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("QuickRestart")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("My first plugin")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+a395cfe8aac0ee2687d75817f75fae451f729511")] [assembly: AssemblyProduct("QuickRestart")] [assembly: AssemblyTitle("QuickRestart")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 QuickRestart { [BepInPlugin("QuickRestart", "QuickRestart", "1.0.0")] public class Plugin : BaseUnityPlugin { public static bool verifying; private ConfigEntry<bool> overrideConfirmation; public static bool bypassConfirm; private Harmony harmony; private static MethodInfo chat; private void Awake() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown overrideConfirmation = ((BaseUnityPlugin)this).Config.Bind<bool>("Config", "Override Confirmation", false, "Ignore the confirmation step of restarting."); bypassConfirm = overrideConfirmation.Value; harmony = new Harmony("QuickRestart"); harmony.PatchAll(); chat = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); ((BaseUnityPlugin)this).Logger.LogInfo((object)"QuickRestart loaded!"); } public static void SendChatMessage(string message) { chat?.Invoke(HUDManager.Instance, new object[2] { message, "" }); HUDManager.Instance.lastChatMessage = ""; } public static void ConfirmRestart() { verifying = true; SendChatMessage("Are you sure? Type CONFIRM or DENY."); } public static void AcceptRestart(StartOfRound manager) { SendChatMessage("Restart confirmed."); verifying = false; int[] array = new int[4] { manager.gameStats.daysSpent, manager.gameStats.scrapValueCollected, manager.gameStats.deaths, manager.gameStats.allStepsTaken }; manager.FirePlayersAfterDeadlineClientRpc(array, false); } public static void DeclineRestart() { SendChatMessage("Restart aborted."); verifying = false; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "QuickRestart"; public const string PLUGIN_NAME = "QuickRestart"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace QuickRestart.Patches { [HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")] public class SubmitChat { private static bool Prefix(HUDManager __instance, ref CallbackContext context) { if (!((CallbackContext)(ref context)).performed) { return true; } if (string.IsNullOrEmpty(__instance.chatTextField.text)) { return true; } PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if ((Object)(object)localPlayerController == (Object)null) { return true; } StartOfRound playersManager = localPlayerController.playersManager; if ((Object)(object)playersManager == (Object)null) { return true; } string text = __instance.chatTextField.text; if (Plugin.verifying) { if (text.ToLower() == "confirm") { ResetTextbox(__instance, localPlayerController); if (!localPlayerController.isInHangarShipRoom || !playersManager.inShipPhase || playersManager.travellingToNewLevel) { Plugin.SendChatMessage("Cannot restart, ship must be in orbit."); return false; } Plugin.AcceptRestart(playersManager); return false; } if (text.ToLower() == "deny") { ResetTextbox(__instance, localPlayerController); Plugin.DeclineRestart(); return false; } return true; } if (text == "/restart") { ResetTextbox(__instance, localPlayerController); if (!GameNetworkManager.Instance.isHostingGame) { Plugin.SendChatMessage("Only the host can restart."); return false; } if (!localPlayerController.isInHangarShipRoom || !playersManager.inShipPhase || playersManager.travellingToNewLevel) { Plugin.SendChatMessage("Cannot restart, ship must be in orbit."); return false; } if (Plugin.bypassConfirm) { Plugin.AcceptRestart(playersManager); } else { Plugin.ConfirmRestart(); } return false; } return true; } private static void ResetTextbox(HUDManager manager, PlayerControllerB local) { local.isTypingChat = false; manager.chatTextField.text = ""; EventSystem.current.SetSelectedGameObject((GameObject)null); manager.PingHUDElement(manager.Chat, 2f, 1f, 0.2f); ((Behaviour)manager.typingIndicator).enabled = false; } } }
BepInEx/plugins/ShipClock.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("ShipClock")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ShipClock")] [assembly: AssemblyTitle("ShipClock")] [assembly: AssemblyVersion("1.0.0.0")] 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; } } } namespace ShipClock { [BepInPlugin("atk.lethalcompany.shipclock", "Ship Clock", "0.9.0")] public class Main : BaseUnityPlugin { private const string PluginGuid = "atk.lethalcompany.shipclock"; private const string PluginName = "Ship Clock"; private const string PluginVersion = "0.9.0"; public void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown Harmony val = new Harmony("atk.lethalcompany.shipclock"); val.PatchAll(typeof(Patches)); } } [HarmonyPatch] internal class Patches { [HarmonyPatch(typeof(TimeOfDay), "SetInsideLightingDimness")] [HarmonyPostfix] public static void SetInsideLightingDimness() { if ((Object)(object)GameNetworkManager.Instance != (Object)null && !GameNetworkManager.Instance.localPlayerController.isPlayerDead) { HUDManager.Instance.SetClockVisible(!GameNetworkManager.Instance.localPlayerController.isInsideFactory); } } } }
BepInEx/plugins/ShipLoot.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using TMPro; using UnityEngine; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ShipLoot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("ShipLoot")] [assembly: AssemblyCopyright("Copyright © tinyhoot 2023")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("1.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace ShipLoot { [BepInPlugin("com.github.tinyhoot.ShipLoot", "ShipLoot", "1.0")] internal class ShipLoot : BaseUnityPlugin { public const string GUID = "com.github.tinyhoot.ShipLoot"; public const string NAME = "ShipLoot"; public const string VERSION = "1.0"; internal static ManualLogSource Log; private void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; new Harmony("com.github.tinyhoot.ShipLoot").PatchAll(Assembly.GetExecutingAssembly()); } } } namespace ShipLoot.Patches { [HarmonyPatch] internal class HudManagerPatcher { private static GameObject _totalCounter; private static TextMeshProUGUI _textMesh; private static float _displayTimeLeft; private const float DisplayTime = 5f; [HarmonyPrefix] [HarmonyPatch(typeof(HUDManager), "PingScan_performed")] private static void OnScan(HUDManager __instance, CallbackContext context) { if (!((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null) && ((CallbackContext)(ref context)).performed && __instance.CanPlayerScan() && !(__instance.playerPingingScan > -0.5f) && (StartOfRound.Instance.inShipPhase || GameNetworkManager.Instance.localPlayerController.isInHangarShipRoom)) { if (!Object.op_Implicit((Object)(object)_totalCounter)) { CopyValueCounter(); } float num = CalculateLootValue(); ((TMP_Text)_textMesh).text = $"SHIP: ${num:F0}"; _displayTimeLeft = 5f; if (!_totalCounter.activeSelf) { ((MonoBehaviour)GameNetworkManager.Instance).StartCoroutine(ShipLootCoroutine()); } } } private static IEnumerator ShipLootCoroutine() { _totalCounter.SetActive(true); while (_displayTimeLeft > 0f) { float displayTimeLeft = _displayTimeLeft; _displayTimeLeft = 0f; yield return (object)new WaitForSeconds(displayTimeLeft); } _totalCounter.SetActive(false); } private static float CalculateLootValue() { List<GrabbableObject> list = (from obj in GameObject.Find("/Environment/HangarShip").GetComponentsInChildren<GrabbableObject>() where ((Object)obj).name != "ClipboardManual" && ((Object)obj).name != "StickyNoteItem" select obj).ToList(); ShipLoot.Log.LogDebug((object)"Calculating total ship scrap value."); CollectionExtensions.Do<GrabbableObject>((IEnumerable<GrabbableObject>)list, (Action<GrabbableObject>)delegate(GrabbableObject scrap) { ShipLoot.Log.LogDebug((object)$"{((Object)scrap).name} - ${scrap.scrapValue}"); }); return list.Sum((GrabbableObject scrap) => scrap.scrapValue); } private static void CopyValueCounter() { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0076: 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) //IL_008d: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("/Systems/UI/Canvas/IngamePlayerHUD/BottomMiddle/ValueCounter"); if (!Object.op_Implicit((Object)(object)val)) { ShipLoot.Log.LogError((object)"Failed to find ValueCounter object to copy!"); } _totalCounter = Object.Instantiate<GameObject>(val.gameObject, val.transform.parent, false); _totalCounter.transform.Translate(0f, 1f, 0f); Vector3 localPosition = _totalCounter.transform.localPosition; _totalCounter.transform.localPosition = new Vector3(localPosition.x + 50f, -50f, localPosition.z); _textMesh = _totalCounter.GetComponentInChildren<TextMeshProUGUI>(); } } }
BepInEx/plugins/SignalTranslatorUpgrade.dll
Decompiled a year agousing System; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("SignalTranslatorUpgrade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Fit more characters into transmissions!")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+7da60c7d33bc262e861d680200695ce99d57357b")] [assembly: AssemblyProduct("SignalTranslatorUpgrade")] [assembly: AssemblyTitle("SignalTranslatorUpgrade")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 SignalTranslatorUpgrade { [BepInPlugin("Fredolx.SignalTranslatorUpgrade", "SignalTranslatorUpgrade", "1.0.0")] public class Plugin : BaseUnityPlugin { public static ManualLogSource Logger; public static string TransmitMessage { get; set; } public static string ClientMessage { get; set; } public static ConfigEntry<int> MaxCharacters { get; set; } private void Awake() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (Logger == null) { Logger = ((BaseUnityPlugin)this).Logger; } Logger.LogInfo((object)"Plugin SignalTranslatorUpgrade is loaded!"); MaxCharacters = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxMessageLength", 30, "The maximum of characters that should be displayed on the screen when transmitting messages"); new Harmony("SignalTranslatorUpgrade").PatchAll(); } } public static class PluginInfo { public const string PLUGIN_GUID = "SignalTranslatorUpgrade"; public const string PLUGIN_NAME = "SignalTranslatorUpgrade"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace SignalTranslatorUpgrade.Patches { [HarmonyPatch(typeof(HUDManager), "UseSignalTranslatorServerRpc")] public class UseSignalTranslatorServerRpc { private static void Postfix(HUDManager __instance, string signalMessage) { if (signalMessage.Length > 12) { SignalTranslator val = Object.FindObjectOfType<SignalTranslator>(); if (!(Time.realtimeSinceStartup - val.timeLastUsingSignalTranslator < 8f)) { val.timeLastUsingSignalTranslator = Time.realtimeSinceStartup; val.timesSendingMessage++; __instance.UseSignalTranslatorClientRpc(signalMessage, val.timesSendingMessage); Plugin.Logger.LogInfo((object)("ServerRPC Postfix: " + signalMessage)); } } } private static void Prefix(ref string signalMessage, HUDManager __instance) { if (Plugin.TransmitMessage != null) { signalMessage = Plugin.TransmitMessage; Plugin.Logger.LogInfo((object)("ServerRPC Prefix: " + signalMessage)); Plugin.TransmitMessage = null; } } } [HarmonyPatch(typeof(HUDManager), "UseSignalTranslatorClientRpc")] public class UseSignalTranslatorClientRpc { private static void Prefix(string signalMessage) { Plugin.Logger.LogInfo((object)("Client RPC Prefix: " + signalMessage)); Plugin.ClientMessage = signalMessage; } } [HarmonyPatch(typeof(HUDManager), "DisplaySignalTranslatorMessage")] public class DisplaySignalTranslatorMessage { private static void Prefix(ref string signalMessage) { signalMessage = ((Plugin.ClientMessage.Length < Plugin.MaxCharacters.Value) ? Plugin.ClientMessage : Plugin.ClientMessage.Substring(0, Plugin.MaxCharacters.Value)); Plugin.Logger.LogInfo((object)("Display: " + signalMessage)); Plugin.ClientMessage = null; } } [HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")] public class ParsePlayerSentence { private static bool Prefix(Terminal __instance) { string text = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded); text = Traverse.Create((object)__instance).Method("RemovePunctuation", new object[1] { text }).GetValue<string>(); string[] array = text.Split(" "); if (array[0] != "transmit") { return true; } Plugin.TransmitMessage = string.Join(" ", array.Skip(1)); return true; } } }
BepInEx/plugins/SkinwalkerMod.dll
Decompiled a year agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dissonance.Config; using HarmonyLib; using Unity.Netcode; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("SkinwalkerMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SkinwalkerMod")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("fd4979a2-cef0-46af-8bf8-97e630b11475")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<float>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<float>(); } } namespace SkinwalkerMod; [BepInPlugin("RugbugRedfern.SkinwalkerMod", "Skinwalker Mod", "1.0.8")] internal class PluginLoader : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod"); private const string modGUID = "RugbugRedfern.SkinwalkerMod"; private const string modVersion = "1.0.8"; private static bool initialized; public static PluginLoader Instance { get; private set; } private void Awake() { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown if (initialized) { return; } initialized = true; Instance = this; harmony.PatchAll(Assembly.GetExecutingAssembly()); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); Type[] array = types; foreach (Type type in array) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic); MethodInfo[] array2 = methods; foreach (MethodInfo methodInfo in array2) { object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false); if (customAttributes.Length != 0) { methodInfo.Invoke(null, null); } } } SkinwalkerLogger.Initialize("RugbugRedfern.SkinwalkerMod"); SkinwalkerLogger.Log("SKINWALKER MOD STARTING UP 1.0.8"); SkinwalkerConfig.InitConfig(); SceneManager.sceneLoaded += SkinwalkerNetworkManagerHandler.ClientConnectInitializer; GameObject val = new GameObject("Skinwalker Mod"); val.AddComponent<SkinwalkerModPersistent>(); ((Object)val).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val); } public void BindConfig<T>(ref ConfigEntry<T> config, string section, string key, T defaultValue, string description = "") { config = ((BaseUnityPlugin)this).Config.Bind<T>(section, key, defaultValue, description); } } internal class SkinwalkerBehaviour : MonoBehaviour { private AudioSource audioSource; public const float PLAY_INTERVAL_MIN = 15f; public const float PLAY_INTERVAL_MAX = 40f; private const float MAX_DIST = 100f; private float nextTimeToPlayAudio; private EnemyAI ai; public void Initialize(EnemyAI ai) { this.ai = ai; audioSource = ai.creatureVoice; SetNextTime(); } private void Update() { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) if (!(Time.time > nextTimeToPlayAudio)) { return; } SetNextTime(); float num = -1f; if (Object.op_Implicit((Object)(object)ai) && !ai.isEnemyDead) { if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || (num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)this).transform.position)) < 100f) { AudioClip sample = SkinwalkerModPersistent.Instance.GetSample(); if (Object.op_Implicit((Object)(object)sample)) { SkinwalkerLogger.Log(((Object)this).name + " played voice line 1"); audioSource.PlayOneShot(sample); } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line 0"); } } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (too far away) " + num); } } else { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (dead) EnemyAI: " + (object)ai); } } private void SetNextTime() { if (SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value <= 0f) { nextTimeToPlayAudio = Time.time + 100000000f; } else { nextTimeToPlayAudio = Time.time + Random.Range(15f, 40f) / SkinwalkerNetworkManager.Instance.VoiceLineFrequency.Value; } } private T CopyComponent<T>(T original, GameObject destination) where T : Component { Type type = ((object)original).GetType(); Component val = destination.AddComponent(type); FieldInfo[] fields = type.GetFields(); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { fieldInfo.SetValue(val, fieldInfo.GetValue(original)); } return (T)(object)((val is T) ? val : null); } } internal class SkinwalkerConfig { public static ConfigEntry<bool> VoiceEnabled_BaboonHawk; public static ConfigEntry<bool> VoiceEnabled_Bracken; public static ConfigEntry<bool> VoiceEnabled_BunkerSpider; public static ConfigEntry<bool> VoiceEnabled_Centipede; public static ConfigEntry<bool> VoiceEnabled_CoilHead; public static ConfigEntry<bool> VoiceEnabled_EyelessDog; public static ConfigEntry<bool> VoiceEnabled_ForestGiant; public static ConfigEntry<bool> VoiceEnabled_GhostGirl; public static ConfigEntry<bool> VoiceEnabled_GiantWorm; public static ConfigEntry<bool> VoiceEnabled_HoardingBug; public static ConfigEntry<bool> VoiceEnabled_Hygrodere; public static ConfigEntry<bool> VoiceEnabled_Jester; public static ConfigEntry<bool> VoiceEnabled_Masked; public static ConfigEntry<bool> VoiceEnabled_Nutcracker; public static ConfigEntry<bool> VoiceEnabled_SporeLizard; public static ConfigEntry<bool> VoiceEnabled_Thumper; public static ConfigEntry<float> VoiceLineFrequency; public static void InitConfig() { PluginLoader.Instance.BindConfig(ref VoiceLineFrequency, "Voice Settings", "VoiceLineFrequency", 1f, "1 is the default, and voice lines will occur every " + 15f.ToString("0") + " to " + 40f.ToString("0") + " seconds per enemy. Setting this to 2 means they will occur twice as often, 0.5 means half as often, etc."); PluginLoader.Instance.BindConfig(ref VoiceEnabled_BaboonHawk, "Monster Voices", "Baboon Hawk", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Bracken, "Monster Voices", "Bracken", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_BunkerSpider, "Monster Voices", "Bunker Spider", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Centipede, "Monster Voices", "Centipede", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_CoilHead, "Monster Voices", "Coil Head", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_EyelessDog, "Monster Voices", "Eyeless Dog", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_ForestGiant, "Monster Voices", "Forest Giant", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_GhostGirl, "Monster Voices", "Ghost Girl", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_GiantWorm, "Monster Voices", "Giant Worm", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_HoardingBug, "Monster Voices", "Hoarding Bug", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Hygrodere, "Monster Voices", "Hygrodere", defaultValue: false); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Jester, "Monster Voices", "Jester", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Masked, "Monster Voices", "Masked", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Nutcracker, "Monster Voices", "Nutcracker", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_SporeLizard, "Monster Voices", "Spore Lizard", defaultValue: true); PluginLoader.Instance.BindConfig(ref VoiceEnabled_Thumper, "Monster Voices", "Thumper", defaultValue: true); SkinwalkerLogger.Log("VoiceEnabled_BaboonHawk" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BaboonHawk.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Bracken" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Bracken.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_BunkerSpider" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_BunkerSpider.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Centipede" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Centipede.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_CoilHead" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_CoilHead.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_EyelessDog" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_EyelessDog.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_ForestGiant" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_ForestGiant.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_GhostGirl" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GhostGirl.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_GiantWorm" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_GiantWorm.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_HoardingBug" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_HoardingBug.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Hygrodere" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Hygrodere.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Jester" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Jester.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Masked" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Masked.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Nutcracker" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Nutcracker.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_SporeLizard" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_SporeLizard.Value}]"); SkinwalkerLogger.Log("VoiceEnabled_Thumper" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_Thumper.Value}]"); SkinwalkerLogger.Log("VoiceLineFrequency" + $" VALUE LOADED FROM CONFIG: [{VoiceLineFrequency.Value}]"); } } internal static class SkinwalkerLogger { internal static ManualLogSource logSource; public static void Initialize(string modGUID) { logSource = Logger.CreateLogSource(modGUID); } public static void Log(object message) { logSource.LogInfo(message); } public static void LogError(object message) { logSource.LogError(message); } public static void LogWarning(object message) { logSource.LogWarning(message); } } public class SkinwalkerModPersistent : MonoBehaviour { private string audioFolder; private List<AudioClip> cachedAudio = new List<AudioClip>(); private float nextTimeToCheckFolder = 30f; private float nextTimeToCheckEnemies = 30f; private const float folderScanInterval = 8f; private const float enemyScanInterval = 5f; public static SkinwalkerModPersistent Instance { get; private set; } private void Awake() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) Instance = this; ((Component)this).transform.position = Vector3.zero; SkinwalkerLogger.Log("Skinwalker Mod Object Initialized"); audioFolder = Path.Combine(Application.dataPath, "..", "Dissonance_Diagnostics"); EnableRecording(); if (!Directory.Exists(audioFolder)) { Directory.CreateDirectory(audioFolder); } } private void Start() { try { if (Directory.Exists(audioFolder)) { Directory.Delete(audioFolder, recursive: true); } } catch (Exception message) { SkinwalkerLogger.Log(message); } } private void OnApplicationQuit() { DisableRecording(); } private void EnableRecording() { DebugSettings.Instance.EnablePlaybackDiagnostics = true; DebugSettings.Instance.RecordFinalAudio = true; } private void Update() { if (Time.realtimeSinceStartup > nextTimeToCheckFolder) { nextTimeToCheckFolder = Time.realtimeSinceStartup + 8f; if (!Directory.Exists(audioFolder)) { SkinwalkerLogger.Log("Audio folder not present. Don't worry about it, it will be created automatically when you play with friends. (" + audioFolder + ")"); return; } string[] files = Directory.GetFiles(audioFolder); SkinwalkerLogger.Log($"Got audio file paths ({files.Length})"); string[] array = files; foreach (string path in array) { ((MonoBehaviour)this).StartCoroutine(LoadWavFile(path, delegate(AudioClip audioClip) { cachedAudio.Add(audioClip); })); } } if (!(Time.realtimeSinceStartup > nextTimeToCheckEnemies)) { return; } nextTimeToCheckEnemies = Time.realtimeSinceStartup + 5f; EnemyAI[] array2 = Object.FindObjectsOfType<EnemyAI>(true); EnemyAI[] array3 = array2; SkinwalkerBehaviour skinwalkerBehaviour = default(SkinwalkerBehaviour); foreach (EnemyAI val in array3) { SkinwalkerLogger.Log("IsEnemyEnabled " + ((Object)val).name + " " + IsEnemyEnabled(val)); if (IsEnemyEnabled(val) && !((Component)val).TryGetComponent<SkinwalkerBehaviour>(ref skinwalkerBehaviour)) { ((Component)val).gameObject.AddComponent<SkinwalkerBehaviour>().Initialize(val); } } } private bool IsEnemyEnabled(EnemyAI enemy) { if ((Object)(object)enemy == (Object)null) { return false; } return ((Object)((Component)enemy).gameObject).name switch { "MaskedPlayerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Masked.Value, "NutcrackerEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Nutcracker.Value, "BaboonHawkEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BaboonHawk.Value, "Flowerman(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Bracken.Value, "SandSpider(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_BunkerSpider.Value, "RedLocustBees(Clone)" => false, "Centipede(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Centipede.Value, "SpringMan(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_CoilHead.Value, "MouthDog(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_EyelessDog.Value, "ForestGiant(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_ForestGiant.Value, "DressGirl(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GhostGirl.Value, "SandWorm(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_GiantWorm.Value, "HoarderBug(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_HoardingBug.Value, "Blob(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Hygrodere.Value, "JesterEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Jester.Value, "PufferEnemy(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_SporeLizard.Value, "Crawler(Clone)" => SkinwalkerNetworkManager.Instance.VoiceEnabled_Thumper.Value, "DocileLocustBees(Clone)" => false, "DoublewingedBird(Clone)" => false, _ => true, }; } internal IEnumerator LoadWavFile(string path, Action<AudioClip> callback) { UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20); try { yield return www.SendWebRequest(); if ((int)www.result == 1) { SkinwalkerLogger.Log("Loaded clip from path " + path); AudioClip audioClip = DownloadHandlerAudioClip.GetContent(www); if (audioClip.length > 0.9f) { callback(audioClip); } try { File.Delete(path); } catch (Exception e) { SkinwalkerLogger.LogWarning(e); } } } finally { ((IDisposable)www)?.Dispose(); } } private void DisableRecording() { DebugSettings.Instance.EnablePlaybackDiagnostics = false; DebugSettings.Instance.RecordFinalAudio = false; if (Directory.Exists(audioFolder)) { Directory.Delete(audioFolder, recursive: true); } } public AudioClip GetSample() { if (cachedAudio.Count > 0) { int index = Random.Range(0, cachedAudio.Count - 1); AudioClip result = cachedAudio[index]; cachedAudio.RemoveAt(index); return result; } while (cachedAudio.Count > 200) { cachedAudio.RemoveAt(0); } return null; } public void ClearCache() { cachedAudio.Clear(); } } internal static class SkinwalkerNetworkManagerHandler { internal static void ClientConnectInitializer(Scene sceneName, LoadSceneMode sceneEnum) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if (((Scene)(ref sceneName)).name == "SampleSceneRelay") { GameObject val = new GameObject("SkinwalkerNetworkManager"); val.AddComponent<NetworkObject>(); val.AddComponent<SkinwalkerNetworkManager>(); Debug.Log((object)"Initialized SkinwalkerNetworkManager"); } } } internal class SkinwalkerNetworkManager : NetworkBehaviour { public NetworkVariable<bool> VoiceEnabled_BaboonHawk = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Bracken = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_BunkerSpider = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Centipede = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_CoilHead = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_EyelessDog = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_ForestGiant = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_GhostGirl = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_GiantWorm = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_HoardingBug = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Hygrodere = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Jester = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Masked = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Nutcracker = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_SporeLizard = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<bool> VoiceEnabled_Thumper = new NetworkVariable<bool>(true, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public NetworkVariable<float> VoiceLineFrequency = new NetworkVariable<float>(1f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static SkinwalkerNetworkManager Instance { get; private set; } private void Awake() { Instance = this; if (GameNetworkManager.Instance.isHostingGame) { VoiceEnabled_BaboonHawk.Value = SkinwalkerConfig.VoiceEnabled_BaboonHawk.Value; VoiceEnabled_Bracken.Value = SkinwalkerConfig.VoiceEnabled_Bracken.Value; VoiceEnabled_BunkerSpider.Value = SkinwalkerConfig.VoiceEnabled_BunkerSpider.Value; VoiceEnabled_Centipede.Value = SkinwalkerConfig.VoiceEnabled_Centipede.Value; VoiceEnabled_CoilHead.Value = SkinwalkerConfig.VoiceEnabled_CoilHead.Value; VoiceEnabled_EyelessDog.Value = SkinwalkerConfig.VoiceEnabled_EyelessDog.Value; VoiceEnabled_ForestGiant.Value = SkinwalkerConfig.VoiceEnabled_ForestGiant.Value; VoiceEnabled_GhostGirl.Value = SkinwalkerConfig.VoiceEnabled_GhostGirl.Value; VoiceEnabled_GiantWorm.Value = SkinwalkerConfig.VoiceEnabled_GiantWorm.Value; VoiceEnabled_HoardingBug.Value = SkinwalkerConfig.VoiceEnabled_HoardingBug.Value; VoiceEnabled_Hygrodere.Value = SkinwalkerConfig.VoiceEnabled_Hygrodere.Value; VoiceEnabled_Jester.Value = SkinwalkerConfig.VoiceEnabled_Jester.Value; VoiceEnabled_Masked.Value = SkinwalkerConfig.VoiceEnabled_Masked.Value; VoiceEnabled_Nutcracker.Value = SkinwalkerConfig.VoiceEnabled_Nutcracker.Value; VoiceEnabled_SporeLizard.Value = SkinwalkerConfig.VoiceEnabled_SporeLizard.Value; VoiceEnabled_Thumper.Value = SkinwalkerConfig.VoiceEnabled_Thumper.Value; VoiceLineFrequency.Value = SkinwalkerConfig.VoiceLineFrequency.Value; SkinwalkerLogger.Log("HOST SENDING CONFIG TO CLIENTS"); } SkinwalkerLogger.Log("SkinwalkerNetworkManager Awake"); } public override void OnDestroy() { ((NetworkBehaviour)this).OnDestroy(); SkinwalkerLogger.Log("SkinwalkerNetworkManager OnDestroy"); SkinwalkerModPersistent.Instance?.ClearCache(); } protected override void __initializeVariables() { if (VoiceEnabled_BaboonHawk == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BaboonHawk cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_BaboonHawk).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk, "VoiceEnabled_BaboonHawk"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BaboonHawk); if (VoiceEnabled_Bracken == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Bracken cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Bracken).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Bracken, "VoiceEnabled_Bracken"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Bracken); if (VoiceEnabled_BunkerSpider == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_BunkerSpider cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_BunkerSpider).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider, "VoiceEnabled_BunkerSpider"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_BunkerSpider); if (VoiceEnabled_Centipede == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Centipede cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Centipede).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Centipede, "VoiceEnabled_Centipede"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Centipede); if (VoiceEnabled_CoilHead == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_CoilHead cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_CoilHead).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_CoilHead, "VoiceEnabled_CoilHead"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_CoilHead); if (VoiceEnabled_EyelessDog == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_EyelessDog cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_EyelessDog).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_EyelessDog, "VoiceEnabled_EyelessDog"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_EyelessDog); if (VoiceEnabled_ForestGiant == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_ForestGiant cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_ForestGiant).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_ForestGiant, "VoiceEnabled_ForestGiant"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_ForestGiant); if (VoiceEnabled_GhostGirl == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GhostGirl cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_GhostGirl).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GhostGirl, "VoiceEnabled_GhostGirl"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GhostGirl); if (VoiceEnabled_GiantWorm == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_GiantWorm cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_GiantWorm).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_GiantWorm, "VoiceEnabled_GiantWorm"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_GiantWorm); if (VoiceEnabled_HoardingBug == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_HoardingBug cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_HoardingBug).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_HoardingBug, "VoiceEnabled_HoardingBug"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_HoardingBug); if (VoiceEnabled_Hygrodere == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Hygrodere cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Hygrodere).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Hygrodere, "VoiceEnabled_Hygrodere"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Hygrodere); if (VoiceEnabled_Jester == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Jester cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Jester).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Jester, "VoiceEnabled_Jester"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Jester); if (VoiceEnabled_Masked == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Masked cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Masked).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Masked, "VoiceEnabled_Masked"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Masked); if (VoiceEnabled_Nutcracker == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Nutcracker cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Nutcracker).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Nutcracker, "VoiceEnabled_Nutcracker"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Nutcracker); if (VoiceEnabled_SporeLizard == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_SporeLizard cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_SporeLizard).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_SporeLizard, "VoiceEnabled_SporeLizard"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_SporeLizard); if (VoiceEnabled_Thumper == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_Thumper cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_Thumper).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_Thumper, "VoiceEnabled_Thumper"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_Thumper); if (VoiceLineFrequency == null) { throw new Exception("SkinwalkerNetworkManager.VoiceLineFrequency cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceLineFrequency).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceLineFrequency, "VoiceLineFrequency"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceLineFrequency); ((NetworkBehaviour)this).__initializeVariables(); } protected internal override string __getTypeName() { return "SkinwalkerNetworkManager"; } }
BepInEx/plugins/SkipToMultiplayerMenu.dll
Decompiled a year agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using HarmonyLib; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("SkipToMultiplayerMenu")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SkipToMultiplayerMenu")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("19daac4f-befb-4658-b237-679df1f71a19")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace SkipToMultiplayerMenu { [BepInPlugin("FlipMods.SkipToMultiplayerMenu", "SkipToMultiplayerMenu", "1.0.0")] public class Plugin : BaseUnityPlugin { private Harmony _harmony; private static Plugin instance; private void Awake() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown instance = this; _harmony = new Harmony("SkipToMultiplayerMenu"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"SkipToMultiplayerMenu loaded"); } public static void Log(string message) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)message); } } public static class PluginInfo { public const string PLUGIN_GUID = "FlipMods.SkipToMultiplayerMenu"; public const string PLUGIN_NAME = "SkipToMultiplayerMenu"; public const string PLUGIN_VERSION = "1.0.0"; } } namespace SkipToMultiplayerMenu.Patches { [HarmonyPatch] internal class SkipToMultiplayerMenuPatcher { private static bool skippedPreInitScene; private static bool skippedInitScene; [HarmonyPatch(typeof(PreInitSceneScript), "Awake")] [HarmonyPrefix] public static bool InitializeGameManager() { if (skippedPreInitScene) { return true; } skippedPreInitScene = true; Plugin.Log("Loading GameManager in InitScene."); SceneManager.LoadScene("InitScene"); return false; } [HarmonyPatch(typeof(InitializeGame), "Start")] [HarmonyPrefix] public static bool LoadMultiplayerMenuScene() { if (skippedInitScene) { return true; } skippedInitScene = true; Plugin.Log("Skipping to MainMenu scene."); SceneManager.LoadScene("MainMenu"); return false; } } }
BepInEx/plugins/SolosBodycams.dll
Decompiled a year agousing System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("SolosBodycams")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Solo's Bodycams")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("SolosBodycams")] [assembly: AssemblyTitle("SolosBodycams")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace SolosBodycams; [BepInPlugin("SolosBodycams", "Solo's Bodycams", "1.0")] public class Plugin : BaseUnityPlugin { private GameObject ShipExternalCamera = null; private int TransformIndexCopy; private bool ActivateCamera1 = false; private bool ActivateCamera2 = false; private bool SwitchedMonitors = false; private RenderTexture NewRT; private Vector3 CameraOriginalPosition; private Quaternion CameraOriginalRotation; private string Spine4Addition = ""; private static Plugin Instance; private static ConfigFile CameraPlacementFile { get; set; } internal static ConfigEntry<bool> BodycamOrHeadcam { get; set; } public void Awake() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown if ((Object)(object)Instance == (Object)null) { Instance = this; ((Object)((Component)this).gameObject).hideFlags = (HideFlags)61; } else if ((Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); } CameraPlacementFile = new ConfigFile(Paths.ConfigPath + "\\SoloMods\\CameraPlacement.cfg", true); BodycamOrHeadcam = CameraPlacementFile.Bind<bool>("CameraPlacement", "Bool", true, "True for HEADCAM, False for BODYCAM"); ((BaseUnityPlugin)this).Logger.LogInfo((object)BodycamOrHeadcam.Value); if (BodycamOrHeadcam.Value) { Spine4Addition = "/spine.004"; } else { Spine4Addition = ""; } Object.DontDestroyOnLoad((Object)((Component)this).gameObject); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin SolosBodycams is loaded!"); SceneManager.sceneLoaded += OnSceneLoaded; } public void OnSceneLoaded(Scene scene, LoadSceneMode mode) { ActivateCamera2 = false; if (!(((Scene)(ref scene)).name == "MainMenu") && !(((Scene)(ref scene)).name == "InitScene") && !(((Scene)(ref scene)).name == "InitSceneLaunchOptions")) { ActivateCamera1 = true; ((MonoBehaviour)this).StartCoroutine(LoadSceneEnter()); } else { ActivateCamera1 = false; SwitchedMonitors = false; } } private IEnumerator LoadSceneEnter() { yield return (object)new WaitForSeconds(5f); ActivateCamera2 = true; if (!((Object)(object)GameObject.Find("Environment/HangarShip/Cameras/ShipCamera") == (Object)null) && !SwitchedMonitors) { NewRT = new RenderTexture(160, 120, 32, (RenderTextureFormat)0); ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube").GetComponent<MeshRenderer>()).materials[2].mainTexture = ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture; ((Renderer)GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001").GetComponent<MeshRenderer>()).materials[2].mainTexture = (Texture)(object)NewRT; if ((Object)(object)ShipExternalCamera == (Object)null) { ShipExternalCamera = Object.Instantiate<GameObject>(GameObject.Find("Environment/HangarShip/Cameras/ShipCamera")); ShipExternalCamera.transform.SetParent(GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").transform.parent); ShipExternalCamera.transform.SetLocalPositionAndRotation(GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").transform.localPosition, GameObject.Find("Environment/HangarShip/Cameras/ShipCamera").transform.localRotation); ShipExternalCamera.AddComponent<Camera>(); CameraOriginalPosition = ShipExternalCamera.transform.localPosition; CameraOriginalRotation = ShipExternalCamera.transform.localRotation; Object.Destroy((Object)(object)((Component)ShipExternalCamera.transform.Find("VolumeMain (1)")).GetComponent<BoxCollider>()); Object.Destroy((Object)(object)ShipExternalCamera.GetComponent<Animator>()); Object.Destroy((Object)(object)ShipExternalCamera.GetComponent<MeshRenderer>()); } ShipExternalCamera.GetComponent<Camera>().targetTexture = NewRT; SwitchedMonitors = true; } } public void Update() { //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_0148: 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_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) if (!ActivateCamera1 || !ActivateCamera2) { return; } TransformIndexCopy = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001/CameraMonitorScript").GetComponent<ManualCameraRenderer>().targetTransformIndex; TransformAndName val = GameObject.Find("Environment/HangarShip/ShipModels2b/MonitorWall/Cube.001/CameraMonitorScript").GetComponent<ManualCameraRenderer>().radarTargets[TransformIndexCopy]; if (!val.isNonPlayer) { ShipExternalCamera.transform.SetPositionAndRotation(val.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003" + Spine4Addition).position + new Vector3(0f, 0.1f, 0f), val.transform.Find("ScavengerModel/metarig/spine/spine.001/spine.002/spine.003" + Spine4Addition).rotation * Quaternion.Euler(0f, 0f, 0f)); DeadBodyInfo[] array = Object.FindObjectsOfType<DeadBodyInfo>(); for (int i = 0; i < array.Length; i++) { if (array[i].playerScript.playerUsername == val.name) { ShipExternalCamera.transform.SetPositionAndRotation(((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003" + Spine4Addition).position + new Vector3(0f, 0.1f, 0f), ((Component)array[i]).gameObject.transform.Find("spine.001/spine.002/spine.003" + Spine4Addition).rotation * Quaternion.Euler(0f, 0f, 0f)); } } } else { ShipExternalCamera.transform.SetPositionAndRotation(val.transform.position + new Vector3(0f, 1.6f, 0f), val.transform.rotation * Quaternion.Euler(0f, -90f, 0f)); } } } public static class PluginInfo { public const string PLUGIN_GUID = "SolosBodycams"; public const string PLUGIN_NAME = "SolosBodycams"; public const string PLUGIN_VERSION = "1.0.0"; }
BepInEx/plugins/Suit Saver.dll
Decompiled a year agousing System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using GameNetcodeStuff; using HarmonyLib; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("Suit Saver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Suit Saver")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("cb7cfb30-b06e-4e41-9de7-03640e1662ea")] [assembly: AssemblyFileVersion("1.1.2.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyVersion("1.0.0.0")] namespace SuitSaver { [BepInPlugin("Hexnet.lethalcompany.suitsaver", "Suit Saver", "1.1.2")] public class SuitSaver : BaseUnityPlugin { private const string modGUID = "Hexnet.lethalcompany.suitsaver"; private const string modName = "Suit Saver"; private const string modVersion = "1.1.2"; private readonly Harmony harmony = new Harmony("Hexnet.lethalcompany.suitsaver"); private void Awake() { harmony.PatchAll(); Debug.Log((object)"[SS]: Suit Saver loaded successfully!"); } } } namespace SuitSaver.Patches { [HarmonyPatch] internal class Patches { [HarmonyPatch(typeof(StartOfRound))] internal class StartPatch { [HarmonyPatch("ResetShip")] [HarmonyPostfix] private static void ResetShipPatch() { Debug.Log((object)"[SS]: Ship has been reset!"); Debug.Log((object)"[SS]: Reloading suit..."); LoadSuitFromFile(); } } [HarmonyPatch(typeof(UnlockableSuit))] internal class SuitPatch { [HarmonyPatch("SwitchSuitClientRpc")] [HarmonyPostfix] private static void SyncSuit(ref UnlockableSuit __instance, int playerID) { PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; int num = (int)localPlayerController.playerClientId; if (playerID != num) { UnlockableSuit.SwitchSuitForPlayer(StartOfRound.Instance.allPlayerScripts[playerID], __instance.syncedSuitID.Value, true); } } [HarmonyPatch("SwitchSuitToThis")] [HarmonyPostfix] private static void EquipSuitPatch() { PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; string unlockableName = StartOfRound.Instance.unlockablesList.unlockables[localPlayerController.currentSuitID].unlockableName; SaveToFile(unlockableName); Debug.Log((object)("[SS]: Successfully saved current suit. (" + unlockableName + ")")); } } [HarmonyPatch(typeof(PlayerControllerB))] internal class JoinGamePatch { [HarmonyPatch("ConnectClientToPlayerObject")] [HarmonyPostfix] private static void LoadSuitPatch(ref PlayerControllerB __instance) { ((Component)GameNetworkManager.Instance.localPlayerController).gameObject.AddComponent<EquipAfterSyncPatch>(); } } internal class EquipAfterSyncPatch : MonoBehaviour { private void Start() { ((MonoBehaviour)this).StartCoroutine(LoadSuit()); } private IEnumerator LoadSuit() { Debug.Log((object)"[SS]: Waiting for suits to sync..."); yield return (object)new WaitForSeconds(1f); LoadSuitFromFile(); } } public static string SavePath = Application.persistentDataPath + "\\suitsaver.txt"; private static void SaveToFile(string suitName) { File.WriteAllText(SavePath, suitName); } private static string LoadFromFile() { if (File.Exists(SavePath)) { return File.ReadAllText(SavePath); } return "-1"; } private static UnlockableSuit GetSuitByName(string Name) { List<UnlockableItem> unlockables = StartOfRound.Instance.unlockablesList.unlockables; UnlockableSuit[] array = Resources.FindObjectsOfTypeAll<UnlockableSuit>(); foreach (UnlockableSuit val in array) { if (val.syncedSuitID.Value >= 0) { string unlockableName = unlockables[val.syncedSuitID.Value].unlockableName; if (unlockableName == Name) { return val; } } } return null; } private static void LoadSuitFromFile() { string text = LoadFromFile(); PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController; if (!(text == "-1")) { UnlockableSuit suitByName = GetSuitByName(text); if ((Object)(object)suitByName != (Object)null) { UnlockableSuit.SwitchSuitForPlayer(localPlayerController, suitByName.syncedSuitID.Value, false); suitByName.SwitchSuitServerRpc((int)localPlayerController.playerClientId); Debug.Log((object)("[SS]: Successfully loaded saved suit. (" + text + ")")); } else { Debug.Log((object)("[SS]: Failed to load saved suit. Perhaps it's locked? (" + text + ")")); } } } } }
BepInEx/plugins/TerminalApi.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using TerminalApi.Classes; using TerminalApi.Interfaces; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")] [assembly: AssemblyCompany("NotAtomicBomb")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Terminal Api for the terminal in Lethal Company")] [assembly: AssemblyFileVersion("1.5.1.0")] [assembly: AssemblyInformationalVersion("1.5.1+9b12d17b39fe1f9518b55effc9f9d6af53ea5e0d")] [assembly: AssemblyProduct("TerminalApi")] [assembly: AssemblyTitle("TerminalApi")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NotAtomicBomb/TerminalApi")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.5.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [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 TerminalApi { internal class DelayedAddTerminalKeyword : IDelayedAction { internal Action<TerminalKeyword, CommandInfo> Action { get; set; } internal CommandInfo CommandInfo { get; set; } internal TerminalKeyword Keyword { get; set; } public void Run() { Action(Keyword, CommandInfo); } } [BepInPlugin("atomic.terminalapi", "Terminal Api", "1.5.0")] public class Plugin : BaseUnityPlugin { internal static ConfigEntry<bool> configEnableLogs; public ManualLogSource Log; internal void SetupConfig() { configEnableLogs = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "enableLogs", true, "Whether or not to display logs pertaining to TerminalAPI. Will still log that the mod has loaded."); } private void Awake() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) SetupConfig(); object obj = this; obj = (object)((!configEnableLogs.Value) ? ((ManualLogSource)null) : new ManualLogSource("Terminal Api")); ((Plugin)obj).Log = (ManualLogSource)obj; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin TerminalApi is loaded!"); if (Log != null) { Logger.Sources.Add((ILogSource)(object)Log); } TerminalApi.plugin = this; Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null); } } public static class TerminalApi { public static Plugin plugin; internal static List<IDelayedAction> QueuedDelayedActions = new List<IDelayedAction>(); internal static List<CommandInfo> CommandInfos = new List<CommandInfo>(); public static Terminal Terminal { get; internal set; } public static List<TerminalNode> SpecialNodes => Terminal.terminalNodes.specialNodes; public static string CurrentText => Terminal.currentText; public static TMP_InputField ScreenText => Terminal.screenText; public static bool IsInGame() { try { return Terminal != null; } catch (NullReferenceException) { return false; } } public static void AddCommand(string commandWord, string displayText, string verbWord = null, bool clearPreviousText = true) { commandWord = commandWord.ToLower(); TerminalKeyword val = CreateTerminalKeyword(commandWord); TerminalNode val2 = CreateTerminalNode(displayText, clearPreviousText); if (verbWord != null) { verbWord = verbWord.ToLower(); TerminalKeyword terminalKeyword = CreateTerminalKeyword(verbWord, isVerb: true); AddTerminalKeyword(val.defaultVerb = terminalKeyword.AddCompatibleNoun(val, val2)); AddTerminalKeyword(val); } else { val.specialKeywordResult = val2; AddTerminalKeyword(val); } } public static void AddCommand(string commandWord, CommandInfo commandInfo, string verbWord = null, bool clearPreviousText = true) { commandWord = commandWord.ToLower(); TerminalKeyword val = CreateTerminalKeyword(commandWord); TerminalNode val3 = (commandInfo.TriggerNode = CreateTerminalNode("", clearPreviousText)); if (verbWord != null) { verbWord = verbWord.ToLower(); TerminalKeyword terminalKeyword = CreateTerminalKeyword(verbWord, isVerb: true); AddTerminalKeyword(val.defaultVerb = terminalKeyword.AddCompatibleNoun(val, val3)); AddTerminalKeyword(val, commandInfo); } else { val.specialKeywordResult = val3; AddTerminalKeyword(val, commandInfo); } } public static TerminalKeyword CreateTerminalKeyword(string word, bool isVerb = false, TerminalNode triggeringNode = null) { TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>(); obj.word = word.ToLower(); obj.isVerb = isVerb; obj.specialKeywordResult = triggeringNode; return obj; } public static TerminalKeyword CreateTerminalKeyword(string word, string displayText, bool clearPreviousText = false, string terminalEvent = "") { TerminalKeyword obj = ScriptableObject.CreateInstance<TerminalKeyword>(); obj.word = word.ToLower(); obj.isVerb = false; obj.specialKeywordResult = CreateTerminalNode(displayText, clearPreviousText, terminalEvent); return obj; } public static TerminalNode CreateTerminalNode(string displayText, bool clearPreviousText = false, string terminalEvent = "") { TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>(); obj.displayText = displayText; obj.clearPreviousText = clearPreviousText; obj.terminalEvent = terminalEvent; return obj; } public static void AddTerminalKeyword(TerminalKeyword terminalKeyword) { if (IsInGame()) { if (GetKeyword(terminalKeyword.word) == null) { Terminal.terminalNodes.allKeywords = Terminal.terminalNodes.allKeywords.Add(terminalKeyword); ManualLogSource log = plugin.Log; if (log != null) { log.LogMessage((object)("Added " + terminalKeyword.word + " keyword to terminal keywords.")); } } else { ManualLogSource log2 = plugin.Log; if (log2 != null) { log2.LogWarning((object)("Failed to add " + terminalKeyword.word + " keyword. Already exists.")); } } } else { ManualLogSource log3 = plugin.Log; if (log3 != null) { log3.LogMessage((object)("Not in game, waiting to be in game to add " + terminalKeyword.word + " keyword.")); } Action<TerminalKeyword, CommandInfo> action = AddTerminalKeyword; DelayedAddTerminalKeyword item = new DelayedAddTerminalKeyword { Action = action, Keyword = terminalKeyword }; QueuedDelayedActions.Add(item); } } public static void AddTerminalKeyword(TerminalKeyword terminalKeyword, CommandInfo commandInfo = null) { if (IsInGame()) { if (GetKeyword(terminalKeyword.word) == null) { if (commandInfo?.DisplayTextSupplier != null) { if (commandInfo?.TriggerNode == null) { commandInfo.TriggerNode = terminalKeyword.specialKeywordResult; } CommandInfos.Add(commandInfo); } if (commandInfo != null) { ((Object)terminalKeyword).name = commandInfo.Title ?? (terminalKeyword.word.Substring(0, 1).ToUpper() + terminalKeyword.word.Substring(1)); string text = "\n>" + ((Object)terminalKeyword).name.ToUpper() + "\n" + commandInfo.Description + "\n\n"; NodeAppendLine(commandInfo.Category, text); } Terminal.terminalNodes.allKeywords = Terminal.terminalNodes.allKeywords.Add(terminalKeyword); ManualLogSource log = plugin.Log; if (log != null) { log.LogMessage((object)("Added " + terminalKeyword.word + " keyword to terminal keywords.")); } } else { ManualLogSource log2 = plugin.Log; if (log2 != null) { log2.LogWarning((object)("Failed to add " + terminalKeyword.word + " keyword. Already exists.")); } } } else { ManualLogSource log3 = plugin.Log; if (log3 != null) { log3.LogMessage((object)("Not in game, waiting to be in game to add " + terminalKeyword.word + " keyword.")); } Action<TerminalKeyword, CommandInfo> action = AddTerminalKeyword; DelayedAddTerminalKeyword item = new DelayedAddTerminalKeyword { Action = action, Keyword = terminalKeyword, CommandInfo = commandInfo }; QueuedDelayedActions.Add(item); } } public static void NodeAppendLine(string word, string text) { if (!IsInGame()) { return; } TerminalKeyword keyword = GetKeyword(word.ToLower()); if ((Object)(object)keyword != (Object)null) { keyword.specialKeywordResult.displayText = keyword.specialKeywordResult.displayText.Trim() + "\n" + text; return; } ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)("Failed to add text to " + word + ". Does not exist.")); } } public static TerminalKeyword GetKeyword(string keyword) { if (IsInGame()) { return ((IEnumerable<TerminalKeyword>)Terminal.terminalNodes.allKeywords).FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword Kw) => Kw.word == keyword)); } return null; } public static void UpdateKeyword(TerminalKeyword keyword) { if (!IsInGame()) { return; } for (int i = 0; i < Terminal.terminalNodes.allKeywords.Length; i++) { if (Terminal.terminalNodes.allKeywords[i].word == keyword.word) { Terminal.terminalNodes.allKeywords[i] = keyword; return; } } ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)("Failed to update " + keyword.word + ". Was not found in keywords.")); } } public static void DeleteKeyword(string word) { if (!IsInGame()) { return; } for (int i = 0; i < Terminal.terminalNodes.allKeywords.Length; i++) { if (Terminal.terminalNodes.allKeywords[i].word == word.ToLower()) { int newSize = Terminal.terminalNodes.allKeywords.Length - 1; for (int j = i + 1; j < Terminal.terminalNodes.allKeywords.Length; j++) { Terminal.terminalNodes.allKeywords[j - 1] = Terminal.terminalNodes.allKeywords[j]; } Array.Resize(ref Terminal.terminalNodes.allKeywords, newSize); ManualLogSource log = plugin.Log; if (log != null) { log.LogMessage((object)(word + " was deleted successfully.")); } return; } } ManualLogSource log2 = plugin.Log; if (log2 != null) { log2.LogWarning((object)("Failed to delete " + word + ". Was not found in keywords.")); } } public static void UpdateKeywordCompatibleNoun(TerminalKeyword verbKeyword, string noun, TerminalNode newTriggerNode) { if (!IsInGame() || !verbKeyword.isVerb) { return; } for (int i = 0; i < verbKeyword.compatibleNouns.Length; i++) { CompatibleNoun val = verbKeyword.compatibleNouns[i]; if (val.noun.word == noun) { val.result = newTriggerNode; UpdateKeyword(verbKeyword); return; } } ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)$"WARNING: No noun found for {verbKeyword}"); } } public static void UpdateKeywordCompatibleNoun(string verbWord, string noun, TerminalNode newTriggerNode) { if (!IsInGame()) { return; } TerminalKeyword keyword = GetKeyword(verbWord); if (!keyword.isVerb || verbWord == null) { return; } for (int i = 0; i < keyword.compatibleNouns.Length; i++) { CompatibleNoun val = keyword.compatibleNouns[i]; if (val.noun.word == noun) { val.result = newTriggerNode; UpdateKeyword(keyword); return; } } ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)$"WARNING: No noun found for {keyword}"); } } public static void UpdateKeywordCompatibleNoun(TerminalKeyword verbKeyword, string noun, string newDisplayText) { if (!IsInGame() || !verbKeyword.isVerb) { return; } for (int i = 0; i < verbKeyword.compatibleNouns.Length; i++) { CompatibleNoun val = verbKeyword.compatibleNouns[i]; if (val.noun.word == noun) { val.result.displayText = newDisplayText; UpdateKeyword(verbKeyword); return; } } ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)$"WARNING: No noun found for {verbKeyword}"); } } public static void UpdateKeywordCompatibleNoun(string verbWord, string noun, string newDisplayText) { if (!IsInGame()) { return; } TerminalKeyword keyword = GetKeyword(verbWord); if (!keyword.isVerb) { return; } for (int i = 0; i < keyword.compatibleNouns.Length; i++) { CompatibleNoun val = keyword.compatibleNouns[i]; if (val.noun.word == noun) { val.result.displayText = newDisplayText; UpdateKeyword(keyword); return; } } ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)$"WARNING: No noun found for {keyword}"); } } public static void AddCompatibleNoun(TerminalKeyword verbKeyword, string noun, string displayText, bool clearPreviousText = false) { if (IsInGame()) { TerminalKeyword keyword = GetKeyword(noun); verbKeyword = verbKeyword.AddCompatibleNoun(keyword, displayText, clearPreviousText); UpdateKeyword(verbKeyword); } } public static void AddCompatibleNoun(TerminalKeyword verbKeyword, string noun, TerminalNode triggerNode) { if (IsInGame()) { TerminalKeyword keyword = GetKeyword(noun); verbKeyword = verbKeyword.AddCompatibleNoun(keyword, triggerNode); UpdateKeyword(verbKeyword); } } public static void AddCompatibleNoun(string verbWord, string noun, TerminalNode triggerNode) { if (!IsInGame()) { return; } TerminalKeyword keyword = GetKeyword(verbWord); TerminalKeyword keyword2 = GetKeyword(noun); if ((Object)(object)keyword == (Object)null) { ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)"The verb given does not exist."); } } else { keyword = keyword.AddCompatibleNoun(keyword2, triggerNode); UpdateKeyword(keyword); } } public static void AddCompatibleNoun(string verbWord, string noun, string displayText, bool clearPreviousText = false) { if (!IsInGame()) { return; } TerminalKeyword keyword = GetKeyword(verbWord); TerminalKeyword keyword2 = GetKeyword(noun); if ((Object)(object)keyword == (Object)null) { ManualLogSource log = plugin.Log; if (log != null) { log.LogWarning((object)"The verb given does not exist."); } } else { keyword = keyword.AddCompatibleNoun(keyword2, displayText, clearPreviousText); UpdateKeyword(keyword); } } public static string GetTerminalInput() { if (IsInGame()) { return CurrentText.Substring(CurrentText.Length - Terminal.textAdded); } return ""; } public static void SetTerminalInput(string terminalInput) { Terminal.TextChanged(CurrentText.Substring(0, CurrentText.Length - Terminal.textAdded) + terminalInput); ScreenText.text = CurrentText; Terminal.textAdded = terminalInput.Length; } } public static class TerminalExtenstionMethods { public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword noun, TerminalNode result) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown if (terminalKeyword.isVerb) { CompatibleNoun val = new CompatibleNoun { noun = noun, result = result }; if (terminalKeyword.compatibleNouns == null) { terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val }; } else { terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val); } return terminalKeyword; } return null; } public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, string noun, TerminalNode result) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown if (terminalKeyword.isVerb) { CompatibleNoun val = new CompatibleNoun { noun = TerminalApi.CreateTerminalKeyword(noun), result = result }; if (terminalKeyword.compatibleNouns == null) { terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val }; } else { terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val); } return terminalKeyword; } return null; } public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, string noun, string displayText) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown if (terminalKeyword.isVerb) { CompatibleNoun val = new CompatibleNoun { noun = TerminalApi.CreateTerminalKeyword(noun), result = TerminalApi.CreateTerminalNode(displayText) }; if (terminalKeyword.compatibleNouns == null) { terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val }; } else { terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val); } return terminalKeyword; } return null; } public static TerminalKeyword AddCompatibleNoun(this TerminalKeyword terminalKeyword, TerminalKeyword noun, string displayText, bool clearPreviousText = false) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown if (terminalKeyword.isVerb) { CompatibleNoun val = new CompatibleNoun { noun = noun, result = TerminalApi.CreateTerminalNode(displayText, clearPreviousText) }; if (terminalKeyword.compatibleNouns == null) { terminalKeyword.compatibleNouns = (CompatibleNoun[])(object)new CompatibleNoun[1] { val }; } else { terminalKeyword.compatibleNouns = terminalKeyword.compatibleNouns.Add(val); } return terminalKeyword; } return null; } internal static T[] Add<T>(this T[] array, T newItem) { int num = array.Length + 1; Array.Resize(ref array, num); array[num - 1] = newItem; return array; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "TerminalApi"; public const string PLUGIN_NAME = "TerminalApi"; public const string PLUGIN_VERSION = "1.5.1"; } } namespace TerminalApi.Interfaces { internal interface IDelayedAction { internal void Run(); } } namespace TerminalApi.Events { [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] [HarmonyPatch(typeof(Terminal))] public static class Events { public class TerminalEventArgs : EventArgs { public Terminal Terminal { get; set; } } public delegate void TerminalEventHandler(object sender, TerminalEventArgs e); public class TerminalParseSentenceEventArgs : TerminalEventArgs { public TerminalNode ReturnedNode { get; set; } public string SubmittedText { get; set; } } public delegate void TerminalParseSentenceEventHandler(object sender, TerminalParseSentenceEventArgs e); public class TerminalTextChangedEventArgs : TerminalEventArgs { public string NewText; public string CurrentInputText; } public delegate void TerminalTextChangedEventHandler(object sender, TerminalTextChangedEventArgs e); public static event TerminalEventHandler TerminalAwake; public static event TerminalEventHandler TerminalWaking; public static event TerminalEventHandler TerminalStarted; public static event TerminalEventHandler TerminalStarting; public static event TerminalEventHandler TerminalBeginUsing; public static event TerminalEventHandler TerminalBeganUsing; public static event TerminalEventHandler TerminalExited; public static event TerminalParseSentenceEventHandler TerminalParsedSentence; public static event TerminalTextChangedEventHandler TerminalTextChanged; [HarmonyPatch("Awake")] [HarmonyPostfix] public static void Awake(ref Terminal __instance) { TerminalApi.Terminal = __instance; if (TerminalApi.QueuedDelayedActions.Count > 0) { ManualLogSource log = TerminalApi.plugin.Log; if (log != null) { log.LogMessage((object)"In game, applying any changes now."); } foreach (IDelayedAction queuedDelayedAction in TerminalApi.QueuedDelayedActions) { queuedDelayedAction.Run(); } TerminalApi.QueuedDelayedActions.Clear(); } Events.TerminalAwake?.Invoke(__instance, new TerminalEventArgs { Terminal = __instance }); } [HarmonyPatch("BeginUsingTerminal")] [HarmonyPostfix] public static void BeganUsing(ref Terminal __instance) { Events.TerminalBeganUsing?.Invoke(__instance, new TerminalEventArgs { Terminal = __instance }); } [HarmonyPatch("QuitTerminal")] [HarmonyPostfix] public static void OnQuitTerminal(ref Terminal __instance) { Events.TerminalExited?.Invoke(__instance, new TerminalEventArgs { Terminal = __instance }); } [HarmonyPatch("BeginUsingTerminal")] [HarmonyPrefix] public static void OnBeginUsing(ref Terminal __instance) { Events.TerminalBeginUsing?.Invoke(__instance, new TerminalEventArgs { Terminal = __instance }); } [HarmonyPatch("ParsePlayerSentence")] [HarmonyPostfix] public static void ParsePlayerSentence(ref Terminal __instance, TerminalNode __result) { CommandInfo commandInfo = TerminalApi.CommandInfos.FirstOrDefault((CommandInfo cI) => (Object)(object)cI.TriggerNode == (Object)(object)__result); if (commandInfo != null) { __result.displayText = commandInfo?.DisplayTextSupplier(); } string submittedText = __instance.screenText.text.Substring(__instance.screenText.text.Length - __instance.textAdded); Events.TerminalParsedSentence?.Invoke(__instance, new TerminalParseSentenceEventArgs { Terminal = __instance, SubmittedText = submittedText, ReturnedNode = __result }); } [HarmonyPatch("Start")] [HarmonyPostfix] public static void Started(ref Terminal __instance) { Events.TerminalStarted?.Invoke(__instance, new TerminalEventArgs { Terminal = __instance }); } [HarmonyPatch("Start")] [HarmonyPrefix] public static void Starting(ref Terminal __instance) { Events.TerminalStarting?.Invoke(__instance, new TerminalEventArgs { Terminal = __instance }); } [HarmonyPatch("TextChanged")] [HarmonyPostfix] public static void OnTextChanged(ref Terminal __instance, string newText) { string currentInputText = ""; if (newText.Trim().Length >= __instance.textAdded) { currentInputText = newText.Substring(newText.Length - __instance.textAdded); } Events.TerminalTextChanged?.Invoke(__instance, new TerminalTextChangedEventArgs { Terminal = __instance, NewText = newText, CurrentInputText = currentInputText }); } [HarmonyPatch("Awake")] [HarmonyPrefix] public static void Waking(ref Terminal __instance) { Events.TerminalWaking?.Invoke(__instance, new TerminalEventArgs { Terminal = __instance }); } } } namespace TerminalApi.Classes { public class CommandInfo { public string Title { get; set; } public string Category { get; set; } public string Description { get; set; } public TerminalNode TriggerNode { get; set; } public Func<string> DisplayTextSupplier { get; set; } } }
BepInEx/plugins/TVLoader.dll
Decompiled a year agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using HarmonyLib; using TVLoader.Utils; using UnityEngine; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("TVLoader")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TVLoader")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("e59845a7-f2f7-4416-9a61-ca1939ce6e2d")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyVersion("1.0.0.0")] namespace TVLoader { [BepInPlugin("rattenbonkers.TVLoader", "TVLoader", "1.1.1")] public class TVLoaderPlugin : BaseUnityPlugin { private const string MyGUID = "rattenbonkers.TVLoader"; private const string PluginName = "TVLoader"; private const string VersionString = "1.1.1"; private static readonly Harmony Harmony = new Harmony("rattenbonkers.TVLoader"); public static ManualLogSource Log = new ManualLogSource("TVLoader"); private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Harmony.PatchAll(); VideoManager.Load(); ((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("PluginName: {0}, VersionString: {1} is loaded. Video Count: {2}", "TVLoader", "1.1.1", VideoManager.Videos.Count)); } } } namespace TVLoader.Utils { internal static class VideoManager { public static List<string> Videos = new List<string>(); public static void Load() { string[] directories = Directory.GetDirectories(Paths.PluginPath); foreach (string text in directories) { string path = Path.Combine(Paths.PluginPath, text, "Television Videos"); if (Directory.Exists(path)) { string[] files = Directory.GetFiles(path, "*.mp4"); Videos.AddRange(files); TVLoaderPlugin.Log.LogInfo((object)$"{text} has {files.Length} videos."); } } string path2 = Path.Combine(Paths.PluginPath, "Television Videos"); if (!Directory.Exists(path2)) { Directory.CreateDirectory(path2); } string[] files2 = Directory.GetFiles(path2, "*.mp4"); Videos.AddRange(files2); TVLoaderPlugin.Log.LogInfo((object)$"Global has {files2.Length} videos."); TVLoaderPlugin.Log.LogInfo((object)$"Loaded {Videos.Count} total."); } } } namespace TVLoader.Patches { [HarmonyPatch(typeof(TVScript))] internal class TVScriptPatches { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static EventHandler <>9__13_0; internal void <PrepareVideo>b__13_0(VideoPlayer source) { TVLoaderPlugin.Log.LogInfo((object)"Prepared next video!"); } } private static FieldInfo currentClipProperty = typeof(TVScript).GetField("currentClip", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo currentTimeProperty = typeof(TVScript).GetField("currentClipTime", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo wasTvOnLastFrameProp = typeof(TVScript).GetField("wasTvOnLastFrame", BindingFlags.Instance | BindingFlags.NonPublic); private static FieldInfo timeSinceTurningOffTVProp = typeof(TVScript).GetField("timeSinceTurningOffTV", BindingFlags.Instance | BindingFlags.NonPublic); private static MethodInfo setMatMethod = typeof(TVScript).GetMethod("SetTVScreenMaterial", BindingFlags.Instance | BindingFlags.NonPublic); private static MethodInfo onEnableMethod = typeof(TVScript).GetMethod("OnEnable", BindingFlags.Instance | BindingFlags.NonPublic); private static bool tvHasPlayedBefore = false; private static RenderTexture renderTexture; private static VideoPlayer currentVideoPlayer; private static VideoPlayer nextVideoPlayer; [HarmonyPrefix] [HarmonyPatch("Update")] public static bool Update(TVScript __instance) { if ((Object)(object)currentVideoPlayer == (Object)null) { currentVideoPlayer = ((Component)__instance).GetComponent<VideoPlayer>(); renderTexture = currentVideoPlayer.targetTexture; if (VideoManager.Videos.Count > 0) { PrepareVideo(__instance, 0); } } return false; } [HarmonyPrefix] [HarmonyPatch("TurnTVOnOff")] public static bool TurnTVOnOff(TVScript __instance, bool on) { TVLoaderPlugin.Log.LogInfo((object)$"TVOnOff: {on}"); if (VideoManager.Videos.Count == 0) { return false; } int num = (int)currentClipProperty.GetValue(__instance); if (on && tvHasPlayedBefore) { num = (num + 1) % VideoManager.Videos.Count; currentClipProperty.SetValue(__instance, num); } __instance.tvOn = on; if (on) { PlayVideo(__instance); __instance.tvSFX.PlayOneShot(__instance.switchTVOn); WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOn, 1f); } else { __instance.video.Stop(); __instance.tvSFX.PlayOneShot(__instance.switchTVOff); WalkieTalkie.TransmitOneShotAudio(__instance.tvSFX, __instance.switchTVOff, 1f); } setMatMethod.Invoke(__instance, new object[1] { on }); return false; } [HarmonyPrefix] [HarmonyPatch("TVFinishedClip")] public static bool TVFinishedClip(TVScript __instance, VideoPlayer source) { if (!__instance.tvOn || GameNetworkManager.Instance.localPlayerController.isInsideFactory) { return false; } TVLoaderPlugin.Log.LogInfo((object)"TVFinishedClip"); int num = (int)currentClipProperty.GetValue(__instance); if (VideoManager.Videos.Count > 0) { num = (num + 1) % VideoManager.Videos.Count; } currentTimeProperty.SetValue(__instance, 0f); currentClipProperty.SetValue(__instance, num); PlayVideo(__instance); return false; } private static void PrepareVideo(TVScript instance, int index = -1) { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown if (index == -1) { index = (int)currentClipProperty.GetValue(instance) + 1; } if ((Object)(object)nextVideoPlayer != (Object)null && ((Component)nextVideoPlayer).gameObject.activeInHierarchy) { Object.Destroy((Object)(object)nextVideoPlayer); } nextVideoPlayer = ((Component)instance).gameObject.AddComponent<VideoPlayer>(); nextVideoPlayer.playOnAwake = false; nextVideoPlayer.isLooping = false; nextVideoPlayer.source = (VideoSource)1; nextVideoPlayer.controlledAudioTrackCount = 1; nextVideoPlayer.audioOutputMode = (VideoAudioOutputMode)1; nextVideoPlayer.SetTargetAudioSource((ushort)0, instance.tvSFX); nextVideoPlayer.url = "file://" + VideoManager.Videos[index % VideoManager.Videos.Count]; nextVideoPlayer.Prepare(); VideoPlayer obj = nextVideoPlayer; object obj2 = <>c.<>9__13_0; if (obj2 == null) { EventHandler val = delegate { TVLoaderPlugin.Log.LogInfo((object)"Prepared next video!"); }; <>c.<>9__13_0 = val; obj2 = (object)val; } obj.prepareCompleted += (EventHandler)obj2; } private static void PlayVideo(TVScript instance) { tvHasPlayedBefore = true; if (VideoManager.Videos.Count != 0) { if ((Object)(object)nextVideoPlayer != (Object)null) { VideoPlayer val = currentVideoPlayer; instance.video = (currentVideoPlayer = nextVideoPlayer); nextVideoPlayer = null; TVLoaderPlugin.Log.LogInfo((object)$"Destroy {val}"); Object.Destroy((Object)(object)val); onEnableMethod.Invoke(instance, new object[0]); } currentTimeProperty.SetValue(instance, 0f); instance.video.targetTexture = renderTexture; instance.video.Play(); PrepareVideo(instance); } } } }