Decompiled source of ReturnByDeath v1.0.0

Mods/ReturnByDeath.dll

Decompiled 17 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BoneLib;
using BoneLib.BoneMenu;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Marrow;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using ReturnByDeath;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Core), "ReturnByDeath", "1.0.0", "jay", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("ReturnByDeath")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ReturnByDeath")]
[assembly: AssemblyTitle("ReturnByDeath")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
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 ReturnByDeath
{
	public class Core : MelonMod
	{
		private enum State
		{
			Idle,
			Dead,
			Flash
		}

		private const string DefaultSoundName = "respawn.wav";

		private const string EmbeddedSoundResource = "ReturnByDeath.respawn.wav";

		private const float PreviewDeadSeconds = 2.5f;

		private static Core _instance;

		private MelonPreferences_Category _prefs;

		private MelonPreferences_Entry<bool> _enabled;

		private MelonPreferences_Entry<string> _soundFile;

		private MelonPreferences_Entry<float> _volume;

		private MelonPreferences_Entry<float> _blackFadeSeconds;

		private MelonPreferences_Entry<float> _whiteHoldSeconds;

		private MelonPreferences_Entry<float> _whiteFadeSeconds;

		private MelonPreferences_Entry<float> _maxDeadSeconds;

		private string _soundFolder;

		private State _state;

		private float _stateTime;

		private bool _respawnSignal;

		private bool _sawNotAlive;

		private bool _levelLoading;

		private bool _preview;

		private IntPtr _deadRig = IntPtr.Zero;

		private GameObject _overlay;

		private Camera _overlayCam;

		private Material _overlayMat;

		private Mesh _quadMesh;

		private GameObject _audioGo;

		private AudioSource _audioSource;

		private AudioClip _clip;

		private bool _clipLoadFailed;

		public override void OnInitializeMelon()
		{
			_instance = this;
			_prefs = MelonPreferences.CreateCategory("ReturnByDeath");
			_enabled = _prefs.CreateEntry<bool>("Enabled", true, "Enabled", "Turn the mod on or off.", false, false, (ValueValidator)null, (string)null);
			_soundFile = _prefs.CreateEntry<string>("SoundFile", "respawn.wav", "Sound file", "File in UserData\\ReturnByDeath played on respawn. .wav works on its own; .mp3 and .ogg need AudioImportLib. Can also be a full path.", false, false, (ValueValidator)null, (string)null);
			_volume = _prefs.CreateEntry<float>("Volume", 1f, "Volume", "Respawn sound volume, 0 to 1.", false, false, (ValueValidator)null, (string)null);
			_blackFadeSeconds = _prefs.CreateEntry<float>("BlackFadeSeconds", 0f, "Black fade seconds", "Time to fade to black on death. 0 = instant cut.", false, false, (ValueValidator)null, (string)null);
			_whiteHoldSeconds = _prefs.CreateEntry<float>("WhiteHoldSeconds", 0.4f, "White hold seconds", "Time the screen stays fully white after respawn.", false, false, (ValueValidator)null, (string)null);
			_whiteFadeSeconds = _prefs.CreateEntry<float>("WhiteFadeSeconds", 2.5f, "White fade seconds", "Time for the white to fade away. Game audio comes back when this ends.", false, false, (ValueValidator)null, (string)null);
			_maxDeadSeconds = _prefs.CreateEntry<float>("MaxDeadSeconds", 20f, "Max dead seconds", "Safety limit. If no respawn is seen after this many seconds (level loading not counted), the effect ends.", false, false, (ValueValidator)null, (string)null);
			_soundFolder = Path.Combine(MelonEnvironment.UserDataDirectory, "ReturnByDeath");
			Directory.CreateDirectory(_soundFolder);
			WriteDefaultSoundIfMissing();
			Hooking.OnPlayerDeath += OnPlayerDeath;
			Hooking.OnLevelLoading += delegate
			{
				_levelLoading = true;
			};
			Hooking.OnLevelLoaded += delegate
			{
				OnLevelLoaded();
			};
			PatchRespawn();
			SetupMenu();
			((MelonBase)this).LoggerInstance.Msg("Loaded. Sound folder: " + _soundFolder);
		}

		private void PatchRespawn()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			try
			{
				MethodInfo method = typeof(Health).GetMethod("Respawn", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
				MethodInfo method2 = typeof(Core).GetMethod("RespawnPostfix", BindingFlags.Static | BindingFlags.NonPublic);
				((MelonBase)this).HarmonyInstance.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Could not patch Health.Respawn, using polling only: " + ex.Message);
			}
		}

		private static void RespawnPostfix(Health __instance)
		{
			try
			{
				_instance?.OnHealthRespawn(__instance);
			}
			catch (Exception ex)
			{
				Core instance = _instance;
				if (instance != null)
				{
					((MelonBase)instance).LoggerInstance.Warning("Respawn hook error: " + ex.Message);
				}
			}
		}

		private void SetupMenu()
		{
			//IL_0019: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Page obj = Page.Root.CreatePage("ReturnByDeath", new Color(0.55f, 0.2f, 0.85f), 0, true);
				obj.CreateFunction("Kill Me (test)", Color.red, (Action)KillPlayer);
				obj.CreateFunction("Preview Effect", Color.white, (Action)PreviewEffect);
				obj.CreateBool("Enabled", Color.green, _enabled.Value, (Action<bool>)delegate(bool v)
				{
					_enabled.Value = v;
					_prefs.SaveToFile(false);
				});
				obj.CreateFloat("Volume", Color.yellow, _volume.Value, 0.1f, 0f, 1f, (Action<float>)delegate(float v)
				{
					_volume.Value = v;
					_prefs.SaveToFile(false);
				});
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("BoneMenu setup failed: " + ex.Message);
			}
		}

		private void KillPlayer()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			RigManager rigManager = Player.RigManager;
			if (!Alive((Object)(object)rigManager))
			{
				((MelonBase)this).LoggerInstance.Warning("Kill: no player rig.");
				return;
			}
			Health health = rigManager.health;
			Player_Health val = (Alive((Object)(object)health) ? ((Il2CppObjectBase)health).TryCast<Player_Health>() : null);
			if ((Object)(object)val == (Object)null)
			{
				((MelonBase)this).LoggerInstance.Warning("Kill: player has no Player_Health.");
				return;
			}
			((MelonBase)this).LoggerInstance.Msg($"Kill button. healthMode={((Health)val).healthMode}, alive={((Health)val).alive}, reloadLevelOnDeath={val.reloadLevelOnDeath}, deathTime={val.deathTimeAmount}");
			((Health)val).Death();
		}

		private void PreviewEffect()
		{
			if (_state == State.Idle)
			{
				EnterDeath(IntPtr.Zero);
				_preview = true;
			}
		}

		private void OnPlayerDeath(RigManager rig)
		{
			if (_enabled.Value)
			{
				RigManager rigManager = Player.RigManager;
				if (!Alive((Object)(object)rigManager) || !((Object)(object)rig != (Object)null) || !(((Il2CppObjectBase)rig).Pointer != ((Il2CppObjectBase)rigManager).Pointer))
				{
					EnterDeath(((Object)(object)rig != (Object)null) ? ((Il2CppObjectBase)rig).Pointer : IntPtr.Zero);
				}
			}
		}

		private void EnterDeath(IntPtr rigPtr)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (_state != State.Dead)
			{
				_state = State.Dead;
				_stateTime = 0f;
				_respawnSignal = false;
				_sawNotAlive = false;
				_preview = false;
				_deadRig = rigPtr;
				if (Alive((Object)(object)_audioSource))
				{
					_audioSource.Stop();
				}
				AudioListener.pause = true;
				EnsureOverlay();
				SetOverlay(Color.black, (_blackFadeSeconds.Value <= 0f) ? 1f : 0f);
				((MelonBase)this).LoggerInstance.Msg("Death. Screen black, audio off.");
			}
		}

		private void OnHealthRespawn(Health health)
		{
			if (_state != State.Dead || _levelLoading || _stateTime < 0.25f)
			{
				return;
			}
			RigManager rigManager = Player.RigManager;
			if (Alive((Object)(object)rigManager))
			{
				Health health2 = rigManager.health;
				if (Alive((Object)(object)health2) && (Object)(object)health != (Object)null && ((Il2CppObjectBase)health).Pointer != ((Il2CppObjectBase)health2).Pointer)
				{
					return;
				}
			}
			_respawnSignal = true;
		}

		private void OnLevelLoaded()
		{
			_levelLoading = false;
			if ((Object)(object)_clip == (Object)null && !_clipLoadFailed)
			{
				LoadClip();
			}
			if (_state == State.Dead)
			{
				_respawnSignal = true;
			}
		}

		public override void OnUpdate()
		{
			if (_state != State.Idle)
			{
				float num = Mathf.Min(Time.unscaledDeltaTime, 0.1f);
				_stateTime += num;
				if (_state == State.Dead)
				{
					UpdateDead();
				}
				else if (_state == State.Flash)
				{
					UpdateFlash();
				}
			}
		}

		private void UpdateDead()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			AudioListener.pause = true;
			EnsureOverlay();
			float value = _blackFadeSeconds.Value;
			SetOverlay(Color.black, (value <= 0f) ? 1f : Mathf.Clamp01(_stateTime / value));
			if (_levelLoading)
			{
				_stateTime = Mathf.Min(_stateTime, 1f);
			}
			else if (_preview)
			{
				if (_stateTime >= 2.5f)
				{
					_respawnSignal = true;
				}
			}
			else
			{
				PollRespawn();
			}
			bool flag = _stateTime > _maxDeadSeconds.Value;
			if (flag && !_respawnSignal)
			{
				((MelonBase)this).LoggerInstance.Msg("No respawn seen in time, ending effect.");
			}
			if ((_respawnSignal || flag) && !_levelLoading && (Object)(object)FindCamera() != (Object)null)
			{
				EnterFlash();
			}
		}

		private void PollRespawn()
		{
			if (_stateTime < 0.5f)
			{
				return;
			}
			RigManager rigManager = Player.RigManager;
			if (!Alive((Object)(object)rigManager))
			{
				return;
			}
			if (_deadRig != IntPtr.Zero && ((Il2CppObjectBase)rigManager).Pointer != _deadRig)
			{
				_respawnSignal = true;
				return;
			}
			Health health = rigManager.health;
			if (Alive((Object)(object)health))
			{
				if (!health.alive)
				{
					_sawNotAlive = true;
				}
				else if (_sawNotAlive)
				{
					_respawnSignal = true;
				}
			}
		}

		private void EnterFlash()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			_state = State.Flash;
			_stateTime = 0f;
			_respawnSignal = false;
			_preview = false;
			EnsureOverlay();
			SetOverlay(Color.white, 1f);
			PlaySound();
			((MelonBase)this).LoggerInstance.Msg("Respawn. White flash + sound.");
		}

		private void UpdateFlash()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			EnsureOverlay();
			float num = Mathf.Max(0f, _whiteHoldSeconds.Value);
			float num2 = Mathf.Max(0.01f, _whiteFadeSeconds.Value);
			float stateTime = _stateTime;
			float alpha = ((stateTime < num) ? 1f : (1f - Mathf.Clamp01((stateTime - num) / num2)));
			SetOverlay(Color.white, alpha);
			if (stateTime >= num + num2)
			{
				AudioListener.pause = false;
				HideOverlay();
				_state = State.Idle;
			}
		}

		private Camera FindCamera()
		{
			try
			{
				OpenControllerRig controllerRig = Player.ControllerRig;
				if (Alive((Object)(object)controllerRig))
				{
					Il2CppReferenceArray<Camera> cameras = controllerRig.cameras;
					if (cameras != null)
					{
						for (int i = 0; i < ((Il2CppArrayBase<Camera>)(object)cameras).Length; i++)
						{
							Camera val = ((Il2CppArrayBase<Camera>)(object)cameras)[i];
							if (Alive((Object)(object)val) && ((Behaviour)val).isActiveAndEnabled)
							{
								return val;
							}
						}
					}
				}
			}
			catch
			{
			}
			try
			{
				Camera main = Camera.main;
				if (Alive((Object)(object)main))
				{
					return main;
				}
			}
			catch
			{
			}
			return null;
		}

		private void EnsureOverlay()
		{
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: 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_0092: Expected O, but got Unknown
			Camera val = FindCamera();
			if (!((Object)(object)val == (Object)null) && (!Alive((Object)(object)_overlay) || !Alive((Object)(object)_overlayCam) || !(((Il2CppObjectBase)_overlayCam).Pointer == ((Il2CppObjectBase)val).Pointer)))
			{
				if (!Alive((Object)(object)_quadMesh))
				{
					_quadMesh = BuildQuad();
				}
				if (!Alive((Object)(object)_overlayMat))
				{
					_overlayMat = BuildMaterial();
				}
				if (!Alive((Object)(object)_overlay))
				{
					_overlay = new GameObject("ReturnByDeath_Overlay");
					_overlay.AddComponent<MeshFilter>().sharedMesh = _quadMesh;
					MeshRenderer obj = _overlay.AddComponent<MeshRenderer>();
					((Renderer)obj).sharedMaterial = _overlayMat;
					((Renderer)obj).shadowCastingMode = (ShadowCastingMode)0;
					((Renderer)obj).receiveShadows = false;
					((Renderer)obj).allowOcclusionWhenDynamic = false;
				}
				_overlayCam = val;
				Transform transform = _overlay.transform;
				transform.SetParent(((Component)val).transform, false);
				float num = Mathf.Max(val.nearClipPlane * 2f, 0.02f);
				transform.localPosition = new Vector3(0f, 0f, num);
				transform.localRotation = Quaternion.identity;
				transform.localScale = Vector3.one * num * 60f;
				_overlay.layer = FirstRenderedLayer(val.cullingMask);
			}
		}

		private static int FirstRenderedLayer(int mask)
		{
			if ((mask & 1) != 0)
			{
				return 0;
			}
			for (int i = 0; i < 32; i++)
			{
				if ((mask & (1 << i)) != 0)
				{
					return i;
				}
			}
			return 0;
		}

		private static Mesh BuildQuad()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			//IL_0029: 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_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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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)
			Mesh val = new Mesh();
			((Object)val).name = "ReturnByDeath_Quad";
			val.vertices = Il2CppStructArray<Vector3>.op_Implicit((Vector3[])(object)new Vector3[4]
			{
				new Vector3(-0.5f, -0.5f, 0f),
				new Vector3(0.5f, -0.5f, 0f),
				new Vector3(-0.5f, 0.5f, 0f),
				new Vector3(0.5f, 0.5f, 0f)
			});
			val.uv = Il2CppStructArray<Vector2>.op_Implicit((Vector2[])(object)new Vector2[4]
			{
				new Vector2(0f, 0f),
				new Vector2(1f, 0f),
				new Vector2(0f, 1f),
				new Vector2(1f, 1f)
			});
			val.triangles = Il2CppStructArray<int>.op_Implicit(new int[6] { 0, 3, 1, 3, 0, 2 });
			val.RecalculateBounds();
			((Object)val).hideFlags = (HideFlags)32;
			return val;
		}

		private Material BuildMaterial()
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: 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_00b5: Expected O, but got Unknown
			string[] obj = new string[4] { "UI/Default", "Sprites/Default", "Universal Render Pipeline/Unlit", "Unlit/Color" };
			Shader val = null;
			string[] array = obj;
			foreach (string text in array)
			{
				Shader val2 = Shader.Find(text);
				if (Alive((Object)(object)val2))
				{
					val = val2;
					((MelonBase)this).LoggerInstance.Msg("Overlay shader: " + text);
					break;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				((MelonBase)this).LoggerInstance.Error("No usable overlay shader found. Screen effect will not show.");
			}
			Material val3 = new Material(val)
			{
				name = "ReturnByDeath_Overlay",
				renderQueue = 5000
			};
			val3.SetFloat("unity_GUIZTestMode", 8f);
			((Object)val3).hideFlags = (HideFlags)32;
			return val3;
		}

		private void SetOverlay(Color color, float alpha)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (Alive((Object)(object)_overlayMat))
			{
				color.a = alpha;
				_overlayMat.color = color;
				if (Alive((Object)(object)_overlay))
				{
					_overlay.SetActive(alpha > 0.001f);
				}
			}
		}

		private void HideOverlay()
		{
			if (Alive((Object)(object)_overlay))
			{
				_overlay.SetActive(false);
			}
		}

		private void PlaySound()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			if ((Object)(object)_clip == (Object)null && !_clipLoadFailed)
			{
				LoadClip();
			}
			if (!((Object)(object)_clip == (Object)null))
			{
				if (!Alive((Object)(object)_audioSource))
				{
					_audioGo = new GameObject("ReturnByDeath_Audio");
					Object.DontDestroyOnLoad((Object)(object)_audioGo);
					((Object)_audioGo).hideFlags = (HideFlags)32;
					_audioSource = _audioGo.AddComponent<AudioSource>();
					_audioSource.playOnAwake = false;
					_audioSource.loop = false;
					_audioSource.spatialBlend = 0f;
					_audioSource.ignoreListenerPause = true;
					_audioSource.bypassEffects = true;
					_audioSource.bypassListenerEffects = true;
					_audioSource.bypassReverbZones = true;
					_audioSource.priority = 0;
				}
				_audioSource.volume = Mathf.Clamp01(_volume.Value);
				_audioSource.clip = _clip;
				_audioSource.Play();
			}
		}

		private void WriteDefaultSoundIfMissing()
		{
			try
			{
				if (FindAudioFiles().Any())
				{
					return;
				}
				using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ReturnByDeath.respawn.wav");
				if (stream == null)
				{
					return;
				}
				using FileStream destination = File.Create(Path.Combine(_soundFolder, "respawn.wav"));
				stream.CopyTo(destination);
				((MelonBase)this).LoggerInstance.Msg("Wrote default sound to " + Path.Combine(_soundFolder, "respawn.wav"));
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Could not write default sound: " + ex.Message);
			}
		}

		private void LoadClip()
		{
			string text = ResolveSoundPath();
			if (text == null)
			{
				_clipLoadFailed = true;
				((MelonBase)this).LoggerInstance.Warning("No respawn sound found. Put a .wav file in " + _soundFolder);
				return;
			}
			try
			{
				if (text.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))
				{
					_clip = WavLoader.Load(text);
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("WAV loader failed (" + ex.Message + "), trying AudioImportLib.");
				_clip = null;
			}
			if ((Object)(object)_clip == (Object)null)
			{
				try
				{
					_clip = LoadWithAudioImportLib(text);
				}
				catch (Exception ex2)
				{
					((MelonBase)this).LoggerInstance.Error("Could not load " + Path.GetFileName(text) + ": " + (ex2.InnerException?.Message ?? ex2.Message));
				}
			}
			if ((Object)(object)_clip == (Object)null)
			{
				_clipLoadFailed = true;
				return;
			}
			((Object)_clip).hideFlags = (HideFlags)32;
			((MelonBase)this).LoggerInstance.Msg($"Respawn sound loaded: {Path.GetFileName(text)} ({_clip.length:0.0}s)");
		}

		private static AudioClip LoadWithAudioImportLib(string path)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			Assembly? assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "AudioImportLib");
			if (assembly == null)
			{
				throw new InvalidOperationException("AudioImportLib is not installed. Use a .wav file or install AudioImportLib.");
			}
			MethodInfo methodInfo = assembly.GetType("AudioImportLib.API")?.GetMethod("LoadAudioClip", BindingFlags.Static | BindingFlags.Public);
			if (methodInfo == null)
			{
				throw new InvalidOperationException("AudioImportLib.API.LoadAudioClip not found.");
			}
			object[] parameters = ((methodInfo.GetParameters().Length < 2) ? new object[1] { path } : new object[2] { path, true });
			return (AudioClip)methodInfo.Invoke(null, parameters);
		}

		private string ResolveSoundPath()
		{
			string value = _soundFile.Value;
			if (!string.IsNullOrWhiteSpace(value))
			{
				string text = (Path.IsPathRooted(value) ? value : Path.Combine(_soundFolder, value));
				if (File.Exists(text))
				{
					return text;
				}
			}
			return (from f in FindAudioFiles()
				orderby f
				select f).FirstOrDefault();
		}

		private IEnumerable<string> FindAudioFiles()
		{
			return from f in Directory.EnumerateFiles(_soundFolder)
				where f.EndsWith(".wav", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase)
				select f;
		}

		public override void OnDeinitializeMelon()
		{
			AudioListener.pause = false;
		}

		private static bool Alive(Object o)
		{
			if (o == null)
			{
				return false;
			}
			try
			{
				return !((Il2CppObjectBase)o).WasCollected && o != (Object)null;
			}
			catch
			{
				return false;
			}
		}
	}
	internal static class WavLoader
	{
		public static AudioClip Load(string path)
		{
			return Load(File.ReadAllBytes(path), Path.GetFileNameWithoutExtension(path));
		}

		public static AudioClip Load(byte[] b, string name)
		{
			if (b.Length < 44 || Ascii(b, 0) != "RIFF" || Ascii(b, 8) != "WAVE")
			{
				throw new InvalidDataException("Not a RIFF/WAVE file.");
			}
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = -1;
			int num6 = 0;
			int num7 = 12;
			while (num7 + 8 <= b.Length)
			{
				string text = Ascii(b, num7);
				int num8 = BitConverter.ToInt32(b, num7 + 4);
				int num9 = num7 + 8;
				if (text == "fmt ")
				{
					num = BitConverter.ToUInt16(b, num9);
					num2 = BitConverter.ToUInt16(b, num9 + 2);
					num3 = BitConverter.ToInt32(b, num9 + 4);
					num4 = BitConverter.ToUInt16(b, num9 + 14);
					if (num == 65534 && num8 >= 26)
					{
						num = BitConverter.ToUInt16(b, num9 + 24);
					}
				}
				else if (text == "data")
				{
					num5 = num9;
					num6 = Math.Min(num8, b.Length - num9);
					break;
				}
				num7 = num9 + num8 + (num8 & 1);
			}
			if (num5 < 0 || num2 <= 0 || num3 <= 0)
			{
				throw new InvalidDataException("Missing fmt or data chunk.");
			}
			if (num != 1 && num != 3)
			{
				throw new InvalidDataException($"Unsupported WAV format {num} (only PCM and float).");
			}
			int num10 = num4 / 8;
			int num11 = num6 / num10;
			num11 -= num11 % num2;
			float[] array = new float[num11];
			int num12 = 0;
			int num13 = num5;
			while (num12 < num11)
			{
				float[] array2 = array;
				int num14 = num12;
				array2[num14] = num4 switch
				{
					8 => (float)(b[num13] - 128) / 128f, 
					16 => (float)BitConverter.ToInt16(b, num13) / 32768f, 
					24 => (float)(b[num13] | (b[num13 + 1] << 8) | ((sbyte)b[num13 + 2] << 16)) / 8388608f, 
					32 => (num != 3) ? ((float)BitConverter.ToInt32(b, num13) / 2.1474836E+09f) : BitConverter.ToSingle(b, num13), 
					_ => throw new InvalidDataException($"Unsupported bit depth {num4}."), 
				};
				num12++;
				num13 += num10;
			}
			AudioClip obj = AudioClip.Create(name, num11 / num2, num2, num3, false);
			obj.SetData(Il2CppStructArray<float>.op_Implicit(array), 0);
			return obj;
		}

		private static string Ascii(byte[] b, int offset)
		{
			return Encoding.ASCII.GetString(b, offset, 4);
		}
	}
}