Decompiled source of ItHurts v1.0.3

ItHurts.dll

Decompiled 3 weeks 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
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("ItHurts")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ItHurts")]
[assembly: AssemblyTitle("ItHurts")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ItHurts
{
	public class FallSync : MonoBehaviourPun, IOnEventCallback
	{
		public void OnEnable()
		{
			PhotonNetwork.AddCallbackTarget((object)this);
		}

		public void OnDisable()
		{
			PhotonNetwork.RemoveCallbackTarget((object)this);
		}

		public void OnEvent(EventData photonEvent)
		{
			//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_0090: Unknown result type (might be due to invalid IL or missing references)
			if (photonEvent.Code != Plugin.ModEventCodes.FallSoundEvent)
			{
				return;
			}
			object customData = photonEvent.CustomData;
			if (customData is Vector3)
			{
				Vector3 val = (Vector3)customData;
				if ((Object)(object)Plugin.ItHurts != (Object)null)
				{
					Plugin.ItHurts.settings.volume = Plugin.BoundConfig.SFXVolume.Value;
					Plugin.ItHurts.settings.range = Plugin.BoundConfig.SFXRange.Value;
					Plugin.ItHurts.settings.spatialBlend = Plugin.BoundConfig.SFXSpatialBlend.Value;
					Plugin.ItHurts.Play(val);
				}
			}
		}
	}
	public class ModConfig
	{
		public readonly ConfigEntry<float> SFXVolume;

		public readonly ConfigEntry<float> SFXRange;

		public readonly ConfigEntry<float> SFXSpatialBlend;

		public readonly ConfigEntry<float> MinRepeatGap;

		public ModConfig(ConfigFile cfg)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			cfg.SaveOnConfigSet = false;
			SFXVolume = cfg.Bind<float>("General", "Fall Volume", 1f, new ConfigDescription("Volume of the fall damage sound.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			SFXRange = cfg.Bind<float>("General", "Fall Sound Range", 120f, new ConfigDescription("Maximum distance the fall damage sound can be heard from.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f), Array.Empty<object>()));
			SFXSpatialBlend = cfg.Bind<float>("General", "Spatial Blend", 0.8f, new ConfigDescription("How 3D the sound is. 0 = heard equally everywhere, 1 = full positional audio.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			MinRepeatGap = cfg.Bind<float>("General", "Min Repeat Gap", 5f, new ConfigDescription("Minimum seconds before the same character can trigger the sound again.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 20f), Array.Empty<object>()));
			ClearOrphanedEntries(cfg);
			cfg.Save();
			cfg.SaveOnConfigSet = true;
		}

		private static void ClearOrphanedEntries(ConfigFile cfg)
		{
			((Dictionary<ConfigDefinition, string>)AccessTools.Property(typeof(ConfigFile), "OrphanedEntries").GetValue(cfg)).Clear();
		}
	}
	[HarmonyPatch(typeof(CharacterMovement), "CheckFallDamage")]
	public static class PatchCheckFallDamage
	{
		internal static bool insideCheckFallDamage;

		internal static CharacterMovement currentInstance;

		private static void Prefix(CharacterMovement __instance)
		{
			insideCheckFallDamage = true;
			currentInstance = __instance;
		}

		private static void Postfix()
		{
			insideCheckFallDamage = false;
			currentInstance = null;
		}
	}
	[HarmonyPatch(typeof(CharacterAfflictions), "AddStatus")]
	public static class PatchAddStatus
	{
		private static void Postfix(CharacterAfflictions __instance, STATUSTYPE statusType, bool __result)
		{
			//IL_000c: 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)
			try
			{
				if (!PatchCheckFallDamage.insideCheckFallDamage || (int)statusType != 0 || !__result || (Object)(object)Plugin.ItHurts == (Object)null || Plugin.ItHurts.clips == null || Plugin.ItHurts.clips.Length == 0)
				{
					return;
				}
				Character character = __instance.character;
				if (!((Object)(object)character == (Object)null) && character.IsLocal)
				{
					int instanceID = ((Object)character).GetInstanceID();
					float time = Time.time;
					if (!Plugin.lastPlayTime.TryGetValue(instanceID, out var value) || !(time - value < Plugin.BoundConfig.MinRepeatGap.Value))
					{
						Plugin.lastPlayTime[instanceID] = time;
						Plugin.ItHurts.settings.volume = Plugin.BoundConfig.SFXVolume.Value;
						Plugin.ItHurts.settings.range = Plugin.BoundConfig.SFXRange.Value;
						Plugin.ItHurts.settings.spatialBlend = Plugin.BoundConfig.SFXSpatialBlend.Value;
						Plugin.RaiseFallSoundEvent(character.Center);
					}
				}
			}
			catch (Exception arg)
			{
				ManualLogSource log = Plugin.Log;
				if (log != null)
				{
					log.LogError((object)$"ItHurts patch error: {arg}");
				}
			}
		}
	}
	[BepInPlugin("ItHurts", "ItHurts", "1.0.3")]
	public class Plugin : BaseUnityPlugin
	{
		internal static class ModEventCodes
		{
			internal static readonly byte FallSoundEvent = 78;
		}

		public const string Id = "ItHurts";

		internal static SFX_Instance ItHurts;

		internal static FallSync syncInstance;

		private readonly Harmony harmony = new Harmony("ItHurts");

		internal static readonly Dictionary<int, float> lastPlayTime = new Dictionary<int, float>();

		private const int SFXLimit = 10;

		internal static ManualLogSource Log { get; private set; }

		internal static Plugin Instance { get; private set; }

		internal static ModConfig BoundConfig { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			BoundConfig = new ModConfig(((BaseUnityPlugin)this).Config);
			GetSyncInstance();
			LoadItHurts();
			harmony.PatchAll();
			Log.LogInfo((object)"ItHurts loaded.");
		}

		internal static void RaiseFallSoundEvent(Vector3 position)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			if (PhotonNetwork.OfflineMode)
			{
				if ((Object)(object)ItHurts != (Object)null)
				{
					ItHurts.settings.volume = BoundConfig.SFXVolume.Value;
					ItHurts.settings.range = BoundConfig.SFXRange.Value;
					ItHurts.settings.spatialBlend = BoundConfig.SFXSpatialBlend.Value;
					ItHurts.Play(position);
				}
			}
			else
			{
				PhotonNetwork.RaiseEvent(ModEventCodes.FallSoundEvent, (object)position, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)1
				}, SendOptions.SendReliable);
			}
		}

		internal static FallSync GetSyncInstance()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)syncInstance != (Object)null)
			{
				return syncInstance;
			}
			syncInstance = Object.FindFirstObjectByType<FallSync>();
			if ((Object)(object)syncInstance == (Object)null)
			{
				syncInstance = new GameObject("FallSync Listener Instance").AddComponent<FallSync>();
				Object.DontDestroyOnLoad((Object)(object)((Component)syncInstance).gameObject);
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogInfo((object)"Created FallSync listener instance.");
				}
			}
			return syncInstance;
		}

		private void LoadItHurts()
		{
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Expected O, but got Unknown
			string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
			List<string> list = Directory.GetFiles(directoryName, "*.wav").Take(10).ToList();
			if (list.Count == 0)
			{
				Log.LogWarning((object)("No .wav files found in " + directoryName));
				return;
			}
			List<AudioClip> list2 = new List<AudioClip>();
			foreach (string item in list)
			{
				try
				{
					AudioClip val = LoadAudioClip(item);
					if ((Object)(object)val != (Object)null)
					{
						list2.Add(val);
					}
				}
				catch (Exception ex)
				{
					Log.LogError((object)("Failed to load sound file " + item + ": " + ex.Message));
				}
			}
			if (list2.Count == 0)
			{
				Log.LogError((object)"No fall audio clips were loaded.");
				return;
			}
			ItHurts = ScriptableObject.CreateInstance<SFX_Instance>();
			ItHurts.clips = list2.ToArray();
			ItHurts.settings = new SFX_Settings
			{
				volume = BoundConfig.SFXVolume.Value,
				range = BoundConfig.SFXRange.Value,
				spatialBlend = BoundConfig.SFXSpatialBlend.Value
			};
			Log.LogInfo((object)$"Created fall SFX with {list2.Count} clip(s).");
		}

		private AudioClip LoadAudioClip(string filePath)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Invalid comparison between Unknown and I4
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(new Uri(filePath).AbsoluteUri, (AudioType)20);
			try
			{
				UnityWebRequestAsyncOperation val = audioClip.SendWebRequest();
				while (!((AsyncOperation)val).isDone)
				{
				}
				if ((int)audioClip.result == 2 || (int)audioClip.result == 3)
				{
					Log.LogError((object)("Error loading " + filePath + ": " + audioClip.error));
					return null;
				}
				return DownloadHandlerAudioClip.GetContent(audioClip);
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
		}
	}
}