Decompiled source of KRWSoundReplaceMod v1.0.1

KRW's Sound Replace Mod.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;

[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("KRW's Sound Replace Mod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("KRW's Sound Replace Mod")]
[assembly: AssemblyTitle("KRW's Sound Replace Mod")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace KRWSoundReplaceMod;

[BepInPlugin("mods.krwclassic.soundreplacemod", "KRW's Sound Replace Mod", "1.0.0")]
public class Class1 : BaseUnityPlugin
{
	private class SoundModComponent : MonoBehaviour
	{
		[CompilerGenerated]
		private sealed class <LoadAudioClip>d__2 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public string path;

			public string soundName;

			public SoundModComponent <>4__this;

			private UnityWebRequest <www>5__1;

			private AudioClip <clip>5__2;

			private float <boostFactor>5__3;

			private float <boost>5__4;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <LoadAudioClip>d__2(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<www>5__1 = null;
				<clip>5__2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Invalid comparison between Unknown and I4
				//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b2: Invalid comparison between Unknown and I4
				//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						_logger.LogInfo((object)("Loading sound: " + soundName + " from " + path));
						<www>5__1 = UnityWebRequestMultimedia.GetAudioClip("file://" + path, (AudioType)20);
						<>1__state = -3;
						<>2__current = <www>5__1.SendWebRequest();
						<>1__state = 1;
						return true;
					case 1:
						<>1__state = -3;
						if ((int)<www>5__1.result == 2 || (int)<www>5__1.result == 3)
						{
							_logger.LogError((object)("Failed to load sound " + soundName + ": " + <www>5__1.error));
						}
						else
						{
							<clip>5__2 = ((DownloadHandlerAudioClip)<www>5__1.downloadHandler).audioClip;
							if ((Object)(object)<clip>5__2 != (Object)null)
							{
								<boostFactor>5__3 = (_volumeBoosts.TryGetValue(soundName, out <boost>5__4) ? <boost>5__4 : 1f);
								_soundReplacements[soundName] = ApplyVolumeBoost(<clip>5__2, <boostFactor>5__3);
								_logger.LogInfo((object)$"Successfully loaded and boosted sound: {soundName} (Boost: {<boostFactor>5__3}x)");
							}
							else
							{
								_logger.LogError((object)("Failed to create AudioClip for sound: " + soundName));
							}
							<clip>5__2 = null;
						}
						<>m__Finally1();
						<www>5__1 = null;
						return false;
					}
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<www>5__1 != null)
				{
					((IDisposable)<www>5__1).Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private void Start()
		{
			LoadCustomSounds();
		}

		private void LoadCustomSounds()
		{
			string text = Path.Combine(Paths.PluginPath, "KRWs_Sound_Replace_Mod", "Sounds");
			_logger.LogInfo((object)("Checking if sound folder exists: " + text));
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
				_logger.LogInfo((object)("Created sound folder at: " + text));
				return;
			}
			_logger.LogInfo((object)("Loading custom sounds from: " + text));
			string[] files = Directory.GetFiles(text, "*.wav");
			_logger.LogInfo((object)$"Found {files.Length} .wav files in the folder:");
			if (files.Length == 0)
			{
				_logger.LogWarning((object)"No .wav files found in the specified folder. Please check the file names and formats.");
			}
			string[] array = files;
			foreach (string text2 in array)
			{
				_logger.LogInfo((object)("File: " + text2));
			}
			string[] array2 = files;
			foreach (string path in array2)
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
				_logger.LogInfo((object)("Found sound file: " + fileNameWithoutExtension));
				((MonoBehaviour)this).StartCoroutine(LoadAudioClip(path, fileNameWithoutExtension));
			}
		}

		[IteratorStateMachine(typeof(<LoadAudioClip>d__2))]
		private IEnumerator LoadAudioClip(string path, string soundName)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <LoadAudioClip>d__2(0)
			{
				<>4__this = this,
				path = path,
				soundName = soundName
			};
		}

		private static AudioClip ApplyVolumeBoost(AudioClip originalClip, float boostFactor)
		{
			int num = originalClip.samples * originalClip.channels;
			float[] array = new float[num];
			originalClip.GetData(array, 0);
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Mathf.Clamp(array[i] * boostFactor, -1f, 1f);
			}
			AudioClip val = AudioClip.Create(((Object)originalClip).name, originalClip.samples, originalClip.channels, originalClip.frequency, false);
			val.SetData(array, 0);
			return val;
		}
	}

	[HarmonyPatch(typeof(AudioSource))]
	[HarmonyPatch("Play", new Type[] { })]
	private static class AudioSourcePlayPatch
	{
		private static void Prefix(AudioSource __instance)
		{
			if ((Object)(object)__instance.clip != (Object)null)
			{
				string name = ((Object)__instance.clip).name;
				_logger.LogInfo((object)("Attempting to play sound: " + name));
				if (_soundReplacements.TryGetValue(name, out var value))
				{
					__instance.clip = value;
					_logger.LogInfo((object)("Checking volume boost for sound: " + name));
					if (_volumeBoosts.TryGetValue(name, out var value2))
					{
						float volume = __instance.volume;
						float num = volume * value2 * volumeMultiplier;
						__instance.volume = Mathf.Clamp(num, 0f, 1f);
						_logger.LogInfo((object)$"Original volume: {volume}, Boosted volume: {num}, Final volume: {__instance.volume}");
					}
					else
					{
						_logger.LogInfo((object)("No volume boost found for sound: " + name));
					}
				}
				else
				{
					_logger.LogInfo((object)("No replacement found for sound: " + name));
				}
			}
			else
			{
				_logger.LogWarning((object)"AudioSource clip is null.");
			}
		}
	}

	private static ManualLogSource _logger;

	private static Dictionary<string, AudioClip> _soundReplacements = new Dictionary<string, AudioClip>();

	private static Dictionary<string, float> _volumeBoosts = new Dictionary<string, float>();

	private static float volumeMultiplier = 2f;

	private void Awake()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Expected O, but got Unknown
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Expected O, but got Unknown
		_logger = ((BaseUnityPlugin)this).Logger;
		Harmony val = new Harmony("mods.krwclassic.soundreplacemod");
		val.PatchAll();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"KRW's Sound Replace Mod loaded!");
		LoadConfig();
		GameObject val2 = new GameObject("KRWSoundReplaceModObject");
		val2.AddComponent<SoundModComponent>();
		Object.DontDestroyOnLoad((Object)(object)val2);
	}

	private void LoadConfig()
	{
		string path = Path.Combine(Paths.PluginPath, "KRWs_Sound_Replace_Mod", "config.json");
		if (File.Exists(path))
		{
			string text = File.ReadAllText(path);
			_volumeBoosts = JsonConvert.DeserializeObject<Dictionary<string, float>>(text);
			_logger.LogInfo((object)"Loaded volume boosts from config.");
		}
		else
		{
			_logger.LogWarning((object)"Config file not found. Using default volume boosts.");
			_volumeBoosts["HAPPY_Guitar"] = 1f;
			_volumeBoosts["HAPPY_Violin"] = 1f;
			_volumeBoosts["HAPPY_Accordion"] = 1f;
			_volumeBoosts["HAPPY_Flute"] = 1f;
		}
	}
}
public static class PluginInfo
{
	public const string PLUGIN_GUID = "mods.krwclassic.soundreplacemod";

	public const string PLUGIN_NAME = "KRW's Sound Replace Mod";

	public const string PLUGIN_VERSION = "1.0.0";
}