Decompiled source of LethalRockAndStone v1.0.2

LethalRockAndStone.dll

Decompiled 5 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using GameNetcodeStuff;
using LethalCompanyInputUtils.Api;
using Microsoft.CodeAnalysis;
using On;
using On.GameNetcodeStuff;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;

[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("LethalRockAndStone")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("LethalRockAndStone mod")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("LethalRockAndStone")]
[assembly: AssemblyTitle("LethalRockAndStone")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.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 LethalRockAndStone
{
	[BepInPlugin("LethalRockAndStone", "LethalRockAndStone", "1.0.2")]
	public class LethalRockAndStonePlugin : BaseUnityPlugin
	{
		[Serializable]
		public class CustomMessage
		{
			public string name;

			public int clipIndex;

			public ulong steamId;
		}

		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static hook_StartDisconnect <>9__17_0;

			internal void <Awake>b__17_0(orig_StartDisconnect orig, GameNetworkManager self)
			{
				orig.Invoke(self);
				MessageManager.UnregisterNamedMessageHandler("LethalRockAndStone_OnRequestBroadcast");
				MessageManager.UnregisterNamedMessageHandler("LethalRockAndStone_OnReceiveBroadcast");
			}
		}

		internal static ManualLogSource mls;

		internal static RockAndStoneBinds keys = new RockAndStoneBinds();

		internal static float VoiceVolume = 0.7f;

		internal static readonly Random random = new Random();

		internal readonly List<string> dwarfs = new List<string> { "driller", "engineer", "gunner", "scout" };

		internal string currentDwarf = "driller";

		public static Dictionary<string, List<AudioClip>> sounds = new Dictionary<string, List<AudioClip>>();

		public static Dictionary<ulong, long> lastBroadcastEnded = new Dictionary<ulong, long>();

		internal static PlayerControllerB player => GameNetworkManager.Instance.localPlayerController;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static T GetPrivateField<T>(object instance, string fieldName)
		{
			FieldInfo field = instance.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
			return (T)field.GetValue(instance);
		}

		private void Awake()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			mls = Logger.CreateLogSource("LethalRockAndStone");
			mls.LogInfo((object)"Plugin LethalRockAndStone is loaded!");
			loadAudioClips();
			VoiceVolume = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Volume", 0.7f, "Voiceline volume multiplier").Value;
			keys.RockAndStoneKey.performed += RockAndStoneKeyPerformed;
			PlayerControllerB.ConnectClientToPlayerObject += new hook_ConnectClientToPlayerObject(playerConnected);
			object obj = <>c.<>9__17_0;
			if (obj == null)
			{
				hook_StartDisconnect val = delegate(orig_StartDisconnect orig, GameNetworkManager self)
				{
					orig.Invoke(self);
					MessageManager.UnregisterNamedMessageHandler("LethalRockAndStone_OnRequestBroadcast");
					MessageManager.UnregisterNamedMessageHandler("LethalRockAndStone_OnReceiveBroadcast");
				};
				<>c.<>9__17_0 = val;
				obj = (object)val;
			}
			GameNetworkManager.StartDisconnect += (hook_StartDisconnect)obj;
		}

		public void loadAudioClips()
		{
			foreach (string dwarf in dwarfs)
			{
				sounds.Add(dwarf, new List<AudioClip>());
			}
			string[] manifestResourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames();
			foreach (string text in manifestResourceNames)
			{
				mls.LogInfo((object)("Found resource called " + text));
			}
			AssetBundle val = AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetManifestResourceNames()[0]));
			string[] allAssetNames = val.GetAllAssetNames();
			foreach (string text2 in allAssetNames)
			{
				mls.LogInfo((object)("Found asset " + text2));
				string text3 = text2.Substring(30);
				int num = text3.IndexOf("/");
				if (num >= 0)
				{
					text3 = text3.Substring(0, num);
					mls.LogInfo((object)("Dwarf: " + text3));
					if (dwarfs.Contains(text3))
					{
						sounds[text3].Add(val.LoadAsset<AudioClip>(text2));
					}
				}
			}
		}

		public bool canSendBroadcast(ulong id, long duration)
		{
			long num = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds();
			mls.LogInfo((object)$"now: {num}, last: {lastBroadcastEnded.GetValueOrDefault(id, 0L)}");
			if (num - lastBroadcastEnded.GetValueOrDefault(id, 0L) >= 0)
			{
				lastBroadcastEnded[id] = num + duration;
				mls.LogInfo((object)"returned true");
				return true;
			}
			return false;
		}

		public void RequestBroadcast(int id)
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			mls.LogInfo((object)"RequestBroadcast");
			byte[] array = SerializeToBytes(currentDwarf, id, player.playerSteamId);
			int num = array.Length;
			mls.LogInfo((object)$"IsHost: {IsHost}|IsClient: {IsClient}");
			if (IsHost)
			{
				mls.LogInfo((object)"RequestBroadcast - IsHost");
				broadcast(NetworkManager.Singleton.LocalClientId, num, array);
				return;
			}
			mls.LogInfo((object)"RequestBroadcast - !IsHost");
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num + 4, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				MessageManager.SendNamedMessage("LethalRockAndStone_OnRequestBroadcast", 0uL, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				mls.LogInfo((object)$"Error occurred requesting broadcast\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public void OnRequestBroadcast(ulong senderId, FastBufferReader reader)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			if (!IsHost)
			{
				return;
			}
			mls.LogInfo((object)$"Broadcast request received from client: {senderId}");
			if (!((FastBufferReader)(ref reader)).TryBeginRead(4))
			{
				mls.LogError((object)"client error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				mls.LogError((object)"client error: Cant begin read");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			broadcast(senderId, num, data);
		}

		public void broadcast(ulong senderId, int len, byte[] data)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			mls.LogInfo((object)"broadcast");
			CustomMessage customMessage = ParsePacket(data);
			if (!canSendBroadcast(senderId, (long)sounds[customMessage.name][customMessage.clipIndex].length * 1000))
			{
				return;
			}
			mls.LogInfo((object)"broadcast - canSendBroadcast");
			FastBufferWriter val = default(FastBufferWriter);
			foreach (ulong connectedClientsId in NetworkManager.Singleton.ConnectedClientsIds)
			{
				((FastBufferWriter)(ref val))..ctor(len + 4, (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref len, default(ForPrimitives));
					((FastBufferWriter)(ref val)).WriteBytesSafe(data, -1, 0);
					MessageManager.SendNamedMessage("LethalRockAndStone_OnReceiveBroadcast", connectedClientsId, val, (NetworkDelivery)3);
				}
				catch (Exception arg)
				{
					mls.LogInfo((object)$"Error occurred sending broadcast to client {connectedClientsId}\n{arg}");
				}
				finally
				{
					((IDisposable)(FastBufferWriter)(ref val)).Dispose();
				}
			}
			playPlayerSound(customMessage.name, customMessage.clipIndex, customMessage.steamId);
		}

		public void OnReceiveMessage(ulong _, FastBufferReader reader)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(4))
			{
				mls.LogError((object)"client error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				mls.LogError((object)"client error: Cant begin read");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			CustomMessage customMessage = ParsePacket(data);
			playPlayerSound(customMessage.name, customMessage.clipIndex, customMessage.steamId);
			mls.LogInfo((object)"Handled message");
		}

		public byte[] SerializeToBytes(string name, int index, ulong steamId)
		{
			CustomMessage graph = new CustomMessage
			{
				name = name,
				clipIndex = index,
				steamId = steamId
			};
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			binaryFormatter.Serialize(memoryStream, graph);
			return memoryStream.ToArray();
		}

		public CustomMessage ParsePacket(byte[] data)
		{
			using MemoryStream memoryStream = new MemoryStream();
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			memoryStream.Write(data, 0, data.Length);
			memoryStream.Seek(0L, SeekOrigin.Begin);
			CustomMessage result = (CustomMessage)binaryFormatter.Deserialize(memoryStream);
			mls.LogInfo((object)"parsed rock and stone");
			return result;
		}

		public void playPlayerSound(string name, int clipIndex, ulong steamIdOfSender)
		{
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			AudioClip val = sounds[name][clipIndex];
			if ((Object)(object)val == (Object)null)
			{
				mls.LogError((object)"ERROR PLAYING SOUND - AUDIO CLIP NOT FOUND");
				return;
			}
			PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts;
			foreach (PlayerControllerB val2 in allPlayerScripts)
			{
				if (val2.playerSteamId == steamIdOfSender)
				{
					val2.itemAudio.PlayOneShot(val, VoiceVolume);
					RoundManager.Instance.PlayAudibleNoise(((Component)val2).transform.position, 22f, 0.6f, 0, val2.isInHangarShipRoom && val2.playersManager.hangarDoorsClosed, 6);
					WalkieTalkie.TransmitOneShotAudio(val2.itemAudio, val, VoiceVolume);
				}
			}
		}

		public void playerConnected(orig_ConnectClientToPlayerObject orig, PlayerControllerB self)
		{
			//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			orig.Invoke(self);
			if (IsHost)
			{
				MessageManager.RegisterNamedMessageHandler("LethalRockAndStone_OnRequestBroadcast", new HandleNamedMessageDelegate(OnRequestBroadcast));
				currentDwarf = dwarfs[random.Next(dwarfs.Count)];
				mls.LogInfo((object)("Chose dwarf " + currentDwarf));
			}
			else
			{
				currentDwarf = dwarfs[random.Next(dwarfs.Count)];
				mls.LogInfo((object)("Chose dwarf " + currentDwarf));
				MessageManager.RegisterNamedMessageHandler("LethalRockAndStone_OnReceiveBroadcast", new HandleNamedMessageDelegate(OnReceiveMessage));
			}
		}

		public void RockAndStoneKeyPerformed(CallbackContext obj)
		{
			if (((CallbackContext)(ref obj)).performed)
			{
				mls.LogInfo((object)"onKey");
				if (!player.isTypingChat && !player.inTerminalMenu && !player.isPlayerDead)
				{
					RequestBroadcast(GetRandomClipIndex());
				}
			}
		}

		public int GetRandomClipIndex()
		{
			List<AudioClip> list = sounds[currentDwarf];
			return random.Next(list.Count);
		}
	}
	public class RockAndStoneBinds : LcInputActions
	{
		[InputAction("<Keyboard>/v", Name = "RockAndStone")]
		public InputAction RockAndStoneKey { get; set; }
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "LethalRockAndStone";

		public const string PLUGIN_NAME = "LethalRockAndStone";

		public const string PLUGIN_VERSION = "1.0.2";
	}
}