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 CustomSounds v81 Fork v81.1.0
BepInEx/plugins/CustomSounds_v81_Fork/CustomSounds.dll
Decompiled 42 minutes agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Logging; using CustomSounds.NetcodePatcher; using CustomSounds.Networking; using CustomSounds.Patches; using HarmonyLib; using LCSoundTool; using Microsoft.CodeAnalysis; using TMPro; using Unity.Netcode; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [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("81.1.0")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyVersion("81.1.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace CustomSounds { [BepInPlugin("CustomSounds", "Custom Sounds v81 Fork", "81.1.0")] public class Plugin : BaseUnityPlugin { public struct SoundData { public string SoundName; public float? RandomPercentage; public string CustomName; public string FilePath; public string FileExtension; public string PackName; public string AudioSource; public string DirectoryPath; public string RelativeDirectoryPath; } public class FolderTree { public Dictionary<string, FolderTree> SubFolders { get; set; } = new Dictionary<string, FolderTree>(); public List<SoundData> Files { get; set; } = new List<SoundData>(); } public static class SoundDataProcessor { public static FolderTree BuildFolderTree(List<SoundData> soundDataList) { FolderTree folderTree = new FolderTree(); foreach (SoundData soundData in soundDataList) { FolderTree folderTree2 = folderTree; string[] array = (soundData.RelativeDirectoryPath ?? "").Split(new char[1] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); foreach (string key in array) { if (!folderTree2.SubFolders.TryGetValue(key, out var value)) { value = new FolderTree(); folderTree2.SubFolders[key] = value; } folderTree2 = value; } folderTree2.Files.Add(soundData); } return folderTree; } public static string DisplayTree(bool isListing, FolderTree tree, int indent = 0, bool isRoot = true, int soundCount = 0) { StringBuilder stringBuilder = new StringBuilder(); if (isRoot) { soundCount = CountSounds(tree); string text = (isListing ? "Listing all currently loaded custom sounds:" : "Customsounds reloaded."); stringBuilder.AppendLine(text + $" ({soundCount} sounds)"); } foreach (KeyValuePair<string, FolderTree> subFolder in tree.SubFolders) { if (isRoot) { stringBuilder.Append('\n'); } string text2 = (subFolder.Key.EndsWith("-AS", StringComparison.Ordinal) ? (subFolder.Key.Substring(0, subFolder.Key.Length - 3) + " (AudioSource)") : subFolder.Key); stringBuilder.AppendLine(new string(' ', indent * 2) + ((indent > 0) ? "∟ " : "") + text2 + " :"); stringBuilder.Append(DisplayTree(isListing, subFolder.Value, indent + 1, isRoot: false)); } foreach (SoundData file in tree.Files) { string text3 = (file.RandomPercentage.HasValue ? $" (Random: {file.RandomPercentage * 100f}%)" : ""); string text4 = (string.IsNullOrEmpty(file.CustomName) ? "" : (" [" + file.CustomName + "]")); stringBuilder.AppendLine(new string(' ', indent * 2) + "- " + file.SoundName + text3 + text4 + " [" + file.FileExtension.ToUpperInvariant() + "]"); } return stringBuilder.ToString(); } private static int CountSounds(FolderTree tree) { int num = tree.Files.Count; foreach (FolderTree value in tree.SubFolders.Values) { num += CountSounds(value); } return num; } } private const string PLUGIN_GUID = "CustomSounds"; private const string PLUGIN_NAME = "Custom Sounds v81 Fork"; private const string PLUGIN_VERSION = "81.1.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 bool hasAcceptedSync = false; public static List<SoundData> soundDataList = new List<SoundData>(); private static readonly string[] SoundPatterns = new string[3] { "*.wav", "*.ogg", "*.mp3" }; public static bool Initialized { get; private set; } private void Awake() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown if ((Object)(object)Instance != (Object)null) { return; } Instance = this; logger = Logger.CreateLogSource("CustomSounds"); harmony = new Harmony("CustomSounds"); harmony.PatchAll(typeof(TerminalParsePlayerSentencePatch)); modifiedSounds = new HashSet<string>(); string customSoundsFolderPath = GetCustomSoundsFolderPath(); if (!Directory.Exists(customSoundsFolderPath)) { logger.LogInfo((object)"\"CustomSounds\" folder not found. Creating it now."); Directory.CreateDirectory(Path.Combine(customSoundsFolderPath, "YourOwnSoundPack")); File.WriteAllText(Path.Combine(customSoundsFolderPath, "READ-ME-PLEASE.txt"), "If you're interested in creating your own sound pack, please refer to the 'For Sound Packs Creator' section on the CustomSounds Thunderstore page. If you simply wish to replace a few sounds on your own, you can drop the desired sounds into the 'YourOwnSoundPack' folder."); } string bepInExConfigPath = Paths.BepInExConfigPath; try { List<string> list = File.ReadAllLines(bepInExConfigPath).ToList(); int num = list.FindIndex((string line) => line.StartsWith("HideManagerGameObject", StringComparison.Ordinal)); if (num != -1 && list[num].Contains("false")) { logger.LogInfo((object)"\"HideManagerGameObject\" value not correctly set. Fixing it now."); list[num] = "HideManagerGameObject = true"; File.WriteAllLines(bepInExConfigPath, list); harmony.PatchAll(typeof(MenuPatcher)); } else if (num != -1) { logger.LogDebug((object)"\"HideManagerGameObject\" is correctly set to true."); } } catch (Exception ex) { logger.LogError((object)("Error modifying config file: " + ex.Message)); } Type[] types = Assembly.GetExecutingAssembly().GetTypes(); for (int num2 = 0; num2 < types.Length; num2++) { MethodInfo[] methods = types[num2].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); } } } logger.LogInfo((object)"Plugin CustomSounds is loaded!"); } internal void Start() { Initialize(); } internal void OnDestroy() { Initialize(); } internal void Initialize() { if (!Initialized) { Initialized = true; ReloadSounds(); } } public GameObject LoadNetworkPrefabFromEmbeddedResource() { using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CustomSounds.Bundle.audionetworkhandler"); if (stream == null) { logger.LogError((object)"Asset bundle not found in embedded resources."); return null; } byte[] array = new byte[stream.Length]; int num; for (int i = 0; i < array.Length; i += num) { num = stream.Read(array, i, array.Length - i); if (num <= 0) { break; } } AssetBundle val = AssetBundle.LoadFromMemory(array); if ((Object)(object)val == (Object)null) { logger.LogError((object)"Failed to load AssetBundle from memory."); return null; } return val.LoadAsset<GameObject>("audionetworkhandler"); } public string GetCustomSoundsFolderPath() { return Path.Combine(Paths.PluginPath, "CustomSounds"); } public void RevertSounds() { if (currentSounds == null || currentSounds.Count == 0) { logger.LogInfo((object)"No sounds to revert."); return; } HashSet<string> hashSet = new HashSet<string>(); foreach (string currentSound in currentSounds) { int num = currentSound.IndexOf('-'); string text = ((num >= 0) ? currentSound.Substring(0, num) : currentSound); if (hashSet.Add(text)) { logger.LogInfo((object)(text + " restored.")); SoundTool.RestoreAudioClip(text); } } logger.LogInfo((object)"Original game sounds restored."); } public void ReloadSounds() { oldSounds = new HashSet<string>(currentSounds); currentSounds.Clear(); modifiedSounds.Clear(); soundDataList.Clear(); ProcessDirectory(Path.GetDirectoryName(Paths.PluginPath)); } private string GetRelativePathToCustomSounds(string filePath) { string[] array = filePath.Split(Path.DirectorySeparatorChar); int num = Array.IndexOf(array, "CustomSounds"); if (num == -1 || num == array.Length - 1) { return ""; } return Path.Combine(array.Skip(num + 1).ToArray()); } private void ProcessDirectory(string directoryPath) { string[] directories; try { directories = Directory.GetDirectories(directoryPath, "*", SearchOption.AllDirectories); } catch (Exception ex) { logger.LogError((object)("Couldn't list folders under " + directoryPath + ": " + ex.Message)); return; } string[] array = directories; foreach (string text in array) { ProcessSoundFiles(text, Path.GetFileName(text)); } } private void ProcessSoundFiles(string directoryPath, string packName) { string[] soundPatterns = SoundPatterns; foreach (string searchPattern in soundPatterns) { string[] files = Directory.GetFiles(directoryPath, searchPattern); foreach (string text in files) { if (text.Contains("CustomSounds")) { ProcessSingleFile(text, packName); } } } } private void ProcessSingleFile(string file, string packName) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); (string soundName, float? percentage, string customName) tuple = ParseSoundFileName(fileNameWithoutExtension); string item = tuple.soundName; float? item2 = tuple.percentage; string item3 = tuple.customName; string fileName = Path.GetFileName(Path.GetDirectoryName(file)); string text = (fileName.EndsWith("-AS", StringComparison.Ordinal) ? fileName.Substring(0, fileName.Length - 3) : null); SoundData item4 = new SoundData { SoundName = item, RandomPercentage = item2, CustomName = item3, FilePath = file, FileExtension = Path.GetExtension(file).TrimStart('.').ToLowerInvariant(), PackName = packName, AudioSource = text, DirectoryPath = Path.GetDirectoryName(file), RelativeDirectoryPath = Path.GetDirectoryName(GetRelativePathToCustomSounds(file)) }; AudioClip audioClip = SoundTool.GetAudioClip(Path.GetDirectoryName(file), file); if ((Object)(object)audioClip == (Object)null) { logger.LogWarning((object)("Couldn't load " + file + "; skipped.")); return; } ((Object)audioClip).name = fileNameWithoutExtension; soundDataList.Add(item4); currentSounds.Add(item4.SoundName); StringBuilder stringBuilder = new StringBuilder("Sound replaced: ").Append(item); if (item2.HasValue) { stringBuilder.Append($" (Percentage = {item2.Value * 100f}%)"); } if (!string.IsNullOrEmpty(item3)) { stringBuilder.Append(" (Custom Name = ").Append(item3).Append(')'); } stringBuilder.Append(" (File Extension = ").Append(item4.FileExtension).Append(')'); logger.LogInfo((object)stringBuilder.ToString()); if (item2.HasValue) { if (text != null) { SoundTool.ReplaceAudioClip(item, audioClip, item2.Value, text); } else { SoundTool.ReplaceAudioClip(item, audioClip, item2.Value); } } else if (text != null) { SoundTool.ReplaceAudioClip(item, audioClip, text); } else { SoundTool.ReplaceAudioClip(item, audioClip); } } private (string soundName, float? percentage, string customName) ParseSoundFileName(string fullSoundName) { string[] array = Path.GetFileNameWithoutExtension(fullSoundName).Split('-'); if (int.TryParse(array[^1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return (soundName: array[0], percentage: (float)result / 100f, customName: string.Join(" ", array.Skip(1).Take(array.Length - 2))); } return (soundName: array[0], percentage: null, customName: string.Join(" ", array.Skip(1))); } } } namespace CustomSounds.Patches { [HarmonyPatch(typeof(MenuManager))] internal class MenuPatcher { [HarmonyPatch("Start")] [HarmonyPostfix] public static void StartPostFix(MenuManager __instance) { ((MonoBehaviour)__instance).StartCoroutine(DelayedMainMenuModification()); } private static IEnumerator DelayedMainMenuModification() { yield return (object)new WaitForSeconds(0f); ChangeHostButtonFromMainMenu(); } private static void ChangeHostButtonFromMainMenu() { Plugin.Instance.logger.LogDebug((object)"Adding the restart note to the Host button..."); GameObject val = GameObject.Find("MenuContainer"); Transform val2 = (((Object)(object)val != (Object)null) ? val.transform.Find("MainButtons") : null); Transform val3 = (((Object)(object)val2 != (Object)null) ? val2.Find("HostButton") : null); TextMeshProUGUI val4 = (((Object)(object)val3 != (Object)null) ? ((Component)val3).GetComponentInChildren<TextMeshProUGUI>() : null); if (!((Object)(object)val4 == (Object)null)) { ((TMP_Text)val4).text = "<line-height=0.28em>" + ((TMP_Text)val4).text + "\n<size=8><color=#B0B0B0> Please restart the game for <color=#E6B800>CustomSounds</color> to work properly!</color></size></line-height>"; } } } [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(); if ((Object)(object)networkPrefab == (Object)null) { Plugin.Instance.logger.LogError((object)"No AudioNetworkHandler prefab; CustomSounds' network object won't be registered."); return; } 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_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) try { if (!((Object)(object)networkPrefab == (Object)null) && (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)) { Plugin.Instance.logger.LogInfo((object)"Spawning network handler"); networkHandlerHost = Object.Instantiate<GameObject>(networkPrefab, Vector3.zero, Quaternion.identity); networkHandlerHost.GetComponent<NetworkObject>().Spawn(true); } } catch (Exception ex) { Plugin.Instance.logger.LogError((object)("Failed to spawn network handler: " + ex.Message)); } } [HarmonyPostfix] [HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")] private static void DestroyNetworkHandler() { try { if (!((Object)(object)networkHandlerHost == (Object)null) && (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)) { Plugin.Instance.logger.LogInfo((object)"Destroying network handler"); Object.Destroy((Object)(object)networkHandlerHost); networkHandlerHost = null; } } catch (Exception ex) { Plugin.Instance.logger.LogError((object)("Failed to destroy network handler: " + ex.Message)); } } } [HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")] public static class TerminalParsePlayerSentencePatch { private const string Help = "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"; private const string NotSupported = "/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n"; public static bool Prefix(Terminal __instance, ref TerminalNode __result) { string text = (((Object)(object)__instance.screenText != (Object)null) ? __instance.screenText.text : null); if (string.IsNullOrEmpty(text)) { return true; } int num = text.LastIndexOf('\n'); string[] array = text.Substring(num + 1).Trim().ToLowerInvariant() .Split(' '); if (array.Length < 2 || (array[0] != "customsounds" && array[0] != "cs")) { return true; } Plugin.Instance.logger.LogInfo((object)("Received terminal command: " + string.Join(" ", array))); string text2 = array[1]; if (text2 != null) { switch (text2.Length) { case 6: { char c = text2[2]; if (c != 'l') { if (c != 's') { if (c != 'v' || !(text2 == "revert")) { break; } goto IL_028e; } if (!(text2 == "unsync")) { break; } goto IL_02d0; } if (!(text2 == "reload")) { break; } goto IL_025e; } case 2: { char c = text2[1]; if (c != 'l') { if (c != 'u') { if (c != 'v' || !(text2 == "rv")) { break; } goto IL_028e; } if (!(text2 == "fu")) { break; } goto IL_02d0; } if (!(text2 == "rl")) { break; } goto IL_025e; } case 4: { char c = text2[0]; if (c != 'h') { if (c != 'l') { if (c != 's' || !(text2 == "sync")) { break; } goto IL_02d0; } if (!(text2 == "list")) { break; } goto IL_02a6; } if (!(text2 == "help")) { break; } goto IL_02c2; } case 1: { char c = text2[0]; if ((uint)c <= 108u) { if (c != 'h') { if (c != 'l') { break; } goto IL_02a6; } goto IL_02c2; } if (c != 's' && c != 'u') { break; } goto IL_02d0; } case 12: { if (!(text2 == "force-unsync")) { break; } goto IL_02d0; } IL_025e: Plugin.Instance.RevertSounds(); Plugin.Instance.ReloadSounds(); __result = CreateTerminalNode(Plugin.SoundDataProcessor.DisplayTree(isListing: false, Plugin.SoundDataProcessor.BuildFolderTree(Plugin.soundDataList))); return false; IL_02a6: __result = CreateTerminalNode(Plugin.SoundDataProcessor.DisplayTree(isListing: true, Plugin.SoundDataProcessor.BuildFolderTree(Plugin.soundDataList))); return false; IL_02c2: __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"); return false; IL_028e: Plugin.Instance.RevertSounds(); __result = CreateTerminalNode("Game sounds reverted to original.\n\n"); return false; IL_02d0: __result = CreateTerminalNode("/!\\ ERROR /!\\ \nThis command is not supported in this version of CustomSounds\n\n"); return false; } } __result = CreateTerminalNode("Unknown customsounds command.\n\n"); return false; } private static TerminalNode CreateTerminalNode(string message) { TerminalNode obj = ScriptableObject.CreateInstance<TerminalNode>(); obj.displayText = message; obj.clearPreviousText = true; return obj; } } } namespace CustomSounds.Networking { public class AudioNetworkHandler : NetworkBehaviour { public static AudioNetworkHandler Instance { get; private set; } public override void OnNetworkSpawn() { Instance = this; ((NetworkBehaviour)this).OnNetworkSpawn(); } public override void OnNetworkDespawn() { if ((Object)(object)Instance == (Object)(object)this) { Instance = null; } ((NetworkBehaviour)this).OnNetworkDespawn(); } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } protected override void __initializeRpcs() { ((NetworkBehaviour)this).__initializeRpcs(); } protected internal override string __getTypeName() { return "AudioNetworkHandler"; } } } namespace __GEN { internal class NetworkVariableSerializationHelper { [RuntimeInitializeOnLoadMethod] internal static void InitializeSerialization() { } } } namespace CustomSounds.NetcodePatcher { [AttributeUsage(AttributeTargets.Module)] internal class NetcodePatchedAssemblyAttribute : Attribute { } }