Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of FunModPackPlxnked v1.0.0
plugins/2018-LC_API/LC_API.dll
Decompiled 2 years 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.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.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using LC_API.BundleAPI; using LC_API.ClientAPI; using LC_API.Comp; using LC_API.Data; using LC_API.Exceptions; using LC_API.Extensions; using LC_API.GameInterfaceAPI; using LC_API.GameInterfaceAPI.Events; using LC_API.GameInterfaceAPI.Events.Cache; using LC_API.GameInterfaceAPI.Events.EventArgs.Player; using LC_API.GameInterfaceAPI.Events.Handlers; using LC_API.GameInterfaceAPI.Features; using LC_API.ManualPatches; using LC_API.Networking; using LC_API.ServerAPI; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Steamworks; using Steamworks.Data; using TMPro; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.InputSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: IgnoresAccessChecksTo("")] [assembly: AssemblyCompany("2018")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Utilities for plugin devs")] [assembly: AssemblyFileVersion("3.3.2.0")] [assembly: AssemblyInformationalVersion("3.3.2+b15ff9853204e171c8e31468a9134b397b67e7e8")] [assembly: AssemblyProduct("Lethal Company API")] [assembly: AssemblyTitle("LC_API")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("3.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 LC_API { internal static class CheatDatabase { private const string SIG_REQ_GUID = "LC_API_ReqGUID"; private const string SIG_SEND_MODS = "LC_APISendMods"; private static Dictionary<string, PluginInfo> PluginsLoaded = new Dictionary<string, PluginInfo>(); public static void RunLocalCheatDetector() { PluginsLoaded = Chainloader.PluginInfos; using Dictionary<string, PluginInfo>.ValueCollection.Enumerator enumerator = PluginsLoaded.Values.GetEnumerator(); while (enumerator.MoveNext()) { switch (enumerator.Current.Metadata.GUID) { case "mikes.lethalcompany.mikestweaks": case "mom.llama.enhancer": case "Posiedon.GameMaster": case "LethalCompanyScalingMaster": case "verity.amberalert": ModdedServer.SetServerModdedOnly(); break; } } } public static void OtherPlayerCheatDetector() { Plugin.Log.LogWarning((object)"Asking all other players for their mod list.."); GameTips.ShowTip("Mod List:", "Asking all other players for installed mods.."); GameTips.ShowTip("Mod List:", "Check the logs for more detailed results.\n<size=13>(Note that if someone doesnt show up on the list, they may not have LC_API installed)</size>"); Network.Broadcast("LC_API_ReqGUID"); } [NetworkMessage("LC_APISendMods", false)] internal static void ReceivedModListHandler(ulong senderId, List<string> mods) { string text = LC_API.GameInterfaceAPI.Features.Player.Get(senderId).Username + " responded with these mods:\n" + string.Join("\n", mods); GameTips.ShowTip("Mod List:", text); Plugin.Log.LogWarning((object)text); } [NetworkMessage("LC_API_ReqGUID", false)] internal static void ReceivedModListHandler(ulong senderId) { List<string> list = new List<string>(); foreach (PluginInfo value in PluginsLoaded.Values) { list.Add(value.Metadata.GUID); } Network.Broadcast("LC_APISendMods", list); } } [BepInPlugin("LC_API", "Lethal Company API", "3.3.2")] public sealed class Plugin : BaseUnityPlugin { internal static ManualLogSource Log; private ConfigEntry<bool> configOverrideModServer; private ConfigEntry<bool> configLegacyAssetLoading; private ConfigEntry<bool> configDisableBundleLoader; internal static ConfigEntry<bool> configVanillaSupport; internal static Harmony Harmony; internal static Plugin Instance { get; private set; } public static bool Initialized { get; private set; } private void Awake() { //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Expected O, but got Unknown //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_028c: Expected O, but got Unknown //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Expected O, but got Unknown //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Expected O, but got Unknown //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02d2: Expected O, but got Unknown //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Expected O, but got Unknown //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_0302: Expected O, but got Unknown //IL_030d: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Expected O, but got Unknown Instance = this; configOverrideModServer = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Force modded server browser", false, "Should the API force you into the modded server browser?"); configLegacyAssetLoading = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Legacy asset bundle loading", false, "Should the BundleLoader use legacy asset loading? Turning this on may help with loading assets from older plugins."); configDisableBundleLoader = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Disable BundleLoader", false, "Should the BundleLoader be turned off? Enable this if you are having problems with mods that load assets using a different method from LC_API's BundleLoader."); configVanillaSupport = ((BaseUnityPlugin)this).Config.Bind<bool>("Compatibility", "Vanilla Compatibility", false, "Allows you to join vanilla servers, but disables many networking-related things and could cause mods to not work properly."); CommandHandler.commandPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Prefix", "/", "Command prefix"); Log = ((BaseUnityPlugin)this).Logger; ((BaseUnityPlugin)this).Logger.LogWarning((object)"\n.____ _________ _____ __________ .___ \r\n| | \\_ ___ \\ / _ \\ \\______ \\| | \r\n| | / \\ \\/ / /_\\ \\ | ___/| | \r\n| |___\\ \\____ / | \\| | | | \r\n|_______ \\\\______ /______\\____|__ /|____| |___| \r\n \\/ \\//_____/ \\/ \r\n "); ((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Starting up.."); if (configOverrideModServer.Value) { ModdedServer.SetServerModdedOnly(); } if (configVanillaSupport.Value) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API is starting with VANILLA SUPPORT ENABLED."); } Harmony = new Harmony("ModAPI"); MethodInfo methodInfo = AccessTools.Method(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyCreated", (Type[])null, (Type[])null); AccessTools.Method(typeof(GameNetworkManager), "LobbyDataIsJoinable", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerPatch), "OnLobbyCreate", (Type[])null, (Type[])null); MethodInfo methodInfo3 = AccessTools.Method(typeof(MenuManager), "Awake", (Type[])null, (Type[])null); MethodInfo methodInfo4 = AccessTools.Method(typeof(ServerPatch), "CacheMenuManager", (Type[])null, (Type[])null); AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); MethodInfo methodInfo5 = AccessTools.Method(typeof(HUDManager), "SubmitChat_performed", (Type[])null, (Type[])null); MethodInfo methodInfo6 = AccessTools.Method(typeof(CommandHandler.SubmitChatPatch), "Transpiler", (Type[])null, (Type[])null); MethodInfo methodInfo7 = AccessTools.Method(typeof(GameNetworkManager), "Awake", (Type[])null, (Type[])null); MethodInfo methodInfo8 = AccessTools.Method(typeof(ServerPatch), "GameNetworkManagerAwake", (Type[])null, (Type[])null); MethodInfo methodInfo9 = AccessTools.Method(typeof(NetworkManager), "StartClient", (Type[])null, (Type[])null); MethodInfo methodInfo10 = AccessTools.Method(typeof(NetworkManager), "StartHost", (Type[])null, (Type[])null); MethodInfo methodInfo11 = AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null); MethodInfo methodInfo12 = AccessTools.Method(typeof(RegisterPatch), "Postfix", (Type[])null, (Type[])null); MethodInfo methodInfo13 = AccessTools.Method(typeof(UnregisterPatch), "Postfix", (Type[])null, (Type[])null); Harmony.Patch((MethodBase)methodInfo3, new HarmonyMethod(methodInfo4), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo6), (HarmonyMethod)null, (HarmonyMethod)null); Harmony.Patch((MethodBase)methodInfo7, new HarmonyMethod(methodInfo8), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Harmony.Patch((MethodBase)methodInfo9, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Harmony.Patch((MethodBase)methodInfo10, (HarmonyMethod)null, new HarmonyMethod(methodInfo12), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Harmony.Patch((MethodBase)methodInfo11, (HarmonyMethod)null, new HarmonyMethod(methodInfo13), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Network.Init(); Events.Patch(Harmony); } internal void Start() { Initialize(); } internal void OnDestroy() { Initialize(); } internal void Initialize() { //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: Expected O, but got Unknown if (!Initialized) { Initialized = true; if (!configDisableBundleLoader.Value) { BundleLoader.Load(configLegacyAssetLoading.Value); } GameObject val = new GameObject("API"); Object.DontDestroyOnLoad((Object)val); val.AddComponent<LC_APIManager>(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"LC_API Started!"); CheatDatabase.RunLocalCheatDetector(); } } internal static void PatchMethodManual(MethodInfo method, MethodInfo patch, Harmony harmony) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown harmony.Patch((MethodBase)method, new HarmonyMethod(patch), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } public static class Utils { public static string ReplaceWithCase(this string input, string toReplace, string replacement) { Dictionary<string, string> map = new Dictionary<string, string> { { toReplace, replacement } }; return input.ReplaceWithCase(map); } public static string ReplaceWithCase(this string input, Dictionary<string, string> map) { string text = input; foreach (KeyValuePair<string, string> item in map) { string key = item.Key; string value = item.Value; text = Regex.Replace(text, key, delegate(Match match) { string value2 = match.Value; char[] array = value2.ToCharArray(); string[] source = value2.Split(' '); bool flag = char.IsUpper(array[0]); bool flag2 = source.All((string w) => char.IsUpper(w[0]) || !char.IsLetter(w[0])); if (array.All((char c) => char.IsUpper(c) || !char.IsLetter(c))) { return value.ToUpper(); } if (flag2) { return Regex.Replace(value, "\\b\\w", (Match charMatch) => charMatch.Value.ToUpper()); } char[] array2 = value.ToCharArray(); array2[0] = (flag ? char.ToUpper(array2[0]) : char.ToLower(array2[0])); return new string(array2); }, RegexOptions.IgnoreCase); } return text; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "LC_API"; public const string PLUGIN_NAME = "Lethal Company API"; public const string PLUGIN_VERSION = "3.3.2"; } } namespace LC_API.ServerAPI { public static class ModdedServer { private static bool moddedOnly; [Obsolete("Use SetServerModdedOnly() instead. This will be removed/private in a future update.")] public static bool setModdedOnly; public static int GameVersion { get; internal set; } public static bool ModdedOnly => moddedOnly; public static void SetServerModdedOnly() { moddedOnly = true; Plugin.Log.LogMessage((object)"A plugin has set your game to only allow you to play with other people who have mods!"); } public static void OnSceneLoaded() { if (Object.op_Implicit((Object)(object)GameNetworkManager.Instance) && ModdedOnly) { GameNetworkManager instance = GameNetworkManager.Instance; instance.gameVersionNum += 16440; setModdedOnly = true; } } } [Obsolete("ServerAPI.Networking is obsolete and will be removed in future versions. Use LC_API.Networking.Network.")] public static class Networking { private sealed class Data<T> { public readonly string Signature; public readonly T Value; public Data(string signature, T value) { Signature = signature; Value = value; } } private const string StringMessageRegistrationName = "LCAPI_NET_LEGACY_STRING"; private const string ListStringMessageRegistrationName = "LCAPI_NET_LEGACY_LISTSTRING"; private const string IntMessageRegistrationName = "LCAPI_NET_LEGACY_INT"; private const string FloatMessageRegistrationName = "LCAPI_NET_LEGACY_FLOAT"; private const string Vector3MessageRegistrationName = "LCAPI_NET_LEGACY_VECTOR3"; private const string SyncVarMessageRegistrationName = "LCAPI_NET_LEGACY_SYNCVAR_SET"; public static Action<string, string> GetString = delegate { }; public static Action<List<string>, string> GetListString = delegate { }; public static Action<int, string> GetInt = delegate { }; public static Action<float, string> GetFloat = delegate { }; public static Action<Vector3, string> GetVector3 = delegate { }; private static Dictionary<string, string> syncStringVars = new Dictionary<string, string>(); public static void Broadcast(string data, string signature) { if (data.Contains("/")) { Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )"); } else { Network.Broadcast("LCAPI_NET_LEGACY_STRING", new Data<string>(signature, data)); } } public static void Broadcast(List<string> data, string signature) { string text = ""; foreach (string datum in data) { if (datum.Contains("/")) { Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( / )"); return; } if (datum.Contains("\n")) { Plugin.Log.LogError((object)"Invalid character in broadcasted string event! ( NewLine )"); return; } text = text + datum + "\n"; } Network.Broadcast("LCAPI_NET_LEGACY_LISTSTRING", new Data<string>(signature, text)); } public static void Broadcast(int data, string signature) { Network.Broadcast("LCAPI_NET_LEGACY_INT", new Data<int>(signature, data)); } public static void Broadcast(float data, string signature) { Network.Broadcast("LCAPI_NET_LEGACY_FLOAT", new Data<float>(signature, data)); } public static void Broadcast(Vector3 data, string signature) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) Network.Broadcast("LCAPI_NET_LEGACY_VECTOR3", new Data<Vector3>(signature, data)); } public static void RegisterSyncVariable(string name) { if (!syncStringVars.ContainsKey(name)) { syncStringVars.Add(name, ""); } else { Plugin.Log.LogError((object)("Cannot register Sync Variable! A Sync Variable has already been registered with name " + name)); } } public static void SetSyncVariable(string name, string value) { if (syncStringVars.ContainsKey(name)) { syncStringVars[name] = value; Broadcast(new List<string> { name, value }, "LCAPI_NET_LEGACY_SYNCVAR_SET"); } else { Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!")); } } private static void SetSyncVariableB(string name, string value) { if (syncStringVars.ContainsKey(name)) { syncStringVars[name] = value; } else { Plugin.Log.LogError((object)("Cannot set the value of Sync Variable " + name + " as it is not registered!")); } } internal static void LCAPI_NET_SYNCVAR_SET(List<string> list, string arg2) { if (arg2 == "LCAPI_NET_LEGACY_SYNCVAR_SET") { SetSyncVariableB(list[0], list[1]); } } public static string GetSyncVariable(string name) { if (syncStringVars.ContainsKey(name)) { return syncStringVars[name]; } Plugin.Log.LogError((object)("Cannot get the value of Sync Variable " + name + " as it is not registered!")); return ""; } internal static void InitializeLegacyNetworking() { GetListString = (Action<List<string>, string>)Delegate.Combine(GetListString, new Action<List<string>, string>(LCAPI_NET_SYNCVAR_SET)); Network.RegisterMessage("LCAPI_NET_LEGACY_STRING", relayToSelf: false, delegate(ulong senderId, Data<string> data) { GetString(data.Value, data.Signature); }); Network.RegisterMessage("LCAPI_NET_LEGACY_LISTSTRING", relayToSelf: false, delegate(ulong senderId, Data<string> data) { GetListString(data.Value.Split('\n').ToList(), data.Signature); }); Network.RegisterMessage("LCAPI_NET_LEGACY_INT", relayToSelf: false, delegate(ulong senderId, Data<int> data) { GetInt(data.Value, data.Signature); }); Network.RegisterMessage("LCAPI_NET_LEGACY_FLOAT", relayToSelf: false, delegate(ulong senderId, Data<float> data) { GetFloat(data.Value, data.Signature); }); Network.RegisterMessage("LCAPI_NET_LEGACY_VECTOR3", relayToSelf: false, delegate(ulong senderId, Data<Vector3> data) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) GetVector3(data.Value, data.Signature); }); } } } namespace LC_API.Networking { public static class Network { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static HandleNamedMessageDelegate <>9__35_2; public static Events.CustomEventHandler <>9__35_0; public static Events.CustomEventHandler <>9__35_1; internal void <Init>b__35_0() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown StartedNetworking = true; if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager; object obj = <>9__35_2; if (obj == null) { HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader) { //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_003d: 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_0059: Unknown result type (might be due to invalid IL or missing references) byte[] bytes = default(byte[]); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives)); NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>(); networkMessageWrapper.Sender = senderClientId; byte[] array = networkMessageWrapper.ToBytes(); FastBufferWriter val2 = default(FastBufferWriter); ((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1); try { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)4); } finally { ((IDisposable)(FastBufferWriter)(ref val2)).Dispose(); } }; <>9__35_2 = val; obj = (object)val; } customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj); } RegisterAllMessages(); } internal void <Init>b__35_2(ulong senderClientId, FastBufferReader reader) { //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_003d: 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_0059: Unknown result type (might be due to invalid IL or missing references) byte[] bytes = default(byte[]); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives)); NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>(); networkMessageWrapper.Sender = senderClientId; byte[] array = networkMessageWrapper.ToBytes(); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val, (NetworkDelivery)4); } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } internal void <Init>b__35_1() { StartedNetworking = false; if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE"); } UnregisterAllMessages(); } } internal const string MESSAGE_RELAY_UNIQUE_NAME = "LC_API_RELAY_MESSAGE"; private static MethodInfo _registerInfo = null; private static MethodInfo _registerInfoGeneric = null; internal static Dictionary<string, NetworkMessageFinalizerBase> NetworkMessageFinalizers { get; } = new Dictionary<string, NetworkMessageFinalizerBase>(); internal static bool StartedNetworking { get; set; } = false; internal static MethodInfo RegisterInfo { get { if (_registerInfo == null) { MethodInfo[] methods = typeof(Network).GetMethods(); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name == "RegisterMessage" && !methodInfo.IsGenericMethod) { _registerInfo = methodInfo; break; } } } return _registerInfo; } } internal static MethodInfo RegisterInfoGeneric { get { if (_registerInfo == null) { MethodInfo[] methods = typeof(Network).GetMethods(); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name == "RegisterMessage" && methodInfo.IsGenericMethod) { _registerInfoGeneric = methodInfo; break; } } } return _registerInfoGeneric; } } public static event Events.CustomEventHandler RegisterNetworkMessages; internal static event Events.CustomEventHandler UnregisterNetworkMessages; internal static byte[] ToBytes(this object @object) { if (@object == null) { return null; } return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@object)); } internal static T ToObject<T>(this byte[] bytes) where T : class { return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes)); } internal static void OnRegisterNetworkMessages() { Network.RegisterNetworkMessages.InvokeSafely(); } internal static void OnUnregisterNetworkMessages() { Network.UnregisterNetworkMessages.InvokeSafely(); } internal static void RegisterAllMessages() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown foreach (NetworkMessageFinalizerBase value in NetworkMessageFinalizers.Values) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(value.UniqueName, new HandleNamedMessageDelegate(value.Read)); } } internal static void UnregisterAllMessages() { foreach (string key in NetworkMessageFinalizers.Keys) { UnregisterMessage(key, andRemoveHandler: false); } } public static void RegisterAll() { Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly); for (int i = 0; i < typesFromAssembly.Length; i++) { RegisterAll(typesFromAssembly[i]); } } public static void RegisterAll(Type type) { if (!type.IsClass) { return; } NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>(); if (customAttribute != null) { if (type.BaseType.Name == "NetworkMessageHandler`1") { Type type2 = type.BaseType.GetGenericArguments()[0]; RegisterInfoGeneric.MakeGenericMethod(type2).Invoke(null, new object[3] { customAttribute.UniqueName, customAttribute.RelayToSelf, type.GetMethod("Handler").CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), type2), Activator.CreateInstance(type)) }); } else if (type.BaseType.Name == "NetworkMessageHandler") { RegisterInfo.Invoke(null, new object[3] { customAttribute.UniqueName, customAttribute.RelayToSelf, type.GetMethod("Handler").CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong)), Activator.CreateInstance(type)) }); } return; } MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { customAttribute = methodInfo.GetCustomAttribute<NetworkMessage>(); if (customAttribute != null) { if (!methodInfo.IsStatic) { throw new Exception("Detected NetworkMessage attribute on non-static method. All NetworkMessages on methods must be static."); } if (methodInfo.GetParameters().Length == 1) { RegisterInfo.Invoke(null, new object[3] { customAttribute.UniqueName, customAttribute.RelayToSelf, methodInfo.CreateDelegate(typeof(Action<>).MakeGenericType(typeof(ulong))) }); } else { Type parameterType = methodInfo.GetParameters()[1].ParameterType; RegisterInfoGeneric.MakeGenericMethod(parameterType).Invoke(null, new object[3] { customAttribute.UniqueName, customAttribute.RelayToSelf, methodInfo.CreateDelegate(typeof(Action<, >).MakeGenericType(typeof(ulong), parameterType)) }); } } } } public static void UnregisterAll(bool andRemoveHandler = true) { Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly); for (int i = 0; i < typesFromAssembly.Length; i++) { UnregisterAll(typesFromAssembly[i], andRemoveHandler); } } public static void UnregisterAll(Type type, bool andRemoveHandler = true) { if (!type.IsClass) { return; } NetworkMessage customAttribute = type.GetCustomAttribute<NetworkMessage>(); if (customAttribute != null) { UnregisterMessage(customAttribute.UniqueName, andRemoveHandler); return; } MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < methods.Length; i++) { customAttribute = methods[i].GetCustomAttribute<NetworkMessage>(); if (customAttribute != null) { UnregisterMessage(customAttribute.UniqueName, andRemoveHandler); } } } public static void RegisterMessage<T>(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived) where T : class { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown if (NetworkMessageFinalizers.ContainsKey(uniqueName)) { throw new Exception(uniqueName + " already registered"); } NetworkMessageFinalizer<T> networkMessageFinalizer = new NetworkMessageFinalizer<T>(uniqueName, relayToSelf, onReceived); NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer); if (StartedNetworking) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read)); } } public static void RegisterMessage(string uniqueName, bool relayToSelf, Action<ulong> onReceived) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown if (NetworkMessageFinalizers.ContainsKey(uniqueName)) { throw new Exception(uniqueName + " already registered"); } NetworkMessageFinalizer networkMessageFinalizer = new NetworkMessageFinalizer(uniqueName, relayToSelf, onReceived); NetworkMessageFinalizers.Add(uniqueName, networkMessageFinalizer); if (StartedNetworking) { NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(uniqueName, new HandleNamedMessageDelegate(networkMessageFinalizer.Read)); } } public static void UnregisterMessage(string uniqueName, bool andRemoveHandler = true) { if ((!andRemoveHandler && NetworkMessageFinalizers.ContainsKey(uniqueName)) || (andRemoveHandler && NetworkMessageFinalizers.Remove(uniqueName))) { NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(uniqueName); } } public static void Broadcast<T>(string uniqueName, T @object) where T : class { if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value)) { if (!(value is NetworkMessageFinalizer<T> networkMessageFinalizer)) { throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!"); } networkMessageFinalizer.Send(@object); } } public static void Broadcast(string uniqueName) { if (NetworkMessageFinalizers.TryGetValue(uniqueName, out var value)) { if (!(value is NetworkMessageFinalizer networkMessageFinalizer)) { throw new Exception("Network handler for " + uniqueName + " was not broadcast with the right type!"); } networkMessageFinalizer.Send(); } } internal static void Init() { RegisterNetworkMessages += delegate { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown StartedNetworking = true; if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { CustomMessagingManager customMessagingManager = NetworkManager.Singleton.CustomMessagingManager; object obj = <>c.<>9__35_2; if (obj == null) { HandleNamedMessageDelegate val = delegate(ulong senderClientId, FastBufferReader reader) { //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_003d: 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_0059: Unknown result type (might be due to invalid IL or missing references) byte[] bytes = default(byte[]); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives)); NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>(); networkMessageWrapper.Sender = senderClientId; byte[] array = networkMessageWrapper.ToBytes(); FastBufferWriter val2 = default(FastBufferWriter); ((FastBufferWriter)(ref val2))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1); try { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(array, default(ForPrimitives)); NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(networkMessageWrapper.UniqueName, val2, (NetworkDelivery)4); } finally { ((IDisposable)(FastBufferWriter)(ref val2)).Dispose(); } }; <>c.<>9__35_2 = val; obj = (object)val; } customMessagingManager.RegisterNamedMessageHandler("LC_API_RELAY_MESSAGE", (HandleNamedMessageDelegate)obj); } RegisterAllMessages(); }; UnregisterNetworkMessages += delegate { StartedNetworking = false; if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler("LC_API_RELAY_MESSAGE"); } UnregisterAllMessages(); }; SetupNetworking(); RegisterAll(); LC_API.ServerAPI.Networking.InitializeLegacyNetworking(); } internal static void SetupNetworking() { Type[] types = Assembly.GetExecutingAssembly().GetTypes(); for (int i = 0; i < types.Length; i++) { MethodInfo[] methods = types[i].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); } } } } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class NetworkMessage : Attribute { public string UniqueName { get; } public bool RelayToSelf { get; } public NetworkMessage(string uniqueName, bool relayToSelf = false) { UniqueName = uniqueName; RelayToSelf = relayToSelf; } } public abstract class NetworkMessageHandler<T> where T : class { public abstract void Handler(ulong sender, T message); } public abstract class NetworkMessageHandler { public abstract void Handler(ulong sender); } internal abstract class NetworkMessageFinalizerBase { internal abstract string UniqueName { get; } internal abstract bool RelayToSelf { get; } public abstract void Read(ulong sender, FastBufferReader reader); } internal class NetworkMessageFinalizer : NetworkMessageFinalizerBase { internal override string UniqueName { get; } internal override bool RelayToSelf { get; } internal Action<ulong> OnReceived { get; } public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong> onReceived) { UniqueName = uniqueName; RelayToSelf = relayToSelf; OnReceived = onReceived; } public void Send() { //IL_005d: 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_0091: 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) if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { ((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater()); return; } byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId).ToBytes(); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives)); if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost) { NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4); } else { NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4); } } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } public override void Read(ulong fakeSender, FastBufferReader reader) { //IL_0021: 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) if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { ((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader)); return; } byte[] bytes = default(byte[]); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives)); NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>(); if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender) { OnReceived(networkMessageWrapper.Sender); } } private IEnumerator SendLater() { int timesWaited = 0; while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { yield return (object)new WaitForSeconds(0.1f); timesWaited++; if (timesWaited % 20 == 0) { Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}"); } if (timesWaited >= 100) { Plugin.Log.LogError((object)"Dropping network message"); yield return null; } } Send(); } private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader) { //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) int timesWaited = 0; while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { yield return (object)new WaitForSeconds(0.1f); timesWaited++; if (timesWaited % 20 == 0) { Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}"); } if (timesWaited >= 100) { Plugin.Log.LogError((object)"Dropping network message"); yield return null; } } Read(fakeSender, reader); } } internal class NetworkMessageFinalizer<T> : NetworkMessageFinalizerBase where T : class { internal override string UniqueName { get; } internal override bool RelayToSelf { get; } internal Action<ulong, T> OnReceived { get; } public NetworkMessageFinalizer(string uniqueName, bool relayToSelf, Action<ulong, T> onReceived) { UniqueName = uniqueName; RelayToSelf = relayToSelf; OnReceived = onReceived; } public void Send(T obj) { //IL_0069: 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_009d: 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) if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { ((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(SendLater(obj)); return; } byte[] array = new NetworkMessageWrapper(UniqueName, LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId, obj.ToBytes()).ToBytes(); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(FastBufferWriter.GetWriteSize<byte>(array, -1, 0), (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(array, default(ForPrimitives)); if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost) { NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(UniqueName, val, (NetworkDelivery)4); } else { NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("LC_API_RELAY_MESSAGE", LC_API.GameInterfaceAPI.Features.Player.HostPlayer.ClientId, val, (NetworkDelivery)4); } } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } public override void Read(ulong fakeSender, FastBufferReader reader) { //IL_0021: 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) if ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { ((MonoBehaviour)NetworkManager.Singleton).StartCoroutine(ReadLater(fakeSender, reader)); return; } byte[] bytes = default(byte[]); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref bytes, default(ForPrimitives)); NetworkMessageWrapper networkMessageWrapper = bytes.ToObject<NetworkMessageWrapper>(); if (RelayToSelf || LC_API.GameInterfaceAPI.Features.Player.LocalPlayer.ClientId != networkMessageWrapper.Sender) { OnReceived(networkMessageWrapper.Sender, networkMessageWrapper.Message.ToObject<T>()); } } private IEnumerator SendLater(T obj) { int timesWaited = 0; while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { yield return (object)new WaitForSeconds(0.1f); timesWaited++; if (timesWaited % 20 == 0) { Plugin.Log.LogWarning((object)$"Waiting to send network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}"); } if (timesWaited >= 100) { Plugin.Log.LogError((object)"Dropping network message"); yield return null; } } Send(obj); } private IEnumerator ReadLater(ulong fakeSender, FastBufferReader reader) { //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) int timesWaited = 0; while ((Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null || (Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null) { yield return (object)new WaitForSeconds(0.1f); timesWaited++; if (timesWaited % 20 == 0) { Plugin.Log.LogWarning((object)$"Waiting to read network message. Waiting on host?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.HostPlayer == (Object)null} Waiting on local player?: {(Object)(object)LC_API.GameInterfaceAPI.Features.Player.LocalPlayer == (Object)null}"); } if (timesWaited >= 100) { Plugin.Log.LogError((object)"Dropping network message"); yield return null; } } Read(fakeSender, reader); } } internal class NetworkMessageWrapper { public string UniqueName { get; set; } public ulong Sender { get; set; } public byte[] Message { get; set; } internal NetworkMessageWrapper(string uniqueName, ulong sender) { UniqueName = uniqueName; Sender = sender; } internal NetworkMessageWrapper(string uniqueName, ulong sender, byte[] message) { UniqueName = uniqueName; Sender = sender; Message = message; } internal NetworkMessageWrapper() { } } internal static class RegisterPatch { internal static void Postfix() { Network.OnRegisterNetworkMessages(); } } internal static class UnregisterPatch { internal static void Postfix() { Network.OnUnregisterNetworkMessages(); } } } namespace LC_API.Networking.Serializers { public struct Vector2S { private Vector2? v2; public float x { get; set; } public float y { get; set; } [JsonIgnore] public Vector2 vector2 { get { //IL_002f: 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 (!v2.HasValue) { v2 = new Vector2(x, y); } return v2.Value; } } public Vector2S(float x, float y) { v2 = null; this.x = x; this.y = y; } public static implicit operator Vector2(Vector2S vector2S) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return vector2S.vector2; } public static implicit operator Vector2S(Vector2 vector2) { //IL_0000: 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) return new Vector2S(vector2.x, vector2.y); } } public struct Vector2IntS { private Vector2Int? v2; public int x { get; set; } public int y { get; set; } [JsonIgnore] public Vector2Int vector2 { get { //IL_002f: 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 (!v2.HasValue) { v2 = new Vector2Int(x, y); } return v2.Value; } } public Vector2IntS(int x, int y) { v2 = null; this.x = x; this.y = y; } public static implicit operator Vector2Int(Vector2IntS vector2S) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return vector2S.vector2; } public static implicit operator Vector2IntS(Vector2Int vector2) { return new Vector2IntS(((Vector2Int)(ref vector2)).x, ((Vector2Int)(ref vector2)).y); } } public struct Vector3S { private Vector3? v3; public float x { get; set; } public float y { get; set; } public float z { get; set; } [JsonIgnore] public Vector3 vector3 { get { //IL_0035: 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) if (!v3.HasValue) { v3 = new Vector3(x, y, z); } return v3.Value; } } public Vector3S(float x, float y, float z) { v3 = null; this.x = x; this.y = y; this.z = z; } public static implicit operator Vector3(Vector3S vector3S) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return vector3S.vector3; } public static implicit operator Vector3S(Vector3 vector3) { //IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references) return new Vector3S(vector3.x, vector3.y, vector3.z); } } public struct Vector3IntS { private Vector3Int? v3; public int x { get; set; } public int y { get; set; } public int z { get; set; } [JsonIgnore] public Vector3Int vector3 { get { //IL_0035: 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) if (!v3.HasValue) { v3 = new Vector3Int(x, y, z); } return v3.Value; } } public Vector3IntS(int x, int y, int z) { v3 = null; this.x = x; this.y = y; this.z = z; } public static implicit operator Vector3Int(Vector3IntS vector3S) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return vector3S.vector3; } public static implicit operator Vector3IntS(Vector3Int vector3) { return new Vector3IntS(((Vector3Int)(ref vector3)).x, ((Vector3Int)(ref vector3)).y, ((Vector3Int)(ref vector3)).z); } } public struct Vector4S { private Vector4? v4; public float x { get; set; } public float y { get; set; } public float z { get; set; } public float w { get; set; } [JsonIgnore] public Vector4 Vector4 { get { //IL_003b: 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) if (!v4.HasValue) { v4 = new Vector4(x, y, z, w); } return v4.Value; } } public Vector4S(float x, float y, float z, float w) { v4 = null; this.x = x; this.y = y; this.z = z; this.w = w; } public static implicit operator Vector4(Vector4S vector4S) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return vector4S.Vector4; } public static implicit operator Vector4S(Vector4 vector4) { //IL_0000: 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_000c: 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) return new Vector4S(vector4.x, vector4.y, vector4.z, vector4.w); } } public struct QuaternionS { private Quaternion? q; public float x { get; set; } public float y { get; set; } public float z { get; set; } public float w { get; set; } [JsonIgnore] public Quaternion Quaternion { get { //IL_003b: 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) if (!q.HasValue) { q = new Quaternion(x, y, z, w); } return q.Value; } } public QuaternionS(float x, float y, float z, float w) { q = null; this.x = x; this.y = y; this.z = z; this.w = w; } public static implicit operator Quaternion(QuaternionS quaternionS) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return quaternionS.Quaternion; } public static implicit operator QuaternionS(Quaternion quaternion) { //IL_0000: 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_000c: 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) return new QuaternionS(quaternion.x, quaternion.y, quaternion.z, quaternion.w); } } public struct ColorS { private Color? c; public float r { get; set; } public float g { get; set; } public float b { get; set; } public float a { get; set; } [JsonIgnore] public Color Color { get { //IL_003b: 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) if (!c.HasValue) { c = new Color(r, g, b, a); } return c.Value; } } public ColorS(float r, float g, float b, float a) { c = null; this.r = r; this.g = g; this.b = b; this.a = a; } public static implicit operator Color(ColorS colorS) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return colorS.Color; } public static implicit operator ColorS(Color color) { //IL_0000: 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_000c: 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) return new ColorS(color.r, color.g, color.b, color.a); } } public struct Color32S { private Color32? c; public byte r { get; set; } public byte g { get; set; } public byte b { get; set; } public byte a { get; set; } [JsonIgnore] public Color32 Color { get { //IL_003b: 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) if (!c.HasValue) { c = new Color32(r, g, b, a); } return c.Value; } } public Color32S(byte r, byte g, byte b, byte a) { c = null; this.r = r; this.g = g; this.b = b; this.a = a; } public static implicit operator Color32(Color32S colorS) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return colorS.Color; } public static implicit operator Color32S(Color32 color) { //IL_0000: 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_000c: 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) return new Color32S(color.r, color.g, color.b, color.a); } } public struct RayS { private Ray? r; public Vector3S origin { get; set; } public Vector3S direction { get; set; } [JsonIgnore] public Ray Ray { get { //IL_0039: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (!r.HasValue) { r = new Ray((Vector3)origin, (Vector3)direction); } return r.Value; } } public RayS(Vector3 origin, Vector3 direction) { //IL_000d: 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) r = null; this.origin = origin; this.direction = direction; } public static implicit operator Ray(RayS rayS) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return rayS.Ray; } public static implicit operator RayS(Ray ray) { //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) return new RayS(((Ray)(ref ray)).origin, ((Ray)(ref ray)).direction); } } public struct Ray2DS { private Ray2D? r; public Vector2S origin { get; set; } public Vector2S direction { get; set; } [JsonIgnore] public Ray2D Ray { get { //IL_0039: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (!r.HasValue) { r = new Ray2D((Vector2)origin, (Vector2)direction); } return r.Value; } } public Ray2DS(Vector2 origin, Vector2 direction) { //IL_000d: 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) r = null; this.origin = origin; this.direction = direction; } public static implicit operator Ray2D(Ray2DS ray2DS) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return ray2DS.Ray; } public static implicit operator Ray2DS(Ray2D ray2D) { //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) return new Ray2DS(((Ray2D)(ref ray2D)).origin, ((Ray2D)(ref ray2D)).direction); } } } namespace LC_API.ManualPatches { internal static class ServerPatch { internal static bool OnLobbyCreate(GameNetworkManager __instance, Result result, Lobby lobby) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0009: Unknown result type (might be due to invalid IL or missing references) if ((int)result != 1) { Debug.LogError((object)$"Lobby could not be created! {result}", (Object)(object)__instance); } __instance.lobbyHostSettings.lobbyName = "[MODDED]" + __instance.lobbyHostSettings.lobbyName.ToString(); Plugin.Log.LogMessage((object)"server pre-setup success"); return true; } internal static bool CacheMenuManager(MenuManager __instance) { LC_APIManager.MenuManager = __instance; return true; } internal static bool ChatCommands(HUDManager __instance, CallbackContext context) { if (__instance.chatTextField.text.ToLower().Contains("/modcheck")) { CheatDatabase.OtherPlayerCheatDetector(); return false; } return true; } internal static void GameNetworkManagerAwake(GameNetworkManager __instance) { if ((Object)(object)GameNetworkManager.Instance == (Object)null) { ModdedServer.GameVersion = __instance.gameVersionNum; } } } } namespace LC_API.GameInterfaceAPI { public static class GameState { private static readonly Action NothingAction = delegate { }; public static int AlivePlayerCount { get; private set; } public static ShipState ShipState { get; private set; } public static event Action PlayerDied; public static event Action LandOnMoon; public static event Action WentIntoOrbit; public static event Action ShipStartedLeaving; internal static void GSUpdate() { if (!((Object)(object)StartOfRound.Instance == (Object)null)) { if (StartOfRound.Instance.shipHasLanded && ShipState != ShipState.OnMoon) { ShipState = ShipState.OnMoon; GameState.LandOnMoon.InvokeActionSafe(); } if (StartOfRound.Instance.inShipPhase && ShipState != 0) { ShipState = ShipState.InOrbit; GameState.WentIntoOrbit.InvokeActionSafe(); } if (StartOfRound.Instance.shipIsLeaving && ShipState != ShipState.LeavingMoon) { ShipState = ShipState.LeavingMoon; GameState.ShipStartedLeaving.InvokeActionSafe(); } if (AlivePlayerCount < StartOfRound.Instance.livingPlayers) { GameState.PlayerDied.InvokeActionSafe(); } AlivePlayerCount = StartOfRound.Instance.livingPlayers; } } static GameState() { GameState.PlayerDied = NothingAction; GameState.LandOnMoon = NothingAction; GameState.WentIntoOrbit = NothingAction; GameState.ShipStartedLeaving = NothingAction; } } public class GameTips { private static List<string> tipHeaders = new List<string>(); private static List<string> tipBodys = new List<string>(); private static float lastMessageTime; public static void ShowTip(string header, string body) { tipHeaders.Add(header); tipBodys.Add(body); } public static void UpdateInternal() { lastMessageTime -= Time.deltaTime; if ((tipHeaders.Count > 0) & (lastMessageTime < 0f)) { lastMessageTime = 5f; if ((Object)(object)HUDManager.Instance != (Object)null) { HUDManager.Instance.DisplayTip(tipHeaders[0], tipBodys[0], false, false, "LC_Tip1"); } tipHeaders.RemoveAt(0); tipBodys.RemoveAt(0); } } } } namespace LC_API.GameInterfaceAPI.Features { public class Item : NetworkBehaviour { private bool hasNewProps; internal static GameObject ItemNetworkPrefab { get; set; } public static Dictionary<GrabbableObject, Item> Dictionary { get; } = new Dictionary<GrabbableObject, Item>(); public static IReadOnlyCollection<Item> List => Dictionary.Values; public GrabbableObject GrabbableObject { get; private set; } public Item ItemProperties => GrabbableObject.itemProperties; public ScanNodeProperties ScanNodeProperties { get; set; } public bool IsHeld => GrabbableObject.isHeld; public bool IsTwoHanded => ItemProperties.twoHanded; public Player Holder { get { if (!IsHeld) { return null; } if (!Player.Dictionary.TryGetValue(GrabbableObject.playerHeldBy, out var value)) { return null; } return value; } } public string Name { get { return ItemProperties.itemName; } set { if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to set item name on client."); } string oldName = ItemProperties.itemName.ToLower(); CloneProperties(); ItemProperties.itemName = value; OverrideTooltips(oldName, value.ToLower()); ScanNodeProperties.headerText = value; SetGrabbableNameClientRpc(value); } } public Vector3 Position { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ((Component)GrabbableObject).transform.position; } set { //IL_0029: 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) //IL_0036: 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_004d: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to set item position on client."); } GrabbableObject.startFallingPosition = value; GrabbableObject.targetFloorPosition = value; ((Component)GrabbableObject).transform.position = value; SetItemPositionClientRpc(value); } } public Quaternion Rotation { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ((Component)GrabbableObject).transform.rotation; } set { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ((Component)GrabbableObject).transform.rotation = value; } } public Vector3 Scale { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ((Component)GrabbableObject).transform.localScale; } set { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ((Component)GrabbableObject).transform.localScale = value; } } public bool IsScrap { get { return ItemProperties.isScrap; } set { if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to set item name on client."); } CloneProperties(); ItemProperties.isScrap = value; SetIsScrapClientRpc(value); } } public int ScrapValue { get { return GrabbableObject.scrapValue; } set { if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to set scrap value on client."); } GrabbableObject.SetScrapValue(value); SetScrapValueClientRpc(value); } } [ClientRpc] private void SetGrabbableNameClientRpc(string name) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: 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_00ba: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(66243798u, val, (RpcDelivery)0); bool flag = name != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(name, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 66243798u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { string oldName = ItemProperties.itemName.ToLower(); CloneProperties(); ItemProperties.itemName = name; OverrideTooltips(oldName, name.ToLower()); ScanNodeProperties.headerText = name; } } private void OverrideTooltips(string oldName, string newName) { for (int i = 0; i < ItemProperties.toolTips.Length; i++) { ItemProperties.toolTips[i] = ItemProperties.toolTips[i].ReplaceWithCase(oldName, newName); } if (IsHeld && (Object)(object)Holder == (Object)(object)Player.LocalPlayer) { GrabbableObject.SetControlTipsForItem(); } } [ClientRpc] private void SetItemPositionClientRpc(Vector3 pos) { //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_00ce: 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_00da: 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_00eb: 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(949135576u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref pos); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 949135576u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { GrabbableObject.startFallingPosition = pos; GrabbableObject.targetFloorPosition = pos; ((Component)GrabbableObject).transform.position = pos; } } } public void SetAndSyncRotation(Quaternion rotation) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to sync item rotation from client."); } SetItemRotationClientRpc(rotation); } [ClientRpc] private void SetItemRotationClientRpc(Quaternion rotation) { //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_00c9: 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(1528367091u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref rotation); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1528367091u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Rotation = rotation; } } } public void SetAndSyncScale(Vector3 scale) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to sync item scale from client."); } SetItemScaleClientRpc(scale); } [ClientRpc] private void SetItemScaleClientRpc(Vector3 scale) { //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_00c9: 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(2688253945u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe(ref scale); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2688253945u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Scale = scale; } } } [ClientRpc] private void SetIsScrapClientRpc(bool isScrap) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: 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_007d: 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_0097: 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(4227417717u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref isScrap, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 4227417717u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { CloneProperties(); ItemProperties.isScrap = isScrap; } } } [ClientRpc] private void SetScrapValueClientRpc(int scrapValue) { //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)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3866863385u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, scrapValue); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3866863385u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { GrabbableObject.SetScrapValue(scrapValue); } } } public void RemoveFromHolder(Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion)) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to remove item from player on client."); } if (IsHeld) { ((NetworkBehaviour)this).NetworkObject.RemoveOwnership(); Holder.Inventory.RemoveItem(this); RemoveFromHolderClientRpc(); Position = position; Rotation = rotation; } } [ClientRpc] private void RemoveFromHolderClientRpc() { //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(1050513218u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1050513218u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && IsHeld) { Holder.Inventory.RemoveItem(this); } } } public void EnablePhysics(bool enable) { GrabbableObject.EnablePhysics(enable); } public void EnableMeshes(bool enable) { GrabbableObject.EnableItemMeshes(enable); } public void FallToGround(bool randomizePosition = false) { GrabbableObject.FallToGround(randomizePosition); } public bool PocketItem() { if (!IsHeld || (Object)(object)Holder.HeldItem != (Object)(object)this || IsTwoHanded) { return false; } GrabbableObject.PocketItem(); return true; } public bool GiveTo(Player player, bool switchTo = true) { if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to give item to player on client."); } return player.Inventory.TryAddItem(this, switchTo); } public void InitializeScrap() { if (RoundManager.Instance.AnomalyRandom != null) { InitializeScrap((int)((float)RoundManager.Instance.AnomalyRandom.Next(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier)); } else { InitializeScrap((int)((float)Random.Range(ItemProperties.minValue, ItemProperties.maxValue) * RoundManager.Instance.scrapValueMultiplier)); } } public void InitializeScrap(int scrapValue) { if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to initialize scrap on client."); } ScrapValue = scrapValue; InitializeScrapClientRpc(); } [ClientRpc] private void InitializeScrapClientRpc() { //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)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1334565671u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1334565671u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } MeshFilter val3 = default(MeshFilter); if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshFilter>(ref val3) && ItemProperties.meshVariants != null && ItemProperties.meshVariants.Length != 0) { if (RoundManager.Instance.ScrapValuesRandom != null) { val3.mesh = ItemProperties.meshVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.meshVariants.Length)]; } else { val3.mesh = ItemProperties.meshVariants[0]; } } MeshRenderer val4 = default(MeshRenderer); if (((Component)GrabbableObject).gameObject.TryGetComponent<MeshRenderer>(ref val4) && ItemProperties.materialVariants != null && ItemProperties.materialVariants.Length != 0) { if (RoundManager.Instance.ScrapValuesRandom != null) { ((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[RoundManager.Instance.ScrapValuesRandom.Next(ItemProperties.materialVariants.Length)]; } else { ((Renderer)val4).sharedMaterial = ItemProperties.materialVariants[0]; } } } public static Item CreateAndSpawnItem(string itemName, bool andInitialize = true, Vector3 position = default(Vector3), Quaternion rotation = default(Quaternion)) { //IL_006c: 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) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to create and spawn item on client."); } string name = itemName.ToLower(); GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab; if ((Object)(object)val != (Object)null) { GameObject obj = Object.Instantiate<GameObject>(val, position, rotation); obj.GetComponent<NetworkObject>().Spawn(false); Item component = obj.GetComponent<Item>(); if (component.IsScrap && andInitialize) { component.InitializeScrap(); } return component; } return null; } public static Item CreateAndGiveItem(string itemName, Player player, bool andInitialize = true, bool switchTo = true) { //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to create and give item on client."); } string name = itemName.ToLower(); GameObject val = ((IEnumerable<Item>)StartOfRound.Instance.allItemsList.itemsList).FirstOrDefault((Func<Item, bool>)((Item i) => i.itemName.ToLower().Contains(name)))?.spawnPrefab; if ((Object)(object)val != (Object)null) { GameObject obj = Object.Instantiate<GameObject>(val, Vector3.zero, default(Quaternion)); obj.GetComponent<NetworkObject>().Spawn(false); Item component = obj.GetComponent<Item>(); if (component.IsScrap && andInitialize) { component.InitializeScrap(); } component.GiveTo(player, switchTo); return component; } return null; } private void Awake() { GrabbableObject = ((Component)this).GetComponent<GrabbableObject>(); ScanNodeProperties = ((Component)GrabbableObject).gameObject.GetComponentInChildren<ScanNodeProperties>(); Dictionary.Add(GrabbableObject, this); } private void CloneProperties() { Item itemProperties = Object.Instantiate<Item>(ItemProperties); if (hasNewProps) { Object.Destroy((Object)(object)ItemProperties); } GrabbableObject.itemProperties = itemProperties; hasNewProps = true; } public override void OnDestroy() { Dictionary.Remove(GrabbableObject); ((NetworkBehaviour)this).OnDestroy(); } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_Item() { //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 //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(66243798u, new RpcReceiveHandler(__rpc_handler_66243798)); NetworkManager.__rpc_func_table.Add(949135576u, new RpcReceiveHandler(__rpc_handler_949135576)); NetworkManager.__rpc_func_table.Add(1528367091u, new RpcReceiveHandler(__rpc_handler_1528367091)); NetworkManager.__rpc_func_table.Add(2688253945u, new RpcReceiveHandler(__rpc_handler_2688253945)); NetworkManager.__rpc_func_table.Add(4227417717u, new RpcReceiveHandler(__rpc_handler_4227417717)); NetworkManager.__rpc_func_table.Add(3866863385u, new RpcReceiveHandler(__rpc_handler_3866863385)); NetworkManager.__rpc_func_table.Add(1050513218u, new RpcReceiveHandler(__rpc_handler_1050513218)); NetworkManager.__rpc_func_table.Add(1334565671u, new RpcReceiveHandler(__rpc_handler_1334565671)); } private static void __rpc_handler_66243798(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string grabbableNameClientRpc = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref grabbableNameClientRpc, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((Item)(object)target).SetGrabbableNameClientRpc(grabbableNameClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_949135576(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 itemPositionClientRpc = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref itemPositionClientRpc); target.__rpc_exec_stage = (__RpcExecStage)2; ((Item)(object)target).SetItemPositionClientRpc(itemPositionClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1528367091(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) { Quaternion itemRotationClientRpc = default(Quaternion); ((FastBufferReader)(ref reader)).ReadValueSafe(ref itemRotationClientRpc); target.__rpc_exec_stage = (__RpcExecStage)2; ((Item)(object)target).SetItemRotationClientRpc(itemRotationClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2688253945(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 itemScaleClientRpc = default(Vector3); ((FastBufferReader)(ref reader)).ReadValueSafe(ref itemScaleClientRpc); target.__rpc_exec_stage = (__RpcExecStage)2; ((Item)(object)target).SetItemScaleClientRpc(itemScaleClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4227417717(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool isScrapClientRpc = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref isScrapClientRpc, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)2; ((Item)(object)target).SetIsScrapClientRpc(isScrapClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3866863385(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) { int scrapValueClientRpc = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref scrapValueClientRpc); target.__rpc_exec_stage = (__RpcExecStage)2; ((Item)(object)target).SetScrapValueClientRpc(scrapValueClientRpc); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1050513218(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; ((Item)(object)target).RemoveFromHolderClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1334565671(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; ((Item)(object)target).InitializeScrapClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } [MethodImpl(MethodImplOptions.NoInlining)] protected internal override string __getTypeName() { return "Item"; } } public class Player : NetworkBehaviour { public class PlayerInventory : NetworkBehaviour { public Player Player { get; private set; } public Item[] Items => Player.PlayerController.ItemSlots.Select((GrabbableObject i) => (!((Object)(object)i != (Object)null)) ? null : Item.Dictionary[i]).ToArray(); public int CurrentSlot { get { return Player.PlayerController.currentItemSlot; } set { //IL_0011: 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) if (Player.IsLocalPlayer) { SetSlotServerRpc(value); } else if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { SetSlotClientRpc(value); } } } [ServerRpc] private void SetSlotServerRpc(int slot, ServerRpcParams serverRpcParams = default(ServerRpcParams)) { //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_010e: 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_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)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; } FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1475903090u, serverRpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, slot); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 1475903090u, serverRpcParams, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && serverRpcParams.Receive.SenderClientId == Player.ClientId) { SetSlotClientRpc(slot); } } [ClientRpc] private void SetSlotClientRpc(int slot) { //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)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2977994897u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, slot); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2977994897u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Player.PlayerController.SwitchToItemSlot(slot, (GrabbableObject)null); } } } public int GetFirstEmptySlot() { return Player.PlayerController.FirstEmptyItemSlot(); } public bool TryGetFirstEmptySlot(out int slot) { slot = Player.PlayerController.FirstEmptyItemSlot(); return slot != -1; } public bool TryAddItem(Item item, bool switchTo = true) { //IL_0052: 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_005b: 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) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to add item from client."); } if (TryGetFirstEmptySlot(out var slot)) { if (item.IsTwoHanded && !Player.HasFreeHands) { return false; } if (item.IsHeld) { item.RemoveFromHolder(); } ((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId); if (item.IsTwoHanded) { SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId); } else if (switchTo && Player.HasFreeHands) { SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId); } else if (Player.PlayerController.currentItemSlot == slot) { SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId); } else { SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId); } return true; } return false; } public bool TryAddItemToSlot(Item item, int slot, bool switchTo = true) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0083: 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) if (!NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { throw new NoAuthorityException("Tried to add item from client."); } if (slot < Player.PlayerController.ItemSlots.Length && (Object)(object)Player.PlayerController.ItemSlots[slot] == (Object)null) { if (item.IsTwoHanded && !Player.HasFreeHands) { return false; } if (item.IsHeld) { item.RemoveFromHolder(); } ((NetworkBehaviour)item).NetworkObject.ChangeOwnership(Player.ClientId); if (item.IsTwoHanded) { SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId); } else if (switchTo && Player.HasFreeHands) { SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId); } else if (Player.PlayerController.currentItemSlot == slot) { SetSlotAndItemClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId); } else { SetItemInSlotClientRpc(slot, ((NetworkBehaviour)item).NetworkObjectId);
plugins/CapyCat-Solos_Bodycams/SoloBodycams/SolosBodycams.dll
Decompiled 2 years 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 float yadd = 0f; private static Plugin Instance; private static ConfigFile SoloBodycamConfigs { get; set; } internal static ConfigEntry<bool> BodycamOrHeadcam { get; set; } internal static ConfigEntry<int> RenderTextureX { 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_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: 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); } SoloBodycamConfigs = new ConfigFile(Paths.ConfigPath + "\\SoloMods\\CameraPlacement.cfg", true); BodycamOrHeadcam = SoloBodycamConfigs.Bind<bool>("CameraPlacement", "Bool", true, "True for HEADCAM, False for BODYCAM"); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Headcam: " + BodycamOrHeadcam.Value)); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Bodycam: " + !BodycamOrHeadcam.Value)); RenderTextureX = SoloBodycamConfigs.Bind<int>("Camera Resolution", "Width (pixels)", 160, "Width of the camera display, Height is calculated internally from width (4:3). WARNING: SETTING THIS NUMBER HIGHER THAN 160 COULD CAUSE PERFORMANCE ISSUES"); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Render Texture X value: " + RenderTextureX.Value)); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Render Texture Y value: " + RenderTextureX.Value / 4 * 3)); 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(RenderTextureX.Value, RenderTextureX.Value / 4 * 3, 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>(); ShipExternalCamera.GetComponent<Camera>().cullingMask = 557520895; ShipExternalCamera.GetComponent<Camera>().nearClipPlane = 0.35f; 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_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_0235: 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 { yadd += 1f; ShipExternalCamera.transform.SetPositionAndRotation(val.transform.position + new Vector3(0f, 1.6f, 0f), Quaternion.Euler(val.transform.eulerAngles + new Vector3(0f, -90f + yadd, 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"; }
plugins/Clementinise-CustomSounds/CustomSounds.dll
Decompiled 2 years 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.Cryptography; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using CustomSounds.Networking; using CustomSounds.Patches; using GameNetcodeStuff; using HarmonyLib; using LCSoundTool; using Unity.Netcode; using UnityEngine; 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: AssemblyTitle("CustomSounds")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomSounds")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9e086160-a7fd-4721-ba09-3e8534cb7011")] [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")] internal class <Module> { static <Module>() { } } namespace CustomSounds { [BepInPlugin("CustomSounds", "Custom Sounds", "2.2.0")] public class Plugin : BaseUnityPlugin { private const string PLUGIN_GUID = "CustomSounds"; private const string PLUGIN_NAME = "Custom Sounds"; private const string PLUGIN_VERSION = "2.2.0"; public static Plugin Instance; internal ManualLogSource logger; private Harmony harmony; public HashSet<string> currentSounds = new HashSet<string>(); public HashSet<string> oldSounds = new HashSet<string>(); public HashSet<string> modifiedSounds = new HashSet<string>(); public Dictionary<string, string> soundHashes = new Dictionary<string, string>(); public Dictionary<string, string> soundPacks = new Dictionary<string, string>(); public static ConfigEntry<KeyboardShortcut> AcceptSyncKey; public ConfigEntry<bool> configUseNetworking; private Dictionary<string, string> customSoundNames = new Dictionary<string, string>(); public static bool Initialized { get; private set; } private void Awake() { //IL_0065: 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_0089: Expected O, but got Unknown if (!((Object)(object)Instance == (Object)null)) { return; } Instance = this; logger = Logger.CreateLogSource("CustomSounds"); configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", true, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs CustomSounds to join and also \"EnableNetworking\" set to true."); AcceptSyncKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Experimental", "AcceptSyncKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Key to accept audio sync."); harmony = new Harmony("CustomSounds"); harmony.PatchAll(typeof(TerminalParsePlayerSentencePatch)); harmony.PatchAll(typeof(RemapKeyPatch)); if (configUseNetworking.Value) { harmony.PatchAll(typeof(NetworkObjectManager)); } modifiedSounds = new HashSet<string>(); string customSoundsFolderPath = GetCustomSoundsFolderPath(); if (!Directory.Exists(customSoundsFolderPath)) { logger.LogInfo((object)"\"CustomSounds\" folder not found. Creating it now."); Directory.CreateDirectory(customSoundsFolderPath); } string path = Path.Combine(Paths.BepInExConfigPath); try { List<string> list = File.ReadAllLines(path).ToList(); int num = list.FindIndex((string line) => line.StartsWith("HideManagerGameObject")); if (num != -1) { logger.LogInfo((object)"\"hideManagerGameObject\" value not correctly set. Fixing it now."); list[num] = "HideManagerGameObject = true"; } File.WriteAllLines(path, list); } catch (Exception ex) { logger.LogError((object)("Error modifying config file: " + ex.Message)); } 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); } } } logger.LogInfo((object)"Plugin CustomSounds is loaded!"); } internal void Start() { Initialize(); } internal void OnDestroy() { Initialize(); } internal void Initialize() { if (!Initialized) { Initialized = true; DeleteTempFolder(); ReloadSounds(serverSync: false, isTemporarySync: false); } } private void OnApplicationQuit() { DeleteTempFolder(); } public GameObject LoadNetworkPrefabFromEmbeddedResource() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string name = "CustomSounds.Bundle.audionetworkhandler"; using Stream stream = executingAssembly.GetManifestResourceStream(name); if (stream == null) { Debug.LogError((object)"Asset bundle not found in embedded resources."); return null; } byte[] array = new byte[stream.Length]; stream.Read(array, 0, array.Length); AssetBundle val = AssetBundle.LoadFromMemory(array); if ((Object)(object)val == (Object)null) { Debug.LogError((object)"Failed to load AssetBundle from memory."); return null; } return val.LoadAsset<GameObject>("audionetworkhandler"); } public void DeleteTempFolder() { string customSoundsTempFolderPath = GetCustomSoundsTempFolderPath(); if (Directory.Exists(customSoundsTempFolderPath)) { try { Directory.Delete(customSoundsTempFolderPath, recursive: true); logger.LogInfo((object)"Temporary-Sync folder deleted successfully."); } catch (Exception ex) { logger.LogError((object)("Error deleting Temporary-Sync folder: " + ex.Message)); } } } public string GetCustomSoundsFolderPath() { return Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)Instance).Info.Location), "CustomSounds"); } public string GetCustomSoundsTempFolderPath() { return Path.Combine(GetCustomSoundsFolderPath(), "Temporary-Sync"); } public static byte[] SerializeWavToBytes(string filePath) { try { return File.ReadAllBytes(filePath); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); return null; } } public static string SerializeWavToBase64(string filePath) { try { byte[] inArray = File.ReadAllBytes(filePath); return Convert.ToBase64String(inArray); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); return null; } } public static void DeserializeBytesToWav(byte[] byteArray, string audioFileName) { try { string customSoundsTempFolderPath = Instance.GetCustomSoundsTempFolderPath(); if (!Directory.Exists(customSoundsTempFolderPath)) { Instance.logger.LogInfo((object)"\"Temporary-Sync\" folder not found. Creating it now."); Directory.CreateDirectory(customSoundsTempFolderPath); } File.WriteAllBytes(Path.Combine(customSoundsTempFolderPath, audioFileName), byteArray); Console.WriteLine("WAV file \"" + audioFileName + "\" created!"); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } } public static List<byte[]> SplitAudioData(byte[] audioData, int maxSegmentSize = 62000) { List<byte[]> list = new List<byte[]>(); for (int i = 0; i < audioData.Length; i += maxSegmentSize) { int num = Mathf.Min(maxSegmentSize, audioData.Length - i); byte[] array = new byte[num]; Array.Copy(audioData, i, array, 0, num); list.Add(array); } return list; } public static byte[] CombineAudioSegments(List<byte[]> segments) { List<byte> list = new List<byte>(); foreach (byte[] segment in segments) { list.AddRange(segment); } return list.ToArray(); } public void ShowCustomTip(string header, string body, bool isWarning) { HUDManager.Instance.DisplayTip(header, body, isWarning, false, "LC_Tip1"); } public void ForceUnsync() { DeleteTempFolder(); ReloadSounds(serverSync: false, isTemporarySync: false); } public void RevertSounds() { HashSet<string> hashSet = new HashSet<string>(); foreach (string currentSound in currentSounds) { string text = currentSound; if (currentSound.Contains("-")) { text = currentSound.Substring(0, currentSound.IndexOf("-")); } if (!hashSet.Contains(text)) { logger.LogInfo((object)(text + " restored.")); SoundTool.RestoreAudioClip(text); hashSet.Add(text); } } logger.LogInfo((object)"Original game sounds restored."); } public static string CalculateMD5(string filename) { using MD5 mD = MD5.Create(); using FileStream inputStream = File.OpenRead(filename); byte[] array = mD.ComputeHash(inputStream); return BitConverter.ToString(array).Replace("-", "").ToLowerInvariant(); } public void ReloadSounds(bool serverSync, bool isTemporarySync) { oldSounds = new HashSet<string>(currentSounds); modifiedSounds.Clear(); string directoryName = Path.GetDirectoryName(Paths.PluginPath); currentSounds.Clear(); customSoundNames.Clear(); string customSoundsTempFolderPath = GetCustomSoundsTempFolderPath(); if (isTemporarySync) { logger.LogInfo((object)("Temporary folder: " + customSoundsTempFolderPath)); if (Directory.Exists(customSoundsTempFolderPath)) { ProcessDirectory(customSoundsTempFolderPath, serverSync, isTemporarySync: true); } } ProcessDirectory(directoryName, serverSync, isTemporarySync: false); } private void ProcessDirectory(string directoryPath, bool serverSync, bool isTemporarySync) { string[] directories = Directory.GetDirectories(directoryPath, "CustomSounds", SearchOption.AllDirectories); foreach (string text in directories) { string fileName = Path.GetFileName(Path.GetDirectoryName(text)); ProcessSoundFiles(text, fileName, serverSync, isTemporarySync); string[] directories2 = Directory.GetDirectories(text); foreach (string text2 in directories2) { string fileName2 = Path.GetFileName(text2); ProcessSoundFiles(text2, fileName2, serverSync, isTemporarySync); } } } private (string soundName, int? percentage, string customName) ParseSoundFileName(string fullSoundName) { string[] array = fullSoundName.Split(new char[1] { '-' }); string s = array[^1].Replace(".wav", ""); if (int.TryParse(s, out var result)) { string item = array[0]; string item2 = string.Join(" ", array.Skip(1).Take(array.Length - 2)); return (item, result, item2); } return (array[0], null, string.Join(" ", array.Skip(1)).Replace(".wav", "")); } private void ProcessSoundFiles(string directoryPath, string packName, bool serverSync, bool isTemporarySync) { string[] files = Directory.GetFiles(directoryPath, "*.wav"); foreach (string text in files) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text); (string soundName, int? percentage, string customName) tuple = ParseSoundFileName(fileNameWithoutExtension); string item = tuple.soundName; int? item2 = tuple.percentage; string item3 = tuple.customName; string text2 = (item2.HasValue ? $"{item}-{item3}-{item2.Value}" : (item + "-" + item3)); string text3 = CalculateMD5(text); if (isTemporarySync || !currentSounds.Contains(text2)) { if (soundHashes.TryGetValue(text2, out var value) && value != text3) { modifiedSounds.Add(text2); } AudioClip audioClip = SoundTool.GetAudioClip(directoryPath, "", text); SoundTool.ReplaceAudioClip(item, audioClip); soundHashes[text2] = text3; currentSounds.Add(text2); soundPacks[item] = packName; string text4 = "[" + packName + "] " + item + " sound replaced!"; if (item2 > 0) { text4 += $" (Random chance: {item2}%)"; } logger.LogInfo((object)text4); string key = item + (item2.HasValue ? $"-{item2.Value}-{item3}" : ("-" + item3)); if (!string.IsNullOrEmpty(item3)) { customSoundNames[key] = item3; } if (serverSync) { string text5 = Path.Combine(directoryPath, fileNameWithoutExtension + ".wav"); logger.LogInfo((object)("[" + text5 + "] " + fileNameWithoutExtension + ".wav!")); AudioNetworkHandler.Instance.QueueAudioData(SerializeWavToBytes(text5), fileNameWithoutExtension + ".wav"); } } } } public string ListAllSounds(bool isListing) { StringBuilder stringBuilder = new StringBuilder(isListing ? "Listing all currently loaded custom sounds:\n\n" : "Customsounds reloaded.\n\n"); Dictionary<string, List<string>> soundsByPack = new Dictionary<string, List<string>>(); Action<HashSet<string>, string> action = delegate(HashSet<string> soundsSet, string status) { foreach (string item5 in soundsSet) { (string soundName, int? percentage, string customName) tuple = ParseSoundFileName(item5); string item = tuple.soundName; int? item2 = tuple.percentage; string item3 = tuple.customName; string text = (item2.HasValue ? $" (Random: {item2.Value}%)" : ""); string text2 = ""; string key = item + (item2.HasValue ? $"-{item2.Value}-{item3}" : ("-" + item3)); if (customSoundNames.TryGetValue(key, out var value)) { text2 = " [" + value + "]"; } string key2 = (soundPacks.ContainsKey(item) ? soundPacks[item] : "Unknown"); if (!soundsByPack.ContainsKey(key2)) { soundsByPack[key2] = new List<string>(); } string item4 = (isListing ? (item + text + text2) : (item + " (" + status + ")" + text + text2)); soundsByPack[key2].Add(item4); } }; if (!isListing) { action(new HashSet<string>(currentSounds.Except(oldSounds)), "N¹"); action(new HashSet<string>(oldSounds.Except(currentSounds)), "D²"); action(new HashSet<string>(oldSounds.Intersect(currentSounds).Except(modifiedSounds)), "A.E³"); action(new HashSet<string>(modifiedSounds), "M⁴"); } else { action(new HashSet<string>(currentSounds), "N¹"); } foreach (string key3 in soundsByPack.Keys) { stringBuilder.AppendLine(key3 + " :"); foreach (string item6 in soundsByPack[key3]) { stringBuilder.AppendLine("- " + item6); } stringBuilder.AppendLine(); } if (!isListing) { stringBuilder.AppendLine("Footnotes:"); stringBuilder.AppendLine("¹ N = New"); stringBuilder.AppendLine("² D = Deleted"); stringBuilder.AppendLine("³ A.E = Already Existed"); stringBuilder.AppendLine("⁴ M = Modified"); stringBuilder.AppendLine(); } return stringBuilder.ToString(); } } } namespace CustomSounds.Patches { [HarmonyPatch] public class NetworkObjectManager { private static GameObject networkPrefab; private static GameObject networkHandlerHost; [HarmonyPatch(typeof(GameNetworkManager), "Start")] [HarmonyPrefix] public static void Init() { if (!((Object)(object)networkPrefab != (Object)null)) { networkPrefab = Plugin.Instance.LoadNetworkPrefabFromEmbeddedResource(); networkPrefab.AddComponent<AudioNetworkHandler>(); NetworkManager.Singleton.AddNetworkPrefab(networkPrefab); Plugin.Instance.logger.LogInfo((object)"Created AudioNetworkHandler prefab"); } } [HarmonyPostfix] [HarmonyPatch(typeof(StartOfRound), "Awake")] private static void SpawnNetworkHandler() { //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) try { if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { Plugin.Instance.logger.LogInfo((object)"Spawning network handler"); networkHandlerHost = Object.Instantiate<GameObject>(networkPrefab, Vector3.zero, Quaternion.identity); if (networkHandlerHost.GetComponent<NetworkObject>().IsSpawned) { Debug.Log((object)"NetworkObject is spawned and active."); } else { Debug.Log((object)"Failed to spawn NetworkObject."); } networkHandlerHost.GetComponent<NetworkObject>().Spawn(true); if ((Object)(object)AudioNetworkHandler.Instance != (Object)null) { Debug.Log((object)"Successfully accessed AudioNetworkHandler instance."); } else { Debug.Log((object)"AudioNetworkHandler instance is null."); } } } catch { Plugin.Instance.logger.LogError((object)"Failed to spawned network handler"); } } [HarmonyPostfix] [HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")] private static void DestroyNetworkHandler() { try { if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { Plugin.Instance.logger.LogInfo((object)"Destroying network handler"); Object.Destroy((Object)(object)networkHandlerHost); networkHandlerHost = null; } } catch { Plugin.Instance.logger.LogError((object)"Failed to destroy network handler"); } } } [HarmonyPatch] public class RemapKeyPatch { public Harmony _harmony; public static InputActionAsset asset; private static string defaultKey; private static string path; public static string actionName; public static void UpdateInputActionAsset(string thing) { asset = InputActionAsset.FromJson("\r\n {\r\n \"maps\" : [\r\n {\r\n \"name\" : \"CustomSounds\",\r\n \"actions\": [\r\n {\"name\": \"" + actionName + "\", \"type\" : \"button\"}\r\n ],\r\n \"bindings\" : [\r\n {\"path\" : \"" + thing + "\", \"action\": \"" + actionName + "\"}\r\n ]\r\n }\r\n ]\r\n }"); } [HarmonyPatch(typeof(KepRemapPanel), "LoadKeybindsUI")] [HarmonyPrefix] public static void AddRemappableKey(KepRemapPanel __instance) { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown Debug.Log((object)("[CustomSounds] Default key for sync is " + defaultKey)); for (int i = 0; i < __instance.remappableKeys.Count; i++) { if (__instance.remappableKeys[i].ControlName == "Accept Sync") { return; } } RemappableKey val = new RemappableKey(); UpdateInputActionAsset(defaultKey); if ((Object)(object)asset == (Object)null) { Debug.LogError((object)"InputActionAsset is null."); return; } InputAction val2 = asset.FindAction("CustomSounds/" + actionName, false); if (val2 == null) { Debug.LogError((object)"Action 'CustomSounds/AcceptSyncAction' not found."); return; } InputActionReference currentInput = InputActionReference.Create(asset.FindAction("CustomSounds/" + actionName, false)); val.ControlName = "Accept Sync"; val.currentInput = currentInput; __instance.remappableKeys.Add(val); } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] public static void ReadInput(PlayerControllerB __instance) { if (((((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled && (!((NetworkBehaviour)__instance).IsServer || __instance.isHostPlayerObject)) || __instance.isTestingPlayer) && Application.isFocused) { if (!Object.op_Implicit((Object)(object)asset) || !asset.enabled) { UpdateInputActionAsset(defaultKey); asset.Enable(); } InputAction val = asset.FindAction("CustomSounds/" + actionName, false); if (val != null && val.WasPressedThisFrame() && AudioNetworkHandler.isRequestingSync) { Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Sync request accepted successfully!", isWarning: false); AudioNetworkHandler.hasAcceptedSync = true; AudioNetworkHandler.isRequestingSync = false; } } } [HarmonyPatch(typeof(IngamePlayerSettings), "CompleteRebind")] [HarmonyPrefix] public static void SavingActionRebind(IngamePlayerSettings __instance) { //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) //IL_0083: 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) if (!(__instance.rebindingOperation.action.name != actionName)) { string text = ((object)__instance.rebindingOperation.action).ToString(); string text2 = text.Split('[', ']')[1]; string value = text2.Replace("/Keyboard/", ""); defaultKey = text2; try { KeyCode val = (KeyCode)Enum.Parse(typeof(KeyCode), value, ignoreCase: true); Plugin.AcceptSyncKey.Value = new KeyboardShortcut(val, Array.Empty<KeyCode>()); } catch (Exception ex) { Debug.LogError((object)("Erreur lors de la conversion de la chaîne en KeyCode: " + ex.Message)); } UpdateInputActionAsset(defaultKey); } } [HarmonyPatch(typeof(KepRemapPanel), "ResetKeybindsUI")] [HarmonyPrefix] public static void ResetAcceptAction(KepRemapPanel __instance) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) Plugin.AcceptSyncKey.Value = new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()); defaultKey = "<Keyboard>/f8"; UpdateInputActionAsset(defaultKey); bool flag = UpdateAcceptSyncKeybind(__instance, "<Keyboard>/f8"); } private static bool UpdateAcceptSyncKeybind(KepRemapPanel panel, string defaultBinding) { foreach (RemappableKey remappableKey in panel.remappableKeys) { if (remappableKey.ControlName == "Accept Sync") { remappableKey.currentInput = InputActionReference.Create(asset.FindAction("CustomSounds/AcceptSyncAction", false)); Debug.Log((object)"[CustomSounds] Found and updated 'Accept Sync' keybinding"); return true; } } Debug.Log((object)"[CustomSounds] 'Accept Sync' keybinding not found"); return false; } static RemapKeyPatch() { //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) KeyboardShortcut value = Plugin.AcceptSyncKey.Value; defaultKey = "<Keyboard>/" + ((object)(KeyboardShortcut)(ref value)).ToString(); path = Application.persistentDataPath + "/AcceptSyncButton.txt"; actionName = "AcceptSyncAction"; } } [HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")] public static class TerminalParsePlayerSentencePatch { public static bool Prefix(Terminal __instance, ref TerminalNode __result) { string[] array = __instance.screenText.text.Split(new char[1] { '\n' }); if (array.Length == 0) { return true; } string[] array2 = array.Last().Trim().ToLower() .Split(new char[1] { ' ' }); if (array2.Length == 0 || (array2[0] != "customsounds" && array2[0] != "cs")) { return true; } Plugin.Instance.logger.LogInfo((object)("Received terminal command: " + string.Join(" ", array2))); if (array2.Length > 1 && (array2[0] == "customsounds" || array2[0] == "cs")) { switch (array2[1]) { case "reload": case "rl": Plugin.Instance.RevertSounds(); Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false); __result = CreateTerminalNode(Plugin.Instance.ListAllSounds(isListing: false)); return false; case "revert": case "rv": Plugin.Instance.RevertSounds(); __result = CreateTerminalNode("Game sounds reverted to original.\n\n"); return false; case "list": case "l": __result = CreateTerminalNode(Plugin.Instance.ListAllSounds(isListing: true)); return false; case "help": case "h": if (NetworkManager.Singleton.IsHost) { __result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n>CUSTOMSOUNDS SYNC/S\nTo start the sync of custom sounds with clients\n\n>CUSTOMSOUNDS FORCE-UNSYNC/FU\nTo force the unsync process for all clients\n\n"); } else { __result = CreateTerminalNode("CustomSounds commands \n(Can also be used with 'CS' as an alias).\n\n>CUSTOMSOUNDS LIST/L\nTo display all currently loaded sounds\n\n>CUSTOMSOUNDS RELOAD/RL\nTo reload and apply sounds from the 'CustomSounds' folder and its subfolders.\n\n>CUSTOMSOUNDS REVERT/RV\nTo unload all custom sounds and restore original game sounds\n\n>CUSTOMSOUNDS UNSYNC/U\nUnsyncs sounds sent by the host.\n\n"); } return false; case "sync": case "s": if (NetworkManager.Singleton.IsHost) { if (Plugin.Instance.configUseNetworking.Value) { __result = CreateTerminalNode("Custom sound sync initiated. \nSyncing sounds with clients...\n\n"); Plugin.Instance.ReloadSounds(serverSync: true, isTemporarySync: false); } else { __result = CreateTerminalNode("Custom sound sync is currently disabled. \nPlease enable network support in the plugin config to use this feature.\n\n"); } } else { __result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command can only be used by the host!\n\n"); } return false; case "unsync": case "u": if (!NetworkManager.Singleton.IsHost) { __result = CreateTerminalNode("Unsyncing custom sounds. \nTemporary files deleted and original sounds reloaded.\n\n"); Plugin.Instance.DeleteTempFolder(); Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false); } else { __result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command cannot be used by the host!\n\n"); } return false; case "fu": case "force-unsync": if (NetworkManager.Singleton.IsHost) { __result = CreateTerminalNode("Forcing unsync for all clients. \nAll client-side temporary synced files have been deleted, and original sounds reloaded.\n\n"); AudioNetworkHandler.Instance.ForceUnsync(); } else { __result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command can only be used by the host!\n\n"); } return false; default: __result = CreateTerminalNode("Unknown customsounds command.\n\n"); return false; } } return true; } private static TerminalNode CreateTerminalNode(string message) { TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>(); val.displayText = message; val.clearPreviousText = true; return val; } } } namespace CustomSounds.Networking { public class AudioNetworkHandler : NetworkBehaviour { private struct AudioData { public List<byte[]> Segments; public string FileName; public AudioData(List<byte[]> segments, string fileName) { Segments = segments; FileName = fileName; } } private List<byte[]> receivedAudioSegments = new List<byte[]>(); private string audioFileName; private int totalAudioFiles; private int processedAudioFiles; private int totalSegments; private int processedSegments; public static bool isRequestingSync; private float[] progressThresholds = new float[4] { 0.25f, 0.5f, 0.75f, 1f }; private int lastThresholdIndex = -1; public static bool hasAcceptedSync; private Queue<AudioData> audioQueue = new Queue<AudioData>(); private bool isSendingAudio = false; public static AudioNetworkHandler Instance { get; private set; } private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); Debug.Log((object)"AudioNetworkHandler instance created."); } else { Object.Destroy((Object)(object)((Component)this).gameObject); Debug.Log((object)"Extra AudioNetworkHandler instance destroyed."); } } public void QueueAudioData(byte[] audioData, string audioName) { List<byte[]> list = Plugin.SplitAudioData(audioData); totalSegments += list.Count; audioQueue.Enqueue(new AudioData(list, audioName)); if (!isSendingAudio) { totalAudioFiles = audioQueue.Count; processedAudioFiles = 0; ((MonoBehaviour)this).StartCoroutine(SendAudioDataQueue()); } } private IEnumerator SendAudioDataQueue() { isSendingAudio = true; totalSegments = 0; processedSegments = 0; lastThresholdIndex = -1; RequestSyncWithClients(); yield return (object)new WaitForSeconds(6f); isRequestingSync = false; DisplayStartingSyncMessageClientRpc(); yield return (object)new WaitForSeconds(2f); while (audioQueue.Count > 0) { AudioData audioData = audioQueue.Dequeue(); yield return ((MonoBehaviour)this).StartCoroutine(SendAudioDataCoroutine(audioData.Segments, audioData.FileName)); processedAudioFiles++; UpdateProgress(); } NotifyClientsQueueCompletedServerRpc(); isSendingAudio = false; } private void RequestSyncWithClients() { foreach (NetworkClient connectedClients in NetworkManager.Singleton.ConnectedClientsList) { RequestSyncClientRpc(connectedClients.ClientId); } } [ClientRpc] private void RequestSyncClientRpc(ulong clientId) { //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_00e9: 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(3186703908u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, clientId); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3186703908u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsServer) { Plugin.Instance.ShowCustomTip("CustomSounds Sync", $"Press {Plugin.AcceptSyncKey.Value} to accept the audio sync request.", isWarning: false); isRequestingSync = true; } } } [ServerRpc(RequireOwnership = false)] private void NotifyClientsQueueCompletedServerRpc(ServerRpcParams rpcParams = default(ServerRpcParams)) { //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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(152710787u, rpcParams, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 152710787u, rpcParams, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ProcessLastAudioFileClientRpc(); } } } public void ForceUnsync() { ForceUnsyncClientsClientRpc(); } [ClientRpc] private void ForceUnsyncClientsClientRpc() { //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)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3960362720u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3960362720u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { if (((NetworkBehaviour)this).IsServer) { Debug.Log((object)"Forcing all clients to delete Temporary-Sync folder."); return; } Plugin.Instance.ShowCustomTip("CustomSounds Sync", "The CustomSounds sync has been reset by the host.\nTemporary files deleted and original sounds reloaded", isWarning: false); Plugin.Instance.DeleteTempFolder(); Plugin.Instance.RevertSounds(); Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: false); } } [ClientRpc] private void ProcessLastAudioFileClientRpc() { //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(234624598u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 234624598u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && hasAcceptedSync) { hasAcceptedSync = false; ProcessLastAudioFile(); Debug.Log((object)"Reverting all sounds."); Plugin.Instance.RevertSounds(); Debug.Log((object)"All sounds reverted!"); Debug.Log((object)"Reloading all sounds."); Plugin.Instance.ReloadSounds(serverSync: false, isTemporarySync: true); Debug.Log((object)"All sounds reloaded!"); } } } private void ProcessLastAudioFile() { if (receivedAudioSegments.Count > 0 && !string.IsNullOrEmpty(audioFileName)) { byte[] byteArray = Plugin.CombineAudioSegments(receivedAudioSegments); Plugin.DeserializeBytesToWav(byteArray, audioFileName); receivedAudioSegments.Clear(); audioFileName = null; } } public void SendAudioData(byte[] audioData, string audioName) { List<byte[]> list = Plugin.SplitAudioData(audioData); audioFileName = audioName; SendAudioMetaDataToClientsServerRpc(list.Count, audioName); ((MonoBehaviour)this).StartCoroutine(SendAudioDataCoroutine(list, audioName)); } [ServerRpc] public void SendAudioMetaDataToClientsServerRpc(int totalSegments, string fileName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0127: 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_00db: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Invalid comparison between Unknown and I4 //IL_010d: 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)) { 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(3991320206u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, totalSegments); bool flag = fileName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(fileName, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3991320206u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Debug.Log((object)$"Sending metadata to clients: {totalSegments} segments, file name: {fileName}"); ReceiveAudioMetaDataClientRpc(totalSegments, fileName); } } private IEnumerator SendAudioDataCoroutine(List<byte[]> audioSegments, string audioName) { foreach (byte[] segment in audioSegments) { SendBytesToServerRpc(segment, audioName); processedSegments++; UpdateProgress(); yield return (object)new WaitForSeconds(0.2f); } } [ServerRpc] public void SendBytesToServerRpc(byte[] audioSegment, string audioName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0165: 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_00ce: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Invalid comparison between Unknown and I4 //IL_0119: 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_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: 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) 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(3131260794u, val, (RpcDelivery)0); bool flag = audioSegment != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioSegment, default(ForPrimitives)); } bool flag2 = audioName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives)); if (flag2) { ((FastBufferWriter)(ref val2)).WriteValueSafe(audioName, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3131260794u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Debug.Log((object)("Sending segment to server: " + audioName)); ReceiveBytesClientRpc(audioSegment, audioName); } } [ClientRpc] public void ReceiveAudioMetaDataClientRpc(int totalSegments, string fileName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: 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_0095: 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_00c7: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1027341762u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, totalSegments); bool flag = fileName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(fileName, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1027341762u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Debug.Log((object)$"Received metadata on client: {totalSegments} segments expected, file name: {fileName}"); audioFileName = fileName; receivedAudioSegments.Clear(); } } [ClientRpc] public void ReceiveBytesClientRpc(byte[] audioSegment, string audioName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_0088: 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_00d3: 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_00ac: 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_0105: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2945580654u, val, (RpcDelivery)0); bool flag = audioSegment != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioSegment, default(ForPrimitives)); } bool flag2 = audioName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives)); if (flag2) { ((FastBufferWriter)(ref val2)).WriteValueSafe(audioName, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2945580654u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && !((NetworkBehaviour)this).IsServer && hasAcceptedSync) { if (!string.IsNullOrEmpty(audioName) && audioFileName != audioName) { ProcessLastAudioFile(); audioFileName = audioName; } receivedAudioSegments.Add(audioSegment); } } [ClientRpc] private void DisplayStartingSyncMessageClientRpc() { //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)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3964799390u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3964799390u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { if (hasAcceptedSync) { Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Starting audio synchronization. Please wait...", isWarning: false); Plugin.Instance.DeleteTempFolder(); } else if (((NetworkBehaviour)this).IsServer) { Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Initiating audio synchronization. Sending files to clients...", isWarning: false); } } } private void UpdateProgress() { float progress = (float)processedSegments / (float)totalSegments; int currentThresholdIndex = GetCurrentThresholdIndex(progress); if (currentThresholdIndex > lastThresholdIndex) { lastThresholdIndex = currentThresholdIndex; UpdateProgressClientRpc(progress); } } private int GetCurrentThresholdIndex(float progress) { for (int num = progressThresholds.Length - 1; num >= 0; num--) { if (progress >= progressThresholds[num]) { return num; } } return -1; } [ClientRpc] private void UpdateProgressClientRpc(float progress) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: 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_007d: 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_0097: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3902617409u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<float>(ref progress, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3902617409u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost) || (!((NetworkBehaviour)this).IsServer && !hasAcceptedSync)) { return; } string text = GenerateProgressBar(progress); if (progress < 1f) { if (!((NetworkBehaviour)this).IsServer) { Plugin.Instance.ShowCustomTip("CustomSounds Sync", "Sounds transfer progression:\n" + text, isWarning: false); } } else if (((NetworkBehaviour)this).IsServer) { Plugin.Instance.ShowCustomTip("CustomSounds Sync", "All sounds have been successfully sent!", isWarning: false); } else { Plugin.Instance.ShowCustomTip("CustomSounds Sync", "All sounds have been successfully received!", isWarning: false); } } private string GenerateProgressBar(float progress) { int num = 26; progress = Mathf.Clamp(progress, 0f, 1f); int num2 = (int)(progress * (float)num); return "[" + new string('#', num2) + new string('-', num - num2) + "] " + (int)(progress * 100f) + "%"; } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_AudioNetworkHandler() { //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 //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(3186703908u, new RpcReceiveHandler(__rpc_handler_3186703908)); NetworkManager.__rpc_func_table.Add(152710787u, new RpcReceiveHandler(__rpc_handler_152710787)); NetworkManager.__rpc_func_table.Add(3960362720u, new RpcReceiveHandler(__rpc_handler_3960362720)); NetworkManager.__rpc_func_table.Add(234624598u, new RpcReceiveHandler(__rpc_handler_234624598)); NetworkManager.__rpc_func_table.Add(3991320206u, new RpcReceiveHandler(__rpc_handler_3991320206)); NetworkManager.__rpc_func_table.Add(3131260794u, new RpcReceiveHandler(__rpc_handler_3131260794)); NetworkManager.__rpc_func_table.Add(1027341762u, new RpcReceiveHandler(__rpc_handler_1027341762)); NetworkManager.__rpc_func_table.Add(2945580654u, new RpcReceiveHandler(__rpc_handler_2945580654)); NetworkManager.__rpc_func_table.Add(3964799390u, new RpcReceiveHandler(__rpc_handler_3964799390)); NetworkManager.__rpc_func_table.Add(3902617409u, new RpcReceiveHandler(__rpc_handler_3902617409)); } private static void __rpc_handler_3186703908(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 clientId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref clientId); target.__rpc_exec_stage = (__RpcExecStage)2; ((AudioNetworkHandler)(object)target).RequestSyncClientRpc(clientId); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_152710787(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_0033: 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_004d: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { ServerRpcParams server = rpcParams.Server; target.__rpc_exec_stage = (__RpcExecStage)1; ((AudioNetworkHandler)(object)target).NotifyClientsQueueCompletedServerRpc(server); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3960362720(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; ((AudioNetworkHandler)(object)target).ForceUnsyncClientsClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_234624598(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; ((AudioNetworkHandler)(object)target).ProcessLastAudioFileClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3991320206(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_0070: 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_008f: 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 //IL_00bb: 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) 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!"); } return; } int num = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref num); bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string fileName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref fileName, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((AudioNetworkHandler)(object)target).SendAudioMetaDataToClientsServerRpc(num, fileName); target.__rpc_exec_stage = (__RpcExecStage)0; } private static void __rpc_handler_3131260794(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_007c: 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_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 //IL_00c1: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: 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_0111: Unknown result type (might be due to invalid IL or missing references) 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!"); } return; } bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); byte[] audioSegment = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioSegment, default(ForPrimitives)); } bool flag2 = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives)); string audioName = null; if (flag2) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref audioName, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((AudioNetworkHandler)(object)target).SendBytesToServerRpc(audioSegment, audioName); target.__rpc_exec_stage = (__RpcExecStage)0; } private static void __rpc_handler_1027341762(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_0023: 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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int num = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref num); bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string fileName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref fileName, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((AudioNetworkHandler)(object)target).ReceiveAudioMetaDataClientRpc(num, fileName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_2945580654(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0074: 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_0058: 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_00a6: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); byte[] audioSegment = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioSegment, default(ForPrimitives)); } bool flag2 = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives)); string audioName = null; if (flag2) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref audioName, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((AudioNetworkHandler)(object)target).ReceiveBytesClientRpc(audioSegment, audioName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3964799390(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; ((AudioNetworkHandler)(object)target).DisplayStartingSyncMessageClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3902617409(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { float progress = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref progress, default(ForPrimitives)); target.__rpc_exec_stage = (__RpcExecStage)2; ((AudioNetworkHandler)(object)target).UpdateProgressClientRpc(progress); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "AudioNetworkHandler"; } } }
plugins/Electric131-IsThisTheWayICame/IsThisTheWayICame.dll
Decompiled 2 years agousing System; using System.CodeDom.Compiler; 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 BepInEx; using HarmonyLib; using IsThisTheWayICame.Properties; using Microsoft.CodeAnalysis; using Unity.Netcode; 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("IsThisTheWayICame")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("IsThisTheWayICame")] [assembly: AssemblyTitle("IsThisTheWayICame")] [assembly: AssemblyVersion("1.0.0.0")] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); } } 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 IsThisTheWayICame { [BepInPlugin("Electric.IsThisTheWayICame", "IsThisTheWayICame", "1.1.4")] public class Plugin : BaseUnityPlugin { [HarmonyPatch(typeof(RoundManager))] internal class RoundManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref RoundManager __instance) { if (((NetworkBehaviour)__instance).IsServer && (Object)(object)Networker.Instance == (Object)null) { GameObject val = Object.Instantiate<GameObject>(NetworkerPrefab); val.GetComponent<NetworkObject>().Spawn(true); Networker.fakeChance.Value = fakeChance; Networker.changeOnUse.Value = changeOnUse; Networker.changeOnUseChance.Value = changeOnUseChance; } } [HarmonyPatch("SetExitIDs")] [HarmonyPostfix] private static void SetExitIDsPatch() { random = null; } } [HarmonyPatch(typeof(EntranceTeleport))] internal class EntranceTeleportPatch { [HarmonyPatch("TeleportPlayer")] [HarmonyPrefix] private static void TeleportPlayerPatch(ref EntranceTeleport __instance) { if (__instance.entranceId < 1 || !__instance.isEntranceToBuilding) { return; } if (random == null) { Networker.Instance.FullRelocation(); } else if (Networker.changeOnUse.Value) { double num = random.NextDouble(); if (num < (double)((float)Networker.changeOnUseChance.Value / 100f)) { Networker.Instance.FullRelocation(); } } } } [HarmonyPatch(typeof(GameNetworkManager))] internal class GameNetworkManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch() { ((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(NetworkerPrefab); } } public class Networker : NetworkBehaviour { public static Networker Instance; public static NetworkVariable<int> fakeChance = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<bool> changeOnUse = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> changeOnUseChance = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private void Awake() { Instance = this; } public void FullRelocation() { if (((NetworkBehaviour)this).IsOwner) { FullRelocationClientRpc(); } else { FullRelocationServerRpc(); } } [ClientRpc] public void FullRelocationClientRpc() { //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) //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) //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_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0132: 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_020a: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3354949447u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3354949447u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } bool flag = false; if (random == null) { flag = true; random = new Random(StartOfRound.Instance.randomMapSeed + 172); realExits.Clear(); realExitTPData.Clear(); } Scene val3 = SceneManager.GetSceneByName("SampleSceneRelay"); Scene sceneByName = SceneManager.GetSceneByName(RoundManager.Instance.currentLevel.sceneName); if (GameNetworkManager.Instance.isHostingGame) { val3 = sceneByName; } GameObject[] rootGameObjects = ((Scene)(ref val3)).GetRootGameObjects(); List<GameObject> list = new List<GameObject>(); foreach (GameObject tempAudioSource in tempAudioSources) { Object.Destroy((Object)(object)tempAudioSource); } tempAudioSources.Clear(); GameObject[] array = rootGameObjects; foreach (GameObject val4 in array) { if (((Object)val4).name.StartsWith("EntranceTeleport") && ((Object)val4).name != "EntranceTeleportA(Clone)") { if (flag) { realExits.Add(val4.transform); realExitTPData.Add(new Tuple<Vector3, Quaternion>(val4.transform.GetChild(0).position, val4.transform.GetChild(0).rotation)); } list.Add(val4); } } if (realExits.Count > list.Count || realExitTPData.Count > list.Count) { Debug.LogError((object)"ITTWIC (IsThisTheWayICame) - Exits have exceeded data limit! This normally means something has gone wrong between host and client!"); } foreach (GameObject item in list) { Relocate(((Scene)(ref sceneByName)).GetRootGameObjects()[0].transform, item.transform); } } [ServerRpc(RequireOwnership = false)] public void FullRelocationServerRpc() { //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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(858788495u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 858788495u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { FullRelocationClientRpc(); } } } protected override void __initializeVariables() { if (fakeChance == null) { throw new Exception("Networker.fakeChance cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)fakeChance).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)fakeChance, "fakeChance"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)fakeChance); if (changeOnUse == null) { throw new Exception("Networker.changeOnUse cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)changeOnUse).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)changeOnUse, "changeOnUse"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)changeOnUse); if (changeOnUseChance == null) { throw new Exception("Networker.changeOnUseChance cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)changeOnUseChance).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)changeOnUseChance, "changeOnUseChance"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)changeOnUseChance); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_Networker() { //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(3354949447u, new RpcReceiveHandler(__rpc_handler_3354949447)); NetworkManager.__rpc_func_table.Add(858788495u, new RpcReceiveHandler(__rpc_handler_858788495)); } private static void __rpc_handler_3354949447(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; ((Networker)(object)target).FullRelocationClientRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_858788495(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; ((Networker)(object)target).FullRelocationServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "Networker"; } } private class TemporaryAudioSource : MonoBehaviour { public AudioSource audioSource; public float deletionTime = 0f; public TemporaryAudioSource() { audioSource = ((Component)this).gameObject.AddComponent<AudioSource>(); } } private const string modGUID = "Electric.IsThisTheWayICame"; private const string modName = "IsThisTheWayICame"; private const string modVersion = "1.1.4"; private readonly Harmony harmony = new Harmony("Electric.IsThisTheWayICame"); private static int fakeChance; private static bool changeOnUse; private static int changeOnUseChance; private static GameObject NetworkerPrefab; private static Random? random; private static List<Transform> realExits = new List<Transform>(); private static List<Tuple<Vector3, Quaternion>> realExitTPData = new List<Tuple<Vector3, Quaternion>>(); private static Tuple<Vector3, Quaternion>? tempLoc; private static List<GameObject> tempAudioSources = new List<GameObject>(); private void Awake() { AssetBundle val = AssetBundle.LoadFromMemory(Resources.networker); NetworkerPrefab = val.LoadAsset<GameObject>("Assets/Networker.prefab"); NetworkerPrefab.AddComponent<Networker>(); fakeChance = Mathf.Clamp(((BaseUnityPlugin)this).Config.Bind<int>("General", "Fake Chance", 40, "Chance that the fire exit will teleport you to a mimic. (0-100)").Value, 0, 100); changeOnUse = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Change on Use", true, "If true, the destination will change whenever a player uses the exterior door").Value; changeOnUseChance = Mathf.Clamp(((BaseUnityPlugin)this).Config.Bind<int>("General", "Change on Use Chance", 25, "Chance that the destination will change when used. (0-100)").Value, 0, 100); NetcodeWeaver(); harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"IsThisTheWayICame loaded!"); } private static void NetcodeWeaver() { 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); } } } } private static void Relocate(Transform root, Transform obj) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_00e4: 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_00f1: 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_00fb: 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_0106: 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_0125: 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_008d: 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) Transform val = PickDoor(root, obj, StartOfRound.Instance.randomMapSeed); Transform child = obj.GetChild(0); GameObject val2 = new GameObject("TemporaryAudioSource"); tempAudioSources.Add(val2); TemporaryAudioSource temporaryAudioSource = val2.AddComponent<TemporaryAudioSource>(); if (!(((Object)((Component)val).gameObject).name == "MimicDoor(Clone)")) { if (tempLoc == null) { Debug.LogError((object)"Could not find real exit. Report to developer!"); return; } child.rotation = tempLoc.Item2; child.position = tempLoc.Item1; val2.transform.position = child.position; Traverse.Create((object)((Component)obj).GetComponent<EntranceTeleport>()).Field("exitPointAudio").SetValue((object)temporaryAudioSource.audioSource); } else { Vector3 val3 = default(Vector3); ((Vector3)(ref val3))..ctor(0f, 0.065f, 0.002f); val3 += val.forward * -1.5f; child.position = val.position + val3; child.rotation = val.rotation; val2.transform.position = child.position; ((Component)obj).GetComponent<EntranceTeleport>().entrancePointAudio = temporaryAudioSource.audioSource; } } private static Transform PickDoor(Transform root, Transform original, int seed) { if (random == null) { return original; } double num = random.NextDouble(); if (num < (double)((float)fakeChance / 100f)) { List<Transform> list = FindMimics(root, new List<Transform>()); if (list.Count == 0) { num = random.NextDouble(); tempLoc = realExitTPData.ToArray()[(int)Mathf.Floor((float)num * (float)realExitTPData.Count)]; return original; } num = random.NextDouble(); return list.ToArray()[(int)Mathf.Floor((float)num * (float)list.Count)]; } num = random.NextDouble(); tempLoc = realExitTPData.ToArray()[(int)Mathf.Floor((float)num * (float)realExitTPData.Count)]; return original; } private static List<Transform> FindMimics(Transform findFrom, List<Transform> current) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown if (((Object)((Component)findFrom).gameObject).name == "MimicDoor(Clone)") { current.Add(findFrom); } foreach (Transform item in findFrom) { Transform findFrom2 = item; FindMimics(findFrom2, current); } return current; } } } namespace IsThisTheWayICame.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("IsThisTheWayICame.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[] networker { get { object @object = ResourceManager.GetObject("networker", resourceCulture); return (byte[])@object; } } internal Resources() { } } }
plugins/Fredolx-MeteoMultiplier/MeteoMultiplier.dll
Decompiled 2 years 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 HarmonyLib; using Microsoft.CodeAnalysis; [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("MeteoMultiplier")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Multiplies loot value according to meteorigical conditions. An improved version of the other mod with a similar name")] [assembly: AssemblyFileVersion("1.1.2.0")] [assembly: AssemblyInformationalVersion("1.1.2+37958e3e65680d2507b3186c6d648ddc4862187a")] [assembly: AssemblyProduct("MeteoMultiplier")] [assembly: AssemblyTitle("MeteoMultiplier")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.2.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 MeteoMultiplier { [BepInPlugin("com.github.fredolx.meteomultiplier", "MeteoMultiplier", "1.1.2")] public class Plugin : BaseUnityPlugin { public static Dictionary<LevelWeatherType, ConfigEntry<float>> Multipliers = new Dictionary<LevelWeatherType, ConfigEntry<float>>(); public static Dictionary<LevelWeatherType, ConfigEntry<float>> SpawnMultipliers = new Dictionary<LevelWeatherType, ConfigEntry<float>>(); public static ConfigEntry<bool> MultipliersEnabled; public static ConfigEntry<bool> SpawnMultipliersEnabled; public static ConfigEntry<bool> MultiplyApparatusEnabled; public const LevelWeatherType DEFAULT_WEATHER = -1; private void Awake() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MeteoMultiplier is loaded!"); Harmony val = new Harmony("MeteoMultiplier"); SetConfig(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"MultipliersEnabled: {MultipliersEnabled}"); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"MultiplyApparatusEnabled: {MultiplyApparatusEnabled}"); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Multipliers:\n" + string.Join("\n", Multipliers.Select((KeyValuePair<LevelWeatherType, ConfigEntry<float>> x) => $"{x.Key}:{x.Value.Value}")))); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"SpawnMultipliersEnabled: {SpawnMultipliersEnabled}"); ((BaseUnityPlugin)this).Logger.LogInfo((object)("SpawnMultipliers:\n" + string.Join("\n", SpawnMultipliers.Select((KeyValuePair<LevelWeatherType, ConfigEntry<float>> x) => $"{x.Key}:{x.Value.Value}")))); val.PatchAll(); } private void SetConfig() { MultipliersEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Multipliers", "Enabled", true, "Enables multipliers (scrap value according to meteo)"); MultiplyApparatusEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Multipliers", "MultiplyApparatusEnabled", true, "Also multiply the value of the apparatus (power module) according to meteo"); SetMultipliers(); SpawnMultipliersEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawn Multipliers", "Enabled", false, "Enables spawn multipliers (amount of scrap in the map)"); SetSpawnMultipliers(); } private void SetMultipliers() { Multipliers.Add((LevelWeatherType)(-1), ((BaseUnityPlugin)this).Config.Bind<float>("Multipliers", "None", 0.4f, "No weather event")); Multipliers.Add((LevelWeatherType)0, ((BaseUnityPlugin)this).Config.Bind<float>("Multipliers", "DustClouds", 0.44f, "Dust Clouds")); Multipliers.Add((LevelWeatherType)3, ((BaseUnityPlugin)this).Config.Bind<float>("Multipliers", "Foggy", 0.44f, "Foggy")); Multipliers.Add((LevelWeatherType)1, ((BaseUnityPlugin)this).Config.Bind<float>("Multipliers", "Rainy", 0.44f, "Rainy")); Multipliers.Add((LevelWeatherType)2, ((BaseUnityPlugin)this).Config.Bind<float>("Multipliers", "Stormy", 0.52f, "Stormy")); Multipliers.Add((LevelWeatherType)4, ((BaseUnityPlugin)this).Config.Bind<float>("Multipliers", "Flooded", 0.56f, "Flooded")); Multipliers.Add((LevelWeatherType)5, ((BaseUnityPlugin)this).Config.Bind<float>("Multipliers", "Eclipsed", 0.6f, "Eclipsed")); } private void SetSpawnMultipliers() { SpawnMultipliers.Add((LevelWeatherType)(-1), ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Multipliers", "None", 1f, "No weather event")); SpawnMultipliers.Add((LevelWeatherType)0, ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Multipliers", "DustClouds", 1.25f, "Dust Clouds")); SpawnMultipliers.Add((LevelWeatherType)3, ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Multipliers", "Foggy", 1.25f, "Foggy")); SpawnMultipliers.Add((LevelWeatherType)1, ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Multipliers", "Rainy", 1.25f, "Rainy")); SpawnMultipliers.Add((LevelWeatherType)2, ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Multipliers", "Stormy", 1.5f, "Stormy")); SpawnMultipliers.Add((LevelWeatherType)4, ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Multipliers", "Flooded", 1.5f, "Flooded")); SpawnMultipliers.Add((LevelWeatherType)5, ((BaseUnityPlugin)this).Config.Bind<float>("Spawn Multipliers", "Eclipsed", 1.5f, "Eclipsed")); } } public static class PluginInfo { public const string PLUGIN_GUID = "MeteoMultiplier"; public const string PLUGIN_NAME = "MeteoMultiplier"; public const string PLUGIN_VERSION = "1.1.2"; } } namespace MeteoMultiplier.Patches { [HarmonyPatch(typeof(LungProp), "DisconnectFromMachinery")] public class MultiplyApparatus { private static void Prefix(LungProp __instance) { //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_0022: 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) LevelWeatherType currentWeather = __instance.roundManager.currentLevel.currentWeather; if (Plugin.MultiplyApparatusEnabled.Value) { if (Plugin.Multipliers.ContainsKey(currentWeather)) { ((GrabbableObject)__instance).SetScrapValue((int)((float)((GrabbableObject)__instance).scrapValue * Plugin.Multipliers[currentWeather].Value)); } else { ((GrabbableObject)__instance).SetScrapValue((int)((float)((GrabbableObject)__instance).scrapValue * Plugin.Multipliers[(LevelWeatherType)(-1)].Value)); } } } } [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] public class SpawnScrapInLevelPatches { private static void Prefix(RoundManager __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: 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_002b: 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) LevelWeatherType currentWeather = __instance.currentLevel.currentWeather; if (Plugin.MultipliersEnabled.Value) { if (Plugin.Multipliers.ContainsKey(currentWeather)) { __instance.scrapValueMultiplier = Plugin.Multipliers[currentWeather].Value; } else { __instance.scrapValueMultiplier = Plugin.Multipliers[(LevelWeatherType)(-1)].Value; } } if (Plugin.SpawnMultipliersEnabled.Value) { if (Plugin.SpawnMultipliers.ContainsKey(currentWeather)) { __instance.scrapAmountMultiplier = Plugin.SpawnMultipliers[currentWeather].Value; } else { __instance.scrapAmountMultiplier = Plugin.SpawnMultipliers[(LevelWeatherType)(-1)].Value; } } } } }
plugins/FutureSavior-Boombox_Sync_Fix/BoomboxSyncFix.dll
Decompiled 2 years 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.Logging; using BoomboxSyncFix.Patches; 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("BoomboxSyncFix")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("A mod to fix the base game bug of the Boombox not being synced between users.")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0+71645702ebc3ea437c29afaa8432d4398a219be3")] [assembly: AssemblyProduct("BoomboxSyncFix")] [assembly: AssemblyTitle("BoomboxSyncFix")] [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 BoomboxSyncFix { [BepInPlugin("BoomboxSyncFix", "BoomboxSyncFix", "1.1.0")] public class BoomboxSyncFixPlugin : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("BoomboxSyncFix"); public static BoomboxSyncFixPlugin Instance; internal ManualLogSource logger; private void Awake() { if ((Object)(object)Instance == (Object)null) { Instance = this; } logger = Logger.CreateLogSource("BoomboxSyncFix"); logger.LogInfo((object)"Plugin BoomboxSyncFix has loaded!"); harmony.PatchAll(typeof(BoomboxSyncFixPlugin)); harmony.PatchAll(typeof(BoomboxItemStartMusicPatch)); } } public static class PluginInfo { public const string PLUGIN_GUID = "BoomboxSyncFix"; public const string PLUGIN_NAME = "BoomboxSyncFix"; public const string PLUGIN_VERSION = "1.1.0"; } } namespace BoomboxSyncFix.Patches { [HarmonyPatch] internal class BoomboxItemStartMusicPatch { private static Dictionary<BoomboxItem, bool> seedSyncDictionary = new Dictionary<BoomboxItem, bool>(); private static FieldInfo playersManagerField = AccessTools.Field(typeof(BoomboxItem), "playersManager"); [HarmonyPatch(typeof(BoomboxItem), "StartMusic")] [HarmonyPrefix] public static void StartMusicPatch(BoomboxItem __instance) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown StartOfRound val = (StartOfRound)playersManagerField.GetValue(__instance); if ((!seedSyncDictionary.TryGetValue(__instance, out var value) || !value) && (Object)(object)val != (Object)null && val.randomMapSeed > 0) { int num = val.randomMapSeed - 10; __instance.musicRandomizer = new Random(num); BoomboxSyncFixPlugin.Instance.logger.LogInfo((object)$"Musicrandomizer variable has been synced with seed: {num}"); seedSyncDictionary[__instance] = true; } } [HarmonyPatch(typeof(StartOfRound), "OnPlayerConnectedClientRpc")] [HarmonyPrefix] public static void OnPlayerConnectedPatch(StartOfRound __instance) { BoomboxSyncFixPlugin.Instance.logger.LogInfo((object)"Another client joined -- forcing everyone to reintialize musicRandomizer."); forceReinitialize(seedSyncDictionary); } [HarmonyPatch(typeof(StartOfRound), "openingDoorsSequence")] [HarmonyPrefix] public static void openingDoorsSequencePatch(StartOfRound __instance) { BoomboxSyncFixPlugin.Instance.logger.LogInfo((object)"Round has loaded for all -- forcing everyone to reinitialize musicRandomizer."); forceReinitialize(seedSyncDictionary); } private static void forceReinitialize(Dictionary<BoomboxItem, bool> seedSyncDictionary) { foreach (BoomboxItem item in seedSyncDictionary.Keys.ToList()) { seedSyncDictionary[item] = false; } } } }
plugins/HolographicWings-LethalExpansion/LethalExpansion.dll
Decompiled 2 years 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.18")] [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__32_1; public static UnityAction <>9__32_0; public static Func<PluginInfo, bool> <>9__32_2; public static Func<AudioMixerGroup, bool> <>9__33_0; public static Func<GameObject, bool> <>9__33_1; public static Func<AudioMixerGroup, bool> <>9__33_2; public static Func<AudioMixerGroup, bool> <>9__33_3; public static Func<AudioMixerGroup, bool> <>9__33_4; public static Func<PluginInfo, bool> <>9__36_0; public static Func<PluginInfo, bool> <>9__36_1; public static Func<PluginInfo, bool> <>9__36_2; public static Func<PluginInfo, bool> <>9__36_3; internal bool <OnSceneLoaded>b__32_1(PluginInfo p) { return p.Metadata.GUID == "CoomfyDungeon"; } internal void <OnSceneLoaded>b__32_0() { ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true); ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true); } internal bool <OnSceneLoaded>b__32_2(PluginInfo p) { return p.Metadata.GUID == "BiggerLobby"; } internal bool <LoadCustomMoon>b__33_0(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <LoadCustomMoon>b__33_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__33_2(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <LoadCustomMoon>b__33_3(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <LoadCustomMoon>b__33_4(AudioMixerGroup a) { return ((Object)a).name == "Master"; } internal bool <waitForSession>b__36_0(PluginInfo p) { return p.Metadata.GUID == "BrutalCompanyPlus"; } internal bool <waitForSession>b__36_1(PluginInfo p) { return p.Metadata.GUID == "LethalAdjustments"; } internal bool <waitForSession>b__36_2(PluginInfo p) { return p.Metadata.GUID == "CoomfyDungeon"; } internal bool <waitForSession>b__36_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.18"; public static readonly Version ModVersion = new Version("1.3.18"); public static readonly int[] CompatibleGameVersions = new int[4] { 45, 47, 48, 49 }; 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.good }, { "299792458.MoreMoneyStart", compatibility.good } }; private List<PluginInfo> loadedPlugins = new List<PluginInfo>(); 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 bool dungeonGeneratorReady = 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_0c42: Unknown result type (might be due to invalid IL or missing references) //IL_0c48: Expected O, but got Unknown //IL_0c91: Unknown result type (might be due to invalid IL or missing references) //IL_0c9e: Expected O, but got Unknown //IL_0ca3: Unknown result type (might be due to invalid IL or missing references) //IL_0cb0: Expected O, but got Unknown //IL_0d17: Unknown result type (might be due to invalid IL or missing references) //IL_0d24: Expected O, but got Unknown //IL_0d2b: Unknown result type (might be due to invalid IL or missing references) //IL_0d38: Expected O, but got Unknown //IL_0d56: Unknown result type (might be due to invalid IL or missing references) //IL_0d5b: Unknown result type (might be due to invalid IL or missing references) //IL_0d67: 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.18 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.AddItem(new ConfigItem("LegacyMoonLoading", false, "Modules", "Roll back to Synchronous moon loading. (Freeze the game longer and highter chance of crash)")); 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.18 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_026e: 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_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Expected O, but got Unknown //IL_0416: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0435: Expected O, but got Unknown //IL_045c: 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_0154: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Expected O, but got Unknown //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_0738: Unknown result type (might be due to invalid IL or missing references) //IL_0727: 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; dungeonGeneratorReady = 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__32_0; if (obj == null) { UnityAction val = delegate { ConfigManager.Instance.SetItemValue("CoomfyDungeonCompatibility", value: true); ConfigManager.Instance.SetEntryValue("CoomfyDungeonCompatibility", value: true); }; <>c.<>9__32_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 (((Scene)(ref scene)).name == "CompanyBuilding") { SpaceLight.SetActive(false); terrainfixer.SetActive(false); dungeonGeneratorReady = true; } 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); dungeonGeneratorReady = true; 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); } } if (ConfigManager.Instance.FindItemValue<bool>("LegacyMoonLoading")) { LoadCustomMoon(scene).RunSynchronously(); } else { 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]; } dungeonGeneratorReady = true; 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; } dungeonGeneratorReady = false; 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 AddAudioClip(AudioClip[] clips) { foreach (AudioClip val in clips) { if ((Object)(object)val != (Object)null && !audioClips.ContainsKey(((Object)val).name) && !audioClips.ContainsValue(val)) { audioClips.Add(((Object)val).name, val); } } } public void AddAudioClip(string[] names, AudioClip[] clips) { for (int i = 0; i < clips.Length && i < names.Length; i++) { if ((Object)(object)clips[i] != (Object)null && !audioClips.ContainsKey(names[i]) && !audioClips.ContainsValue(clips[i])) { audioClips.Add(names[i], clips[i]); } } } 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(SI_NetworkDataInterfacing), 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).AddListene
plugins/HolographicWings-LethalExpansion/LethalSDK.dll
Decompiled 2 years 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 ScrapType scrapType = ScrapType.Normal; public string itemName = string.Empty; public int minValue = 0; public int maxValue = 0; public bool twoHanded = false; public GrabAnim HandedAnimation = GrabAnim.OneHanded; 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[9] { 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), new ScrapSpawnChancePerScene("Others", 10) }; [Header("Shovel")] public int shovelHitForce = 1; public AudioSource shovelAudio; public string reelUp = "ShovelReelUp"; public string swing = "ShovelSwing"; public string[] hitSFX = new string[2] { "ShovelHitDefault", "ShovelHitDefault2" }; [Header("Flashlight")] public bool usingPlayerHelmetLight = false; public int flashlightInterferenceLevel = 0; public Light flashlightBulb; public Light flashlightBulbGlow; public AudioSource flashlightAudio; public string[] flashlightClips = new string[1] { "FlashlightClick" }; public string outOfBatteriesClip = "FlashlightOutOfBatteries"; public string flashlightFlicker = "FlashlightFlicker"; public Material bulbLight; public Material bulbDark; public MeshRenderer flashlightMesh; public int flashlightTypeID = 0; public bool changeMaterial = true; [Header("Noisemaker")] public AudioSource noiseAudio; public AudioSource noiseAudioFar; public string[] noiseSFX = new string[1] { "ClownHorn1" }; public string[] noiseSFXFar = new string[1] { "ClownHornFar" }; public float noiseRange = 60f; public float maxLoudness = 1f; public float minLoudness = 0.6f; public float minPitch = 0.93f; public float maxPitch = 1f; public Animator triggerAnimator; [Header("WhoopieCushion")] public AudioSource whoopieCushionAudio; public string[] fartAudios = new string[4] { "Fart1", "Fart2", "Fart3", "Fart5" }; [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(); } } public enum ScrapType { Normal, Shovel, Flashlight, Noisemaker, WhoopieCushion } public enum GrabAnim { OneHanded, TwoHanded, Shotgun, Jetpack, Clipboard } } 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); } else { NetworkObject component = scrap.prefab.GetComponent<NetworkObject>(); string text = string.Empty; if (component.AlwaysReplicateAsRoot) { text += "\n- AlwaysReplicateAsRoot should be false."; } if (!component.SynchronizeTransform) { text += "\n- SynchronizeTransform should be true."; } if (component.ActiveSceneSynchronization) { text += "\n- ActiveSceneSynchronization should be false."; } if (!component.SceneMigrationSynchronization) { text += "\n- SceneMigrationSynchronization should be true."; } if (!component.SpawnWithObservers) { text += "\n- SpawnWithObservers should be true."; } if (!component.DontDestroyWithOwner) { text += "\n- DontDestroyWithOwner should be true."; } if (component.AutoObjectParentSync) { text += "\n- AutoObjectParentSync should be false."; } if (text.Length > 0) { EditorGUILayout.HelpBox("The NetworkObject of the Prefab have incorrect settings: " + text, (MessageType)2); } } 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_009d: 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) 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); if (assetBundleDirectory != null || assetBundleDirectory.Length != 0 || assetBundleDirectory != string.Empty) { AssetBundleManifest val3 = null; try { val3 = BuildPipeline.BuildAssetBundles(assetBundleDirectory, val, val2); } catch (Exception ex) { Debug.LogError((object)ex.Message); } 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."); } } 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; [HideInInspector] public GameObject instance; public InterfaceType interfaceType = InterfaceType.None; public void Awake() { //IL_018c: 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 ((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) { SI_NetworkDataInterfacing component2 = ((Component)this).GetComponent<SI_NetworkDataInterfacing>(); if ((Object)(object)component2 != (Object)null) { StringStringPair[] data = component2.getData(); InterfaceType interfaceType = this.interfaceType; InterfaceType interfaceType2 = interfaceType; if (interfaceType2 != InterfaceType.Base && interfaceType2 == InterfaceType.Entrance) { SI_EntranceTeleport componentInChildren = prefab.GetComponentInChildren<SI_EntranceTeleport>(); if ((Object)(object)componentInChildren != (Object)null) { if (data.Any((StringStringPair e) => e._string1.ToLower() == "entranceid")) { int.TryParse(data.First((StringStringPair e) => e._string1.ToLower() == "entranceid")._string2, out componentInChildren.EntranceID); } if (data.Any((StringStringPair e) => e._string1.ToLower() == "audioreverbpreset")) { int.TryParse(data.First((StringStringPair e) => e._string1.ToLower() == "audioreverbpreset")._string2, out componentInChildren.AudioReverbPreset); } } } } 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 enum InterfaceType { None, Base, Entrance } [AddComponentMenu("LethalSDK/NetworkDataInterfacing")] public class SI_NetworkDataInterfacing : MonoBehaviour { public StringStringPair[] data; [HideInInspector] public string serializedData; private void OnValidate() { serializedData = string.Join(";", data.Select((StringStringPair p) => p._string1 + "," + p._string2)); } public virtual StringStringPair[] getData() { return (from s in serializedData.Split(new char[1] { ';' }) select s.Split(new char[1] { ',' }) into split where split.Length == 2 select new StringStringPair(split[0], split[1])).ToArray(); } } 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 = 2; 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.Empt
plugins/no00ob-LCSoundTool/LC_SoundTool.dll
Decompiled 2 years agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; 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 HarmonyLib; using LCSoundTool.Networking; using LCSoundTool.Patches; using LCSoundTool.Resources; using LCSoundTool.Utilities; using LCSoundToolMod.Properties; using Microsoft.CodeAnalysis; 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: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("LC_SoundTool")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Various audio related functions. Mainly logs all sounds that are playing and what type of playback they're into the BepInEx console.")] [assembly: AssemblyFileVersion("1.4.0.0")] [assembly: AssemblyInformationalVersion("1.4.0")] [assembly: AssemblyProduct("LC_SoundTool")] [assembly: AssemblyTitle("LC_SoundTool")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/no00ob/LCSoundTool")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.4.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 LCSoundToolMod { public static class PluginInfo { public const string PLUGIN_GUID = "LC_SoundTool"; public const string PLUGIN_NAME = "LC_SoundTool"; public const string PLUGIN_VERSION = "1.4.0"; } } namespace LCSoundToolMod.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("LCSoundToolMod.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[] soundtool { get { object @object = ResourceManager.GetObject("soundtool", resourceCulture); return (byte[])@object; } } internal Resources() { } } } namespace LCSoundTool { public class AudioSourceExtension : MonoBehaviour { public AudioSource audioSource; public bool playOnAwake = false; public bool loop = false; private bool updateHasBeenLogged = false; private bool hasPlayed = false; private void OnEnable() { if (!((Object)(object)audioSource == (Object)null) && !audioSource.isPlaying) { if (playOnAwake) { audioSource.Play(); } if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in OnEnable function!"); } updateHasBeenLogged = false; hasPlayed = false; } } private void OnDisable() { if (!((Object)(object)audioSource == (Object)null) && audioSource.isPlaying) { if (playOnAwake) { audioSource.Stop(); } if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Stopped playback of {audioSource} with clip {audioSource.clip} in OnDisable function!"); } updateHasBeenLogged = false; hasPlayed = false; } } private void Update() { if ((Object)(object)audioSource == (Object)null) { return; } if ((Object)(object)audioSource.clip == (Object)null) { hasPlayed = false; } if (audioSource.isPlaying) { updateHasBeenLogged = false; } else if (!((Behaviour)audioSource).isActiveAndEnabled) { hasPlayed = false; } else { if (!playOnAwake) { return; } if ((Object)(object)audioSource.clip != (Object)null && !hasPlayed) { audioSource.Play(); if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Started playback of {audioSource} with clip {audioSource.clip} in Update function!"); } updateHasBeenLogged = false; hasPlayed = true; } else if (!updateHasBeenLogged) { updateHasBeenLogged = true; if (SoundTool.infoDebugging) { SoundTool.Instance.logger.LogDebug((object)$"(AudioSourceExtension) Can not start playback of {audioSource} with missing clip in Update function!"); } } } } } public class RandomAudioClip { public AudioClip clip; [Range(0f, 1f)] public float chance = 1f; public RandomAudioClip(AudioClip clip, float chance) { this.clip = clip; this.chance = chance; } } [BepInPlugin("LCSoundTool", "LC Sound Tool", "1.4.0")] public class SoundTool : BaseUnityPlugin { public enum AudioType { wav, ogg, mp3 } private const string PLUGIN_GUID = "LCSoundTool"; private const string PLUGIN_NAME = "LC Sound Tool"; private ConfigEntry<bool> configUseNetworking; private ConfigEntry<bool> configSyncRandomSeed; private ConfigEntry<float> configPlayOnAwakePatchRepeatDelay; private readonly Harmony harmony = new Harmony("LCSoundTool"); public static SoundTool Instance; internal ManualLogSource logger; public KeyboardShortcut toggleAudioSourceDebugLog; public KeyboardShortcut toggleIndepthDebugLog; public KeyboardShortcut toggleInformationalDebugLog; public bool wasKeyDown; public bool wasKeyDown2; public bool wasKeyDown3; public static bool debugAudioSources; public static bool indepthDebugging; public static bool infoDebugging; public static bool networkingInitialized { get; private set; } public static bool networkingAvailable { get; private set; } public static Dictionary<string, List<RandomAudioClip>> replacedClips { get; private set; } public static Dictionary<string, AudioClip> networkedClips => NetworkHandler.networkedAudioClips; public static Dictionary<string, AudioType> clipTypes { get; private set; } public static event Action ClientNetworkedAudioChanged { add { NetworkHandler.ClientNetworkedAudioChanged += value; } remove { NetworkHandler.ClientNetworkedAudioChanged -= value; } } public static event Action HostNetworkedAudioChanged { add { NetworkHandler.HostNetworkedAudioChanged += value; } remove { NetworkHandler.HostNetworkedAudioChanged -= value; } } public static bool IsDebuggingOn() { if (debugAudioSources || indepthDebugging || infoDebugging) { return true; } return false; } private void Awake() { //IL_012e: 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_014c: 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_016a: 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) networkingAvailable = true; if ((Object)(object)Instance == (Object)null) { Instance = this; } configUseNetworking = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "EnableNetworking", false, "Whether or not to use the networking built into this plugin. If set to true everyone in the lobby needs LCSoundTool installed and networking enabled to join."); configSyncRandomSeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Experimental", "SyncUnityRandomSeed", false, "Whether or not to sync the default Unity randomization seed with all clients. For this feature, networking has to be set to true. Will send the UnityEngine.Random.seed from the host to all clients automatically upon loading a networked scene."); configPlayOnAwakePatchRepeatDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Experimental", "NewPlayOnAwakePatchRepeatDelay", 90f, "How long to wait between checks for new playOnAwake AudioSources. Runs the same patching that is done when each scene is loaded with this delay between each run. DO NOT set too low or high. Anything below 10 or above 600 can cause issues. This time is in seconds. Set to 0 to disable rerunning the patch, but be warned that this might break runtime initialized playOnAwake AudioSources."); 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); } } } logger = Logger.CreateLogSource("LCSoundTool"); logger.LogInfo((object)"Plugin LCSoundTool is loaded!"); toggleAudioSourceDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[0]); toggleIndepthDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }); toggleInformationalDebugLog = new KeyboardShortcut((KeyCode)286, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }); debugAudioSources = false; indepthDebugging = false; infoDebugging = false; replacedClips = new Dictionary<string, List<RandomAudioClip>>(); clipTypes = new Dictionary<string, AudioType>(); } private void Start() { if (!configUseNetworking.Value) { networkingAvailable = false; Instance.logger.LogWarning((object)"Networking disabled. Mod in fully client side mode, but no networked actions can take place! You can safely ignore this if you want the mod to run fully client side."); } else { networkingAvailable = true; } if (configUseNetworking.Value) { logger.LogDebug((object)"Loading SoundTool AssetBundle..."); Assets.bundle = AssetBundle.LoadFromMemory(LCSoundToolMod.Properties.Resources.soundtool); if ((Object)(object)Assets.bundle == (Object)null) { logger.LogError((object)"Failed to load SoundTool AssetBundle!"); } else { logger.LogDebug((object)"Finished loading SoundTool AssetBundle!"); } } harmony.PatchAll(typeof(AudioSourcePatch)); if (configUseNetworking.Value) { harmony.PatchAll(typeof(GameNetworkManagerPatch)); harmony.PatchAll(typeof(StartOfRoundPatch)); } SceneManager.sceneLoaded += OnSceneLoaded; } private void Update() { if (configUseNetworking.Value) { if (!networkingInitialized) { if ((Object)(object)NetworkHandler.Instance != (Object)null) { networkingInitialized = true; } } else if ((Object)(object)NetworkHandler.Instance == (Object)null) { networkingInitialized = false; } } else { networkingInitialized = false; } if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsDown() && !wasKeyDown3) { wasKeyDown3 = true; wasKeyDown2 = false; wasKeyDown = false; } if (((KeyboardShortcut)(ref toggleInformationalDebugLog)).IsUp() && wasKeyDown3) { wasKeyDown3 = false; wasKeyDown2 = false; wasKeyDown = false; infoDebugging = !infoDebugging; Instance.logger.LogDebug((object)$"Toggling informational debug logs {infoDebugging}!"); return; } if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && !wasKeyDown2) { wasKeyDown2 = true; wasKeyDown = false; } if (((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsUp() && wasKeyDown2) { wasKeyDown2 = false; wasKeyDown = false; debugAudioSources = !debugAudioSources; indepthDebugging = debugAudioSources; infoDebugging = debugAudioSources; Instance.logger.LogDebug((object)$"Toggling in-depth AudioSource debug logs {debugAudioSources}!"); return; } if (!wasKeyDown2 && !((KeyboardShortcut)(ref toggleIndepthDebugLog)).IsDown() && ((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsDown() && !wasKeyDown) { wasKeyDown = true; wasKeyDown2 = false; } if (((KeyboardShortcut)(ref toggleAudioSourceDebugLog)).IsUp() && wasKeyDown) { wasKeyDown = false; wasKeyDown2 = false; debugAudioSources = !debugAudioSources; if (indepthDebugging && !debugAudioSources) { indepthDebugging = false; } Instance.logger.LogDebug((object)$"Toggling AudioSource debug logs {debugAudioSources}!"); } } private void OnDestroy() { SceneManager.sceneLoaded -= OnSceneLoaded; } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { //IL_0013: 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)Instance == (Object)null)) { PatchPlayOnAwakeAudio(scene); OnSceneLoadedNetworking(); if (((Scene)(ref scene)).name.ToLower().Contains("level")) { ((MonoBehaviour)this).StopAllCoroutines(); ((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, 1f)); } } } private IEnumerator PatchPlayOnAwakeDelayed(Scene scene, float wait) { //IL_000e: 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) if (infoDebugging) { logger.LogDebug((object)$"Started playOnAwake patch coroutine with delay of {wait} seconds"); } yield return (object)new WaitForSecondsRealtime(wait); if (infoDebugging) { logger.LogDebug((object)"Running playOnAwake patch coroutine!"); } PatchPlayOnAwakeAudio(scene); float repeatWait = configPlayOnAwakePatchRepeatDelay.Value; if (repeatWait != 0f) { if (repeatWait < 10f) { repeatWait = 10f; } if (repeatWait > 600f) { repeatWait = 600f; } ((MonoBehaviour)this).StartCoroutine(PatchPlayOnAwakeDelayed(scene, repeatWait)); } } private void PatchPlayOnAwakeAudio(Scene scene) { if (infoDebugging) { Instance.logger.LogDebug((object)("Grabbing all playOnAwake AudioSources for loaded scene " + ((Scene)(ref scene)).name)); } AudioSource[] allPlayOnAwakeAudioSources = GetAllPlayOnAwakeAudioSources(); if (infoDebugging) { Instance.logger.LogDebug((object)$"Found a total of {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)!"); Instance.logger.LogDebug((object)$"Starting setup on {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSource(s)..."); } AudioSource[] array = allPlayOnAwakeAudioSources; AudioSourceExtension audioSourceExtension = default(AudioSourceExtension); foreach (AudioSource val in array) { val.Stop(); if (((Component)((Component)val).transform).TryGetComponent<AudioSourceExtension>(ref audioSourceExtension)) { audioSourceExtension.audioSource = val; audioSourceExtension.playOnAwake = true; audioSourceExtension.loop = val.loop; val.playOnAwake = false; if (infoDebugging) { Instance.logger.LogDebug((object)$"-Set- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!"); } continue; } AudioSourceExtension audioSourceExtension2 = ((Component)val).gameObject.AddComponent<AudioSourceExtension>(); audioSourceExtension2.audioSource = val; audioSourceExtension2.playOnAwake = true; audioSourceExtension2.loop = val.loop; val.playOnAwake = false; if (infoDebugging) { Instance.logger.LogDebug((object)$"-Add- {Array.IndexOf(allPlayOnAwakeAudioSources, val) + 1} {val} done!"); } } if (infoDebugging) { Instance.logger.LogDebug((object)$"Done setting up {allPlayOnAwakeAudioSources.Length} playOnAwake AudioSources!"); } } private void OnSceneLoadedNetworking() { if (networkingAvailable && networkingInitialized && configSyncRandomSeed.Value) { int num = (int)DateTime.Now.Ticks; Random.InitState(num); SendUnityRandomSeed(num); } } public AudioSource[] GetAllPlayOnAwakeAudioSources() { AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true); List<AudioSource> list = new List<AudioSource>(); for (int i = 0; i < array.Length; i++) { if (array[i].playOnAwake) { list.Add(array[i]); } } return list.ToArray(); } public static void ReplaceAudioClip(string originalName, AudioClip newClip) { if (string.IsNullOrEmpty(originalName)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); return; } if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); return; } string name = newClip.GetName(); float num = 100f; if (name.Contains("-")) { string[] array = name.Split('-'); if (array.Length > 1) { string s = array[^1]; if (int.TryParse(s, out var result)) { num = (float)result * 0.01f; name = string.Join("-", array, 0, array.Length - 1); } } } if (replacedClips.ContainsKey(originalName) && num >= 100f) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with 100% chance of playback! This is not allowed."); return; } num = Mathf.Clamp01(num); if (replacedClips.ContainsKey(originalName)) { replacedClips[originalName].Add(new RandomAudioClip(newClip, num)); } else { replacedClips[originalName] = new List<RandomAudioClip> { new RandomAudioClip(newClip, num) }; } float num2 = 0f; for (int i = 0; i < replacedClips[originalName].Count(); i++) { num2 += replacedClips[originalName][i].chance; } if ((num2 < 1f || num2 > 1f) && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} does not equal 100% (at least yet?)"); } else if (num2 == 1f && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} is equal to 100%"); } } public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip) { if ((Object)(object)originalClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); } else if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); } else { ReplaceAudioClip(originalClip.GetName(), newClip); } } public static void ReplaceAudioClip(string originalName, AudioClip newClip, float chance) { if (string.IsNullOrEmpty(originalName)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); return; } if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); return; } string name = newClip.GetName(); if (replacedClips.ContainsKey(originalName) && chance >= 100f) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip that already has been replaced with 100% chance of playback! This is not allowed."); return; } chance = Mathf.Clamp01(chance); if (replacedClips.ContainsKey(originalName)) { replacedClips[originalName].Add(new RandomAudioClip(newClip, chance)); } else { replacedClips[originalName] = new List<RandomAudioClip> { new RandomAudioClip(newClip, chance) }; } float num = 0f; for (int i = 0; i < replacedClips[originalName].Count(); i++) { num += replacedClips[originalName][i].chance; } if ((num < 1f || num > 1f) && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} does not equal 100% (at least yet?)"); } else if (num == 1f && replacedClips[originalName].Count() > 1) { Instance.logger.LogDebug((object)$"The current total combined chance for replaced {replacedClips[originalName].Count()} random audio clips for audio clip {originalName} is equal to 100%"); } } public static void ReplaceAudioClip(AudioClip originalClip, AudioClip newClip, float chance) { if ((Object)(object)originalClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without original clip specified! This is not allowed."); } else if ((Object)(object)newClip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to replace an audio clip without new clip specified! This is not allowed."); } else { ReplaceAudioClip(originalClip.GetName(), newClip, chance); } } public static void RemoveRandomAudioClip(string name, float chance) { if (string.IsNullOrEmpty(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed."); } else if (!replacedClips.ContainsKey(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed."); } else { if (!(chance > 0f)) { return; } for (int i = 0; i < replacedClips[name].Count(); i++) { if (replacedClips[name][i].chance == chance) { replacedClips[name].RemoveAt(i); break; } } } } public static void RestoreAudioClip(string name) { if (string.IsNullOrEmpty(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed."); } else if (!replacedClips.ContainsKey(name)) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip that does not exist! This is not allowed."); } else { replacedClips.Remove(name); } } public static void RestoreAudioClip(AudioClip clip) { if ((Object)(object)clip == (Object)null) { Instance.logger.LogWarning((object)"Plugin LCSoundTool is trying to restore an audio clip without original clip specified! This is not allowed."); } else { RestoreAudioClip(clip.GetName()); } } public static AudioClip GetAudioClip(string modFolder, string soundName) { return GetAudioClip(modFolder, string.Empty, soundName); } public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName) { AudioType audioType = AudioType.wav; bool flag = true; string text = " "; string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName); string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName); string path = Path.Combine(Paths.PluginPath, modFolder, subFolder); string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName); string path2 = Path.Combine(Paths.PluginPath, subFolder); if (!Directory.Exists(path)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!")); } else { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!")); if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author."); } } flag = false; } if (!File.Exists(text2)) { Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!")); flag = false; Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "...")); if (File.Exists(text3)) { Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!")); text2 = text3; flag = true; } else { Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!")); } } if (Directory.Exists(path2)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!")); } else if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!"); } } if (File.Exists(text4)) { Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!")); text = " legacy "; text2 = text4; flag = true; } string[] array = soundName.Split('.'); if (array[^1].ToLower().Contains("ogg")) { audioType = AudioType.ogg; Instance.logger.LogDebug((object)"File detected as an Ogg Vorbis file!"); } else if (array[^1].ToLower().Contains("mp3")) { audioType = AudioType.mp3; Instance.logger.LogDebug((object)"File detected as a MPEG MP3 file!"); } AudioClip val = null; if (flag) { Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2)); switch (audioType) { case AudioType.wav: val = WavUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.ogg: val = OggUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.mp3: val = Mp3Utility.LoadFromDiskToAudioClip(text2); break; } Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!"); } else { Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!")); } if (string.IsNullOrEmpty(val.GetName())) { string empty = string.Empty; string[] array2 = new string[0]; switch (audioType) { case AudioType.wav: empty = soundName.Replace(".wav", ""); array2 = empty.Split('/'); if (array2.Length <= 1) { array2 = empty.Split('\\'); } empty = array2[^1]; ((Object)val).name = empty; break; case AudioType.ogg: empty = soundName.Replace(".ogg", ""); array2 = empty.Split('/'); if (array2.Length <= 1) { array2 = empty.Split('\\'); } empty = array2[^1]; ((Object)val).name = empty; break; case AudioType.mp3: empty = soundName.Replace(".mp3", ""); array2 = empty.Split('/'); if (array2.Length <= 1) { array2 = empty.Split('\\'); } empty = array2[^1]; ((Object)val).name = empty; break; } } if ((Object)(object)val != (Object)null) { clipTypes.Add(val.GetName(), audioType); } return val; } public static AudioClip GetAudioClip(string modFolder, string soundName, AudioType audioType) { return GetAudioClip(modFolder, string.Empty, soundName, audioType); } public static AudioClip GetAudioClip(string modFolder, string subFolder, string soundName, AudioType audioType) { bool flag = true; string text = " "; string text2 = Path.Combine(Paths.PluginPath, modFolder, subFolder, soundName); string text3 = Path.Combine(Paths.PluginPath, modFolder, soundName); string path = Path.Combine(Paths.PluginPath, modFolder, subFolder); string text4 = Path.Combine(Paths.PluginPath, subFolder, soundName); string path2 = Path.Combine(Paths.PluginPath, subFolder); if (!Directory.Exists(path)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + "/" + subFolder + " does not exist!")); } else { Instance.logger.LogWarning((object)("Requested directory at BepInEx/Plugins/" + modFolder + " does not exist!")); if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"This sound mod might not be compatable with mod managers. You should contact the sound mod's author."); } } flag = false; } if (!File.Exists(text2)) { Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + text2 + "!")); flag = false; Instance.logger.LogDebug((object)("Looking for audio file from mod root instead at " + text3 + "...")); if (File.Exists(text3)) { Instance.logger.LogDebug((object)("Found audio file at path " + text3 + "!")); text2 = text3; flag = true; } else { Instance.logger.LogWarning((object)("Requested audio file does not exist at mod root path " + text3 + "!")); } } if (Directory.Exists(path2)) { if (!string.IsNullOrEmpty(subFolder)) { Instance.logger.LogWarning((object)("Legacy directory location at BepInEx/Plugins/" + subFolder + " found!")); } else if (!modFolder.Contains("-")) { Instance.logger.LogWarning((object)"Legacy directory location at BepInEx/Plugins found!"); } } if (File.Exists(text4)) { Instance.logger.LogWarning((object)("Legacy path contains the requested audio file at path " + text4 + "!")); text = " legacy "; text2 = text4; flag = true; } switch (audioType) { case AudioType.wav: Instance.logger.LogDebug((object)"File defined as a WAV file!"); break; case AudioType.ogg: Instance.logger.LogDebug((object)"File defined as an Ogg Vorbis file!"); break; case AudioType.mp3: Instance.logger.LogDebug((object)"File defined as a MPEG MP3 file!"); break; } AudioClip val = null; if (flag) { Instance.logger.LogDebug((object)("Loading AudioClip " + soundName + " from" + text + "path: " + text2)); switch (audioType) { case AudioType.wav: val = WavUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.ogg: val = OggUtility.LoadFromDiskToAudioClip(text2); break; case AudioType.mp3: val = Mp3Utility.LoadFromDiskToAudioClip(text2); break; } Instance.logger.LogDebug((object)$"Finished loading AudioClip {soundName} with length of {val.length}!"); } else { Instance.logger.LogWarning((object)("Failed to load AudioClip " + soundName + " from invalid" + text + "path at " + text2 + "!")); } if (string.IsNullOrEmpty(val.GetName())) { string empty = string.Empty; string[] array = new string[0]; switch (audioType) { case AudioType.wav: empty = soundName.Replace(".wav", ""); array = empty.Split('/'); if (array.Length <= 1) { array = empty.Split('\\'); } empty = array[^1]; ((Object)val).name = empty; break; case AudioType.ogg: empty = soundName.Replace(".ogg", ""); array = empty.Split('/'); if (array.Length <= 1) { array = empty.Split('\\'); } empty = array[^1]; ((Object)val).name = empty; break; case AudioType.mp3: empty = soundName.Replace(".mp3", ""); array = empty.Split('/'); if (array.Length <= 1) { array = empty.Split('\\'); } empty = array[^1]; ((Object)val).name = empty; break; } } if ((Object)(object)val != (Object)null) { clipTypes.Add(val.GetName(), audioType); } return val; } public static void SendNetworkedAudioClip(AudioClip audioClip) { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)$"Networking disabled! Failed to send {audioClip}!"); return; } if ((Object)(object)audioClip == (Object)null) { Instance.logger.LogWarning((object)$"audioClip variable of SendAudioClip not assigned! Failed to send {audioClip}!"); return; } if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)$"Instance of SoundTool not found or networking has not finished initializing. Failed to send {audioClip}! If you're sending things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!"); return; } string name = audioClip.GetName(); if (clipTypes.ContainsKey(name)) { if (clipTypes[name] == AudioType.ogg) { NetworkHandler.Instance.SendAudioClipServerRpc(name, OggUtility.AudioClipToByteArray(audioClip, out var _)); return; } if (clipTypes[name] == AudioType.mp3) { NetworkHandler.Instance.SendAudioClipServerRpc(name, Mp3Utility.AudioClipToByteArray(audioClip, out var _)); return; } } NetworkHandler.Instance.SendAudioClipServerRpc(name, WavUtility.AudioClipToByteArray(audioClip, out var _)); } public static void RemoveNetworkedAudioClip(AudioClip audioClip) { RemoveNetworkedAudioClip(audioClip.GetName()); } public static void RemoveNetworkedAudioClip(string audioClip) { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)("Networking disabled! Failed to remove " + audioClip + "!")); } else if (string.IsNullOrEmpty(audioClip)) { Instance.logger.LogWarning((object)("audioClip variable of RemoveAudioClip not assigned! Failed to remove " + audioClip + "!")); } else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)("Instance of SoundTool not found or networking has not finished initializing. Failed to remove " + audioClip + "! If you're removing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!")); } else { NetworkHandler.Instance.RemoveAudioClipServerRpc(audioClip); } } public static void SyncNetworkedAudioClips() { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)"Networking disabled! Failed to sync audio clips!"); } else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to sync networked audio! If you're syncing things in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked audio runs only after the player setups a networked connection!"); } else { NetworkHandler.Instance.SyncAudioClipsServerRpc(); } } public static void SendUnityRandomSeed(int seed) { if (!Instance.configUseNetworking.Value) { Instance.logger.LogWarning((object)"Networking disabled! Failed to send Unity random seed!"); } else if ((Object)(object)Instance == (Object)null || (Object)(object)GameNetworkManagerPatch.networkHandlerHost == (Object)null || (Object)(object)NetworkHandler.Instance == (Object)null) { Instance.logger.LogWarning((object)"Instance of SoundTool not found or networking has not finished initializing. Failed to send Unity Random seed! If you're sending the seed in Awake or in a scene such as the main menu it might be too early, please try some of the other built-in Unity methods and make sure your networked methods run only after the player setups a networked connection!"); } else { NetworkHandler.Instance.SendSeedToClientsServerRpc(seed); } } } } namespace LCSoundTool.Utilities { public static class Mp3Utility { public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples) { samples = new float[audioClip.samples * audioClip.channels]; audioClip.GetData(samples, 0); byte[] array = new byte[samples.Length * 2]; int num = 32767; for (int i = 0; i < samples.Length; i++) { short value = (short)(samples[i] * (float)num); BitConverter.GetBytes(value).CopyTo(array, i * 2); } return array; } public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName) { int num = 16; int num2 = num / 8; AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false); val.SetData(ConvertByteArrayToFloatArray(byteArray), 0); return val; } private static float[] ConvertByteArrayToFloatArray(byte[] byteArray) { float[] array = new float[byteArray.Length / 2]; int num = 32767; for (int i = 0; i < array.Length; i++) { short num2 = BitConverter.ToInt16(byteArray, i * 2); array[i] = (float)num2 / (float)num; } return array; } public static AudioClip LoadFromDiskToAudioClip(string path) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 AudioClip result = null; UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)13); try { audioClip.SendWebRequest(); try { while (!audioClip.isDone) { } if ((int)audioClip.result != 1) { SoundTool.Instance.logger.LogError((object)("Failed to load MP3 AudioClip from path: " + path + " Full error: " + audioClip.error)); } else { result = DownloadHandlerAudioClip.GetContent(audioClip); } } catch (Exception ex) { SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace)); } } finally { ((IDisposable)audioClip)?.Dispose(); } return result; } } public static class OggUtility { public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples) { samples = new float[audioClip.samples * audioClip.channels]; audioClip.GetData(samples, 0); byte[] array = new byte[samples.Length * 2]; int num = 32767; for (int i = 0; i < samples.Length; i++) { short value = (short)(samples[i] * (float)num); BitConverter.GetBytes(value).CopyTo(array, i * 2); } return array; } public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName) { int num = 16; int num2 = num / 8; AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false); val.SetData(ConvertByteArrayToFloatArray(byteArray), 0); return val; } private static float[] ConvertByteArrayToFloatArray(byte[] byteArray) { float[] array = new float[byteArray.Length / 2]; int num = 32767; for (int i = 0; i < array.Length; i++) { short num2 = BitConverter.ToInt16(byteArray, i * 2); array[i] = (float)num2 / (float)num; } return array; } public static AudioClip LoadFromDiskToAudioClip(string path) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 AudioClip result = null; UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)14); try { audioClip.SendWebRequest(); try { while (!audioClip.isDone) { } if ((int)audioClip.result != 1) { SoundTool.Instance.logger.LogError((object)("Failed to load OGGVORBIS AudioClip from path: " + path + " Full error: " + audioClip.error)); } else { result = DownloadHandlerAudioClip.GetContent(audioClip); } } catch (Exception ex) { SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace)); } } finally { ((IDisposable)audioClip)?.Dispose(); } return result; } } public static class WavUtility { public static byte[] AudioClipToByteArray(AudioClip audioClip, out float[] samples) { samples = new float[audioClip.samples * audioClip.channels]; audioClip.GetData(samples, 0); byte[] array = new byte[samples.Length * 2]; int num = 32767; for (int i = 0; i < samples.Length; i++) { short value = (short)(samples[i] * (float)num); BitConverter.GetBytes(value).CopyTo(array, i * 2); } return array; } public static AudioClip ByteArrayToAudioClip(byte[] byteArray, string clipName) { int num = 16; int num2 = num / 8; AudioClip val = AudioClip.Create(clipName, byteArray.Length / num2, 1, 44100, false); val.SetData(ConvertByteArrayToFloatArray(byteArray), 0); return val; } private static float[] ConvertByteArrayToFloatArray(byte[] byteArray) { float[] array = new float[byteArray.Length / 2]; int num = 32767; for (int i = 0; i < array.Length; i++) { short num2 = BitConverter.ToInt16(byteArray, i * 2); array[i] = (float)num2 / (float)num; } return array; } public static AudioClip LoadFromDiskToAudioClip(string path) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 AudioClip result = null; UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20); try { audioClip.SendWebRequest(); try { while (!audioClip.isDone) { } if ((int)audioClip.result != 1) { SoundTool.Instance.logger.LogError((object)("Failed to load WAV AudioClip from path: " + path + " Full error: " + audioClip.error)); } else { result = DownloadHandlerAudioClip.GetContent(audioClip); } } catch (Exception ex) { SoundTool.Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace)); } } finally { ((IDisposable)audioClip)?.Dispose(); } return result; } } } namespace LCSoundTool.Patches { [HarmonyPatch(typeof(AudioSource))] internal class AudioSourcePatch { private static Dictionary<string, AudioClip> originalClips = new Dictionary<string, AudioClip>(); [HarmonyPatch("Play", new Type[] { })] [HarmonyPrefix] public static void Play_Patch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayMethod(__instance); } [HarmonyPatch("Play", new Type[] { typeof(ulong) })] [HarmonyPrefix] public static void Play_UlongPatch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayMethod(__instance); } [HarmonyPatch("Play", new Type[] { typeof(double) })] [HarmonyPrefix] public static void Play_DoublePatch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayMethod(__instance); } [HarmonyPatch("PlayDelayed", new Type[] { typeof(float) })] [HarmonyPrefix] public static void PlayDelayed_Patch(AudioSource __instance) { RunDynamicClipReplacement(__instance); DebugPlayDelayedMethod(__instance); } [HarmonyPatch("PlayClipAtPoint", new Type[] { typeof(AudioClip), typeof(Vector3), typeof(float) })] [HarmonyPrefix] public static bool PlayClipAtPoint_Patch(AudioClip clip, Vector3 position, float volume) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0012: 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) GameObject val = new GameObject("One shot audio"); val.transform.position = position; AudioSource val2 = val.AddComponent<AudioSource>(); val2.clip = clip; val2.spatialBlend = 1f; val2.volume = volume; RunDynamicClipReplacement(val2); val2.Play(); DebugPlayClipAtPointMethod(val2, position); Object.Destroy((Object)(object)val, clip.length * ((Time.timeScale < 0.01f) ? 0.01f : Time.timeScale)); return false; } [HarmonyPatch("PlayOneShotHelper", new Type[] { typeof(AudioSource), typeof(AudioClip), typeof(float) })] [HarmonyPrefix] public static void PlayOneShotHelper_Patch(AudioSource source, ref AudioClip clip, float volumeScale) { clip = ReplaceClipWithNew(clip); DebugPlayOneShotMethod(source, clip); } private static void DebugPlayMethod(AudioSource instance) { if ((Object)(object)instance == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name}"); } else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} at"); Transform val = ((Component)instance).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}"); } } } private static void DebugPlayDelayedMethod(AudioSource instance) { if ((Object)(object)instance == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} at {((Component)instance).transform.root} is playing {((Object)instance.clip).name} with delay"); } else if (SoundTool.indepthDebugging && (Object)(object)instance != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{instance} is playing {((Object)instance.clip).name} with delay at"); Transform val = ((Component)instance).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)instance).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)instance).transform.root}"); } } } private static void DebugPlayClipAtPointMethod(AudioSource audioSource, Vector3 position) { //IL_0065: 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) if ((Object)(object)audioSource == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{audioSource} at {((Component)audioSource).transform.root} is playing {((Object)audioSource.clip).name} at point {position}"); } else if (SoundTool.indepthDebugging && (Object)(object)audioSource != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{audioSource} is playing {((Object)audioSource.clip).name} located at point {position} within "); Transform val = ((Component)audioSource).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)audioSource).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)audioSource).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)audioSource).transform.root}"); } } } private static void DebugPlayOneShotMethod(AudioSource source, AudioClip clip) { if ((Object)(object)source == (Object)null || (Object)(object)clip == (Object)null) { return; } if (SoundTool.debugAudioSources && !SoundTool.indepthDebugging && (Object)(object)source != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{source} at {((Component)source).transform.root} is playing one shot {((Object)clip).name}"); } else if (SoundTool.indepthDebugging && (Object)(object)source != (Object)null) { SoundTool.Instance.logger.LogDebug((object)$"{source} is playing one shot {((Object)clip).name} at"); Transform val = ((Component)source).transform; while ((Object)(object)val.parent != (Object)null || (Object)(object)val != (Object)(object)((Component)source).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {val.parent}"); val = val.parent; } if ((Object)(object)val == (Object)(object)((Component)source).transform.root) { SoundTool.Instance.logger.LogDebug((object)$"--- {((Component)source).transform.root}"); } } } private static void RunDynamicClipReplacement(AudioSource instance) { if ((Object)(object)instance == (Object)null || (Object)(object)instance.clip == (Object)null) { return; } string name = instance.clip.GetName(); if (SoundTool.replacedClips.ContainsKey(name)) { if (!originalClips.ContainsKey(name)) { originalClips.Add(name, instance.clip); } List<RandomAudioClip> list = SoundTool.replacedClips[name]; float num = 0f; foreach (RandomAudioClip item in list) { num += item.chance; } float num2 = Random.Range(0f, num); { foreach (RandomAudioClip item2 in list) { if (num2 <= item2.chance) { instance.clip = item2.clip; break; } num2 -= item2.chance; } return; } } if (originalClips.ContainsKey(name)) { instance.clip = originalClips[name]; originalClips.Remove(name); } } private static AudioClip ReplaceClipWithNew(AudioClip original) { if ((Object)(object)original == (Object)null) { return original; } string name = original.GetName(); if (SoundTool.replacedClips.ContainsKey(name)) { if (!originalClips.ContainsKey(name)) { originalClips.Add(name, original); } List<RandomAudioClip> list = SoundTool.replacedClips[name]; float num = 0f; foreach (RandomAudioClip item in list) { num += item.chance; } float num2 = Random.Range(0f, num); foreach (RandomAudioClip item2 in list) { if (num2 <= item2.chance) { return item2.clip; } num2 -= item2.chance; } } else if (originalClips.ContainsKey(name)) { AudioClip result = originalClips[name]; originalClips.Remove(name); return result; } return original; } } [HarmonyPatch(typeof(GameNetworkManager))] internal class GameNetworkManagerPatch { public static GameObject networkPrefab; public static GameObject networkHandlerHost; [HarmonyPatch("Start")] [HarmonyPrefix] public static void Start_Patch() { if (!((Object)(object)networkPrefab != (Object)null)) { SoundTool.Instance.logger.LogDebug((object)"Loading NetworkHandler prefab..."); networkPrefab = Assets.bundle.LoadAsset<GameObject>("SoundToolNetworkHandler.prefab"); if ((Object)(object)networkPrefab == (Object)null) { SoundTool.Instance.logger.LogError((object)"Failed to load NetworkHandler prefab!"); } if ((Object)(object)networkPrefab != (Object)null) { NetworkManager.Singleton.AddNetworkPrefab(networkPrefab); SoundTool.Instance.logger.LogDebug((object)"Registered NetworkHandler prefab!"); } else { SoundTool.Instance.logger.LogWarning((object)"Failed to registered NetworkHandler prefab! No networking can take place."); } } } [HarmonyPatch("StartDisconnect")] [HarmonyPostfix] private static void StartDisconnect_Patch() { try { if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { SoundTool.Instance.logger.LogDebug((object)"Destroying NetworkHandler prefab!"); Object.Destroy((Object)(object)networkHandlerHost); networkHandlerHost = null; } } catch { SoundTool.Instance.logger.LogError((object)"Failed to destroy NetworkHandler prefab!"); } } } [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void SpawnNetworkHandler() { //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) try { if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) { SoundTool.Instance.logger.LogDebug((object)"Spawning NetworkHandler prefab!"); GameNetworkManagerPatch.networkHandlerHost = Object.Instantiate<GameObject>(GameNetworkManagerPatch.networkPrefab, Vector3.zero, Quaternion.identity); GameNetworkManagerPatch.networkHandlerHost.GetComponent<NetworkObject>().Spawn(true); } } catch { SoundTool.Instance.logger.LogError((object)"Failed to spawn NetworkHandler prefab!"); } } } } namespace LCSoundTool.Networking { public class NetworkHandler : NetworkBehaviour { public static NetworkHandler Instance { get; private set; } public static Dictionary<string, AudioClip> networkedAudioClips { get; private set; } public static event Action ClientNetworkedAudioChanged; public static event Action HostNetworkedAudioChanged; public override void OnNetworkSpawn() { Debug.Log((object)"LCSoundTool - NetworkHandler created!"); NetworkHandler.ClientNetworkedAudioChanged = null; NetworkHandler.HostNetworkedAudioChanged = null; networkedAudioClips = new Dictionary<string, AudioClip>(); Instance = this; } [ClientRpc] public void ReceiveAudioClipClientRpc(string clipName, byte[] audioData) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_0088: 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_00c6: 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_0105: 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: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(2736638642u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } bool flag2 = audioData != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives)); if (flag2) { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives)); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2736638642u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } if (!networkedAudioClips.ContainsKey(clipName)) { AudioClip val3 = null; if (SoundTool.clipTypes.ContainsKey(clipName)) { if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg) { val3 = OggUtility.ByteArrayToAudioClip(audioData, clipName); } else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3) { val3 = Mp3Utility.ByteArrayToAudioClip(audioData, clipName); } } if ((Object)(object)val3 == (Object)null) { val3 = WavUtility.ByteArrayToAudioClip(audioData, clipName); } networkedAudioClips.Add(clipName, val3); NetworkHandler.ClientNetworkedAudioChanged?.Invoke(); } else { SoundTool.Instance.logger.LogDebug((object)("Sound " + clipName + " already exists for this client! Skipping addition of this sound for this client.")); } } [ClientRpc] public void RemoveAudioClipClientRpc(string clipName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: 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_00ba: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1355469546u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1355469546u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost) && networkedAudioClips.ContainsKey(clipName)) { networkedAudioClips.Remove(clipName); NetworkHandler.ClientNetworkedAudioChanged?.Invoke(); } } [ClientRpc] public void SyncAudioClipsClientRpc(Strings clipNames) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: 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_007d: 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_0097: 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 != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(3300200130u, val, (RpcDelivery)0); ((FastBufferWriter)(ref val2)).WriteValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable)); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3300200130u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } string[] myStrings = clipNames.MyStrings; for (int i = 0; i < myStrings.Length; i++) { if (!networkedAudioClips.ContainsKey(myStrings[i])) { SendExistingAudioClipServerRpc(myStrings[i]); } } } [ClientRpc] public void ReceiveSeedClientRpc(int seed) { //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)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val = default(ClientRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(1556253924u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, seed); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1556253924u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { Random.InitState(seed); SoundTool.Instance.logger.LogDebug((object)$"Client received a new Unity Random seed of {seed}!"); } } } [ServerRpc(RequireOwnership = false)] public void SendAudioClipServerRpc(string clipName, byte[] audioData) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_0088: 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_00c6: 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_0105: 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: 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(867452943u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } bool flag2 = audioData != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives)); if (flag2) { ((FastBufferWriter)(ref val2)).WriteValueSafe<byte>(audioData, default(ForPrimitives)); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 867452943u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ReceiveAudioClipClientRpc(clipName, audioData); NetworkHandler.HostNetworkedAudioChanged?.Invoke(); } } [ServerRpc(RequireOwnership = false)] public void RemoveAudioClipServerRpc(string clipName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: 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_00ba: 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(3103497155u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 3103497155u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { RemoveAudioClipClientRpc(clipName); NetworkHandler.HostNetworkedAudioChanged?.Invoke(); } } [ServerRpc(RequireOwnership = false)] public void SyncAudioClipsServerRpc() { //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)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(178607916u, val, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 178607916u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Strings clipNames = new Strings(networkedAudioClips.Keys.ToArray()); if (clipNames.MyStrings.Length < 1) { SoundTool.Instance.logger.LogDebug((object)"No sounds found in networkedClips. Syncing process cancelled!"); } else { SyncAudioClipsClientRpc(clipNames); } } } [ServerRpc(RequireOwnership = false)] public void SendExistingAudioClipServerRpc(string clipName) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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_0088: 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_00ba: 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(4006259189u, val, (RpcDelivery)0); bool flag = clipName != null; ((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { ((FastBufferWriter)(ref val2)).WriteValueSafe(clipName, false); } ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4006259189u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } if (networkedAudioClips.ContainsKey(clipName)) { byte[] array = null; if (SoundTool.clipTypes.ContainsKey(clipName)) { if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.ogg) { array = OggUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _); } else if (SoundTool.clipTypes[clipName] == SoundTool.AudioType.mp3) { array = Mp3Utility.AudioClipToByteArray(networkedAudioClips[clipName], out var _); } } if (array == null) { array = WavUtility.AudioClipToByteArray(networkedAudioClips[clipName], out var _); } ReceiveAudioClipClientRpc(clipName, array); } else { SoundTool.Instance.logger.LogWarning((object)"Trying to obtain and sync a sound from the host that does not exist in the host's game!"); } } [ServerRpc(RequireOwnership = false)] public void SendSeedToClientsServerRpc(int seed) { //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)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(4286510828u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, seed); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 4286510828u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost) && ((NetworkBehaviour)this).IsHost) { ReceiveSeedClientRpc(seed); SoundTool.Instance.logger.LogDebug((object)$"Sending a new Unity random seed of {seed} to all clients..."); } } } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_NetworkHandler() { //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 //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(2736638642u, new RpcReceiveHandler(__rpc_handler_2736638642)); NetworkManager.__rpc_func_table.Add(1355469546u, new RpcReceiveHandler(__rpc_handler_1355469546)); NetworkManager.__rpc_func_table.Add(3300200130u, new RpcReceiveHandler(__rpc_handler_3300200130)); NetworkManager.__rpc_func_table.Add(1556253924u, new RpcReceiveHandler(__rpc_handler_1556253924)); NetworkManager.__rpc_func_table.Add(867452943u, new RpcReceiveHandler(__rpc_handler_867452943)); NetworkManager.__rpc_func_table.Add(3103497155u, new RpcReceiveHandler(__rpc_handler_3103497155)); NetworkManager.__rpc_func_table.Add(178607916u, new RpcReceiveHandler(__rpc_handler_178607916)); NetworkManager.__rpc_func_table.Add(4006259189u, new RpcReceiveHandler(__rpc_handler_4006259189)); NetworkManager.__rpc_func_table.Add(4286510828u, new RpcReceiveHandler(__rpc_handler_4286510828)); } private static void __rpc_handler_2736638642(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0067: 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_00a6: 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_0090: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } bool flag2 = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives)); byte[] audioData = null; if (flag2) { ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives)); } target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).ReceiveAudioClipClientRpc(clipName, audioData); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1355469546(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).RemoveAudioClipClientRpc(clipName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3300200130(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0044: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { Strings clipNames = default(Strings); ((FastBufferReader)(ref reader)).ReadValueSafe<Strings>(ref clipNames, default(ForNetworkSerializable)); target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).SyncAudioClipsClientRpc(clipNames); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1556253924(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) { int seed = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref seed); target.__rpc_exec_stage = (__RpcExecStage)2; ((NetworkHandler)(object)target).ReceiveSeedClientRpc(seed); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_867452943(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0067: 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_00a6: 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_0090: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } bool flag2 = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives)); byte[] audioData = null; if (flag2) { ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref audioData, default(ForPrimitives)); } target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).SendAudioClipServerRpc(clipName, audioData); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3103497155(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).RemoveAudioClipServerRpc(clipName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_178607916(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; ((NetworkHandler)(object)target).SyncAudioClipsServerRpc(); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4006259189(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: 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_0061: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); string clipName = null; if (flag) { ((FastBufferReader)(ref reader)).ReadValueSafe(ref clipName, false); } target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).SendExistingAudioClipServerRpc(clipName); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_4286510828(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) { int seed = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref seed); target.__rpc_exec_stage = (__RpcExecStage)1; ((NetworkHandler)(object)target).SendSeedToClientsServerRpc(seed); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "NetworkHandler"; } } public struct Strings : INetworkSerializable { private string[] myStrings; public string[] MyStrings { get { return myStrings; } set { myStrings = value; } } public Strings(string[] myStrings) { this.myStrings = myStrings; } public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //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_0024: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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) if (serializer.IsWriter) { FastBufferWriter fastBufferWriter = serializer.GetFastBufferWriter(); int num = myStrings.Length; ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives)); for (int i = 0; i < myStrings.Length; i++) { ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe(myStrings[i], false); } } if (serializer.IsReader) { FastBufferReader fastBufferReader = serializer.GetFastBufferReader(); int num2 = default(int); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num2, default(ForPrimitives)); myStrings = new string[num2]; for (int j = 0; j < num2; j++) { ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe(ref myStrings[j], false); } } } } } namespace LCSoundTool.Resources { public static class Assets { internal static AssetBundle bundle; } }
plugins/Ozone-Runtime_Netcode_Patcher/NicholaScott.BepInEx.RuntimeNetcodeRPCValidator.dll
Decompiled 2 years 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.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using HarmonyLib; using Unity.Collections; using Unity.Netcode; 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: IgnoresAccessChecksTo("Unity.Netcode.Runtime")] [assembly: AssemblyCompany("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.2.5.0")] [assembly: AssemblyInformationalVersion("0.2.5+6e2f89b3631ae55d2f51a00ccfd3f20fec9d2372")] [assembly: AssemblyProduct("RuntimeNetcodeRPCValidator")] [assembly: AssemblyTitle("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace RuntimeNetcodeRPCValidator { public class AlreadyRegisteredException : Exception { public AlreadyRegisteredException(string PluginGUID) : base("Can't register plugin " + PluginGUID + " until the other instance of NetcodeValidator is Disposed of!") { } } public class InvalidPluginGuidException : Exception { public InvalidPluginGuidException(string pluginGUID) : base("Can't patch plugin " + pluginGUID + " because it doesn't exist!") { } } public class NotNetworkBehaviourException : Exception { public NotNetworkBehaviourException(Type type) : base("Netcode Runtime RPC Validator tried to NetcodeValidator.Patch type " + type.Name + " that doesn't inherit from NetworkBehaviour!") { } } public class MustCallFromDeclaredTypeException : Exception { public MustCallFromDeclaredTypeException() : base("Netcode Runtime RPC Validator tried to run NetcodeValidator.PatchAll from a delegate! You must call PatchAll from a declared type.") { } } public static class FastBufferExtensions { private const BindingFlags BindingAll = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static void WriteSystemSerializable(this FastBufferWriter fastBufferWriter, object serializable) { //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) BinaryFormatter binaryFormatter = new BinaryFormatter(); using MemoryStream memoryStream = new MemoryStream(); binaryFormatter.Serialize(memoryStream, serializable); byte[] array = memoryStream.ToArray(); int num = array.Length; ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref fastBufferWriter)).WriteBytes(array, -1, 0); } private static void ReadSystemSerializable(this FastBufferReader fastBufferReader, out object serializable) { //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) int num = default(int); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); byte[] buffer = new byte[num]; ((FastBufferReader)(ref fastBufferReader)).ReadBytes(ref buffer, num, 0); using MemoryStream memoryStream = new MemoryStream(buffer); memoryStream.Seek(0L, SeekOrigin.Begin); BinaryFormatter binaryFormatter = new BinaryFormatter(); serializable = binaryFormatter.Deserialize(memoryStream); } private static void WriteNetcodeSerializable(this FastBufferWriter fastBufferWriter, object networkSerializable) { //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) //IL_0027: 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_0045: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(1024, (Allocator)2, -1); try { BufferSerializer<BufferSerializerWriter> val2 = default(BufferSerializer<BufferSerializerWriter>); val2..ctor(new BufferSerializerWriter(val)); object obj = ((networkSerializable is INetworkSerializable) ? networkSerializable : null); if (obj != null) { ((INetworkSerializable)obj).NetworkSerialize<BufferSerializerWriter>(val2); } byte[] array = ((FastBufferWriter)(ref val)).ToArray(); int num = array.Length; ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref fastBufferWriter)).WriteBytes(array, -1, 0); } finally { ((IDisposable)(FastBufferWriter)(ref val)).Dispose(); } } private static void ReadNetcodeSerializable(this FastBufferReader fastBufferReader, Type type, out object serializable) { //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_0031: 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_0051: Unknown result type (might be due to invalid IL or missing references) int num = default(int); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); byte[] array = new byte[num]; ((FastBufferReader)(ref fastBufferReader)).ReadBytes(ref array, num, 0); FastBufferReader val = default(FastBufferReader); ((FastBufferReader)(ref val))..ctor(array, (Allocator)2, -1, 0); try { BufferSerializer<BufferSerializerReader> val2 = default(BufferSerializer<BufferSerializerReader>); val2..ctor(new BufferSerializerReader(val)); serializable = Activator.CreateInstance(type); object obj = serializable; object obj2 = ((obj is INetworkSerializable) ? obj : null); if (obj2 != null) { ((INetworkSerializable)obj2).NetworkSerialize<BufferSerializerReader>(val2); } } finally { ((IDisposable)(FastBufferReader)(ref val)).Dispose(); } } public static void WriteMethodInfoAndParameters(this FastBufferWriter fastBufferWriter, MethodBase methodInfo, object[] args) { //IL_001f: 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_0079: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe(methodInfo.Name, false); ParameterInfo[] parameters = methodInfo.GetParameters(); int num = parameters.Length; ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<int>(ref num, default(ForPrimitives)); for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameterInfo = parameters[i]; object obj = args[i]; bool flag = obj == null || parameterInfo.ParameterType == typeof(ServerRpcParams) || parameterInfo.ParameterType == typeof(ClientRpcParams); ((FastBufferWriter)(ref fastBufferWriter)).WriteValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { continue; } if (parameterInfo.ParameterType.GetInterfaces().Contains(typeof(INetworkSerializable))) { fastBufferWriter.WriteNetcodeSerializable(obj); continue; } if (parameterInfo.ParameterType.IsSerializable) { fastBufferWriter.WriteSystemSerializable(obj); continue; } throw new SerializationException(TextHandler.ObjectNotSerializable(parameterInfo)); } } public static MethodInfo ReadMethodInfoAndParameters(this FastBufferReader fastBufferReader, Type methodDeclaringType, ref object[] args) { //IL_0010: 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_0077: 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_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) string name = default(string); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe(ref name, false); int num = default(int); ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); MethodInfo method = methodDeclaringType.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (num != method?.GetParameters().Length) { throw new Exception(TextHandler.InconsistentParameterCount(method, num)); } bool flag = default(bool); for (int i = 0; i < num; i++) { ((FastBufferReader)(ref fastBufferReader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); if (flag) { continue; } ParameterInfo parameterInfo = method.GetParameters()[i]; object serializable; if (parameterInfo.ParameterType.GetInterfaces().Contains(typeof(INetworkSerializable))) { fastBufferReader.ReadNetcodeSerializable(parameterInfo.ParameterType, out serializable); } else { if (!parameterInfo.ParameterType.IsSerializable) { throw new SerializationException(TextHandler.ObjectNotSerializable(parameterInfo)); } fastBufferReader.ReadSystemSerializable(out serializable); } args[i] = serializable; } return method; } } public sealed class NetcodeValidator : IDisposable { private static readonly List<string> AlreadyRegistered = new List<string>(); internal const string TypeCustomMessageHandlerPrefix = "Net"; private static List<(NetcodeValidator validator, Type custom, Type native)> BoundNetworkObjects { get; } = new List<(NetcodeValidator, Type, Type)>(); private List<string> CustomMessageHandlers { get; } private Harmony Patcher { get; } public string PluginGuid { get; } internal static event Action<NetcodeValidator, Type> AddedNewBoundBehaviour; private event Action<string> AddedNewCustomMessageHandler; public NetcodeValidator(string pluginGuid) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown if (!Chainloader.PluginInfos.TryGetValue(pluginGuid, out var _)) { throw new InvalidPluginGuidException(pluginGuid); } if (AlreadyRegistered.Contains(pluginGuid)) { throw new AlreadyRegisteredException(pluginGuid); } AlreadyRegistered.Add(pluginGuid); PluginGuid = pluginGuid; CustomMessageHandlers = new List<string>(); Patcher = new Harmony(pluginGuid + "NicholaScott.BepInEx.RuntimeNetcodeRPCValidator"); Plugin.NetworkManagerInitialized += NetworkManagerInitialized; Plugin.NetworkManagerShutdown += NetworkManagerShutdown; } internal static void TryLoadRelatedComponentsInOrder(NetworkBehaviour __instance, MethodBase __originalMethod) { foreach (var item in from obj in BoundNetworkObjects where obj.native == __originalMethod.DeclaringType select obj into it orderby it.validator.PluginGuid select it) { Plugin.Logger.LogInfo((object)TextHandler.CustomComponentAddedToExistingObject(item, __originalMethod)); Component obj2 = ((Component)__instance).gameObject.AddComponent(item.custom); ((NetworkBehaviour)(object)((obj2 is NetworkBehaviour) ? obj2 : null)).SyncWithNetworkObject(); } } private bool Patch(MethodInfo rpcMethod, out bool isServerRpc, out bool isClientRpc) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown isServerRpc = ((MemberInfo)rpcMethod).GetCustomAttributes<ServerRpcAttribute>().Any(); isClientRpc = ((MemberInfo)rpcMethod).GetCustomAttributes<ClientRpcAttribute>().Any(); bool flag = rpcMethod.Name.EndsWith("ServerRpc"); bool flag2 = rpcMethod.Name.EndsWith("ClientRpc"); if (!isClientRpc && !isServerRpc && !flag2 && !flag) { return false; } if ((!isServerRpc && flag) || (!isClientRpc && flag2)) { Plugin.Logger.LogError((object)TextHandler.MethodLacksRpcAttribute(rpcMethod)); return false; } if ((isServerRpc && !flag) || (isClientRpc && !flag2)) { Plugin.Logger.LogError((object)TextHandler.MethodLacksSuffix(rpcMethod)); return false; } Patcher.Patch((MethodBase)rpcMethod, new HarmonyMethod(typeof(NetworkBehaviourExtensions), "MethodPatch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); return true; } public void BindToPreExistingObjectByBehaviour<TCustomBehaviour, TNativeBehaviour>() where TCustomBehaviour : NetworkBehaviour where TNativeBehaviour : NetworkBehaviour { if (Object.op_Implicit((Object)(object)NetworkManager.Singleton) && (NetworkManager.Singleton.IsListening || NetworkManager.Singleton.IsConnectedClient)) { Plugin.Logger.LogError((object)TextHandler.PluginTriedToBindToPreExistingObjectTooLate(this, typeof(TCustomBehaviour), typeof(TNativeBehaviour))); } else { OnAddedNewBoundBehaviour(this, typeof(TCustomBehaviour), typeof(TNativeBehaviour)); } } public void Patch(Type netBehaviourTyped) { if (netBehaviourTyped.BaseType != typeof(NetworkBehaviour)) { throw new NotNetworkBehaviourException(netBehaviourTyped); } OnAddedNewCustomMessageHandler("Net." + netBehaviourTyped.Name); int num = 0; int num2 = 0; MethodInfo[] methods = netBehaviourTyped.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo rpcMethod in methods) { if (Patch(rpcMethod, out var isServerRpc, out var isClientRpc)) { num += (isServerRpc ? 1 : 0); num2 += (isClientRpc ? 1 : 0); } } Plugin.Logger.LogInfo((object)TextHandler.SuccessfullyPatchedType(netBehaviourTyped, num, num2)); } public void Patch(Assembly assembly) { Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.BaseType == typeof(NetworkBehaviour)) { Patch(type); } } } public void PatchAll() { Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType?.Assembly; if (assembly == null) { throw new MustCallFromDeclaredTypeException(); } Patch(assembly); } public void UnpatchSelf() { Plugin.Logger.LogInfo((object)TextHandler.PluginUnpatchedAllRPCs(this)); Patcher.UnpatchSelf(); } private static void RegisterMessageHandlerWithNetworkManager(string handler) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler(handler, new HandleNamedMessageDelegate(NetworkBehaviourExtensions.ReceiveNetworkMessage)); } private void NetworkManagerInitialized() { AddedNewCustomMessageHandler += RegisterMessageHandlerWithNetworkManager; foreach (string customMessageHandler in CustomMessageHandlers) { RegisterMessageHandlerWithNetworkManager(customMessageHandler); } } private void NetworkManagerShutdown() { AddedNewCustomMessageHandler -= RegisterMessageHandlerWithNetworkManager; foreach (string customMessageHandler in CustomMessageHandlers) { NetworkManager.Singleton.CustomMessagingManager.UnregisterNamedMessageHandler(customMessageHandler); } } public void Dispose() { Plugin.NetworkManagerInitialized -= NetworkManagerInitialized; Plugin.NetworkManagerShutdown -= NetworkManagerShutdown; AlreadyRegistered.Remove(PluginGuid); if (Object.op_Implicit((Object)(object)NetworkManager.Singleton)) { NetworkManagerShutdown(); } if (Patcher.GetPatchedMethods().Any()) { UnpatchSelf(); } } private void OnAddedNewCustomMessageHandler(string obj) { CustomMessageHandlers.Add(obj); this.AddedNewCustomMessageHandler?.Invoke(obj); } private static void OnAddedNewBoundBehaviour(NetcodeValidator validator, Type custom, Type native) { BoundNetworkObjects.Add((validator, custom, native)); NetcodeValidator.AddedNewBoundBehaviour?.Invoke(validator, native); } } public static class NetworkBehaviourExtensions { public enum RpcState { FromUser, FromNetworking } private static RpcState RpcSource; public static ClientRpcParams CreateSendToFromReceived(this ServerRpcParams senderId) { //IL_0002: 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_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) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) ClientRpcParams result = default(ClientRpcParams); result.Send = new ClientRpcSendParams { TargetClientIds = new ulong[1] { senderId.Receive.SenderClientId } }; return result; } public static void SyncWithNetworkObject(this NetworkBehaviour networkBehaviour) { if (!networkBehaviour.NetworkObject.ChildNetworkBehaviours.Contains(networkBehaviour)) { networkBehaviour.NetworkObject.ChildNetworkBehaviours.Add(networkBehaviour); } networkBehaviour.UpdateNetworkProperties(); } private static bool ValidateRPCMethod(NetworkBehaviour networkBehaviour, MethodBase method, RpcState state, out RpcAttribute rpcAttribute) { bool flag = ((MemberInfo)method).GetCustomAttributes<ServerRpcAttribute>().Any(); bool flag2 = ((MemberInfo)method).GetCustomAttributes<ClientRpcAttribute>().Any(); bool num = flag && ((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>().RequireOwnership; rpcAttribute = (RpcAttribute)(flag ? ((object)((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>()) : ((object)((MemberInfo)method).GetCustomAttribute<ClientRpcAttribute>())); if (num && networkBehaviour.OwnerClientId != NetworkManager.Singleton.LocalClientId) { Plugin.Logger.LogError((object)TextHandler.NotOwnerOfNetworkObject((state == RpcState.FromUser) ? "We" : "Client", method, networkBehaviour.NetworkObject)); return false; } if (state == RpcState.FromUser && flag2 && !NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsHost) { Plugin.Logger.LogError((object)TextHandler.CantRunClientRpcFromClient(method)); return false; } if (state == RpcState.FromUser && !flag && !flag2) { Plugin.Logger.LogError((object)TextHandler.MethodPatchedButLacksAttributes(method)); return false; } if (state == RpcState.FromNetworking && !flag && !flag2) { Plugin.Logger.LogError((object)TextHandler.MethodPatchedAndNetworkCalledButLacksAttributes(method)); return false; } if (state == RpcState.FromNetworking && flag && !networkBehaviour.IsServer && !networkBehaviour.IsHost) { Plugin.Logger.LogError((object)TextHandler.CantRunServerRpcAsClient(method)); return false; } return true; } private static bool MethodPatchInternal(NetworkBehaviour networkBehaviour, MethodBase method, object[] args) { //IL_007d: 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_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_00a5: 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_00e3: 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_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0169: 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) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)NetworkManager.Singleton) || (!NetworkManager.Singleton.IsListening && !NetworkManager.Singleton.IsConnectedClient)) { Plugin.Logger.LogError((object)TextHandler.NoNetworkManagerPresentToSendRpc(networkBehaviour)); return false; } RpcState rpcSource = RpcSource; RpcSource = RpcState.FromUser; if (rpcSource == RpcState.FromNetworking) { return true; } if (!ValidateRPCMethod(networkBehaviour, method, rpcSource, out var rpcAttribute)) { return false; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor((method.GetParameters().Length + 1) * 128, (Allocator)2, -1); ulong networkObjectId = networkBehaviour.NetworkObjectId; ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref networkObjectId, default(ForPrimitives)); ushort networkBehaviourId = networkBehaviour.NetworkBehaviourId; ((FastBufferWriter)(ref val)).WriteValueSafe<ushort>(ref networkBehaviourId, default(ForPrimitives)); val.WriteMethodInfoAndParameters(method, args); string text = new StringBuilder("Net").Append(".").Append(method.DeclaringType.Name).ToString(); NetworkDelivery val2 = (NetworkDelivery)(((int)rpcAttribute.Delivery == 0) ? 2 : 0); if (rpcAttribute is ServerRpcAttribute) { NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(text, 0uL, val, val2); } else { ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 0 && parameters[^1].ParameterType == typeof(ClientRpcParams)) { NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage(text, ((ClientRpcParams)args[^1]).Send.TargetClientIds, val, val2); } else { NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll(text, val, val2); } } return false; } internal static void ReceiveNetworkMessage(ulong sender, FastBufferReader reader) { //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_0019: 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_0100: 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_0126: 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) //IL_0136: 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) ulong key = default(ulong); ((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref key, default(ForPrimitives)); ushort num = default(ushort); ((FastBufferReader)(ref reader)).ReadValueSafe<ushort>(ref num, default(ForPrimitives)); int position = ((FastBufferReader)(ref reader)).Position; string text = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false); ((FastBufferReader)(ref reader)).Seek(position); if (!NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(key, out var value)) { Plugin.Logger.LogError((object)TextHandler.RpcCalledBeforeObjectSpawned()); return; } NetworkBehaviour networkBehaviourAtOrderIndex = value.GetNetworkBehaviourAtOrderIndex(num); MethodInfo method = ((object)networkBehaviourAtOrderIndex).GetType().GetMethod(text, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); RpcAttribute rpcAttribute; if (method == null) { Plugin.Logger.LogError((object)TextHandler.NetworkCalledNonExistentMethod(networkBehaviourAtOrderIndex, text)); } else if (ValidateRPCMethod(networkBehaviourAtOrderIndex, method, RpcState.FromNetworking, out rpcAttribute)) { RpcSource = RpcState.FromNetworking; ParameterInfo[] parameters = method.GetParameters(); bool num2 = rpcAttribute is ServerRpcAttribute && parameters.Length != 0 && parameters[^1].ParameterType == typeof(ServerRpcParams); object[] args = null; if (parameters.Length != 0) { args = new object[parameters.Length]; } reader.ReadMethodInfoAndParameters(method.DeclaringType, ref args); if (num2) { args[^1] = (object)new ServerRpcParams { Receive = new ServerRpcReceiveParams { SenderClientId = sender } }; } method.Invoke(networkBehaviourAtOrderIndex, args); } } internal static bool MethodPatch(NetworkBehaviour __instance, MethodBase __originalMethod, object[] __args) { return MethodPatchInternal(__instance, __originalMethod, __args); } } [BepInPlugin("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator", "RuntimeNetcodeRPCValidator", "0.2.5")] public class Plugin : BaseUnityPlugin { private readonly Harmony _harmony = new Harmony("NicholaScott.BepInEx.RuntimeNetcodeRPCValidator"); private List<Type> AlreadyPatchedNativeBehaviours { get; } = new List<Type>(); internal static ManualLogSource Logger { get; private set; } public static event Action NetworkManagerInitialized; public static event Action NetworkManagerShutdown; private void Awake() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown Logger = ((BaseUnityPlugin)this).Logger; NetcodeValidator.AddedNewBoundBehaviour += NetcodeValidatorOnAddedNewBoundBehaviour; _harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkManager), "Initialize", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "OnNetworkManagerInitialized", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _harmony.Patch((MethodBase)AccessTools.Method(typeof(NetworkManager), "Shutdown", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "OnNetworkManagerShutdown", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private void NetcodeValidatorOnAddedNewBoundBehaviour(NetcodeValidator validator, Type netBehaviour) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown if (!AlreadyPatchedNativeBehaviours.Contains(netBehaviour)) { AlreadyPatchedNativeBehaviours.Add(netBehaviour); MethodBase methodBase = AccessTools.Method(netBehaviour, "Awake", (Type[])null, (Type[])null); if (methodBase == null) { methodBase = AccessTools.Method(netBehaviour, "Start", (Type[])null, (Type[])null); } if (methodBase == null) { methodBase = AccessTools.Constructor(netBehaviour, (Type[])null, false); } Logger.LogInfo((object)TextHandler.RegisteredPatchForType(validator, netBehaviour, methodBase)); HarmonyMethod val = new HarmonyMethod(typeof(NetcodeValidator), "TryLoadRelatedComponentsInOrder", (Type[])null); _harmony.Patch(methodBase, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } protected static void OnNetworkManagerInitialized() { Plugin.NetworkManagerInitialized?.Invoke(); } protected static void OnNetworkManagerShutdown() { Plugin.NetworkManagerShutdown?.Invoke(); } } internal static class TextHandler { private const string NoNetworkManagerPresentToSendRpcConst = "NetworkBehaviour {0} tried to send a RPC but the NetworkManager is non-existant!"; private const string MethodLacksAttributeConst = "Can't patch method {0}.{1} because it lacks a [{2}] attribute."; private const string MethodLacksSuffixConst = "Can't patch method {0}.{1} because it's name doesn't end with '{2}'!"; private const string SuccessfullyPatchedTypeConst = "Patched {0} ServerRPC{1} & {2} ClientRPC{3} on NetworkBehaviour {4}."; private const string NotOwnerOfNetworkObjectConst = "{0} tried to run ServerRPC {1} but not the owner of NetworkObject {2}"; private const string CantRunClientRpcFromClientConst = "Tried to run ClientRpc {0} but we're not a host! You should only call ClientRpc(s) from inside a ServerRpc OR if you've checked you're on the server with IsHost!"; private const string CantRunServerRpcAsClientConst = "Received message to run ServerRPC {0}.{1} but we're a client!"; private const string MethodPatchedButLacksAttributesConst = "Rpc Method {0} has been patched to attempt networking but lacks any RpcAttributes! This should never happen!"; private const string MethodPatchedAndNetworkCalledButLacksAttributesConst = "Rpc Method {0} has been patched && even received a network call to execute but lacks any RpcAttributes! This should never happen! Something is VERY fucky!!!"; private const string RpcCalledBeforeObjectSpawnedConst = "An RPC called on a NetworkObject that is not in the spawned objects list. Please make sure the NetworkObject is spawned before calling RPCs."; private const string NetworkCalledNonExistentMethodConst = "NetworkBehaviour {0} received RPC {1} but that method doesn't exist on {2}!"; private const string ObjectNotSerializableConst = "[Network] Parameter ({0} {1}) is not marked [Serializable] nor does it implement INetworkSerializable!"; private const string InconsistentParameterCountConst = "[Network] NetworkBehaviour received a RPC {0} but the number of parameters sent {1} != MethodInfo param count {2}"; private const string PluginTriedToBindToPreExistingObjectTooLateConst = "Plugin '{0}' tried to bind {1} to {2} but it's too late! Make sure you bind to any pre-existing NetworkObjects before NetworkManager.IsListening || IsConnectedClient."; private const string RegisteredPatchForTypeConst = "Successfully registered first patch for type {0}.{1} | Triggered by {2}"; private const string CustomComponentAddedToExistingObjectConst = "Successfully added {0} to {1} via {2}. Triggered by plugin {3}"; private const string PluginUnpatchedAllRPCsConst = "Plugin {0} has unpatched all RPCs!"; internal static string NoNetworkManagerPresentToSendRpc(NetworkBehaviour networkBehaviour) { return $"NetworkBehaviour {networkBehaviour.NetworkBehaviourId} tried to send a RPC but the NetworkManager is non-existant!"; } internal static string MethodLacksRpcAttribute(MethodInfo method) { return string.Format("Can't patch method {0}.{1} because it lacks a [{2}] attribute.", method.DeclaringType?.Name, method.Name, method.Name.EndsWith("ServerRpc") ? "ServerRpc" : "ClientRpc"); } internal static string MethodLacksSuffix(MethodBase method) { return string.Format("Can't patch method {0}.{1} because it's name doesn't end with '{2}'!", method.DeclaringType?.Name, method.Name, (((MemberInfo)method).GetCustomAttribute<ServerRpcAttribute>() != null) ? "ServerRpc" : "ClientRpc"); } internal static string SuccessfullyPatchedType(Type networkType, int serverRpcCount, int clientRpcCount) { return string.Format("Patched {0} ServerRPC{1} & {2} ClientRPC{3} on NetworkBehaviour {4}.", serverRpcCount, (serverRpcCount == 1) ? "" : "s", clientRpcCount, (clientRpcCount == 1) ? "" : "s", networkType.Name); } internal static string NotOwnerOfNetworkObject(string whoIsNotOwner, MethodBase method, NetworkObject networkObject) { return $"{whoIsNotOwner} tried to run ServerRPC {method.Name} but not the owner of NetworkObject {networkObject.NetworkObjectId}"; } internal static string CantRunClientRpcFromClient(MethodBase method) { return $"Tried to run ClientRpc {method.Name} but we're not a host! You should only call ClientRpc(s) from inside a ServerRpc OR if you've checked you're on the server with IsHost!"; } internal static string CantRunServerRpcAsClient(MethodBase method) { return $"Received message to run ServerRPC {method.DeclaringType?.Name}.{method.Name} but we're a client!"; } internal static string MethodPatchedButLacksAttributes(MethodBase method) { return $"Rpc Method {method.Name} has been patched to attempt networking but lacks any RpcAttributes! This should never happen!"; } internal static string MethodPatchedAndNetworkCalledButLacksAttributes(MethodBase method) { return $"Rpc Method {method.Name} has been patched && even received a network call to execute but lacks any RpcAttributes! This should never happen! Something is VERY fucky!!!"; } internal static string RpcCalledBeforeObjectSpawned() { return "An RPC called on a NetworkObject that is not in the spawned objects list. Please make sure the NetworkObject is spawned before calling RPCs."; } internal static string NetworkCalledNonExistentMethod(NetworkBehaviour networkBehaviour, string rpcName) { return $"NetworkBehaviour {networkBehaviour.NetworkBehaviourId} received RPC {rpcName} but that method doesn't exist on {((object)networkBehaviour).GetType().Name}!"; } internal static string ObjectNotSerializable(ParameterInfo paramInfo) { return $"[Network] Parameter ({paramInfo.ParameterType.Name} {paramInfo.Name}) is not marked [Serializable] nor does it implement INetworkSerializable!"; } internal static string InconsistentParameterCount(MethodBase method, int paramsSent) { return $"[Network] NetworkBehaviour received a RPC {method.Name} but the number of parameters sent {paramsSent} != MethodInfo param count {method.GetParameters().Length}"; } internal static string PluginTriedToBindToPreExistingObjectTooLate(NetcodeValidator netcodeValidator, Type from, Type to) { return $"Plugin '{netcodeValidator.PluginGuid}' tried to bind {from.Name} to {to.Name} but it's too late! Make sure you bind to any pre-existing NetworkObjects before NetworkManager.IsListening || IsConnectedClient."; } internal static string RegisteredPatchForType(NetcodeValidator validator, Type netBehaviour, MethodBase method) { return $"Successfully registered first patch for type {netBehaviour.Name}.{method.Name} | Triggered by {validator.PluginGuid}"; } internal static string CustomComponentAddedToExistingObject((NetcodeValidator validator, Type custom, Type native) it, MethodBase methodBase) { return $"Successfully added {it.custom.Name} to {it.native.Name} via {methodBase.Name}. Triggered by plugin {it.validator.PluginGuid}"; } internal static string PluginUnpatchedAllRPCs(NetcodeValidator netcodeValidator) { return $"Plugin {netcodeValidator.PluginGuid} has unpatched all RPCs!"; } } public static class MyPluginInfo { public const string PLUGIN_GUID = "NicholaScott.BepInEx.RuntimeNetcodeRPCValidator"; public const string PLUGIN_NAME = "RuntimeNetcodeRPCValidator"; public const string PLUGIN_VERSION = "0.2.5"; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins/Pooble-LCBetterSaves/LCBetterSaves.dll
Decompiled 2 years agousing System; using System.CodeDom.Compiler; 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 HarmonyLib; using LCBetterSaves; using LCBetterSaves.Properties; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.Events; 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("LCBetterSaves")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyDescription("Better save files for Lethal Company")] [assembly: AssemblyFileVersion("1.7.0.0")] [assembly: AssemblyInformationalVersion("1.7.0+bc6b3c1e6594b34f9290c63661711307c8f99eb1")] [assembly: AssemblyProduct("LCBetterSaves")] [assembly: AssemblyTitle("LCBetterSaves")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.7.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 NewFileUISlot_BetterSaves : MonoBehaviour { public Animator buttonAnimator; public Button button; public bool isSelected; public void Awake() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown buttonAnimator = ((Component)this).GetComponent<Animator>(); button = ((Component)this).GetComponent<Button>(); ((UnityEvent)button.onClick).AddListener(new UnityAction(SetFileToThis)); } public void SetFileToThis() { string currentSaveFileName = "LCSaveFile" + Plugin.newSaveFileNum; GameNetworkManager.Instance.currentSaveFileName = currentSaveFileName; GameNetworkManager.Instance.saveFileNum = Plugin.newSaveFileNum; SetButtonColorForAllFileSlots(); isSelected = true; SetButtonColor(); } public void SetButtonColorForAllFileSlots() { SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>(); SaveFileUISlot_BetterSaves[] array2 = array; foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2) { saveFileUISlot_BetterSaves.SetButtonColor(); saveFileUISlot_BetterSaves.deleteButton.SetActive(false); saveFileUISlot_BetterSaves.renameButton.SetActive(false); } } public void SetButtonColor() { buttonAnimator.SetBool("isPressed", isSelected); } } public class SaveFileUISlot_BetterSaves : MonoBehaviour { public Animator buttonAnimator; public Button button; public TextMeshProUGUI fileStatsText; public int fileNum; public string fileString; public TextMeshProUGUI fileNotCompatibleAlert; public GameObject deleteButton; public GameObject renameButton; public void Awake() { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown buttonAnimator = ((Component)this).GetComponent<Animator>(); button = ((Component)this).GetComponent<Button>(); ((UnityEvent)button.onClick).AddListener(new UnityAction(SetFileToThis)); fileStatsText = ((Component)((Component)this).transform.GetChild(2)).GetComponent<TextMeshProUGUI>(); fileNotCompatibleAlert = ((Component)((Component)this).transform.GetChild(4)).GetComponent<TextMeshProUGUI>(); deleteButton = ((Component)((Component)this).transform.GetChild(3)).gameObject; } public void Start() { UpdateStats(); } private void OnEnable() { if (!Object.FindObjectOfType<MenuManager>().filesCompatible[fileNum]) { ((Behaviour)fileNotCompatibleAlert).enabled = true; } } public void UpdateStats() { try { if (ES3.FileExists(fileString)) { int num = ES3.Load<int>("GroupCredits", fileString, 30); int num2 = ES3.Load<int>("Stats_DaysSpent", fileString, 0); ((TMP_Text)fileStatsText).text = $"${num}\nDays: {num2}"; } else { ((TMP_Text)fileStatsText).text = ""; } } catch (Exception ex) { Debug.LogError((object)("Error updating stats: " + ex.Message)); } } public void SetButtonColor() { buttonAnimator.SetBool("isPressed", GameNetworkManager.Instance.currentSaveFileName == fileString); } public void SetFileToThis() { Plugin.fileToModify = fileNum; GameNetworkManager.Instance.currentSaveFileName = fileString; GameNetworkManager.Instance.saveFileNum = fileNum; SetButtonColorForAllFileSlots(); } public void SetButtonColorForAllFileSlots() { SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>(); SaveFileUISlot_BetterSaves[] array2 = array; foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2) { saveFileUISlot_BetterSaves.SetButtonColor(); saveFileUISlot_BetterSaves.deleteButton.SetActive((Object)(object)saveFileUISlot_BetterSaves == (Object)(object)this); saveFileUISlot_BetterSaves.renameButton.SetActive((Object)(object)saveFileUISlot_BetterSaves == (Object)(object)this); } NewFileUISlot_BetterSaves newFileUISlot_BetterSaves = Object.FindObjectOfType<NewFileUISlot_BetterSaves>(); newFileUISlot_BetterSaves.isSelected = false; newFileUISlot_BetterSaves.SetButtonColor(); } } public class RenameFileButton_BetterSaves : MonoBehaviour { public void RenameFile() { string text = $"LCSaveFile{Plugin.fileToModify}"; string text2 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/HostSettingsContainer/LobbyHostOptions/OptionsNormal/ServerNameField/Text Area/Text").GetComponent<TMP_Text>().text; if (ES3.FileExists(text)) { ES3.Save<string>("Alias_BetterSaves", text2, text); Debug.Log((object)("Granted alias " + text2 + " to file " + text)); } Plugin.RefreshNameFields(); } } public class DeleteFileButton_BetterSaves : MonoBehaviour { public int fileToDelete; public AudioClip deleteFileSFX; public TextMeshProUGUI deleteFileText; public void UpdateFileToDelete() { fileToDelete = Plugin.fileToModify; if (ES3.Load<string>("Alias_BetterSaves", $"LCSaveFile{fileToDelete}", "") != "") { ((TMP_Text)deleteFileText).text = "Do you want to delete file (" + ES3.Load<string>("Alias_BetterSaves", $"LCSaveFile{fileToDelete}", "") + ")?"; } else { ((TMP_Text)deleteFileText).text = $"Do you want to delete File {fileToDelete + 1}?"; } } public void DeleteFile() { string text = $"LCSaveFile{fileToDelete}"; if (ES3.FileExists(text)) { ES3.DeleteFile(text); Object.FindObjectOfType<MenuManager>().MenuAudio.PlayOneShot(deleteFileSFX); } SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>(true); SaveFileUISlot_BetterSaves[] array2 = array; foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2) { Debug.Log((object)$"Deleted {fileToDelete}"); if (saveFileUISlot_BetterSaves.fileNum == fileToDelete) { ((Behaviour)saveFileUISlot_BetterSaves.fileNotCompatibleAlert).enabled = false; Object.FindObjectOfType<MenuManager>().filesCompatible[fileToDelete] = true; } } Plugin.InitializeBetterSaves(); } } namespace LCBetterSaves { [BepInPlugin("LCBetterSaves", "LCBetterSaves", "1.7.0")] public class Plugin : BaseUnityPlugin { private Harmony _harmony = new Harmony("BetterSaves"); public static int fileToModify = -1; public static int newSaveFileNum; public static Sprite renameSprite; public static MenuManager menuManager; public static AudioClip deleteFileSFX; public static TextMeshProUGUI deleteFileText; public static float buttonBaseY; public void Awake() { _harmony.PatchAll(typeof(Plugin)); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin LCBetterSaves is loaded!"); } [HarmonyPatch(typeof(MenuManager), "Start")] public static void Postfix(MenuManager __instance) { //IL_0047: 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) menuManager = __instance; if ((Object)(object)renameSprite == (Object)null) { AssetBundle val = AssetBundle.LoadFromMemory(Resources.lcbettersaves); Texture2D val2 = val.LoadAsset<Texture2D>("Assets/RenameSprite.png"); renameSprite = Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), new Vector2(0.5f, 0.5f)); } InitializeBetterSaves(); } public static void InitializeBetterSaves() { try { DestroyBetterSavesButtons(); DestroyOriginalSaveButtons(); UpdateTopText(); CreateModdedDeleteFileButton(); CreateBetterSaveButtons(); UpdateFilesPanelRect(CountSaveFiles() + 1); GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1"); val.SetActive(false); } catch (Exception ex) { Debug.LogError((object)("An error occurred during initialization: " + ex.Message)); } } public static void DestroyBetterSavesButtons() { try { SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>(); foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array) { Object.Destroy((Object)(object)((Component)saveFileUISlot_BetterSaves).gameObject); } NewFileUISlot_BetterSaves[] array2 = Object.FindObjectsOfType<NewFileUISlot_BetterSaves>(); foreach (NewFileUISlot_BetterSaves newFileUISlot_BetterSaves in array2) { Object.Destroy((Object)(object)((Component)newFileUISlot_BetterSaves).gameObject); } } catch (Exception ex) { Debug.LogError((object)("Error occurred while destroying better saves buttons: " + ex.Message)); } } public static void UpdateTopText() { GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/EnterAName"); if ((Object)(object)val == (Object)null) { Debug.LogError((object)"Panel label not found."); } else { ((TMP_Text)val.GetComponent<TextMeshProUGUI>()).text = "BetterSaves"; } } public static void CreateModdedDeleteFileButton() { //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown GameObject val = GameObject.Find("Canvas/MenuContainer/DeleteFileConfirmation/Panel/Delete"); if ((Object)(object)val == (Object)null) { Debug.LogError((object)"Delete file game object not found."); return; } if ((Object)(object)val.GetComponent<DeleteFileButton_BetterSaves>() != (Object)null) { Debug.LogWarning((object)"DeleteFileButton_BetterSaves component already exists on deleteFileGO"); return; } DeleteFileButton component = val.GetComponent<DeleteFileButton>(); if ((Object)(object)component == (Object)null) { Debug.LogError((object)"DeleteFileButton component not found on deleteFileGO"); return; } if ((Object)(object)deleteFileSFX == (Object)null) { deleteFileSFX = component.deleteFileSFX; } if ((Object)(object)deleteFileText == (Object)null) { deleteFileText = component.deleteFileText; } Object.Destroy((Object)(object)component); if ((Object)(object)val.GetComponent<DeleteFileButton_BetterSaves>() == (Object)null) { DeleteFileButton_BetterSaves deleteFileButton_BetterSaves = val.AddComponent<DeleteFileButton_BetterSaves>(); deleteFileButton_BetterSaves.deleteFileSFX = deleteFileSFX; deleteFileButton_BetterSaves.deleteFileText = deleteFileText; Button component2 = val.GetComponent<Button>(); if ((Object)(object)component2 != (Object)null) { ((UnityEventBase)component2.onClick).RemoveAllListeners(); ((UnityEvent)component2.onClick).AddListener(new UnityAction(deleteFileButton_BetterSaves.DeleteFile)); } else { Debug.LogError((object)"Button component not found on deleteFileGO"); } } else { Debug.LogWarning((object)"DeleteFileButton_BetterSaves component already exists on deleteFileGO"); } } public static void CreateBetterSaveButtons() { try { GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1"); val.SetActive(true); int numSaves = CountSaveFiles(); Debug.Log((object)("Positioning based on " + numSaves + " saves.")); NewFileUISlot_BetterSaves newFileUISlot_BetterSaves = CreateNewFileNode(numSaves); List<string> list = NormalizeFileNames(); newSaveFileNum = list.Count + 1; menuManager.filesCompatible = new bool[16]; for (int i = 0; i < menuManager.filesCompatible.Length; i++) { menuManager.filesCompatible[i] = true; } for (int j = 0; j < list.Count; j++) { CreateModdedSaveNode(int.Parse(list[j].Replace("LCSaveFile", "")), ((Component)newFileUISlot_BetterSaves).gameObject); } val.SetActive(false); } catch (Exception ex) { Debug.LogError((object)("Error occurred while refreshing save buttons: " + ex.Message)); } } public static NewFileUISlot_BetterSaves CreateNewFileNode(int numSaves) { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_017f: 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_0155: 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) GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1"); if ((Object)(object)val == (Object)null) { Debug.LogError((object)"Original GameObject not found."); return null; } Transform parent = val.transform.parent; SaveFileUISlot component = val.GetComponent<SaveFileUISlot>(); if ((Object)(object)component != (Object)null) { Object.Destroy((Object)(object)component); } GameObject val2 = Object.Instantiate<GameObject>(val, parent); ((Object)val2).name = "NewFile"; TMP_Text component2 = ((Component)val2.transform.GetChild(1)).GetComponent<TMP_Text>(); if ((Object)(object)component2 != (Object)null) { component2.text = "New File"; NewFileUISlot_BetterSaves newFileUISlot_BetterSaves = val2.AddComponent<NewFileUISlot_BetterSaves>(); if ((Object)(object)newFileUISlot_BetterSaves == (Object)null) { Debug.LogError((object)"Failed to add NewFileUISlot_BetterSaves component."); return null; } Transform child = val2.transform.GetChild(3); if ((Object)(object)child != (Object)null) { Object.Destroy((Object)(object)((Component)child).gameObject); try { RectTransform component3 = val2.GetComponent<RectTransform>(); if (!((Object)(object)component3 != (Object)null)) { Debug.LogError((object)"RectTransform component not found."); return null; } float x = component3.anchoredPosition.x; if (buttonBaseY == 0f) { buttonBaseY = component3.anchoredPosition.y - component3.sizeDelta.y * 1.75f; } float num = buttonBaseY + component3.sizeDelta.y * (float)(numSaves + 1) / 2f; component3.anchoredPosition = new Vector2(x, num); } catch (Exception ex) { Debug.LogError((object)("Error setting anchored position: " + ex.Message)); return null; } return newFileUISlot_BetterSaves; } Debug.LogError((object)"Delete button not found."); return null; } Debug.LogError((object)"Text component not found."); return null; } private static int CountSaveFiles() { int num = 0; string[] files = ES3.GetFiles(); foreach (string text in files) { if (ES3.FileExists(text) && text.StartsWith("LCSaveFile")) { num++; } } return num; } public static void DestroyOriginalSaveButtons() { Object.Destroy((Object)(object)GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File2")); Object.Destroy((Object)(object)GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File3")); } public static List<string> NormalizeFileNames() { List<string> list = new List<string>(); List<string> list2 = new List<string>(); string text = "PH"; string format = "LGUTempFile{0}"; string format2 = "LGU_{0}.json"; string[] files = ES3.GetFiles(); foreach (string text2 in files) { if (ES3.FileExists(text2) && text2.StartsWith("LCSaveFile")) { Debug.Log((object)("Found file: " + text2)); list.Add(text2); string text3 = string.Format(format2, text2.Substring("LCSaveFile".Length)); if (ES3.FileExists(text3)) { Debug.Log((object)("Found LGU file: " + text3)); list2.Add(text3); } else { list2.Add(text); } } } int num = 1; foreach (string item in list) { string text4 = "TempFile" + num; ES3.RenameFile(item, text4); Debug.Log((object)("Renamed " + item + " to " + text4)); num++; } num = 1; foreach (string item2 in list2) { if (item2 == text) { num++; continue; } string text5 = string.Format(format, num.ToString()); ES3.RenameFile(item2, text5); Debug.Log((object)("Renamed " + item2 + " to " + text5)); num++; } int num2 = 1; List<string> list3 = new List<string>(); foreach (string item3 in list) { string text6 = "TempFile" + num2; string text7 = "LCSaveFile" + num2; if (ES3.FileExists(text6)) { ES3.RenameFile(text6, text7); list3.Add(text7); Debug.Log((object)("Renamed " + text6 + " to " + text7)); } else { Debug.Log((object)("Temporary file " + text6 + " not found. It might have been moved or deleted.")); } num2++; } num2 = 1; foreach (string item4 in list2) { string text8 = string.Format(format, num2.ToString()); string text9 = string.Format(format2, num2.ToString()); if (item4 == text) { num2++; continue; } if (ES3.FileExists(text8)) { ES3.RenameFile(text8, text9); list3.Add(text9); Debug.Log((object)("Renamed " + text8 + " to " + text9)); } else { Debug.Log((object)("Temporary file " + text8 + " not found. It might have been moved or deleted.")); } num2++; } return list3; } public static void CreateModdedSaveNode(int fileNum, GameObject newFileButton) { //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Expected O, but got Unknown //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) GameObject val = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1"); if ((Object)(object)val == (Object)null) { Debug.LogError((object)"Original GameObject not found."); return; } Transform parent = val.transform.parent; GameObject val2 = Object.Instantiate<GameObject>(val, parent); ((Object)val2).name = "File" + fileNum + "_BetterSaves"; string text = ES3.Load<string>("Alias_BetterSaves", "LCSaveFile" + fileNum, ""); if (text == "") { ((Component)val2.transform.GetChild(1)).GetComponent<TMP_Text>().text = "File " + fileNum; } else { ((Component)val2.transform.GetChild(1)).GetComponent<TMP_Text>().text = text; } val2.AddComponent<SaveFileUISlot_BetterSaves>(); SaveFileUISlot_BetterSaves component = val2.GetComponent<SaveFileUISlot_BetterSaves>(); if ((Object)(object)component != (Object)null) { component.fileNum = fileNum; component.fileString = "LCSaveFile" + fileNum; RectTransform component2 = val2.GetComponent<RectTransform>(); if ((Object)(object)component2 != (Object)null) { float x = component2.anchoredPosition.x; float y = newFileButton.GetComponent<RectTransform>().anchoredPosition.y; float num = y - component2.sizeDelta.y * (float)fileNum; component2.anchoredPosition = new Vector2(x, num); } GameObject gameObject = ((Component)val2.transform.GetChild(3)).gameObject; DeleteFileButton_BetterSaves component3 = GameObject.Find("Canvas/MenuContainer/DeleteFileConfirmation/Panel/Delete").GetComponent<DeleteFileButton_BetterSaves>(); ((UnityEvent)gameObject.gameObject.GetComponent<Button>().onClick).AddListener(new UnityAction(component3.UpdateFileToDelete)); gameObject.SetActive(false); component.renameButton = CreateRenameFileButton(val2); } else { Debug.LogError((object)"SaveFileUISlot_BetterSaves component not found on the cloned GameObject."); Object.Destroy((Object)(object)val2); } } public static GameObject CreateRenameFileButton(GameObject fileNode) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_00ae: 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_00d4: 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) try { GameObject gameObject = ((Component)fileNode.transform.GetChild(3)).gameObject; GameObject val = Object.Instantiate<GameObject>(gameObject, fileNode.transform); ((Object)val).name = "RenameButton"; val.GetComponent<Image>().sprite = renameSprite; Button component = val.GetComponent<Button>(); component.onClick = new ButtonClickedEvent(); val.AddComponent<RenameFileButton_BetterSaves>(); RenameFileButton_BetterSaves component2 = val.GetComponent<RenameFileButton_BetterSaves>(); if ((Object)(object)component2 != (Object)null) { ((UnityEvent)component.onClick).AddListener(new UnityAction(component2.RenameFile)); } else { Debug.LogError((object)"RenameFileButton_BetterSaves component not found on renameButton"); } RectTransform component3 = val.GetComponent<RectTransform>(); if ((Object)(object)component3 != (Object)null) { float num = ((Transform)component3).localPosition.x + 20f; float y = ((Transform)component3).localPosition.y; ((Transform)component3).localPosition = Vector2.op_Implicit(new Vector2(num, y)); } val.SetActive(false); return val; } catch (Exception ex) { Debug.LogError((object)("Error occurred while creating rename file button: " + ex.Message)); return null; } } public static void UpdateFilesPanelRect(int numSaves) { //IL_0033: 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_006a: 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_00ba: 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_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) try { GameObject obj = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel"); RectTransform val = ((obj != null) ? obj.GetComponent<RectTransform>() : null); if ((Object)(object)val == (Object)null) { throw new Exception("Failed to find FilesPanel RectTransform."); } Vector2 sizeDelta = val.sizeDelta; GameObject obj2 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/File1"); RectTransform val2 = ((obj2 != null) ? obj2.GetComponent<RectTransform>() : null); if ((Object)(object)val2 == (Object)null) { throw new Exception("Failed to find File1 RectTransform."); } float y = val2.sizeDelta.y; sizeDelta.y = y * (float)(numSaves + 3); val.sizeDelta = sizeDelta; GameObject val3 = GameObject.Find("Canvas/MenuContainer/LobbyHostSettings/FilesPanel/ChallengeMoonButton"); RectTransform component = val3.GetComponent<RectTransform>(); if ((Object)(object)component != (Object)null) { component.anchorMin = new Vector2(0.5f, 0.05f); component.anchorMax = new Vector2(0.5f, 0.05f); component.pivot = new Vector2(0.5f, 0.05f); component.anchoredPosition = new Vector2(0f, 0f); } } catch (Exception ex) { Debug.LogError((object)("Error occurred while updating files panel rect: " + ex.Message)); } } public static void RefreshNameFields() { SaveFileUISlot_BetterSaves[] array = Object.FindObjectsOfType<SaveFileUISlot_BetterSaves>(); SaveFileUISlot_BetterSaves[] array2 = array; foreach (SaveFileUISlot_BetterSaves saveFileUISlot_BetterSaves in array2) { string text = ES3.Load<string>("Alias_BetterSaves", saveFileUISlot_BetterSaves.fileString, ""); if (text == "") { ((Component)((Component)saveFileUISlot_BetterSaves).transform.GetChild(1)).GetComponent<TMP_Text>().text = "File " + (saveFileUISlot_BetterSaves.fileNum + 1); } else { ((Component)((Component)saveFileUISlot_BetterSaves).transform.GetChild(1)).GetComponent<TMP_Text>().text = text; } } } } public static class PluginInfo { public const string PLUGIN_GUID = "LCBetterSaves"; public const string PLUGIN_NAME = "LCBetterSaves"; public const string PLUGIN_VERSION = "1.7.0"; } } namespace LCBetterSaves.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("LCBetterSaves.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[] lcbettersaves { get { object @object = ResourceManager.GetObject("lcbettersaves", resourceCulture); return (byte[])@object; } } internal Resources() { } } }
plugins/RugbugRedfern-Skinwalkers/SkinwalkerMod.dll
Decompiled 2 years agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dissonance; using Dissonance.Config; using HarmonyLib; using SkinwalkerMod.Properties; using Steamworks; using Unity.Netcode; using UnityEngine; 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: 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 { internal class LogoManager : MonoBehaviour { private AssetBundle bundle; private readonly Logo[] logos = new Logo[5] { new Logo { fileName = "Teo", playerNames = new string[9] { "SAMMY", "paddy", "Ozias", "Teo", "Rugbug Redfern", "WuluKing", "Boolie", "TeaEditor", "FlashGamesNemesis" } }, new Logo { fileName = "OfflineTV", playerNames = new string[3] { "Masayoshi", "QUARTERJADE", "DisguisedToast" } }, new Logo { fileName = "Neuro", playerNames = new string[1] { "vedal" } }, new Logo { fileName = "Mogul", playerNames = new string[2] { "ludwig", "AirCoots" } }, new Logo { fileName = "Imp", playerNames = new string[1] { "camila" } } }; private Image cachedHeader; private Image cachedLogoHeader; private void Awake() { try { bundle = AssetBundle.LoadFromMemory(Resources.logos); SceneManager.sceneLoaded += OnSceneLoaded; } catch (Exception ex) { SkinwalkerLogger.LogError("LogoManager Awake Error: " + ex.Message); } } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { try { if (!(((Scene)(ref scene)).name == "MainMenu")) { return; } cachedHeader = GameObject.Find("HeaderImage").GetComponent<Image>(); cachedLogoHeader = ((Component)GameObject.Find("Canvas/MenuContainer").transform.GetChild(0).GetChild(1)).GetComponent<Image>(); string value = SteamClient.Name.ToString(); Logo[] array = logos; foreach (Logo logo in array) { string[] playerNames = logo.playerNames; foreach (string text in playerNames) { if (text.Equals(value, StringComparison.OrdinalIgnoreCase)) { ((MonoBehaviour)this).StartCoroutine(I_ChangeLogo(bundle.LoadAsset<Sprite>("Assets/Logos/" + logo.fileName + ".png"))); return; } } } } catch (Exception ex) { SkinwalkerLogger.LogError("LogoManager OnSceneLoaded Error: " + ex.Message + ". If you launched in LAN mode, then this is just gonna happen, it doesn't break anything so don't worry about it."); } } private IEnumerator I_ChangeLogo(Sprite sprite) { for (int i = 0; i < 20; i++) { if ((Object)(object)cachedHeader == (Object)null) { break; } if ((Object)(object)cachedLogoHeader == (Object)null) { break; } SetHeaderImage(sprite); yield return null; } } private void SetHeaderImage(Sprite sprite) { if (!((Object)(object)sprite == (Object)null)) { cachedHeader.sprite = sprite; cachedLogoHeader.sprite = sprite; } } } internal class Logo { public string fileName; public string[] playerNames; } [BepInPlugin("RugbugRedfern.SkinwalkerMod", "Skinwalker Mod", "2.0.6")] internal class PluginLoader : BaseUnityPlugin { private readonly Harmony harmony = new Harmony("RugbugRedfern.SkinwalkerMod"); private const string modGUID = "RugbugRedfern.SkinwalkerMod"; private const string modVersion = "2.0.6"; private static bool initialized; public static PluginLoader Instance { get; private set; } private void Awake() { //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Expected O, but got Unknown //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown 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 2.0.6"); 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); Logs.SetLogLevel((LogCategory)1, (LogLevel)4); Logs.SetLogLevel((LogCategory)3, (LogLevel)4); Logs.SetLogLevel((LogCategory)2, (LogLevel)4); GameObject val2 = new GameObject("Logo Manager"); val2.AddComponent<LogoManager>(); ((Object)val2).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val2); } 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() { if (Time.time > nextTimeToPlayAudio) { SetNextTime(); AttemptPlaySound(); } } private void AttemptPlaySound() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_012c: 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_0153: Unknown result type (might be due to invalid IL or missing references) float num = -1f; if (Object.op_Implicit((Object)(object)ai) && !ai.isEnemyDead) { if (((Object)((Component)ai).gameObject).name == "DressGirl(Clone)") { DressGirlAI val = (DressGirlAI)ai; if ((Object)(object)val.hauntingPlayer != (Object)(object)StartOfRound.Instance.localPlayerController) { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (not haunted) EnemyAI: " + (object)ai); return; } if (!val.staringInHaunt && !((EnemyAI)val).moveTowardsDestination) { SkinwalkerLogger.Log(((Object)this).name + " played voice line no (not visible) EnemyAI: " + (object)ai); return; } } Vector3 val2 = (StartOfRound.Instance.localPlayerController.isPlayerDead ? ((Component)StartOfRound.Instance.spectateCamera).transform.position : ((Component)StartOfRound.Instance.localPlayerController).transform.position); if ((Object)(object)StartOfRound.Instance == (Object)null || (Object)(object)StartOfRound.Instance.localPlayerController == (Object)null || (num = Vector3.Distance(val2, ((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<bool> VoiceEnabled_OtherEnemies; 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); PluginLoader.Instance.BindConfig(ref VoiceEnabled_OtherEnemies, "Monster Voices", "Other Enemies (Including Modded)", 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("VoiceEnabled_OtherEnemies" + $" VALUE LOADED FROM CONFIG: [{VoiceEnabled_OtherEnemies.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; DebugSettings.Instance.RecordMicrophoneRawAudio = 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) { if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).gameObject == (Object)null)) { SkinwalkerLogger.Log("IsEnemyEnabled check: " + ((Object)val).name); SkinwalkerLogger.Log(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, _ => SkinwalkerNetworkManager.Instance.VoiceEnabled_OtherEnemies.Value, }; } 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() { while (cachedAudio.Count > 200) { cachedAudio.RemoveAt(Random.Range(0, cachedAudio.Count)); } if (cachedAudio.Count > 0) { int index = Random.Range(0, cachedAudio.Count - 1); AudioClip result = cachedAudio[index]; cachedAudio.RemoveAt(index); return result; } 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<bool> VoiceEnabled_OtherEnemies = 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; VoiceEnabled_OtherEnemies.Value = SkinwalkerConfig.VoiceEnabled_OtherEnemies.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 (VoiceEnabled_OtherEnemies == null) { throw new Exception("SkinwalkerNetworkManager.VoiceEnabled_OtherEnemies cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)VoiceEnabled_OtherEnemies).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies, "VoiceEnabled_OtherEnemies"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)VoiceEnabled_OtherEnemies); 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"; } } } namespace SkinwalkerMod.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("SkinwalkerMod.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[] logos { get { object @object = ResourceManager.GetObject("logos", resourceCulture); return (byte[])@object; } } internal Resources() { } } }
plugins/Sligili-More_Emotes/MoreEmotes1.3.2.dll
Decompiled 2 years 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 MoreEmotes.Scripts; using RuntimeNetcodeRPCValidator; using TMPro; using Tools; using Unity.Netcode; using UnityEngine; using UnityEngine.Animations.Rigging; 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 Ref { 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 Method(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; } } public class D : MonoBehaviour { public static bool Debug; public static void L(string msg) { if (Debug) { Debug.Log((object)msg); } } public static void W(string msg) { if (Debug) { Debug.LogWarning((object)msg); } } } } namespace MoreEmotes { [BepInPlugin("MoreEmotes", "MoreEmotes-Sligili", "1.3.2")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class MoreEmotesInitialization : BaseUnityPlugin { private Harmony _harmony; private NetcodeValidator netcodeValidator; private ConfigEntry<string> config_KeyWheel; private ConfigEntry<string> config_KeyWheel_c; private ConfigEntry<bool> config_InventoryCheck; private ConfigEntry<bool> config_UseConfigFile; 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 ConfigEntry<string> config_KeyEmote9; private ConfigEntry<string> config_KeyEmote10; private void Awake() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown ((BaseUnityPlugin)this).Logger.LogInfo((object)"MoreEmotes loaded"); LoadAssetBundles(); LoadAssets(); ConfigFile(); SearchForIncompatibleMods(); _harmony = new Harmony("MoreEmotes"); _harmony.PatchAll(typeof(EmotePatch)); netcodeValidator = new NetcodeValidator("MoreEmotes"); netcodeValidator.PatchAll(); netcodeValidator.BindToPreExistingObjectByBehaviour<SignEmoteText, PlayerControllerB>(); netcodeValidator.BindToPreExistingObjectByBehaviour<SyncAnimatorToOthers, PlayerControllerB>(); } private void LoadAssetBundles() { string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animationsbundle"); string text2 = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "MoreEmotes/animatorbundle"); try { EmotePatch.AnimationsBundle = AssetBundle.LoadFromFile(text); EmotePatch.AnimatorBundle = AssetBundle.LoadFromFile(text2); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Failed to load AssetBundles. Make sure \"animatorsbundle\" and \"animationsbundle\" are inside the MoreEmotes folder.\nError: " + ex.Message)); } } private void LoadAssets() { string path = "Assets/MoreEmotes"; EmotePatch.local = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarig.controller")); EmotePatch.others = EmotePatch.AnimatorBundle.LoadAsset<RuntimeAnimatorController>(Path.Combine(path, "NEWmetarigOtherPlayers.controller")); MoreEmotesEvents.ClapSounds[0] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote1.wav")); MoreEmotesEvents.ClapSounds[1] = EmotePatch.AnimationsBundle.LoadAsset<AudioClip>(Path.Combine(path, "SingleClapEmote2.wav")); EmotePatch.SettingsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesPanel.prefab")); EmotePatch.ButtonPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/MoreEmotesButton.prefab")); EmotePatch.LegsPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/plegs.prefab")); EmotePatch.SignPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/Sign.prefab")); EmotePatch.SignUIPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>(Path.Combine(path, "Resources/SignTextUI.prefab")); EmotePatch.WheelPrefab = EmotePatch.AnimationsBundle.LoadAsset<GameObject>("Assets/MoreEmotes/Resources/MoreEmotesMenu.prefab"); } private void ConfigFile() { EmotePatch.ConfigFile_Keybinds = new string[32]; config_KeyWheel = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL", "Key", "v", (ConfigDescription)null); EmotePatch.ConfigFile_WheelKeybind = config_KeyWheel.Value; config_KeyWheel_c = ((BaseUnityPlugin)this).Config.Bind<string>("EMOTE WHEEL (Controller)", "Key", "leftshoulder", (ConfigDescription)null); EmotePatch.ConfigFile_WheelKeybind_controller = config_KeyWheel_c.Value; config_InventoryCheck = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "InventoryCheck", true, "Prevents some emotes from performing while holding any item/scrap"); EmotePatch.ConfigFile_InventoryCheck = config_InventoryCheck.Value; config_UseConfigFile = ((BaseUnityPlugin)this).Config.Bind<bool>("OTHERS", "ConfigFile", false, "Ignores all in-game saved settings and instead uses the config file"); EmotePatch.UseConfigFile = config_UseConfigFile.Value; config_KeyEmote3 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Middle Finger", "3", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[2] = config_KeyEmote3.Value.Replace(" ", ""); config_KeyEmote4 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "The Griddy", "6", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[5] = config_KeyEmote4.Value.Replace(" ", ""); config_KeyEmote5 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Shy", "5", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[4] = config_KeyEmote5.Value.Replace(" ", ""); config_KeyEmote6 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Clap", "4", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[3] = config_KeyEmote6.Value.Replace(" ", ""); config_KeyEmote7 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Twerk", "7", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[6] = config_KeyEmote7.Value.Replace(" ", ""); config_KeyEmote8 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Salute", "8", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[7] = config_KeyEmote8.Value.Replace(" ", ""); config_KeyEmote9 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Prisyadka", "9", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[8] = config_KeyEmote9.Value.Replace(" ", ""); config_KeyEmote10 = ((BaseUnityPlugin)this).Config.Bind<string>("QUICK EMOTES", "Sign", "0", (ConfigDescription)null); EmotePatch.ConfigFile_Keybinds[9] = config_KeyEmote10.Value.Replace(" ", ""); } private void SearchForIncompatibleMods() { foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos) { BepInPlugin metadata = pluginInfo.Value.Metadata; if (metadata.GUID.Equals("com.malco.lethalcompany.moreshipupgrades", StringComparison.OrdinalIgnoreCase) || metadata.GUID.Equals("Stoneman.LethalProgression", StringComparison.OrdinalIgnoreCase)) { EmotePatch.IncompatibleStuff = true; break; } } } } public static class PluginInfo { public const string GUID = "MoreEmotes"; public const string NAME = "MoreEmotes-Sligili"; public const string VER = "1.3.2"; } } namespace MoreEmotes.Patch { public enum Emotes { D_Sign = 1010, D_Clap = 1004, D_Middle_Finger = 1003, Dance = 1, Point = 2, Middle_Finger = 3, Clap = 4, Shy = 5, The_Griddy = 6, Twerk = 7, Salute = 8, Prisyadka = 9, Sign = 10 } public class EmotePatch { public static AssetBundle AnimationsBundle; public static AssetBundle AnimatorBundle; public static RuntimeAnimatorController local; public static RuntimeAnimatorController others; public static bool UseConfigFile; public static string[] ConfigFile_Keybinds; public static string ConfigFile_WheelKeybind; public static string ConfigFile_WheelKeybind_controller; public static bool ConfigFile_InventoryCheck; public static string EmoteWheelKeyboard; public static string EmoteWheelController; public static bool IncompatibleStuff; private static int s_currentEmoteID = 0; private static float s_defaultPlayerSpeed; private static bool[] s_wasPerformingEmote = new bool[32]; public static bool IsEmoteWheelOpen; private static bool s_isPlayerFirstFrame; private static bool s_isFirstTimeOnMenu; private static bool s_isPlayerSpawning; public const int AlternateEmoteIDOffset = 1000; private static int[] s_doubleEmotesIDS = new int[2] { 3, 4 }; public static bool LocalArmsSeparatedFromCamera; private static Transform s_freeArmsTarget; private static Transform s_lockedArmsTarget; private static CallbackContext emptyContext; public static GameObject ButtonPrefab; public static GameObject SettingsPrefab; public static GameObject LegsPrefab; public static GameObject SignPrefab; public static GameObject SignUIPrefab; public static GameObject WheelPrefab; private static GameObject s_localPlayerLevelBadge; private static GameObject s_localPlayerBetaBadge; private static Transform s_legsMesh; private static EmoteWheel s_selectionWheel; private static SignUI s_customSignInputField; private static SyncAnimatorToOthers s_syncAnimator; private static int _AlternateEmoteIDOffset => 1000; private static void InstantiateSettingsMenu(Transform container) { RebindButton.ConfigFile_Keybinds = ConfigFile_Keybinds; if (!PlayerPrefs.HasKey("InvCheck") || UseConfigFile) { PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0); } ToggleButton.s_InventoryCheck = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1)); SetupUI.UseConfigFile = UseConfigFile; SetupUI.InventoryCheck = ToggleButton.s_InventoryCheck; GameObject gameObject = ((Component)((Component)container).transform.Find("SettingsPanel")).gameObject; Object.Instantiate<GameObject>(ButtonPrefab, gameObject.transform).transform.SetSiblingIndex(7); Object.Instantiate<GameObject>(SettingsPrefab, gameObject.transform); gameObject.AddComponent<SetupUI>(); } private static void CheckEmoteInput(string keyBind, bool needsEmptyHands, int emoteID, PlayerControllerB player) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) Emotes emotes = (Emotes)emoteID; string text = emotes.ToString(); bool flag; if (UseConfigFile) { flag = ConfigFile_InventoryCheck; keyBind = ConfigFile_Keybinds[emoteID - 1]; } else { flag = PlayerPrefs.GetInt("InvCheck") == 1; 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.PerformEmote(emptyContext, emoteID); } } private static void CheckWheelInput(string keybind, string controller, PlayerControllerB player) { //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_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) bool flag = false; bool flag2 = false; if (Gamepad.all.Count != 0 && !controller.Equals(string.Empty)) { flag = InputControlExtensions.IsPressed(((InputControl)Gamepad.current)[controller], 0f); } if (keybind != string.Empty) { flag2 = InputControlExtensions.IsPressed(((InputControl)Keyboard.current)[keybind], 0f) && !((ButtonControl)Keyboard.current[(Key)55]).wasPressedThisFrame; } bool flag3 = flag || flag2; if (flag3 && !IsEmoteWheelOpen && !player.isPlayerDead && !player.inTerminalMenu && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen) { IsEmoteWheelOpen = true; Cursor.visible = true; Cursor.lockState = (CursorLockMode)2; ((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen); player.disableLookInput = true; } else { if (!IsEmoteWheelOpen || (flag3 && !player.quickMenuManager.isMenuOpen && !player.isTypingChat && !s_customSignInputField.IsSignUIOpen)) { return; } int selectedEmoteID = s_selectionWheel.SelectedEmoteID; if (!player.quickMenuManager.isMenuOpen && !s_customSignInputField.IsSignUIOpen) { Cursor.visible = false; Cursor.lockState = (CursorLockMode)1; } if (!player.isPlayerDead && !player.quickMenuManager.isMenuOpen) { if (selectedEmoteID <= 3 || selectedEmoteID == 6 || !ConfigFile_InventoryCheck) { player.PerformEmote(emptyContext, selectedEmoteID); } else if (!player.isHoldingObject) { player.PerformEmote(emptyContext, selectedEmoteID); } } if (!s_customSignInputField.IsSignUIOpen) { player.disableLookInput = false; } IsEmoteWheelOpen = false; ((Component)s_selectionWheel).gameObject.SetActive(IsEmoteWheelOpen); } } private static void OnFirstLocalPlayerFrameWithNewAnimator(PlayerControllerB player) { s_isPlayerFirstFrame = false; s_syncAnimator = ((Component)player).GetComponent<SyncAnimatorToOthers>(); s_customSignInputField.Player = player; s_freeArmsTarget = Object.Instantiate<Transform>(player.localArmsRotationTarget, player.localArmsRotationTarget.parent.parent); s_lockedArmsTarget = player.localArmsRotationTarget; Transform val = ((Component)player).transform.Find("ScavengerModel").Find("metarig").Find("spine") .Find("spine.001") .Find("spine.002") .Find("spine.003"); s_localPlayerLevelBadge = ((Component)val.Find("LevelSticker")).gameObject; s_localPlayerBetaBadge = ((Component)val.Find("BetaBadge")).gameObject; player.SpawnPlayerAnimation(); } private static void SpawnSign(PlayerControllerB player) { //IL_005e: 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) GameObject val = Object.Instantiate<GameObject>(SignPrefab, ((Component)((Component)((Component)player).transform.Find("ScavengerModel")).transform.Find("metarig")).transform); val.transform.SetSiblingIndex(6); ((Object)val).name = "Sign"; val.transform.localPosition = new Vector3(0.029f, -0.45f, 1.3217f); val.transform.localRotation = Quaternion.Euler(65.556f, 180f, 180f); } private static void SpawnLegs(PlayerControllerB player) { //IL_00b4: 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) GameObject val = Object.Instantiate<GameObject>(LegsPrefab, ((Component)((Component)player.playerBodyAnimator).transform.parent).transform); s_legsMesh = val.transform.Find("Mesh"); ((Component)s_legsMesh).transform.parent = ((Component)player.playerBodyAnimator).transform.parent; ((Object)s_legsMesh).name = "LEGS"; GameObject gameObject = ((Component)val.transform.Find("Armature")).gameObject; gameObject.transform.parent = ((Component)player.playerBodyAnimator).transform; ((Object)gameObject).name = "FistPersonLegs"; gameObject.transform.position = new Vector3(0f, 0.197f, 0f); gameObject.transform.localScale = new Vector3(13.99568f, 13.99568f, 13.99568f); Object.Destroy((Object)(object)val); } private static void SetIKWeights(PlayerControllerB player) { Transform val = ((Component)player.playerBodyAnimator).transform.Find("Rig 1"); ChainIKConstraint component = ((Component)val.Find("RightArm")).GetComponent<ChainIKConstraint>(); ChainIKConstraint component2 = ((Component)val.Find("LeftArm")).GetComponent<ChainIKConstraint>(); TwoBoneIKConstraint component3 = ((Component)val.Find("RightLeg")).GetComponent<TwoBoneIKConstraint>(); TwoBoneIKConstraint component4 = ((Component)val.Find("LeftLeg")).GetComponent<TwoBoneIKConstraint>(); Transform val2 = ((Component)player.playerBodyAnimator).transform.Find("ScavengerModelArmsOnly").Find("metarig").Find("spine.003") .Find("RigArms"); ChainIKConstraint component5 = ((Component)val2.Find("RightArm")).GetComponent<ChainIKConstraint>(); ChainIKConstraint component6 = ((Component)val2.Find("LeftArm")).GetComponent<ChainIKConstraint>(); ((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f; ((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component2).weight = 1f; ((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component).weight = 1f; ((RigConstraint<TwoBoneIKConstraintJob, TwoBoneIKConstraintData, TwoBoneIKConstraintJobBinder<TwoBoneIKConstraintData>>)(object)component4).weight = 1f; ((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component5).weight = 1f; ((RigConstraint<ChainIKConstraintJob, ChainIKConstraintData, ChainIKConstraintJobBinder<ChainIKConstraintData>>)(object)component6).weight = 1f; } private static void UpdateLegsMaterial(PlayerControllerB player) { ((Renderer)((Component)s_legsMesh).GetComponent<SkinnedMeshRenderer>()).material = ((Renderer)((Component)((Component)((Component)player.playerBodyAnimator).transform.parent).transform.Find("LOD1")).gameObject.GetComponent<SkinnedMeshRenderer>()).material; } private static void TogglePlayerBadges(PlayerControllerB player, bool enabled) { if ((Object)(object)s_localPlayerBetaBadge != (Object)null) { ((Renderer)s_localPlayerBetaBadge.GetComponent<MeshRenderer>()).enabled = enabled; } if ((Object)(object)s_localPlayerLevelBadge != (Object)null) { ((Renderer)s_localPlayerLevelBadge.GetComponent<MeshRenderer>()).enabled = enabled; } else { Debug.LogError((object)"[MoreEmotes-Sligili] Couldn't find the level badge"); } } public static void UpdateWheelKeybinds() { if (UseConfigFile) { EmoteWheelKeyboard = ConfigFile_WheelKeybind; EmoteWheelController = ConfigFile_WheelKeybind_controller; return; } if (!PlayerPrefs.HasKey("Emote_Wheel_c")) { PlayerPrefs.SetString("Emote_Wheel_c", ConfigFile_WheelKeybind_controller); } EmoteWheelController = PlayerPrefs.GetString("Emote_Wheel_c"); if (!PlayerPrefs.HasKey("Emote_Wheel")) { PlayerPrefs.SetString("Emote_Wheel", ConfigFile_WheelKeybind); } EmoteWheelKeyboard = PlayerPrefs.GetString("Emote_Wheel"); if (!PlayerPrefs.HasKey("InvCheck")) { PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0); } ConfigFile_InventoryCheck = PlayerPrefs.GetInt("InvCheck") == 1; } [HarmonyPatch(typeof(MenuManager), "Start")] [HarmonyPostfix] private static void MenuStart(MenuManager __instance) { D.Debug = false; try { InstantiateSettingsMenu(((Component)((Component)__instance).transform.parent).transform.Find("MenuContainer")); } catch (Exception ex) { if (!s_isFirstTimeOnMenu) { s_isFirstTimeOnMenu = true; } else { Debug.LogError((object)(ex.Message + "\n[MoreEmotes-Sligili] Couldn't find MenuContainer")); } } } [HarmonyPatch(typeof(RoundManager), "Awake")] [HarmonyPostfix] private static void AwakePost(RoundManager __instance) { if (!PlayerPrefs.HasKey("InvCheck")) { PlayerPrefs.SetInt("InvCheck", ConfigFile_InventoryCheck ? 1 : 0); } UpdateWheelKeybinds(); GameObject gameObject = ((Component)((Component)GameObject.Find("Systems").gameObject.transform.Find("UI")).gameObject.transform.Find("Canvas")).gameObject; InstantiateSettingsMenu(gameObject.transform.Find("QuickMenu")); s_selectionWheel = Object.Instantiate<GameObject>(WheelPrefab, gameObject.transform).AddComponent<EmoteWheel>(); s_customSignInputField = Object.Instantiate<GameObject>(SignUIPrefab, gameObject.transform).AddComponent<SignUI>(); EmoteWheel.Keybinds = new string[ConfigFile_Keybinds.Length + 1]; EmoteWheel.Keybinds = ConfigFile_Keybinds; s_isPlayerFirstFrame = true; } [HarmonyPatch(typeof(HUDManager), "EnableChat_performed")] [HarmonyPrefix] private static bool OpenChatPrefix() { if (s_customSignInputField.IsSignUIOpen) { return false; } return true; } [HarmonyPatch(typeof(HUDManager), "SubmitChat_performed")] [HarmonyPrefix] private static bool SubmitChatPrefix() { if (s_customSignInputField.IsSignUIOpen) { return false; } return true; } [HarmonyPatch(typeof(PlayerControllerB), "Start")] [HarmonyPostfix] private static void StartPostfix(PlayerControllerB __instance) { ((Component)((Component)((Component)__instance).gameObject.transform.Find("ScavengerModel")).transform.Find("metarig")).gameObject.AddComponent<MoreEmotesEvents>().Player = __instance; s_defaultPlayerSpeed = __instance.movementSpeed; ((Component)__instance).gameObject.AddComponent<CustomAnimationObjects>(); SpawnSign(__instance); } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPostfix] private static void UpdatePostfix(PlayerControllerB __instance) { if (!__instance.isPlayerControlled || !((NetworkBehaviour)__instance).IsOwner) { __instance.playerBodyAnimator.runtimeAnimatorController = others; return; } if ((Object)(object)__instance.playerBodyAnimator != (Object)(object)local) { if (s_isPlayerFirstFrame) { SpawnLegs(__instance); } __instance.playerBodyAnimator.runtimeAnimatorController = local; if (s_isPlayerFirstFrame) { OnFirstLocalPlayerFrameWithNewAnimator(__instance); } if (s_isPlayerSpawning) { __instance.SpawnPlayerAnimation(); s_isPlayerSpawning = false; } } if (!IncompatibleStuff) { if ((bool)Ref.Method(__instance, "CheckConditionsForEmote") && __instance.performingEmote) { switch (s_currentEmoteID) { case 6: __instance.movementSpeed = s_defaultPlayerSpeed / 2f; break; case 9: __instance.movementSpeed = s_defaultPlayerSpeed / 3f; break; } } else { __instance.movementSpeed = s_defaultPlayerSpeed; } } __instance.localArmsRotationTarget = (LocalArmsSeparatedFromCamera ? (__instance.localArmsRotationTarget = s_freeArmsTarget) : (__instance.localArmsRotationTarget = s_lockedArmsTarget)); CheckWheelInput(EmoteWheelKeyboard, EmoteWheelController, __instance); if (!__instance.quickMenuManager.isMenuOpen && !IsEmoteWheelOpen) { CheckEmoteInput(ConfigFile_Keybinds[2], needsEmptyHands: false, 3, __instance); CheckEmoteInput(ConfigFile_Keybinds[3], needsEmptyHands: true, 4, __instance); CheckEmoteInput(ConfigFile_Keybinds[4], needsEmptyHands: true, 5, __instance); CheckEmoteInput(ConfigFile_Keybinds[5], needsEmptyHands: false, 6, __instance); CheckEmoteInput(ConfigFile_Keybinds[6], needsEmptyHands: true, 7, __instance); CheckEmoteInput(ConfigFile_Keybinds[7], needsEmptyHands: true, 8, __instance); CheckEmoteInput(ConfigFile_Keybinds[8], needsEmptyHands: true, 9, __instance); CheckEmoteInput(ConfigFile_Keybinds[9], needsEmptyHands: true, 10, __instance); } } [HarmonyPatch(typeof(PlayerControllerB), "Update")] [HarmonyPrefix] private static void UpdatePrefix(PlayerControllerB __instance) { if (!((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { D.L(__instance.playerBodyAnimator.GetInteger("emoteNumber").ToString() ?? ""); } if (__instance.performingEmote) { s_wasPerformingEmote[__instance.playerClientId] = true; } if (!__instance.performingEmote && s_wasPerformingEmote[__instance.playerClientId]) { s_wasPerformingEmote[__instance.playerClientId] = false; SetIKWeights(__instance); } } [HarmonyPatch(typeof(PlayerControllerB), "SpawnPlayerAnimation")] [HarmonyPrefix] private static void OnLocalPlayerSpawn(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { s_isPlayerSpawning = true; } } [HarmonyPatch(typeof(PlayerControllerB), "CheckConditionsForEmote")] [HarmonyPrefix] private static bool CheckConditionsPrefix(ref bool __result, PlayerControllerB __instance) { bool flag = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isJumping"); bool flag2 = (bool)Ref.GetInstanceField(typeof(PlayerControllerB), __instance, "isWalking"); if (s_currentEmoteID == 6 || s_currentEmoteID == 9) { __result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && __instance.moveInputVector.x == 0f && !__instance.isSprinting && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu && !__instance.isTypingChat; return false; } if (s_currentEmoteID == 10 || s_currentEmoteID == 1010) { __result = !__instance.inSpecialInteractAnimation && !__instance.isPlayerDead && !flag && !flag2 && !__instance.isCrouching && !__instance.isClimbingLadder && !__instance.isGrabbingObjectAnimation && !__instance.inTerminalMenu; return false; } return true; } [HarmonyPatch(typeof(PlayerControllerB), "PerformEmote")] [HarmonyPrefix] private static bool PerformEmotePrefix(CallbackContext context, int emoteID, PlayerControllerB __instance) { if ((!((NetworkBehaviour)__instance).IsOwner || !__instance.isPlayerControlled || (((NetworkBehaviour)__instance).IsServer && !__instance.isHostPlayerObject)) && !__instance.isTestingPlayer) { return false; } if (s_customSignInputField.IsSignUIOpen && emoteID != 1010) { return false; } if (emoteID > 0 && emoteID < 3 && !IsEmoteWheelOpen && !((CallbackContext)(ref context)).performed) { return false; } D.L("Emote ID pre doubleemote check " + emoteID); int[] array = s_doubleEmotesIDS; foreach (int num in array) { int num2 = num + _AlternateEmoteIDOffset; bool flag = (UseConfigFile ? ConfigFile_InventoryCheck : (PlayerPrefs.GetInt("InvCheck") == 1)); if (emoteID == num && s_currentEmoteID == emoteID && __instance.performingEmote && (!__instance.isHoldingObject || !flag)) { if (emoteID == num) { emoteID += _AlternateEmoteIDOffset; } else { emoteID -= 1000; } } } D.L("Emote ID post doubleemote check " + emoteID); if ((s_currentEmoteID != emoteID && emoteID < 3) || !__instance.performingEmote) { SetIKWeights(__instance); } if (!(bool)Ref.Method(__instance, "CheckConditionsForEmote")) { return false; } if (__instance.timeSinceStartingEmote < 0.5f) { return false; } s_currentEmoteID = emoteID; Action action = delegate { __instance.timeSinceStartingEmote = 0f; __instance.playerBodyAnimator.SetInteger("emoteNumber", emoteID); __instance.performingEmote = true; __instance.StartPerformingEmoteServerRpc(); s_syncAnimator.UpdateEmoteIDForOthers(emoteID); TogglePlayerBadges(__instance, enabled: false); }; switch (emoteID) { case 9: action = (Action)Delegate.Combine(action, (Action)delegate { UpdateLegsMaterial(__instance); }); break; case 10: action = (Action)Delegate.Combine(action, (Action)delegate { ((Component)s_customSignInputField).gameObject.SetActive(true); }); break; } action(); return false; } [HarmonyPatch(typeof(PlayerControllerB), "StopPerformingEmoteServerRpc")] [HarmonyPostfix] private static void StopPerformingEmoteServerPrefix(PlayerControllerB __instance) { if (((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled) { __instance.playerBodyAnimator.SetInteger("emoteNumber", 0); } TogglePlayerBadges(__instance, enabled: true); s_syncAnimator.UpdateEmoteIDForOthers(0); } } } namespace MoreEmotes.Scripts { public class MoreEmotesEvents : MonoBehaviour { private Animator _playerAnimator; private AudioSource _playerAudioSource; public static AudioClip[] ClapSounds = (AudioClip[])(object)new AudioClip[2]; public PlayerControllerB Player; private void Start() { _playerAnimator = ((Component)this).GetComponent<Animator>(); _playerAudioSource = Player.movementAudio; } public void PlayClapSound() { //IL_007d: Unknown result type (might be due to invalid IL or missing references) if (Player.performingEmote) { int currentEmoteID = GetCurrentEmoteID(); if (!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 4) { bool flag = Player.isInHangarShipRoom && Player.playersManager.hangarDoorsClosed; RoundManager.Instance.PlayAudibleNoise(((Component)Player).transform.position, 22f, 0.6f, 0, flag, 6); _playerAudioSource.pitch = Random.Range(0.59f, 0.79f); _playerAudioSource.PlayOneShot(ClapSounds[Random.Range(0, ClapSounds.Length)]); } } } public void PlayFootstepSound() { if (Player.performingEmote) { int currentEmoteID = GetCurrentEmoteID(); if ((!((NetworkBehaviour)Player).IsOwner || !Player.isPlayerControlled || currentEmoteID == 6 || currentEmoteID == 8 || currentEmoteID == 9) && ((Vector2)(ref Player.moveInputVector)).sqrMagnitude == 0f) { Player.PlayFootstepLocal(); Player.PlayFootstepServer(); } } } private int GetCurrentEmoteID() { int num = _playerAnimator.GetInteger("emoteNumber"); if (num >= 1000) { num -= 1000; } return num; } } public class SignEmoteText : NetworkBehaviour { private PlayerControllerB _playerInstance; private TextMeshPro _signModelText; public string Text => ((TMP_Text)_signModelText).text; private void Start() { _playerInstance = ((Component)this).GetComponent<PlayerControllerB>(); _signModelText = ((Component)((Component)_playerInstance).transform.Find("ScavengerModel").Find("metarig").Find("Sign") .Find("Text")).GetComponent<TextMeshPro>(); } public void UpdateSignText(string newText) { if (((NetworkBehaviour)_playerInstance).IsOwner && _playerInstance.isPlayerControlled) { UpdateSignTextServerRpc(newText); } } [ServerRpc(RequireOwnership = false)] private void UpdateSignTextServerRpc(string newText) { UpdateSignTextClientRpc(newText); } [ClientRpc] private void UpdateSignTextClientRpc(string newText) { ((TMP_Text)_signModelText).text = newText; } } public class EmoteWheel : MonoBehaviour { private RectTransform _graphics_selectedBlock; private RectTransform _graphics_selectionArrow; private Text _graphics_emoteInformation; private Text _graphics_pageInformation; private int _blocksNumber = 8; private int _selectedBlock = 1; private float _changePageCooldown = 0.1f; private float _selectionArrowLerpSpeed = 30f; private float _angle; private GameObject[] _pages; public float WheelMovementDeadzone = 3.3f; public float WheelMovementDeadzoneController = 0.7f; public static string[] Keybinds; private Vector2 _wheelCenter; private Vector2 _lastMouseCoords; public int SelectedPageNumber { get; private set; } public int SelectedEmoteID { get; private set; } public bool IsUsingController { get; private set; } private void Awake() { GetVanillaKeybinds(); FindGraphics(); FindPages(((Component)this).gameObject.transform.Find("FunctionalContent")); UpdatePageInfo(); } 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_0022: Unknown result type (might be due to invalid IL or missing references) _wheelCenter = new Vector2((float)(Screen.width / 2), (float)(Screen.height / 2)); Mouse.current.WarpCursorPosition(_wheelCenter); } private void GetVanillaKeybinds() { PlayerInput component = GameObject.Find("PlayerSettingsObject").GetComponent<PlayerInput>(); if ((Object)(object)component == (Object)null) { Debug.LogError((object)" MoreEmotes: PlayerSettingsObject is null"); return; } Keybinds[0] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote1", false), 0, (DisplayStringOptions)0); Keybinds[1] = InputActionRebindingExtensions.GetBindingDisplayString(component.currentActionMap.FindAction("Emote2", false), 0, (DisplayStringOptions)0); } private void FindGraphics() { _graphics_selectionArrow = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("SelectionArrow")).gameObject.GetComponent<RectTransform>(); _graphics_selectedBlock = ((Component)((Component)this).gameObject.transform.Find("SelectedEmote")).gameObject.GetComponent<RectTransform>(); _graphics_emoteInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("EmoteInfo")).GetComponent<Text>(); _graphics_pageInformation = ((Component)((Component)((Component)this).gameObject.transform.Find("Graphics")).gameObject.transform.Find("PageNumber")).GetComponent<Text>(); } private void FindPages(Transform contentParent) { _pages = (GameObject[])(object)new GameObject[((Component)contentParent).transform.childCount]; _graphics_pageInformation.text = "< Page " + (SelectedPageNumber + 1) + "/" + _pages.Length + " >"; for (int i = 0; i < ((Component)contentParent).transform.childCount; i++) { _pages[i] = ((Component)((Component)contentParent).transform.GetChild(i)).gameObject; } } private void Update() { ControllerInput(); if (!IsUsingController) { MouseInput(); } Cursor.visible = !IsUsingController; UpdateSelectionArrow(); PageSelection(); SelectedEmoteID = _selectedBlock + Mathf.RoundToInt((float)(_blocksNumber / 4)) + _blocksNumber * SelectedPageNumber; UpdateEmoteInfo(); } private unsafe void ControllerInput() { //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_00ba: 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_00c5: 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 (Gamepad.all.Count == 0) { IsUsingController = false; return; } float num = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).x).ReadUnprocessedValue(); float num2 = ((InputControl<float>)(object)((Vector2Control)Gamepad.current.rightStick).y).ReadUnprocessedValue(); if (Mathf.Abs(num) < WheelMovementDeadzoneController && Mathf.Abs(num2) < WheelMovementDeadzoneController) { if (System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value) != _lastMouseCoords) { IsUsingController = false; } } else { IsUsingController = true; _lastMouseCoords = System.Runtime.CompilerServices.Unsafe.Read<Vector2>((void*)((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).value); WheelSelection(Vector2.zero, num, num2); } } private void MouseInput() { //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_002b: Unknown result type (might be due to invalid IL or missing references) if (!(Vector2.Distance(_wheelCenter, ((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()) < WheelMovementDeadzone)) { WheelSelection(_wheelCenter, ((InputControl<float>)(object)((Pointer)Mouse.current).position.x).ReadValue(), ((InputControl<float>)(object)((Pointer)Mouse.current).position.y).ReadValue()); } } private void WheelSelection(Vector2 origin, float xAxisValue, float yAxisValue) { //IL_0002: 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_002a: 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_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: 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) bool flag = xAxisValue > origin.x; bool flag2 = yAxisValue > origin.y; int num = ((!flag) ? (flag2 ? 2 : 3) : (flag2 ? 1 : 4)); float num2 = (yAxisValue - origin.y) / (xAxisValue - origin.x); float num3 = 180 * (num - ((num <= 2) ? 1 : 2)); _angle = Mathf.Atan(num2) * (180f / (float)Math.PI) + num3; if (_angle == 90f) { _angle = 270f; } else if (_angle == 270f) { _angle = 90f; } float num4 = 360 / _blocksNumber; _selectedBlock = Mathf.RoundToInt((_angle - num4 * 1.5f) / num4); ((Transform)_graphics_selectedBlock).localRotation = Quaternion.Euler(((Component)this).transform.rotation.z, ((Component)this).transform.rotation.y, num4 * (float)_selectedBlock); } private void PageSelection() { UpdatePageInfo(); if (_changePageCooldown > 0f) { _changePageCooldown -= Time.deltaTime; return; } int num; if (IsUsingController) { if (!Gamepad.current.dpad.left.isPressed && !Gamepad.current.dpad.right.isPressed) { return; } num = (Gamepad.current.dpad.left.isPressed ? 1 : (-1)); } else { if (((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() == 0f) { return; } num = ((((InputControl<float>)(object)((Vector2Control)Mouse.current.scroll).y).ReadValue() > 0f) ? 1 : (-1)); } GameObject[] pages = _pages; foreach (GameObject val in pages) { val.SetActive(false); } SelectedPageNumber = (SelectedPageNumber + num + _pages.Length) % _pages.Length; _pages[SelectedPageNumber].SetActive(true); _changePageCooldown = ((!IsUsingController) ? 0.1f : 0.3f); } private void UpdatePageInfo() { _graphics_pageInformation.text = $"<color=#fe6b02><</color> Page {SelectedPageNumber + 1}/{_pages.Length} <color=#fe6b02>></color>"; } private void UpdateEmoteInfo() { string text = ((SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]); int num = 0; foreach (Emotes value in Enum.GetValues(typeof(Emotes))) { if (value >= Emotes.Dance && value < (Emotes)64) { num++; } } string text2 = ((SelectedEmoteID > num) ? "EMPTY" : ((Emotes)SelectedEmoteID).ToString().Replace("_", " ")); if (SelectedEmoteID > 2 && SelectedEmoteID <= Keybinds.Length) { if (!PlayerPrefs.HasKey(text2.Replace(" ", "_"))) { PlayerPrefs.SetString(text2.Replace(" ", "_"), (SelectedEmoteID > Keybinds.Length) ? "" : Keybinds[SelectedEmoteID - 1]); } else { text = PlayerPrefs.GetString(text2.Replace(" ", "_")); } } text = "<size=120>[" + text + "]</size>"; _graphics_emoteInformation.text = text2 + "\n" + text.ToUpper(); } private void UpdateSelectionArrow() { //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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) float num = 360 / _blocksNumber; Quaternion val = Quaternion.Euler(0f, 0f, _angle - num * 2f); ((Transform)_graphics_selectionArrow).localRotation = Quaternion.Lerp(((Transform)_graphics_selectionArrow).localRotation, val, Time.deltaTime * _selectionArrowLerpSpeed); } } public class RebindButton : MonoBehaviour { public static string[] ConfigFile_Keybinds; private string _defaultKey; private string _playerPrefsString; private Transform _waitingForInput; private Text _keyInfo; public bool IsControllerButton { get; private set; } = false; private void Start() { //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown string text = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text; IsControllerButton = GetControllerFlag(); _playerPrefsString = ((Component)((Component)this).gameObject.transform.Find("Description")).GetComponent<Text>().text.Replace(" ", "_") + (IsControllerButton ? "_c" : ""); _defaultKey = GetDefaultKey(text); FindComponents(); ((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener(new UnityAction(GetKey)); if (!PlayerPrefs.HasKey(_playerPrefsString)) { PlayerPrefs.SetString(_playerPrefsString, _defaultKey); } SetKeybind(PlayerPrefs.GetString(_playerPrefsString)); } private string GetDefaultKey(string emoteName) { if (Enum.TryParse<Emotes>(emoteName.Replace(" ", "_"), out var result)) { return ConfigFile_Keybinds[(int)(result - 1)]; } return IsControllerButton ? "leftshoulder" : "V"; } private bool GetControllerFlag() { Transform val = ((Component)this).gameObject.transform.Find("Description").Find("Subtext"); if ((Object)(object)val == (Object)null) { return false; } Text val2 = default(Text); if (((Component)val).TryGetComponent<Text>(ref val2)) { return val2.text.Equals("(Controller)", StringComparison.OrdinalIgnoreCase); } return false; } private void FindComponents() { ((Component)((Component)((Component)this).transform.parent).transform.Find("Delete")).gameObject.AddComponent<DeleteButton>(); _keyInfo = ((Component)((Component)this).transform.Find("InputText")).GetComponent<Text>(); _waitingForInput = ((Component)this).transform.Find("wait"); } public void SetKeybind(string key) { List<string> list = new List<string> { "up", "down", "left", "right" }; if (list.Contains(key.ToLower()) && key.Length < 5) { key = "dpad/" + key; } PlayerPrefs.SetString(_playerPrefsString, key); _keyInfo.text = key.ToUpper(); ((MonoBehaviour)this).StopAllCoroutines(); ((Component)_waitingForInput).gameObject.SetActive(false); } private void GetKey() { ((Component)_waitingForInput).gameObject.SetActive(true); ((MonoBehaviour)this).StartCoroutine(WaitForKey(delegate(string key) { SetKeybind(key); })); } private IEnumerator WaitForKey(Action<string> callback) { while (!((ButtonControl)Keyboard.current.anyKey).wasPressedThisFrame || (!((InputDevice)Gamepad.current).wasUpdatedThisFrame && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.leftStick, 0f) && !InputControlExtensions.IsActuated((InputControl)(object)Gamepad.current.rightStick, 0f))) { yield return (object)new WaitForEndOfFrame(); Observable.CallOnce<InputControl>(InputSystem.onAnyButtonPress, (Action<InputControl>)delegate(InputControl ctrl) { callback(((ctrl.device == Gamepad.current && IsControllerButton) || (ctrl.device == Keyboard.current && !IsControllerButton)) ? ctrl.name : _defaultKey); }); } } } public class DeleteButton : MonoBehaviour { private void Start() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown RebindButton _rebindButton = ((Component)((Component)((Component)this).transform.parent).transform.Find("Button")).GetComponent<RebindButton>(); ((UnityEvent)((Component)this).GetComponent<Button>().onClick).AddListener((UnityAction)delegate { _rebindButton.SetKeybind(string.Empty); }); } } public class ToggleButton : MonoBehaviour { private Toggle _toggle; public static bool s_InventoryCheck; public string PlayerPrefsString; private void Start() { _toggle = ((Component)this).GetComponent<Toggle>(); _toggle.isOn = s_InventoryCheck; ((UnityEvent<bool>)(object)_toggle.onValueChanged).AddListener((UnityAction<bool>)SetNewValue); if (!PlayerPrefs.HasKey(PlayerPrefsString)) { SetNewValue(s_InventoryCheck); } } public void SetNewValue(bool arg) { PlayerPrefs.SetInt(PlayerPrefsString, arg ? 1 : 0); } } public class EnableDisableButton : MonoBehaviour { public GameObject[] ToAlternateUI = (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((UnityAction)delegate { GameObject[] toAlternateUI = ToAlternateUI; foreach (GameObject val in toAlternateUI) { val.SetActive((!val.activeInHierarchy) ? true : false); } }); if (((Object)((Component)this).gameObject).name.Equals("BackButton", StringComparison.OrdinalIgnoreCase)) { ToAlternateUI[0] = ((Component)((Component)this).transform.parent).gameObject; } if (((Object)((Component)this).gameObject).name.Equals("MoreEmotesButton(Clone)", StringComparison.OrdinalIgnoreCase)) { ToAlternateUI[0] = ((Component)((Component)((Component)this).transform.parent).gameObject.transform.Find("MoreEmotesPanel(Clone)")).gameObject; } } } public class SetupUI : MonoBehaviour { public static bool UseConfigFile; public static bool InventoryCheck; private void Awake() { Transform settingsUIPanel = ((Component)this).transform.Find("MoreEmotesPanel(Clone)"); ((Component)settingsUIPanel.Find("Version")).GetComponent<Text>().text = "1.3.2 - Sligili"; SetupOpenSettingsButton(); SetupBackButton(); SetupRebindButtons(((Component)settingsUIPanel).transform.Find("KeybindButtons")); SetupRebindButtons(((Component)((Component)((Component)settingsUIPanel).transform.Find("Scroll View")).transform.Find("Viewport")).transform.Find("Content")); SetupInventoryCheckToggle(); SetupUseConfigFileToggle(); void SetupBackButton() { ((Component)((Component)settingsUIPanel).transform.Find("BackButton")).gameObject.AddComponent<EnableDisableButton>(); } void SetupInventoryCheckToggle() { ((Component)((Component)settingsUIPanel).transform.Find("Inv")).gameObject.AddComponent<ToggleButton>().PlayerPrefsString = "InvCheck"; } void SetupOpenSettingsButton() { ((Component)((Component)this).transform.Find("MoreEmotesButton(Clone)")).gameObject.AddComponent<EnableDisableButton>(); } static void SetupRebindButtons(Transform ButtonsParent) { Transform[] array = (Transform[])(object)new Transform[ButtonsParent.childCount]; for (int i = 0; i < array.Length; i++) { array[i] = ButtonsParent.GetChild(i); } Transform[] array2 = array; foreach (Transform val in array2) { ((Component)val.Find("Button")).gameObject.AddComponent<RebindButton>(); } } void SetupUseConfigFileToggle() { ((Component)((Component)settingsUIPanel).transform.Find("cfg")).gameObject.GetComponent<Toggle>().isOn = UseConfigFile; } } private void Update() { EmotePatch.UpdateWheelKeybinds(); } } public class SignUI : MonoBehaviour { public PlayerControllerB Player; private TMP_InputField _inputField; private Text _charactersLeftText; private TMP_Text _previewText; private Button _submitButton; private Button _cancelButton; public bool IsSignUIOpen; private void Awake() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown FindComponents(); ((UnityEvent)_submitButton.onClick).AddListener(new UnityAction(SubmitText)); ((UnityEvent)_cancelButton.onClick).AddListener((UnityAction)delegate { Close(cancelAction: true); }); ((UnityEvent<string>)(object)_inputField.onValueChanged).AddListener((UnityAction<string>)delegate(string fieldText) { UpdatePreviewText(fieldText); UpdateCharactersLeftText(); }); } private void OnEnable() { Player.isTypingChat = true; IsSignUIOpen = true; ((Selectable)_inputField).Select(); _inputField.text = string.Empty; _previewText.text = "PREVIEW"; Player.disableLookInput = true; } private void Update() { //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) Cursor.visible = true; Cursor.lockState = (CursorLockMode)2; if (!Player.performingEmote) { Close(cancelAction: true); } if (((ButtonControl)Keyboard.current[(Key)2]).wasPressedThisFrame && !((ButtonControl)Keyboard.current[(Key)51]).isPressed) { SubmitText(); } if (Player.quickMenuManager.isMenuOpen || EmotePatch.IsEmoteWheelOpen || InputControlExtensions.IsPressed(((InputControl)Mouse.current)["rightButton"], 0f)) { Close(cancelAction: true); } if (Gamepad.all.Count != 0) { if (Gamepad.current.buttonWest.isPressed || Gamepad.current.startButton.isPressed) { SubmitText(); } if (Gamepad.current.buttonEast.isPressed || Gamepad.current.selectButton.isPressed) { Close(cancelAction: true); } } } private void FindComponents() { _inputField = ((Component)((Component)this).transform.Find("InputField")).GetComponent<TMP_InputField>(); _charactersLeftText = ((Component)((Component)this).transform.Find("CharsLeft")).GetComponent<Text>(); _submitButton = ((Component)((Component)this).transform.Find("Submit")).GetComponent<Button>(); _cancelButton = ((Component)((Component)this).transform.Find("Cancel")).GetComponent<Button>(); _previewText = ((Component)((Component)((Component)this).transform.Find("Sign")).transform.Find("Text")).GetComponent<TMP_Text>(); } private void UpdateCharactersLeftText() { _charactersLeftText.text = $"CHARACTERS LEFT: <color=yellow>{_inputField.characterLimit - _inputField.text.Length}</color>"; } private void UpdatePreviewText(string text) { _previewText.text = text; } private void SubmitText() { //IL_007c: 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 (_inputField.text.Equals(string.Empty)) { Close(cancelAction: true); return; } D.L("Submitted " + _inputField.text + " to server"); ((Component)Player).GetComponent<SignEmoteText>().UpdateSignText(_inputField.text); float num = 0.5f; if (Player.timeSinceStartingEmote > num) { Player.PerformEmote(default(CallbackContext), 1010); } Close(cancelAction: false); } private void Close(bool cancelAction) { Player.isTypingChat = false; IsSignUIOpen = false; if (cancelAction) { Player.performingEmote = false; Player.StopPerformingEmoteServerRpc(); } if (!Player.quickMenuManager.isMenuOpen) { Cursor.visible = false; Cursor.lockState = (CursorLockMode)1; } Player.disableLookInput = false; ((Component)this).gameObject.SetActive(false); } } public class SyncAnimatorToOthers : NetworkBehaviour { private PlayerControllerB _player; private void Start() { _player = ((Component)this).GetComponent<PlayerControllerB>(); } public void UpdateEmoteIDForOthers(int newID) { if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled) { UpdateCurrentEmoteIDServerRpc(newID); } } [ServerRpc(RequireOwnership = false)] private void UpdateCurrentEmoteIDServerRpc(int newID) { UpdateCurrentEmoteIDClientRpc(newID); } [ClientRpc] private void UpdateCurrentEmoteIDClientRpc(int newID) { if (!((NetworkBehaviour)_player).IsOwner) { _player.playerBodyAnimator.SetInteger("emoteNumber", newID); } } } public class CustomAnimationObjects : MonoBehaviour { private PlayerControllerB _player; private MeshRenderer _sign; private GameObject _signText; private SkinnedMeshRenderer _legs; private void Start() { _player = ((Component)this).GetComponent<PlayerControllerB>(); } private void Update() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_sign == (Object)null || (Object)(object)_signText == (Object)null) { FindSign(); return; } ((Component)_sign).transform.localPosition = ((Component)_sign).transform.parent.Find("spine").localPosition; if ((Object)(object)_legs == (Object)null && ((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled) { FindLegs(); return; } DisableEverything(); if (!_player.performingEmote) { return; } switch (_player.playerBodyAnimator.GetInteger("emoteNumber")) { case 10: case 1010: ((Renderer)_sign).enabled = true; if (!_signText.activeSelf) { _signText.SetActive(true); } if (((NetworkBehaviour)_player).IsOwner) { EmotePatch.LocalArmsSeparatedFromCamera = true; } break; case 9: if ((Object)(object)_legs != (Object)null) { ((Renderer)_legs).enabled = true; } if (((NetworkBehaviour)_player).IsOwner) { EmotePatch.LocalArmsSeparatedFromCamera = true; } break; } } private void DisableEverything() { if ((Object)(object)_legs != (Object)null) { ((Renderer)_legs).enabled = false; } ((Renderer)_sign).enabled = false; if (_signText.activeSelf) { _signText.SetActive(false); } if (((NetworkBehaviour)_player).IsOwner && _player.isPlayerControlled) { EmotePatch.LocalArmsSeparatedFromCamera = false; } } private void FindSign() { _sign = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("metarig").Find("Sign")).GetComponent<MeshRenderer>(); _signText = ((Component)((Component)_sign).transform.Find("Text")).gameObject; } private void FindLegs() { _legs = ((Component)((Component)_player).transform.Find("ScavengerModel").Find("LEGS")).GetComponent<SkinnedMeshRenderer>(); } } }
plugins/Steven-Custom_Boombox_Music/CustomBoomboxTracks.dll
Decompiled 2 years 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}"); } } }
plugins/x753-Mimics/Mimics.dll
Decompiled 2 years agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using DunGen; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyMimics.Properties; using Unity.Netcode; using UnityEngine; using UnityEngine.Events; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")] [assembly: AssemblyCompany("Mimics")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("A mod that adds mimics to Lethal Company")] [assembly: AssemblyFileVersion("2.3.2.0")] [assembly: AssemblyInformationalVersion("2.3.2")] [assembly: AssemblyProduct("Mimics")] [assembly: AssemblyTitle("Mimics")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.3.2.0")] [module: UnverifiableCode] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedByMemcpy<bool>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<bool>(); } } namespace LethalCompanyMimics.Properties { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "16.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("LethalCompanyMimics.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[] mimicdoor { get { object @object = ResourceManager.GetObject("mimicdoor", resourceCulture); return (byte[])@object; } } internal Resources() { } } } namespace Mimics { [BepInPlugin("x753.Mimics", "Mimics", "2.3.2")] public class Mimics : BaseUnityPlugin { [HarmonyPatch(typeof(GameNetworkManager))] internal class GameNetworkManagerPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch() { ((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().AddNetworkPrefab(MimicNetworkerPrefab); } } [HarmonyPatch(typeof(StartOfRound))] internal class StartOfRoundPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref StartOfRound __instance) { if (((NetworkBehaviour)__instance).IsServer && (Object)(object)MimicNetworker.Instance == (Object)null) { GameObject val = Object.Instantiate<GameObject>(MimicNetworkerPrefab); val.GetComponent<NetworkObject>().Spawn(true); MimicNetworker.SpawnWeight0.Value = SpawnRates[0]; MimicNetworker.SpawnWeight1.Value = SpawnRates[1]; MimicNetworker.SpawnWeight2.Value = SpawnRates[2]; MimicNetworker.SpawnWeight3.Value = SpawnRates[3]; MimicNetworker.SpawnWeight4.Value = SpawnRates[4]; MimicNetworker.SpawnWeightMax.Value = SpawnRates[5]; MimicNetworker.SpawnRateDynamic.Value = DynamicSpawnRate; } } } [HarmonyPatch(typeof(Terminal))] internal class TerminalPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPatch(ref StartOfRound __instance) { //IL_0099: 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) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: 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_00e1: Expected O, but got Unknown Terminal val = Object.FindObjectOfType<Terminal>(); if (!Object.op_Implicit((Object)(object)val.enemyFiles.Find((TerminalNode node) => node.creatureName == "Mimics"))) { MimicCreatureID = val.enemyFiles.Count; MimicFile.creatureFileID = MimicCreatureID; val.enemyFiles.Add(MimicFile); TerminalKeyword val2 = val.terminalNodes.allKeywords.First((TerminalKeyword keyword) => keyword.word == "info"); TerminalKeyword val3 = new TerminalKeyword { word = "mimics", isVerb = false, defaultVerb = val2 }; List<CompatibleNoun> list = val2.compatibleNouns.ToList(); list.Add(new CompatibleNoun { noun = val3, result = MimicFile }); val2.compatibleNouns = list.ToArray(); List<TerminalKeyword> list2 = val.terminalNodes.allKeywords.ToList(); list2.Add(val3); val.terminalNodes.allKeywords = list2.ToArray(); } } } [HarmonyPatch(typeof(RoundManager))] internal class RoundManagerPatch { [HarmonyPatch("SetExitIDs")] [HarmonyPostfix] private static void SetExitIDsPatch(ref RoundManager __instance, Vector3 mainEntrancePosition) { //IL_0536: Unknown result type (might be due to invalid IL or missing references) //IL_0547: Unknown result type (might be due to invalid IL or missing references) //IL_054c: Unknown result type (might be due to invalid IL or missing references) //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_0235: Unknown result type (might be due to invalid IL or missing references) //IL_0241: 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_025a: 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_0272: 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_0296: 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_02ae: 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_0565: Unknown result type (might be due to invalid IL or missing references) //IL_056a: Unknown result type (might be due to invalid IL or missing references) //IL_056c: Unknown result type (might be due to invalid IL or missing references) //IL_056e: Unknown result type (might be due to invalid IL or missing references) //IL_05a3: Unknown result type (might be due to invalid IL or missing references) //IL_05e4: Unknown result type (might be due to invalid IL or missing references) //IL_06c0: Unknown result type (might be due to invalid IL or missing references) //IL_06c5: Unknown result type (might be due to invalid IL or missing references) //IL_06c9: Unknown result type (might be due to invalid IL or missing references) //IL_06d5: Unknown result type (might be due to invalid IL or missing references) //IL_06da: Unknown result type (might be due to invalid IL or missing references) //IL_06de: Unknown result type (might be due to invalid IL or missing references) //IL_06e3: Unknown result type (might be due to invalid IL or missing references) //IL_033d: 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_0353: Unknown result type (might be due to invalid IL or missing references) //IL_0358: Unknown result type (might be due to invalid IL or missing references) //IL_035d: Unknown result type (might be due to invalid IL or missing references) //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_036c: Unknown result type (might be due to invalid IL or missing references) //IL_0371: 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_037f: Unknown result type (might be due to invalid IL or missing references) //IL_0388: Unknown result type (might be due to invalid IL or missing references) //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_067b: Unknown result type (might be due to invalid IL or missing references) //IL_0414: Unknown result type (might be due to invalid IL or missing references) //IL_041c: 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_042f: Unknown result type (might be due to invalid IL or missing references) //IL_07d3: Unknown result type (might be due to invalid IL or missing references) //IL_07dd: Expected O, but got Unknown //IL_08ac: Unknown result type (might be due to invalid IL or missing references) //IL_08d3: Unknown result type (might be due to invalid IL or missing references) //IL_084d: Unknown result type (might be due to invalid IL or missing references) //IL_0874: Unknown result type (might be due to invalid IL or missing references) //IL_0987: Unknown result type (might be due to invalid IL or missing references) //IL_09ae: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)MimicNetworker.Instance == (Object)null) { return; } MimicDoor.allMimics = new List<MimicDoor>(); int num = 0; Dungeon currentDungeon = __instance.dungeonGenerator.Generator.CurrentDungeon; if (!((Object)currentDungeon.DungeonFlow).name.StartsWith("Level1") && !((Object)currentDungeon.DungeonFlow).name.StartsWith("Level2")) { return; } int num2 = 0; int[] array = new int[6] { MimicNetworker.SpawnWeight0.Value, MimicNetworker.SpawnWeight1.Value, MimicNetworker.SpawnWeight2.Value, MimicNetworker.SpawnWeight3.Value, MimicNetworker.SpawnWeight4.Value, MimicNetworker.SpawnWeightMax.Value }; int num3 = 0; int[] array2 = array; foreach (int num4 in array2) { num3 += num4; } Random random = new Random(StartOfRound.Instance.randomMapSeed + 753); int num5 = random.Next(0, num3); int num6 = 0; for (int j = 0; j < array.Length; j++) { if (num5 < array[j] + num6) { num2 = j; break; } num6 += array[j]; } if (num2 == 5) { num2 = 999; } EntranceTeleport[] array3 = Object.FindObjectsOfType<EntranceTeleport>(false); int num7 = (array3.Length - 2) / 2; if (MimicNetworker.SpawnRateDynamic.Value && num2 < num7 && num7 > 1) { num2 += random.Next(0, 2); } if (MimicNetworker.SpawnRateDynamic.Value && currentDungeon.AllTiles.Count > 100) { num2 += random.Next(0, 2); } List<Doorway> list = new List<Doorway>(); Bounds val2 = default(Bounds); foreach (Tile allTile in currentDungeon.AllTiles) { foreach (Doorway unusedDoorway in allTile.UnusedDoorways) { if (unusedDoorway.HasDoorPrefabInstance || (Object)(object)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true) == (Object)null) { continue; } GameObject gameObject = ((Component)((Component)((Component)unusedDoorway).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject; if (!((Object)gameObject).name.StartsWith("AlleyExitDoorContainer") || gameObject.activeSelf) { continue; } bool flag = false; Matrix4x4 val = Matrix4x4.TRS(((Component)unusedDoorway).transform.position, ((Component)unusedDoorway).transform.rotation, new Vector3(1f, 1f, 1f)); ((Bounds)(ref val2))..ctor(new Vector3(0f, 1.5f, 5.5f), new Vector3(2f, 6f, 8f)); ((Bounds)(ref val2)).center = ((Matrix4x4)(ref val)).MultiplyPoint3x4(((Bounds)(ref val2)).center); Collider[] array4 = Physics.OverlapBox(((Bounds)(ref val2)).center, ((Bounds)(ref val2)).extents, ((Component)unusedDoorway).transform.rotation, LayerMask.GetMask(new string[3] { "Room", "Railing", "MapHazards" })); Collider[] array5 = array4; int num8 = 0; if (num8 < array5.Length) { Collider val3 = array5[num8]; flag = true; } if (flag) { continue; } foreach (Tile allTile2 in currentDungeon.AllTiles) { if (!((Object)(object)allTile == (Object)(object)allTile2)) { Vector3 origin = ((Component)unusedDoorway).transform.position + 5f * ((Component)unusedDoorway).transform.forward; Bounds val4 = UnityUtil.CalculateProxyBounds(((Component)allTile2).gameObject, true, Vector3.up); Ray val5 = default(Ray); ((Ray)(ref val5)).origin = origin; ((Ray)(ref val5)).direction = Vector3.up; if (((Bounds)(ref val4)).IntersectRay(val5) && (((Object)allTile2).name.Contains("Catwalk") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || (((Object)allTile2).name.Contains("StartRoom") && !((Object)allTile2).name.Contains("Manor")))) { flag = true; } val5 = default(Ray); ((Ray)(ref val5)).origin = origin; ((Ray)(ref val5)).direction = Vector3.down; if (((Bounds)(ref val4)).IntersectRay(val5) && (((Object)allTile2).name.Contains("MediumRoomHallway1B") || ((Object)allTile2).name.Contains("LargeForkTile") || ((Object)allTile2).name.Contains("4x4BigStair") || ((Object)allTile2).name.Contains("ElevatorConnector") || ((Object)allTile2).name.Contains("StartRoom"))) { flag = true; } } } if (!flag) { list.Add(unusedDoorway); } } } Shuffle(list, StartOfRound.Instance.randomMapSeed); List<Vector3> list2 = new List<Vector3>(); foreach (Doorway item in list) { if (num >= num2) { break; } bool flag2 = false; Vector3 val6 = ((Component)item).transform.position + 5f * ((Component)item).transform.forward; foreach (Vector3 item2 in list2) { if (Vector3.Distance(val6, item2) < 4f) { flag2 = true; break; } } if (flag2) { continue; } list2.Add(val6); GameObject gameObject2 = ((Component)((Component)((Component)item).GetComponentInChildren<SpawnSyncedObject>(true)).transform.parent).gameObject; GameObject val7 = Object.Instantiate<GameObject>(MimicPrefab, ((Component)item).transform); val7.transform.position = gameObject2.transform.position; MimicDoor component = val7.GetComponent<MimicDoor>(); component.scanNode.creatureScanID = MimicCreatureID; AudioSource[] componentsInChildren = val7.GetComponentsInChildren<AudioSource>(true); foreach (AudioSource val8 in componentsInChildren) { val8.volume = MimicVolume / 100f; val8.outputAudioMixerGroup = StartOfRound.Instance.ship3DAudio.outputAudioMixerGroup; } if (SpawnRates[5] == 9753 && num == 0) { val7.transform.position = new Vector3(-7f, 0f, -10f); } MimicDoor.allMimics.Add(component); component.mimicIndex = num; num++; GameObject gameObject3 = ((Component)((Component)item).transform.GetChild(0)).gameObject; gameObject3.SetActive(false); Bounds bounds = ((Collider)component.frameBox).bounds; Vector3 center = ((Bounds)(ref bounds)).center; bounds = ((Collider)component.frameBox).bounds; Collider[] array6 = Physics.OverlapBox(center, ((Bounds)(ref bounds)).extents, Quaternion.identity); foreach (Collider val9 in array6) { if (((Object)((Component)val9).gameObject).name.Contains("Shelf")) { ((Component)val9).gameObject.SetActive(false); } } Light componentInChildren = gameObject2.GetComponentInChildren<Light>(true); ((Component)componentInChildren).transform.parent.SetParent(val7.transform); MeshRenderer[] componentsInChildren2 = val7.GetComponentsInChildren<MeshRenderer>(); MeshRenderer[] array7 = componentsInChildren2; foreach (MeshRenderer val10 in array7) { Material[] materials = ((Renderer)val10).materials; foreach (Material val11 in materials) { val11.shader = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.shader; val11.renderQueue = ((Renderer)gameObject3.GetComponentInChildren<MeshRenderer>(true)).material.renderQueue; } } component.interactTrigger.onInteract = new InteractEvent(); ((UnityEvent<PlayerControllerB>)(object)component.interactTrigger.onInteract).AddListener((UnityAction<PlayerControllerB>)component.TouchMimic); if (MimicPerfection) { continue; } component.interactTrigger.timeToHold = 0.9f; if (!ColorBlindMode) { if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0) { ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.490566f, 0.1226415f, 0.1302275f); ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.4339623f, 0.1043965f, 0.1150277f); componentInChildren.colorTemperature = 1250f; } else { ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.5f, 0.1580188f, 0.1657038f); ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(43f / 106f, 0.1358579f, 0.1393619f); componentInChildren.colorTemperature = 1300f; } } else if ((StartOfRound.Instance.randomMapSeed + num) % 2 == 0) { component.interactTrigger.timeToHold = 1.1f; } else { component.interactTrigger.timeToHold = 1f; } if (!EasyMode) { continue; } Random random2 = new Random(StartOfRound.Instance.randomMapSeed + num); switch (random2.Next(0, 4)) { case 0: if (!ColorBlindMode) { ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[0]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f); ((Renderer)val7.GetComponentsInChildren<MeshRenderer>()[1]).material.color = new Color(0.489f, 0.2415526f, 0.1479868f); } else { component.interactTrigger.timeToHold = 1.5f; } break; case 1: component.interactTrigger.hoverTip = "Feed : [LMB]"; component.interactTrigger.holdTip = "Feed : [LMB]"; break; case 2: component.interactTrigger.hoverIcon = component.LostFingersIcon; break; case 3: component.interactTrigger.holdTip = "DIE : [LMB]"; component.interactTrigger.timeToHold = 0.5f; break; default: component.interactTrigger.hoverTip = "BUG, REPORT TO DEVELOPER"; break; } } } } [HarmonyPatch(typeof(SprayPaintItem))] internal class SprayPaintItemPatch { private static FieldInfo SprayHit = typeof(SprayPaintItem).GetField("sprayHit", BindingFlags.Instance | BindingFlags.NonPublic); [HarmonyPatch("SprayPaintClientRpc")] [HarmonyPostfix] private static void SprayPaintClientRpcPatch(SprayPaintItem __instance, Vector3 sprayPos, Vector3 sprayRot) { //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 ((Object)(object)MimicNetworker.Instance == (Object)null) { return; } RaycastHit val = (RaycastHit)SprayHit.GetValue(__instance); if ((Object)(object)((RaycastHit)(ref val)).collider != (Object)null && ((Object)((RaycastHit)(ref val)).collider).name == "MimicSprayCollider") { MimicDoor component = ((Component)((Component)((RaycastHit)(ref val)).collider).transform.parent.parent).GetComponent<MimicDoor>(); component.sprayCount++; if (component.sprayCount > 8) { MimicNetworker.Instance.MimicAddAnger(1, component.mimicIndex); } } } } [HarmonyPatch(typeof(LockPicker))] internal class LockPickerPatch { private static FieldInfo RayHit = typeof(LockPicker).GetField("hit", BindingFlags.Instance | BindingFlags.NonPublic); [HarmonyPatch("ItemActivate")] [HarmonyPostfix] private static void ItemActivatePatch(LockPicker __instance, bool used, bool buttonDown = true) { //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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)MimicNetworker.Instance == (Object)null) { return; } RaycastHit val = (RaycastHit)RayHit.GetValue(__instance); if (!((Object)(object)((GrabbableObject)__instance).playerHeldBy == (Object)null) && !((object)(RaycastHit)(ref val)).Equals((object)default(RaycastHit)) && !((Object)(object)((RaycastHit)(ref val)).transform.parent == (Object)null)) { Transform parent = ((RaycastHit)(ref val)).transform.parent; if (((Object)parent).name.StartsWith("MimicDoor")) { MimicNetworker.Instance.MimicLockPick(__instance, ((Component)parent).GetComponent<MimicDoor>().mimicIndex); } } } } private const string modGUID = "x753.Mimics"; private const string modName = "Mimics"; private const string modVersion = "2.3.2"; private readonly Harmony harmony = new Harmony("x753.Mimics"); private static Mimics Instance; public static GameObject MimicPrefab; public static GameObject MimicNetworkerPrefab; public static TerminalNode MimicFile; public static int MimicCreatureID; public static int[] SpawnRates; public static bool MimicPerfection; public static bool EasyMode; public static bool ColorBlindMode; public static float MimicVolume; public static bool DynamicSpawnRate; private void Awake() { AssetBundle val = AssetBundle.LoadFromMemory(Resources.mimicdoor); MimicPrefab = val.LoadAsset<GameObject>("Assets/MimicDoor.prefab"); MimicNetworkerPrefab = val.LoadAsset<GameObject>("Assets/MimicNetworker.prefab"); MimicFile = val.LoadAsset<TerminalNode>("Assets/MimicFile.asset"); if ((Object)(object)Instance == (Object)null) { Instance = this; } harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin Mimics is loaded!"); SpawnRates = new int[6] { ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Zero Mimics", 23, "Weight of zero mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "One Mimic", 69, "Weight of one mimic spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Two Mimics", 7, "Weight of two mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Three Mimics", 1, "Weight of three mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Four Mimics", 0, "Weight of four mimics spawning").Value, ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Maximum Mimics", 0, "Weight of maximum mimics spawning").Value }; DynamicSpawnRate = ((BaseUnityPlugin)this).Config.Bind<bool>("Spawn Rate", "Dynamic Spawn Rate", true, "Increases mimic spawn rate based on dungeon size and the number of instances of the real thing.").Value; MimicPerfection = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Perfect Mimics", false, "Select this if you want mimics to be the exact same color as the real thing. Overrides all difficulty settings.").Value; EasyMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Easy Mode", false, "Each mimic will have one of several possible imperfections to help you tell if it's a mimic.").Value; ColorBlindMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Difficulty", "Color Blind Mode", false, "Replaces all color differences with another way to differentiate mimics.").Value; MimicVolume = ((BaseUnityPlugin)this).Config.Bind<int>("General", "SFX Volume", 100, "Volume of the mimic's SFX (0-100)").Value; if (MimicVolume < 0f) { MimicVolume = 0f; } if (MimicVolume > 100f) { MimicVolume = 100f; } ((BaseUnityPlugin)this).Config.Bind<int>("Difficulty", "Difficulty Level", 0, "This is an old setting, ignore it."); ((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Difficulty", "Difficulty Level"].Definition); ((BaseUnityPlugin)this).Config.Bind<int>("Spawn Rate", "Five Mimics", 0, "This is an old setting, ignore it."); ((BaseUnityPlugin)this).Config.Remove(((BaseUnityPlugin)this).Config["Spawn Rate", "Five Mimics"].Definition); ((BaseUnityPlugin)this).Config.Save(); 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); } } } } public static void Shuffle<T>(IList<T> list, int seed) { Random random = new Random(seed); int num = list.Count; while (num > 1) { num--; int index = random.Next(num + 1); T value = list[index]; list[index] = list[num]; list[num] = value; } } } public class MimicNetworker : NetworkBehaviour { public static MimicNetworker Instance; public static NetworkVariable<int> SpawnWeight0 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight1 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight2 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight3 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeight4 = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<int> SpawnWeightMax = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); public static NetworkVariable<bool> SpawnRateDynamic = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private void Awake() { Instance = this; } public void MimicAttack(int playerId, int mimicIndex, bool ownerOnly = false) { if (((NetworkBehaviour)this).IsOwner) { Instance.MimicAttackClientRpc(playerId, mimicIndex); } else if (!ownerOnly) { Instance.MimicAttackServerRpc(playerId, mimicIndex); } } [ClientRpc] public void MimicAttackClientRpc(int playerId, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0096: 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(2885019175u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 2885019175u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].Attack(playerId)); } } } [ServerRpc(RequireOwnership = false)] public void MimicAttackServerRpc(int playerId, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0096: 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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1024971481u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1024971481u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Instance.MimicAttackClientRpc(playerId, mimicIndex); } } } public void MimicAddAnger(int amount, int mimicIndex) { if (((NetworkBehaviour)this).IsOwner) { Instance.MimicAddAngerClientRpc(amount, mimicIndex); } else { Instance.MimicAddAngerServerRpc(amount, mimicIndex); } } [ClientRpc] public void MimicAddAngerClientRpc(int amount, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0096: 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(1137632670u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, amount); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 1137632670u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].AddAnger(amount)); } } } [ServerRpc(RequireOwnership = false)] public void MimicAddAngerServerRpc(int amount, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0096: 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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(669208889u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, amount); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 669208889u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Instance.MimicAddAngerClientRpc(amount, mimicIndex); } } } public void MimicLockPick(LockPicker lockPicker, int mimicIndex, bool ownerOnly = false) { int playerId = (int)((GrabbableObject)lockPicker).playerHeldBy.playerClientId; if (((NetworkBehaviour)this).IsOwner) { Instance.MimicLockPickClientRpc(playerId, mimicIndex); } else if (!ownerOnly) { Instance.MimicLockPickServerRpc(playerId, mimicIndex); } } [ClientRpc] public void MimicLockPickClientRpc(int playerId, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0096: 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(3716888238u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendClientRpc(ref val2, 3716888238u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost)) { ((MonoBehaviour)this).StartCoroutine(MimicDoor.allMimics[mimicIndex].MimicLockPick(playerId)); } } } [ServerRpc(RequireOwnership = false)] public void MimicLockPickServerRpc(int playerId, int mimicIndex) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_0096: 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 != 1 && (networkManager.IsClient || networkManager.IsHost)) { ServerRpcParams val = default(ServerRpcParams); FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendServerRpc(1897916243u, val, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val2, playerId); BytePacker.WriteValueBitPacked(val2, mimicIndex); ((NetworkBehaviour)this).__endSendServerRpc(ref val2, 1897916243u, val, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { Instance.MimicLockPickClientRpc(playerId, mimicIndex); } } } protected override void __initializeVariables() { if (SpawnWeight0 == null) { throw new Exception("MimicNetworker.SpawnWeight0 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight0).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight0, "SpawnWeight0"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight0); if (SpawnWeight1 == null) { throw new Exception("MimicNetworker.SpawnWeight1 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight1).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight1, "SpawnWeight1"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight1); if (SpawnWeight2 == null) { throw new Exception("MimicNetworker.SpawnWeight2 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight2).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight2, "SpawnWeight2"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight2); if (SpawnWeight3 == null) { throw new Exception("MimicNetworker.SpawnWeight3 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight3).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight3, "SpawnWeight3"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight3); if (SpawnWeight4 == null) { throw new Exception("MimicNetworker.SpawnWeight4 cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeight4).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeight4, "SpawnWeight4"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeight4); if (SpawnWeightMax == null) { throw new Exception("MimicNetworker.SpawnWeightMax cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnWeightMax).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnWeightMax, "SpawnWeightMax"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnWeightMax); if (SpawnRateDynamic == null) { throw new Exception("MimicNetworker.SpawnRateDynamic cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)SpawnRateDynamic).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)SpawnRateDynamic, "SpawnRateDynamic"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)SpawnRateDynamic); ((NetworkBehaviour)this).__initializeVariables(); } [RuntimeInitializeOnLoadMethod] internal static void InitializeRPCS_MimicNetworker() { //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 //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown NetworkManager.__rpc_func_table.Add(2885019175u, new RpcReceiveHandler(__rpc_handler_2885019175)); NetworkManager.__rpc_func_table.Add(1024971481u, new RpcReceiveHandler(__rpc_handler_1024971481)); NetworkManager.__rpc_func_table.Add(1137632670u, new RpcReceiveHandler(__rpc_handler_1137632670)); NetworkManager.__rpc_func_table.Add(669208889u, new RpcReceiveHandler(__rpc_handler_669208889)); NetworkManager.__rpc_func_table.Add(3716888238u, new RpcReceiveHandler(__rpc_handler_3716888238)); NetworkManager.__rpc_func_table.Add(1897916243u, new RpcReceiveHandler(__rpc_handler_1897916243)); } private static void __rpc_handler_2885019175(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_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)2; ((MimicNetworker)(object)target).MimicAttackClientRpc(playerId, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1024971481(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_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)1; ((MimicNetworker)(object)target).MimicAttackServerRpc(playerId, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1137632670(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_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int amount = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref amount); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)2; ((MimicNetworker)(object)target).MimicAddAngerClientRpc(amount, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_669208889(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_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int amount = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref amount); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)1; ((MimicNetworker)(object)target).MimicAddAngerServerRpc(amount, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_3716888238(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_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)2; ((MimicNetworker)(object)target).MimicLockPickClientRpc(playerId, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_1897916243(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_0043: 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) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { int playerId = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref playerId); int mimicIndex = default(int); ByteUnpacker.ReadValueBitPacked(reader, ref mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)1; ((MimicNetworker)(object)target).MimicLockPickServerRpc(playerId, mimicIndex); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "MimicNetworker"; } } public class MimicDoor : MonoBehaviour { public GameObject playerTarget; public BoxCollider frameBox; public Sprite LostFingersIcon; public Animator mimicAnimator; public GameObject grabPoint; public InteractTrigger interactTrigger; public ScanNodeProperties scanNode; public int anger; public bool angering; public int sprayCount; private bool attacking; public static List<MimicDoor> allMimics; public int mimicIndex; private static MethodInfo RetractClaws = typeof(LockPicker).GetMethod("RetractClaws", BindingFlags.Instance | BindingFlags.NonPublic); public void TouchMimic(PlayerControllerB player) { if (!attacking) { MimicNetworker.Instance.MimicAttack((int)player.playerClientId, mimicIndex); } } public IEnumerator Attack(int playerId) { attacking = true; interactTrigger.interactable = false; PlayerControllerB player = StartOfRound.Instance.allPlayerScripts[playerId]; mimicAnimator.SetTrigger("Attack"); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); playerTarget.transform.position = ((Component)player).transform.position; yield return (object)new WaitForSeconds(0.1f); float num = Vector3.Distance(((Component)GameNetworkManager.Instance.localPlayerController).transform.position, ((Component)frameBox).transform.position); if (num < 8f) { HUDManager.Instance.ShakeCamera((ScreenShakeType)1); } else if (num < 14f) { HUDManager.Instance.ShakeCamera((ScreenShakeType)0); } yield return (object)new WaitForSeconds(0.2f); if (((NetworkBehaviour)player).IsOwner && Vector3.Distance(((Component)player).transform.position, ((Component)this).transform.position) < 8.75f) { player.KillPlayer(Vector3.zero, true, (CauseOfDeath)0, 0); } float startTime = Time.timeSinceLevelLoad; yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)player.deadBody != (Object)null || Time.timeSinceLevelLoad - startTime > 4f)); if ((Object)(object)player.deadBody != (Object)null) { player.deadBody.attachedTo = grabPoint.transform; player.deadBody.attachedLimb = player.deadBody.bodyParts[5]; player.deadBody.matchPositionExactly = true; for (int i = 0; i < player.deadBody.bodyParts.Length; i++) { ((Component)player.deadBody.bodyParts[i]).GetComponent<Collider>().excludeLayers = LayerMask.op_Implicit(-1); } } yield return (object)new WaitForSeconds(2f); if ((Object)(object)player.deadBody != (Object)null) { player.deadBody.attachedTo = null; player.deadBody.attachedLimb = null; player.deadBody.matchPositionExactly = false; ((Component)((Component)player.deadBody).transform.GetChild(0)).gameObject.SetActive(false); player.deadBody = null; } yield return (object)new WaitForSeconds(4.5f); attacking = false; interactTrigger.interactable = true; } public IEnumerator MimicLockPick(int playerId) { if (angering || attacking) { yield break; } LockPicker lockPicker = default(LockPicker); ref LockPicker reference = ref lockPicker; GrabbableObject currentlyHeldObjectServer = StartOfRound.Instance.allPlayerScripts[playerId].currentlyHeldObjectServer; reference = (LockPicker)(object)((currentlyHeldObjectServer is LockPicker) ? currentlyHeldObjectServer : null); if ((Object)(object)lockPicker == (Object)null) { yield break; } attacking = true; interactTrigger.interactable = false; AudioSource component = ((Component)lockPicker).GetComponent<AudioSource>(); component.PlayOneShot(lockPicker.placeLockPickerClips[Random.Range(0, lockPicker.placeLockPickerClips.Length)]); lockPicker.armsAnimator.SetBool("mounted", true); lockPicker.armsAnimator.SetBool("picking", true); component.Play(); component.pitch = Random.Range(0.94f, 1.06f); lockPicker.isOnDoor = true; lockPicker.isPickingLock = true; ((GrabbableObject)lockPicker).grabbable = false; if (((NetworkBehaviour)lockPicker).IsOwner) { ((GrabbableObject)lockPicker).playerHeldBy.DiscardHeldObject(true, ((NetworkBehaviour)MimicNetworker.Instance).NetworkObject, ((Component)this).transform.position + ((Component)this).transform.up * 1.5f - ((Component)this).transform.forward * 1.15f, true); } float startTime = Time.timeSinceLevelLoad; yield return (object)new WaitUntil((Func<bool>)(() => !((GrabbableObject)lockPicker).isHeld || Time.timeSinceLevelLoad - startTime > 10f)); ((Component)lockPicker).transform.localEulerAngles = new Vector3(((Component)this).transform.eulerAngles.x, ((Component)this).transform.eulerAngles.y + 90f, ((Component)this).transform.eulerAngles.z); yield return (object)new WaitForSeconds(5f); RetractClaws.Invoke(lockPicker, null); ((Component)lockPicker).transform.SetParent((Transform)null); ((GrabbableObject)lockPicker).startFallingPosition = ((Component)lockPicker).transform.position; ((GrabbableObject)lockPicker).FallToGround(false); ((GrabbableObject)lockPicker).grabbable = true; yield return (object)new WaitForSeconds(1f); anger = 3; attacking = false; interactTrigger.interactable = false; PlayerControllerB val = null; float num = 9999f; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val2).transform.position); if (num2 < num) { num = num2; val = val2; } } if ((Object)(object)val != (Object)null) { MimicNetworker.Instance.MimicAttackClientRpc((int)val.playerClientId, mimicIndex); } else { interactTrigger.interactable = true; } } public IEnumerator AddAnger(int amount) { if (angering || attacking) { yield break; } angering = true; anger += amount; if (anger == 1) { Sprite oldIcon2 = interactTrigger.hoverIcon; interactTrigger.hoverIcon = LostFingersIcon; mimicAnimator.SetTrigger("Growl"); yield return (object)new WaitForSeconds(2.75f); interactTrigger.hoverIcon = oldIcon2; sprayCount = 0; angering = false; yield break; } if (anger == 2) { interactTrigger.holdTip = "DIE : [LMB]"; interactTrigger.timeToHold = 0.25f; Sprite oldIcon2 = interactTrigger.hoverIcon; interactTrigger.hoverIcon = LostFingersIcon; mimicAnimator.SetTrigger("Growl"); yield return (object)new WaitForSeconds(2.75f); interactTrigger.hoverIcon = oldIcon2; sprayCount = 0; angering = false; yield break; } if (anger > 2) { PlayerControllerB val = null; float num = 9999f; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val2).transform.position); if (num2 < num) { num = num2; val = val2; } } if ((Object)(object)val != (Object)null) { MimicNetworker.Instance.MimicAttackClientRpc((int)val.playerClientId, mimicIndex); } } sprayCount = 0; angering = false; } } public class MimicCollider : MonoBehaviour, IHittable { public MimicDoor mimic; bool IHittable.Hit(int force, Vector3 hitDirection, PlayerControllerB playerWhoHit = null, bool playHitSFX = false) { MimicNetworker.Instance.MimicAddAnger(force, mimic.mimicIndex); return true; } } public class MimicListener : MonoBehaviour, INoiseListener { public MimicDoor mimic; private int tolerance = 100; void INoiseListener.DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot, int noiseID) { //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) if ((noiseLoudness >= 0.9f || noiseID == 101158) && Vector3.Distance(noisePosition, ((Component)mimic).transform.position) < 5f) { switch (noiseID) { case 75: tolerance--; break; case 5: tolerance -= 15; break; case 101158: tolerance -= 35; break; default: tolerance -= 30; break; } if (tolerance <= 0) { tolerance = 100; MimicNetworker.Instance.MimicAddAnger(1, mimic.mimicIndex); } } } } }