Decompiled source of RandomCustomPropSounds v1.0.0

RandomCustomPropSounds.dll

Decompiled 2 years 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.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using LC_API.ServerAPI;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
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("RandomCustomPropSounds")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("RandomCustomPropSounds")]
[assembly: AssemblyTitle("RandomCustomPropSounds")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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 RandomCustomPropSounds
{
	[BepInPlugin("RandomCustomPropSounds", "RandomCustomPropSounds", "1.0.0")]
	public class RandomCustomPropSounds : BaseUnityPlugin
	{
		public const string RandomPropsDir = "RandomProps";

		public const string SeedRPCSignature = "RCPS_SeedSync";

		public static RandomCustomPropSounds Instance;

		public static int Seed = new Random().Next();

		public static int SeedOffset = 0;

		public static Random random = new Random(Seed);

		internal ManualLogSource logger;

		public Dictionary<string, string> soundPacks = new Dictionary<string, string>();

		public static Dictionary<string, HashSet<AudioClip>> ReplacedClips = new Dictionary<string, HashSet<AudioClip>>();

		private Harmony harmony;

		private void Awake()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			if (!((Object)(object)Instance != (Object)null))
			{
				Instance = this;
				logger = Logger.CreateLogSource("RandomCustomPropSounds");
				logger.LogInfo((object)"Plugin RandomCustomPropSounds is loaded!");
				harmony = new Harmony("RandomCustomPropSounds");
				harmony.PatchAll();
				CreateCustomSoundsFolder();
				Networking.GetString = (Action<string, string>)Delegate.Combine(Networking.GetString, new Action<string, string>(GetSeedSync));
			}
		}

		private void GetSeedSync(string data, string signature)
		{
			if (signature != "RCPS_SeedSync")
			{
				return;
			}
			string[] array = data.Split("_");
			try
			{
				int num = int.Parse(array[0]);
				int num2 = int.Parse(array[1]);
				if (num != Seed || num2 != SeedOffset)
				{
					logger.LogInfo((object)$"Received seed {num} & offset {num2} from host.");
					Seed = num;
					SeedOffset = num2;
					random = new Random(Seed);
					for (int i = 0; i < SeedOffset; i++)
					{
						random.Next();
					}
				}
			}
			catch (Exception arg)
			{
				logger.LogWarning((object)$"Failed to parse seed data\n{arg}");
			}
		}

		private void Start()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			LoadSounds();
			GameObject val = new GameObject("RCPSPlayerJoin");
			val.AddComponent<RCPSPlayerJoin>();
			Object.DontDestroyOnLoad((Object)(object)val);
		}

		private void CreateCustomSoundsFolder()
		{
			string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "RandomProps");
			Directory.CreateDirectory(path);
		}

		public void LoadSounds()
		{
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			string path = Path.Combine(directoryName, "RandomProps");
			if (Directory.Exists(path))
			{
				string[] directories = Directory.GetDirectories(path);
				string[] array = directories;
				foreach (string propPath in array)
				{
					ProcessSoundFiles(propPath);
				}
			}
			else
			{
				logger.LogInfo((object)"RandomProps folder not found.");
			}
		}

		private void ProcessSoundFiles(string propPath)
		{
			string[] files = Directory.GetFiles(propPath, "*.wav");
			string[] array = files;
			foreach (string soundPath in array)
			{
				AudioClip audioClip = GetAudioClip(soundPath);
				string fileName = Path.GetFileName(propPath);
				AddAudioClip(fileName, audioClip);
				logger.LogInfo((object)("Added " + fileName + "/" + ((Object)audioClip).name));
			}
		}

		public static void AddAudioClip(string originalName, AudioClip newClip)
		{
			if (string.IsNullOrEmpty(originalName))
			{
				Instance.logger.LogWarning((object)"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)"Trying to replace an audio clip without new clip specified! This is not allowed.");
				return;
			}
			if (ReplacedClips.ContainsKey(originalName))
			{
				ReplacedClips[originalName].Add(newClip);
				return;
			}
			ReplacedClips.Add(originalName, new HashSet<AudioClip> { newClip });
		}

		public static AudioClip GetAudioClip(string soundPath)
		{
			if (!File.Exists(soundPath))
			{
				Instance.logger.LogWarning((object)("Requested audio file does not exist at path " + soundPath + "!"));
				return null;
			}
			Instance.logger.LogDebug((object)("Loading AudioClip from path: " + soundPath));
			return LoadClip(soundPath);
		}

		private static AudioClip LoadClip(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 val = null;
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(path, (AudioType)20);
			try
			{
				audioClip.SendWebRequest();
				try
				{
					while (!audioClip.isDone)
					{
					}
					if ((int)audioClip.result != 1)
					{
						Instance.logger.LogError((object)("Failed to load AudioClip from path: " + path + "\n" + audioClip.error));
					}
					else
					{
						val = DownloadHandlerAudioClip.GetContent(audioClip);
						((Object)val).name = Path.GetFileNameWithoutExtension(path);
					}
				}
				catch (Exception ex)
				{
					Instance.logger.LogError((object)(ex.Message + ", " + ex.StackTrace));
				}
			}
			finally
			{
				((IDisposable)audioClip)?.Dispose();
			}
			return val;
		}
	}
	internal class RCPSPlayerJoin : MonoBehaviour
	{
		private static int playerCount = 1;

		private static float lobbyCheckTimer;

		private static bool wantToSyncSeed;

		public void Awake()
		{
		}

		public void Update()
		{
			if ((Object)(object)GameNetworkManager.Instance != (Object)null)
			{
				if (playerCount < GameNetworkManager.Instance.connectedPlayers)
				{
					lobbyCheckTimer = 4.5f;
					wantToSyncSeed = true;
				}
				playerCount = GameNetworkManager.Instance.connectedPlayers;
			}
			if (lobbyCheckTimer > 0f)
			{
				lobbyCheckTimer -= Time.deltaTime;
			}
			else if (wantToSyncSeed)
			{
				wantToSyncSeed = false;
				SyncSeed();
			}
		}

		private static void SyncSeed()
		{
			if (!((Object)(object)HUDManager.Instance == (Object)null) && ((NetworkBehaviour)HUDManager.Instance).IsServer)
			{
				RandomCustomPropSounds.Instance.logger.LogInfo((object)$"Broadcasting seed {RandomCustomPropSounds.Seed} & offset {RandomCustomPropSounds.SeedOffset} to other players.");
				Networking.Broadcast(RandomCustomPropSounds.Seed + "_" + RandomCustomPropSounds.SeedOffset, "RCPS_SeedSync");
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "RandomCustomPropSounds";

		public const string PLUGIN_NAME = "RandomCustomPropSounds";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace RandomCustomPropSounds.Patches
{
	[HarmonyPatch(typeof(NoisemakerProp))]
	internal class NoisemakerPropPatch
	{
		[HarmonyPatch("ItemActivate")]
		[HarmonyPrefix]
		public static bool ItemActivate_Patch(NoisemakerProp __instance, bool used, bool buttonDown = true)
		{
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return false;
			}
			AudioClip[] array = CollectionExtensions.AddRangeToArray<AudioClip>(__instance.noiseSFX, RandomCustomPropSounds.ReplacedClips[((Object)__instance.noiseSFX[0]).name].ToArray());
			AudioClip[] array2 = CollectionExtensions.AddRangeToArray<AudioClip>(__instance.noiseSFX, RandomCustomPropSounds.ReplacedClips[((Object)__instance.noiseSFXFar[0]).name].ToArray());
			if (array.Length != array2.Length)
			{
				array2 = CollectionExtensions.AddRangeToArray<AudioClip>(__instance.noiseSFXFar, RandomCustomPropSounds.ReplacedClips[((Object)__instance.noiseSFX[0]).name].ToArray());
			}
			int num = RandomCustomPropSounds.random.Next(0, array.Length);
			float num2 = (float)RandomCustomPropSounds.random.Next((int)(__instance.minLoudness * 100f), (int)(__instance.maxLoudness * 100f)) / 100f;
			float num3 = (float)RandomCustomPropSounds.random.Next((int)(__instance.minPitch * 100f), (int)(__instance.maxPitch * 100f)) / 100f;
			RandomCustomPropSounds.SeedOffset += 3;
			RandomCustomPropSounds.Instance.logger.LogInfo((object)$"Playing {((Object)array[num]).name} with loudness: {num2} and pitch: {num3}");
			__instance.noiseAudio.pitch = num3;
			__instance.noiseAudio.PlayOneShot(array[num], num2);
			if ((Object)(object)__instance.noiseAudioFar != (Object)null)
			{
				__instance.noiseAudioFar.pitch = num3;
				__instance.noiseAudioFar.PlayOneShot(array2[num], num2);
			}
			Animator triggerAnimator = __instance.triggerAnimator;
			if (triggerAnimator != null)
			{
				triggerAnimator.SetTrigger("playAnim");
			}
			WalkieTalkie.TransmitOneShotAudio(__instance.noiseAudio, array[num], num2);
			RoundManager.Instance.PlayAudibleNoise(((Component)__instance).transform.position, __instance.noiseRange, num2, 0, ((GrabbableObject)__instance).isInElevator && StartOfRound.Instance.hangarDoorsClosed, 0);
			return false;
		}
	}
}