Decompiled source of DugliEdition v1.0.0

BepInEx/plugins/DugliEdition/DugliEdition.dll

Decompiled 5 hours 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 System.Security;
using System.Security.Permissions;
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.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("Maxim")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DugliEdition")]
[assembly: AssemblyTitle("DugliEdition")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 DugliEdition
{
	[BepInPlugin("Maxim.DugliEdition", "DugliEdition", "1.0")]
	public class DugliEdition : BaseUnityPlugin
	{
		private readonly List<AudioClip> _voiceClips = new List<AudioClip>();

		private readonly List<string> _voiceNames = new List<string>();

		private AudioSource? _audioSource;

		private bool _voicesReady;

		private int _lastVoiceIndex = -1;

		private float _lastPickupVoiceTime = -100f;

		private const byte VoiceEventCode = 196;

		private const float PickupVoiceCooldown = 5f;

		private const float DefaultPickupChance = 35f;

		private ConfigEntry<float>? _pickupChance;

		internal static DugliEdition Instance { get; private set; }

		internal static ManualLogSource Logger => Instance._logger;

		private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger;

		internal Harmony? Harmony { get; set; }

		private void Awake()
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			Instance = this;
			((Component)this).transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			_audioSource = ((Component)this).gameObject.AddComponent<AudioSource>();
			_audioSource.playOnAwake = false;
			_audioSource.spatialBlend = 0f;
			_audioSource.volume = 1f;
			_pickupChance = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "PickupVoiceChancePercent", 35f, new ConfigDescription("Chance (0-100%) that picking up an object triggers a voice line.", (AcceptableValueBase)null, Array.Empty<object>()));
			PhotonNetwork.NetworkingClient.EventReceived += OnPhotonEvent;
			Patch();
			((MonoBehaviour)this).StartCoroutine(LoadVoiceLibrary());
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!");
		}

		private IEnumerator LoadVoiceLibrary()
		{
			string soundsPath = Path.Combine(Paths.PluginPath, "DugliEdition", "Sounds");
			if (!Directory.Exists(soundsPath))
			{
				Logger.LogWarning((object)("Voice folder not found: " + soundsPath));
				yield break;
			}
			string[] files = Directory.GetFiles(soundsPath, "*.wav", SearchOption.TopDirectoryOnly);
			Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
			if (files.Length == 0)
			{
				Logger.LogWarning((object)("No WAV voice files found in: " + soundsPath));
				yield break;
			}
			string[] array = files;
			foreach (string file in array)
			{
				string uri = new Uri(file).AbsoluteUri;
				UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(uri, (AudioType)20);
				try
				{
					yield return request.SendWebRequest();
					if ((int)request.result != 1)
					{
						Logger.LogError((object)("Could not load voice '" + Path.GetFileName(file) + "': " + request.error));
						continue;
					}
					AudioClip clip = DownloadHandlerAudioClip.GetContent(request);
					if ((Object)(object)clip == (Object)null)
					{
						Logger.LogError((object)("Voice decoded as null: " + Path.GetFileName(file)));
						continue;
					}
					_voiceClips.Add(clip);
					_voiceNames.Add(Path.GetFileNameWithoutExtension(file));
					Logger.LogInfo((object)("Voice loaded: " + Path.GetFileName(file)));
				}
				finally
				{
					((IDisposable)request)?.Dispose();
				}
			}
			_voicesReady = _voiceClips.Count > 0;
			Logger.LogInfo((object)(_voicesReady ? $"Voice library ready: {_voiceClips.Count} phrase(s). Press F6 for a random phrase." : "Voice library is empty; add WAV files to BepInEx/plugins/DugliEdition/Sounds."));
		}

		internal void Patch()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0026: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				Harmony val2 = val;
				Harmony = val;
			}
			Harmony.PatchAll();
		}

		internal void Unpatch()
		{
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
			if (Input.GetKeyDown((KeyCode)287))
			{
				PlayRandomVoice("F6", syncToOthers: true);
			}
		}

		internal void OnLocalPickup()
		{
			if (!(Time.unscaledTime - _lastPickupVoiceTime < 5f))
			{
				float num = Mathf.Clamp(_pickupChance?.Value ?? 35f, 0f, 100f);
				if (!(Random.value * 100f >= num))
				{
					_lastPickupVoiceTime = Time.unscaledTime;
					PlayRandomVoice("local pickup", syncToOthers: true);
				}
			}
		}

		private void PlayRandomVoice(string reason, bool syncToOthers)
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Expected O, but got Unknown
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			if (!_voicesReady || (Object)(object)_audioSource == (Object)null || _voiceClips.Count == 0)
			{
				Logger.LogWarning((object)"Voice library is not ready yet or contains no valid WAV files.");
				return;
			}
			int num = Random.Range(0, _voiceClips.Count);
			if (_voiceClips.Count > 1 && num == _lastVoiceIndex)
			{
				num = (num + 1) % _voiceClips.Count;
			}
			_lastVoiceIndex = num;
			PlayVoiceByIndex(num, reason);
			if (!syncToOthers || !PhotonNetwork.InRoom)
			{
				return;
			}
			try
			{
				RaiseEventOptions val = new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				};
				PhotonNetwork.RaiseEvent((byte)196, (object)num, val, SendOptions.SendReliable);
			}
			catch (Exception ex)
			{
				Logger.LogError((object)("Could not sync voice over Photon: " + ex.Message));
			}
		}

		private void OnPhotonEvent(EventData photonEvent)
		{
			if (photonEvent.Code == 196 && photonEvent.CustomData is int index)
			{
				PlayVoiceByIndex(index, "multiplayer event");
			}
		}

		private void PlayVoiceByIndex(int index, string reason)
		{
			if (!_voicesReady || (Object)(object)_audioSource == (Object)null || index < 0 || index >= _voiceClips.Count)
			{
				Logger.LogWarning((object)$"Received voice index {index}, but the local voice library is not ready or does not match.");
				return;
			}
			_lastVoiceIndex = index;
			_audioSource.PlayOneShot(_voiceClips[index]);
			Logger.LogInfo((object)("Playing voice: " + _voiceNames[index] + " (" + reason + ")."));
		}

		private void OnDestroy()
		{
			if (PhotonNetwork.NetworkingClient != null)
			{
				PhotonNetwork.NetworkingClient.EventReceived -= OnPhotonEvent;
			}
		}
	}
	[HarmonyPatch(typeof(PhysGrabObject), "GrabStarted")]
	internal static class DugliPickupPatch
	{
		[HarmonyPostfix]
		private static void Postfix(PhysGrabObject __instance)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null || __instance.playerGrabbing == null)
				{
					return;
				}
				bool flag = default(bool);
				foreach (PhysGrabber item in __instance.playerGrabbing)
				{
					if ((Object)(object)item == (Object)null || (Object)(object)item.playerAvatar == (Object)null)
					{
						continue;
					}
					FieldInfo fieldInfo = AccessTools.Field(typeof(PlayerAvatar), "isLocal");
					int num;
					if (fieldInfo != null)
					{
						object value = fieldInfo.GetValue(item.playerAvatar);
						if (value is bool)
						{
							flag = (bool)value;
							num = 1;
						}
						else
						{
							num = 0;
						}
					}
					else
					{
						num = 0;
					}
					if (((uint)num & (flag ? 1u : 0u)) == 0)
					{
						continue;
					}
					DugliEdition.Instance?.OnLocalPickup();
					break;
				}
			}
			catch (Exception arg)
			{
				DugliEdition.Logger.LogError((object)$"Pickup voice patch failed: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(PlayerController))]
	internal static class ExamplePlayerControllerPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("Start")]
		private static void Start_Prefix(PlayerController __instance)
		{
			DugliEdition.Logger.LogDebug((object)$"{__instance} Start Prefix");
		}

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void Start_Postfix(PlayerController __instance)
		{
			DugliEdition.Logger.LogDebug((object)$"{__instance} Start Postfix");
		}
	}
}