Decompiled source of RussianMemeMonsterSounds v1.4.1

BepInEx/plugins/RussianMemeMonsterSounds/RussianMemeMonsterSounds.dll

Decompiled 31 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using Newtonsoft.Json;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.Networking;

[assembly: AssemblyTitle("RussianMemeMonsterSounds")]
[assembly: AssemblyDescription("Русские мемы | Звуки мобов — R.E.P.O. monster voices")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("1.4.0.0")]
namespace RussianMemeMonsterSounds;

public sealed class MemeVoiceActor : MonoBehaviour
{
	private static readonly FieldInfo SpawnedField = AccessTools.Field(typeof(EnemyParent), "Spawned");

	private static readonly FieldInfo DeadField = AccessTools.Field(typeof(EnemyHealth), "dead");

	internal readonly List<Sound> Bindings = new List<Sound>();

	internal MonsterRuntime Runtime;

	private readonly Dictionary<string, int> previousPicks = new Dictionary<string, int>();

	private Plugin plugin;

	private Enemy enemy;

	private EnemyParent enemyParent;

	private EnemyHealth health;

	private PhotonView networkView;

	private AudioSource voice;

	private GameObject voiceObject;

	private Random random;

	private float nextRandom;

	private float busyUntil;

	private float ambientAllowedAt;

	private int priority = -1;

	private bool wasPresent;

	private bool wasAggro;

	private bool wasPlaying;

	private bool listenerPaused;

	private AudioClip currentClip;

	private string currentCategory;

	private int currentStart;

	private int lastTriggerFrame = -1;

	internal bool Available
	{
		get
		{
			if (Runtime != null && Runtime.Enabled.Value && (Object)(object)voice != (Object)null && ((Behaviour)this).isActiveAndEnabled)
			{
				return ((Component)this).gameObject.activeInHierarchy;
			}
			return false;
		}
	}

	internal int ViewId
	{
		get
		{
			if (!((Object)(object)networkView != (Object)null))
			{
				return 0;
			}
			return networkView.ViewID;
		}
	}

	internal bool Present
	{
		get
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Invalid comparison between Unknown and I4
			if (!Available)
			{
				return false;
			}
			if ((Object)(object)enemyParent != (Object)null && SpawnedField != null && !(bool)SpawnedField.GetValue(enemyParent))
			{
				return false;
			}
			if ((Object)(object)health != (Object)null && DeadField != null && (bool)DeadField.GetValue(health))
			{
				return false;
			}
			if (!((Object)(object)enemy == (Object)null))
			{
				return (int)enemy.CurrentState != 11;
			}
			return true;
		}
	}

	internal void Initialize(Plugin owner, Enemy target, MonsterRuntime runtime)
	{
		plugin = owner;
		enemy = target;
		networkView = ((Component)enemy).GetComponent<PhotonView>();
		Runtime = runtime;
		random = new Random(Guid.NewGuid().GetHashCode());
		enemyParent = ((Component)enemy).GetComponentInParent<EnemyParent>();
		health = ((Component)enemy).GetComponentInChildren<EnemyHealth>(true);
		CreateVoice(((Object)(object)enemy.CenterTransform != (Object)null) ? enemy.CenterTransform : ((Component)enemy).transform);
	}

	internal void InitializeObject(Plugin owner, MonsterRuntime runtime, MonoBehaviour[] components)
	{
		plugin = owner;
		Runtime = runtime;
		random = new Random(Guid.NewGuid().GetHashCode());
		networkView = ((Component)this).GetComponent<PhotonView>();
		Transform anchor = ((Component)this).transform;
		if (!string.IsNullOrEmpty(runtime.Definition.voice_anchor))
		{
			foreach (MonoBehaviour val in components)
			{
				if (!((Object)(object)val == (Object)null))
				{
					FieldInfo fieldInfo = AccessTools.Field(((object)val).GetType(), runtime.Definition.voice_anchor);
					Transform val2 = (Transform)((fieldInfo == null) ? null : /*isinst with value type is only supported in some contexts*/);
					if ((Object)(object)val2 != (Object)null)
					{
						anchor = val2;
						break;
					}
				}
			}
		}
		CreateVoice(anchor);
	}

	private void CreateVoice(Transform anchor)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0010: Expected O, but got Unknown
		voiceObject = new GameObject("RussianMemesVoice");
		voiceObject.transform.SetParent(anchor, false);
		voice = voiceObject.AddComponent<AudioSource>();
		voice.playOnAwake = false;
		voice.loop = false;
		voice.spatialBlend = 1f;
		voice.rolloffMode = (AudioRolloffMode)1;
		voice.dopplerLevel = 0f;
		voice.priority = 160;
		ScheduleRandom();
	}

	private void Update()
	{
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Invalid comparison between Unknown and I4
		//IL_0154: Unknown result type (might be due to invalid IL or missing references)
		//IL_015a: Invalid comparison between Unknown and I4
		//IL_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_0168: Invalid comparison between Unknown and I4
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Invalid comparison between Unknown and I4
		//IL_0266: Unknown result type (might be due to invalid IL or missing references)
		//IL_026d: Invalid comparison between Unknown and I4
		if ((Object)(object)plugin == (Object)null || Runtime == null)
		{
			return;
		}
		if (!plugin.Ready || !plugin.ModEnabled.Value || !Present)
		{
			if (wasPresent)
			{
				plugin.Network.Stop(this);
			}
			StopVoice();
			if (wasPresent)
			{
				plugin.ResetLoops(this);
			}
			wasPresent = false;
			wasAggro = false;
			return;
		}
		ConfigureAudio(null);
		if (AudioListener.pause)
		{
			listenerPaused = true;
			return;
		}
		if (listenerPaused)
		{
			listenerPaused = false;
			if ((Object)(object)currentClip != (Object)null)
			{
				PlaySelected(currentClip, currentCategory, currentStart);
			}
		}
		if (wasPlaying && !voice.isPlaying && Time.time >= busyUntil)
		{
			wasPlaying = false;
			priority = -1;
			ambientAllowedAt = Time.time + plugin.AmbientGap.Value;
			ScheduleRandom();
		}
		if (!wasPresent)
		{
			wasPresent = true;
			ScheduleRandom();
		}
		bool flag = (Object)(object)enemy != (Object)null && ((int)enemy.CurrentState == 3 || (int)enemy.CurrentState == 4 || (int)enemy.CurrentState == 5);
		if (plugin.Network.IsAuthority && flag && !wasAggro && plugin.ReplaceActions.Value && Runtime.GetPool("notice").Count > 0)
		{
			Trigger("notice", null, timedRandom: false);
		}
		wasAggro = flag;
		if (plugin.Network.IsAuthority && (!plugin.Network.Online || ViewId > 0) && plugin.RandomEnabled.Value && Runtime.RandomEnabled.Value && Runtime.Pools["random"].Count > 0 && (Object)(object)enemy != (Object)null && (int)enemy.CurrentState != 1 && (int)enemy.CurrentState != 9 && !voice.isPlaying && Time.time >= busyUntil && Time.time >= nextRandom)
		{
			Trigger("random", null, timedRandom: true);
		}
	}

	internal AudioSource Trigger(string category, Sound original, bool timedRandom)
	{
		if (!Available || !Present)
		{
			return null;
		}
		if (!plugin.Network.IsAuthority)
		{
			return voice;
		}
		List<AudioClip> pool = Runtime.GetPool(category);
		if (pool.Count == 0)
		{
			return null;
		}
		int num = category switch
		{
			"notice" => 1, 
			"attack" => 2, 
			"hurt" => 3, 
			_ => 0, 
		};
		bool flag = voice.isPlaying || Time.time < busyUntil;
		bool flag2 = Runtime.Definition.restart_on_attack && category == "attack" && num == priority && lastTriggerFrame != Time.frameCount;
		if (flag && num <= priority && !flag2)
		{
			return voice;
		}
		if (!flag && num == 0 && Time.time < ambientAllowedAt)
		{
			return voice;
		}
		int num2;
		if (pool.Count > 1 && previousPicks.TryGetValue(category, out var value))
		{
			num2 = random.Next(0, pool.Count - 1);
			if (num2 >= value)
			{
				num2++;
			}
		}
		else
		{
			num2 = random.Next(0, pool.Count);
		}
		previousPicks[category] = num2;
		AudioClip clip = pool[num2];
		ConfigureAudio(original);
		if (!plugin.Network.Publish(this, clip, category))
		{
			return null;
		}
		lastTriggerFrame = Time.frameCount;
		return voice;
	}

	internal void PlaySelected(AudioClip clip, string category, int startTimestamp)
	{
		StopVoice();
		int timestamp = plugin.Network.Timestamp;
		int num = VoiceProtocol.SampleOffset(timestamp, startTimestamp, clip.frequency, clip.samples);
		if (num < clip.samples)
		{
			double num2 = VoiceProtocol.ElapsedSeconds(timestamp, startTimestamp);
			voice.Stop();
			ConfigureAudio(null);
			voice.clip = clip;
			currentClip = clip;
			currentCategory = category;
			currentStart = startTimestamp;
			voice.pitch = 1f;
			voice.loop = false;
			voice.timeSamples = num;
			if (num2 < 0.0)
			{
				voice.PlayScheduled(AudioSettings.dspTime - num2);
			}
			else
			{
				voice.Play();
			}
			priority = category switch
			{
				"notice" => 1, 
				"attack" => 2, 
				"hurt" => 3, 
				_ => 0, 
			};
			busyUntil = Time.time + Mathf.Max(0f, (float)(0.0 - num2)) + (float)(clip.samples - num) / (float)clip.frequency;
			ambientAllowedAt = busyUntil + plugin.AmbientGap.Value;
			wasPlaying = true;
			nextRandom = busyUntil + RandomDelay();
			plugin.LogPick(Runtime.Definition.id, category + " @ " + startTimestamp, clip);
		}
	}

	private void ConfigureAudio(Sound original)
	{
		voice.volume = Mathf.Clamp(plugin.Volume.Value * Runtime.Volume.Value, 0f, 1f);
		voice.minDistance = plugin.MinDistance.Value;
		voice.maxDistance = Mathf.Max(voice.minDistance + 0.1f, plugin.MaxDistance.Value);
		AudioSource val = original?.Source;
		if ((Object)(object)val == (Object)null && (Object)(object)AudioManager.instance != (Object)null && (Object)(object)AudioManager.instance.AudioDefault != (Object)null)
		{
			val = AudioManager.instance.AudioDefault.GetComponent<AudioSource>();
		}
		if ((Object)(object)val != (Object)null && (Object)(object)val.outputAudioMixerGroup != (Object)null)
		{
			voice.outputAudioMixerGroup = val.outputAudioMixerGroup;
		}
		else if ((Object)(object)AudioManager.instance != (Object)null)
		{
			voice.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
	}

	private float RandomDelay()
	{
		float num = Mathf.Min(plugin.RandomMin.Value, plugin.RandomMax.Value);
		float num2 = Mathf.Max(plugin.RandomMin.Value, plugin.RandomMax.Value);
		num = Mathf.Max(1f, num);
		num2 = Mathf.Max(1f, num2);
		return num + (num2 - num) * (float)random.NextDouble();
	}

	private void ScheduleRandom()
	{
		nextRandom = Time.time + RandomDelay();
	}

	private void StopVoice()
	{
		if ((Object)(object)voice != (Object)null)
		{
			voice.Stop();
		}
		busyUntil = 0f;
		priority = -1;
		wasPlaying = false;
		currentClip = null;
	}

	internal void StopNetworkVoice()
	{
		StopVoice();
		if ((Object)(object)plugin != (Object)null)
		{
			plugin.ResetLoops(this);
		}
		wasPresent = false;
		wasAggro = false;
		ScheduleRandom();
	}

	private void OnDisable()
	{
		if ((Object)(object)plugin != (Object)null && plugin.Network != null)
		{
			plugin.Network.Stop(this);
		}
		StopVoice();
		if ((Object)(object)plugin != (Object)null)
		{
			plugin.ResetLoops(this);
		}
		wasPresent = false;
		wasAggro = false;
	}

	private void OnDestroy()
	{
		if ((Object)(object)plugin != (Object)null)
		{
			plugin.Unregister(this);
		}
		if ((Object)(object)voiceObject != (Object)null)
		{
			Object.Destroy((Object)(object)voiceObject);
		}
	}
}
internal sealed class NetworkVoiceSync : IOnEventCallback, IDisposable
{
	private sealed class PendingVoice
	{
		internal VoiceCommand Command;

		internal float ReceivedAt;
	}

	private readonly Plugin plugin;

	private readonly VoiceSequenceTracker received = new VoiceSequenceTracker();

	private readonly Dictionary<int, PendingVoice> pending = new Dictionary<int, PendingVoice>();

	private readonly Dictionary<int, VoiceCommand> active = new Dictionary<int, VoiceCommand>();

	private readonly List<object[]> beforeState = new List<object[]>();

	private readonly HashSet<string> enabledMonsters = new HashSet<string>(StringComparer.Ordinal);

	private object room;

	private int masterId;

	private int session;

	private int remoteSession;

	private int sequence;

	private int remoteFlags;

	private bool authorityKnown;

	private bool warnedMismatch;

	private bool warnedMissingHost;

	private float nextHandshake;

	private float joinedAt;

	private string lastSettings;

	internal bool Online
	{
		get
		{
			if (PhotonNetwork.InRoom)
			{
				return !PhotonNetwork.OfflineMode;
			}
			return false;
		}
	}

	internal bool IsAuthority => VoiceProtocol.IsAuthority(PhotonNetwork.InRoom, PhotonNetwork.OfflineMode, PhotonNetwork.IsMasterClient);

	internal int Timestamp
	{
		get
		{
			if (!Online)
			{
				return (int)(Time.realtimeSinceStartupAsDouble * 1000.0);
			}
			return PhotonNetwork.ServerTimestamp;
		}
	}

	private int Flags => (plugin.ModEnabled.Value ? 1 : 0) | (plugin.ReplaceAmbient.Value ? 2 : 0) | (plugin.ReplaceActions.Value ? 4 : 0);

	internal NetworkVoiceSync(Plugin owner)
	{
		plugin = owner;
		PhotonNetwork.AddCallbackTarget((object)this);
	}

	internal bool CanReplace(MemeVoiceActor actor, string category)
	{
		if (Online && actor.ViewId <= 0)
		{
			return false;
		}
		if (IsAuthority)
		{
			if (!(category == "random"))
			{
				return plugin.ReplaceActions.Value;
			}
			return plugin.ReplaceAmbient.Value;
		}
		if (authorityKnown && enabledMonsters.Contains(actor.Runtime.Definition.id) && (remoteFlags & 1) != 0)
		{
			return (remoteFlags & ((category == "random") ? 2 : 4)) != 0;
		}
		return false;
	}

	internal void Tick()
	{
		RefreshContext();
		if (!plugin.Ready || !Online)
		{
			return;
		}
		if (IsAuthority)
		{
			KeyValuePair<int, VoiceCommand>[] array = active.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<int, VoiceCommand> keyValuePair = array[i];
				if (!plugin.TryClip(keyValuePair.Value.ClipKey, out var clip) || VoiceProtocol.ElapsedSeconds(Timestamp, keyValuePair.Value.StartTimestamp) >= (double)clip.length)
				{
					active.Remove(keyValuePair.Key);
				}
			}
			string text = SettingsKey();
			if (Time.realtimeSinceStartup >= nextHandshake || text != lastSettings)
			{
				SendState(null);
				nextHandshake = Time.realtimeSinceStartup + 3f;
				lastSettings = text;
			}
		}
		else if (Time.realtimeSinceStartup >= nextHandshake)
		{
			SendHello();
			nextHandshake = Time.realtimeSinceStartup + (authorityKnown ? 10f : 3f);
			if (!authorityKnown && !warnedMissingHost && Time.realtimeSinceStartup - joinedAt > 10f)
			{
				warnedMissingHost = true;
				plugin.NetworkWarning("The lobby host must install the same sound mod version and pack. Using original sounds until the host is ready.");
			}
		}
		KeyValuePair<int, PendingVoice>[] array2 = pending.ToArray();
		for (int j = 0; j < array2.Length; j++)
		{
			KeyValuePair<int, PendingVoice> keyValuePair2 = array2[j];
			PendingVoice value = keyValuePair2.Value;
			if (Time.realtimeSinceStartup - value.ReceivedAt > 5f || Apply(value.Command))
			{
				pending.Remove(keyValuePair2.Key);
			}
		}
	}

	private void RefreshContext()
	{
		object objA = (Online ? PhotonNetwork.CurrentRoom : null);
		int num = ((Online && PhotonNetwork.MasterClient != null) ? PhotonNetwork.MasterClient.ActorNumber : 0);
		if (!object.ReferenceEquals(objA, room) || num != masterId)
		{
			room = objA;
			masterId = num;
			session = NewSession();
			sequence = 0;
			remoteSession = 0;
			remoteFlags = 0;
			authorityKnown = false;
			warnedMismatch = false;
			warnedMissingHost = false;
			lastSettings = null;
			nextHandshake = 0f;
			joinedAt = Time.realtimeSinceStartup;
			ResetRemoteState();
			plugin.ResetNetworkVoices();
			if (Online)
			{
				plugin.NetworkInfo(IsAuthority ? "Host selects and synchronizes all monster lines." : "Waiting for the host's synchronized sound pack.");
			}
		}
	}

	private static int NewSession()
	{
		return (Guid.NewGuid().GetHashCode() & 0x7FFFFFFF) | 1;
	}

	private string[] EnabledIds()
	{
		return plugin.EnabledMonsterIds().OrderBy<string, string>((string id) => id, StringComparer.Ordinal).ToArray();
	}

	private string SettingsKey()
	{
		return Flags + ":" + string.Join(",", EnabledIds());
	}

	private void SendHello()
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected O, but got Unknown
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		if (Online && !IsAuthority && plugin.Ready)
		{
			object[] data = new object[5]
			{
				"fraer.russianmememonstersounds/voice",
				1,
				(byte)0,
				0,
				plugin.PackFingerprint
			};
			RaiseEventOptions val = new RaiseEventOptions();
			val.Receivers = (ReceiverGroup)2;
			Send(data, val);
		}
	}

	private void SendState(int[] targets)
	{
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Expected O, but got Unknown
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_005f: Expected O, but got Unknown
		object[] data = new object[7]
		{
			"fraer.russianmememonstersounds/voice",
			1,
			(byte)1,
			session,
			plugin.PackFingerprint,
			Flags,
			EnabledIds()
		};
		RaiseEventOptions options;
		if (targets != null)
		{
			RaiseEventOptions val = new RaiseEventOptions();
			val.TargetActors = targets;
			options = val;
		}
		else
		{
			RaiseEventOptions val2 = new RaiseEventOptions();
			val2.Receivers = (ReceiverGroup)0;
			options = val2;
		}
		Send(data, options);
	}

	private bool Send(object[] data, RaiseEventOptions options)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		return PhotonNetwork.RaiseEvent((byte)188, (object)data, options, SendOptions.SendReliable);
	}

	internal bool Publish(MemeVoiceActor actor, AudioClip clip, string category)
	{
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: Expected O, but got Unknown
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		RefreshContext();
		if (!IsAuthority)
		{
			return false;
		}
		if (!Online)
		{
			actor.PlaySelected(clip, category, Timestamp);
			return true;
		}
		if (actor.ViewId <= 0)
		{
			return false;
		}
		VoiceCommand voiceCommand = new VoiceCommand();
		voiceCommand.ViewId = actor.ViewId;
		voiceCommand.MonsterId = actor.Runtime.Definition.id;
		voiceCommand.ClipKey = ((Object)clip).name;
		voiceCommand.Category = category;
		voiceCommand.Sequence = ++sequence;
		voiceCommand.StartTimestamp = Timestamp + (int)(plugin.NetworkDelay.Value * 1000f);
		VoiceCommand voiceCommand2 = voiceCommand;
		object[] data = VoiceProtocol.Encode(voiceCommand2, session, plugin.PackFingerprint);
		RaiseEventOptions val = new RaiseEventOptions();
		val.Receivers = (ReceiverGroup)0;
		if (!Send(data, val))
		{
			plugin.NetworkWarning("Could not send synchronized voice event; keeping the original game sound.");
			return false;
		}
		active[voiceCommand2.ViewId] = voiceCommand2;
		actor.PlaySelected(clip, category, voiceCommand2.StartTimestamp);
		return true;
	}

	internal void Stop(MemeVoiceActor actor)
	{
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b5: Expected O, but got Unknown
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		if (Online && IsAuthority && actor.ViewId > 0 && active.Remove(actor.ViewId))
		{
			VoiceCommand voiceCommand = new VoiceCommand();
			voiceCommand.ViewId = actor.ViewId;
			voiceCommand.MonsterId = actor.Runtime.Definition.id;
			voiceCommand.ClipKey = "";
			voiceCommand.Category = "";
			voiceCommand.Stop = true;
			voiceCommand.Sequence = ++sequence;
			voiceCommand.StartTimestamp = Timestamp;
			VoiceCommand command = voiceCommand;
			object[] data = VoiceProtocol.Encode(command, session, plugin.PackFingerprint);
			RaiseEventOptions val = new RaiseEventOptions();
			val.Receivers = (ReceiverGroup)0;
			Send(data, val);
		}
	}

	internal void Forget(MemeVoiceActor actor)
	{
		Stop(actor);
		if (actor.ViewId > 0)
		{
			pending.Remove(actor.ViewId);
		}
	}

	public void OnEvent(EventData photonEvent)
	{
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c6: Expected O, but got Unknown
		if (photonEvent.Code != 188 || !Online || !plugin.Ready)
		{
			return;
		}
		RefreshContext();
		if (!VoiceProtocol.TryHeader(photonEvent.CustomData, out var data, out var kind, out var num, out var pack))
		{
			return;
		}
		if (kind == 0)
		{
			if (!IsAuthority || photonEvent.Sender <= 0)
			{
				return;
			}
			int[] array = new int[1] { photonEvent.Sender };
			SendState(array);
			if (pack == plugin.PackFingerprint)
			{
				VoiceCommand[] array2 = active.Values.ToArray();
				foreach (VoiceCommand command in array2)
				{
					object[] data2 = VoiceProtocol.Encode(command, session, plugin.PackFingerprint);
					RaiseEventOptions val = new RaiseEventOptions();
					val.TargetActors = array;
					Send(data2, val);
				}
			}
		}
		else
		{
			if (!VoiceProtocol.AuthorizedSender(photonEvent.Sender, masterId, IsAuthority))
			{
				return;
			}
			if (pack != plugin.PackFingerprint)
			{
				if (!warnedMismatch)
				{
					plugin.NetworkWarning("Sound pack differs from the lobby host. Install the same mod version and audio files on every computer.");
				}
				warnedMismatch = true;
				authorityKnown = false;
				ResetRemoteState();
				plugin.ResetNetworkVoices();
			}
			else if (kind == 1)
			{
				if (data.Length != 7 || !(data[5] is int) || !(data[6] is IEnumerable enumerable) || data[6] is string)
				{
					return;
				}
				HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
				foreach (object item in enumerable)
				{
					if (!(item is string) || hashSet.Count >= 128)
					{
						return;
					}
					hashSet.Add((string)item);
				}
				if (remoteSession != num)
				{
					received.Clear();
					pending.Clear();
					plugin.ResetNetworkVoices();
					remoteSession = num;
				}
				remoteFlags = (int)data[5];
				enabledMonsters.Clear();
				enabledMonsters.UnionWith(hashSet);
				if (!authorityKnown)
				{
					plugin.NetworkInfo("Synchronized with host " + masterId + "; matching sound pack " + pack.Substring(0, 12) + ".");
				}
				authorityKnown = true;
				if ((remoteFlags & 1) == 0)
				{
					plugin.ResetNetworkVoices();
				}
				object[][] array3 = beforeState.ToArray();
				beforeState.Clear();
				object[][] array4 = array3;
				foreach (object[] data3 in array4)
				{
					ReceiveCommand(data3);
				}
			}
			else if (!authorityKnown || remoteSession != num)
			{
				if (beforeState.Count < 32)
				{
					beforeState.Add(data);
				}
				SendHello();
			}
			else
			{
				ReceiveCommand(data);
			}
		}
	}

	private void ReceiveCommand(object[] data)
	{
		if (!VoiceProtocol.TryCommand(data, out var command, out var num, out var pack) || num != remoteSession || pack != plugin.PackFingerprint || !received.Accept(command.ViewId, command.Sequence))
		{
			return;
		}
		if (!Apply(command))
		{
			if (pending.Count < 128 || pending.ContainsKey(command.ViewId))
			{
				pending[command.ViewId] = new PendingVoice
				{
					Command = command,
					ReceivedAt = Time.realtimeSinceStartup
				};
			}
		}
		else
		{
			pending.Remove(command.ViewId);
		}
	}

	private bool Apply(VoiceCommand command)
	{
		PhotonView val = PhotonView.Find(command.ViewId);
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		MemeVoiceActor memeVoiceActor = plugin.ResolveNetworkActor(val, command.MonsterId);
		if ((Object)(object)memeVoiceActor == (Object)null)
		{
			return false;
		}
		if (command.Stop)
		{
			memeVoiceActor.StopNetworkVoice();
			return true;
		}
		if (!authorityKnown || (remoteFlags & 1) == 0 || !enabledMonsters.Contains(command.MonsterId))
		{
			return true;
		}
		if (!plugin.ModEnabled.Value || !memeVoiceActor.Runtime.Enabled.Value)
		{
			return true;
		}
		if (!memeVoiceActor.Present)
		{
			return false;
		}
		if (!plugin.TryClip(command.ClipKey, out var clip))
		{
			return true;
		}
		memeVoiceActor.PlaySelected(clip, command.Category, command.StartTimestamp);
		return true;
	}

	private void ResetRemoteState()
	{
		received.Clear();
		pending.Clear();
		active.Clear();
		beforeState.Clear();
		enabledMonsters.Clear();
	}

	public void Dispose()
	{
		PhotonNetwork.RemoveCallbackTarget((object)this);
		ResetRemoteState();
	}
}
[Serializable]
public sealed class PackDefinition
{
	public int schema_version;

	public MonsterDefinition[] monsters;
}
[Serializable]
public sealed class MonsterDefinition
{
	public string id;

	public string name_ru;

	public string game_name;

	public string[] enemy_components;

	public string[] object_components;

	public string voice_anchor;

	public bool restart_on_attack;

	public SoundRule[] rules;
}
[Serializable]
public sealed class SoundRule
{
	public string component;

	public string category;

	public string[] fields;
}
[HarmonyPatch(typeof(Enemy), "Start")]
internal static class EnemyStartPatch
{
	private static void Postfix(Enemy __instance)
	{
		if ((Object)(object)Plugin.Instance != (Object)null)
		{
			Plugin.Instance.Register(__instance);
		}
	}
}
[HarmonyPatch]
internal static class ObjectStartPatch
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		yield return AccessTools.Method(typeof(ShopKeeper), "Start", (Type[])null, (Type[])null);
		yield return AccessTools.Method(typeof(ItemGun), "Start", (Type[])null, (Type[])null);
	}

	private static void Postfix(MonoBehaviour __instance)
	{
		if ((Object)(object)Plugin.Instance != (Object)null)
		{
			Plugin.Instance.RegisterObject(__instance);
		}
	}
}
[HarmonyPatch]
internal static class SoundPlayPatch
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		try
		{
			MethodInfo[] methods = typeof(Sound).GetMethods(BindingFlags.Instance | BindingFlags.Public);
			foreach (MethodInfo method in methods)
			{
				if (method.Name == "Play" && method.ReturnType == typeof(AudioSource))
				{
					yield return method;
				}
			}
		}
		finally
		{
		}
	}

	private static bool Prefix(Sound __instance, ref AudioSource __result)
	{
		if ((Object)(object)Plugin.Instance == (Object)null || !Plugin.Instance.HandleOneShot(__instance, out var source))
		{
			return true;
		}
		__result = source;
		return false;
	}
}
[HarmonyPatch(typeof(Sound), "PlayLoop")]
internal static class SoundLoopPatch
{
	private static void Prefix(Sound __instance, bool playing, ref float volumeMultiplier)
	{
		if ((Object)(object)Plugin.Instance != (Object)null && Plugin.Instance.HandleLoop(__instance, playing))
		{
			volumeMultiplier = 0f;
		}
	}
}
[BepInPlugin("fraer.russianmememonstersounds", "Русские мемы | Звуки мобов", "1.4.0")]
public sealed class Plugin : BaseUnityPlugin
{
	public const string Guid = "fraer.russianmememonstersounds";

	public const string Version = "1.4.0";

	internal static Plugin Instance;

	internal bool Ready;

	internal NetworkVoiceSync Network;

	internal string PackFingerprint = "";

	internal ConfigEntry<bool> ModEnabled;

	internal ConfigEntry<bool> ReplaceActions;

	internal ConfigEntry<bool> ReplaceAmbient;

	internal ConfigEntry<bool> RandomEnabled;

	internal ConfigEntry<bool> Verbose;

	internal ConfigEntry<float> Volume;

	internal ConfigEntry<float> MinDistance;

	internal ConfigEntry<float> MaxDistance;

	internal ConfigEntry<float> RandomMin;

	internal ConfigEntry<float> RandomMax;

	internal ConfigEntry<float> AmbientGap;

	internal ConfigEntry<float> NetworkDelay;

	private readonly List<MonsterRuntime> monsters = new List<MonsterRuntime>();

	private readonly Dictionary<Sound, SoundBinding> bindings = new Dictionary<Sound, SoundBinding>();

	private readonly HashSet<MemeVoiceActor> actors = new HashSet<MemeVoiceActor>();

	private readonly List<AudioClip> loadedClips = new List<AudioClip>();

	private readonly Dictionary<string, AudioClip> clipsByKey = new Dictionary<string, AudioClip>(StringComparer.Ordinal);

	private Harmony harmony;

	private int loadFailures;

	private void Awake()
	{
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Expected O, but got Unknown
		//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Expected O, but got Unknown
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Expected O, but got Unknown
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_0181: Expected O, but got Unknown
		//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Expected O, but got Unknown
		//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ff: Expected O, but got Unknown
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Expected O, but got Unknown
		//IL_0276: Unknown result type (might be due to invalid IL or missing references)
		//IL_0280: Expected O, but got Unknown
		Instance = this;
		ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable the sound mod.");
		ReplaceActions = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ReplaceActionSounds", true, "Replace mapped notice, attack, transformation and hurt sounds.");
		ReplaceAmbient = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ReplaceAmbientSounds", true, "Replace mapped ambient monster vocals.");
		RandomEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Random", "Enabled", true, "Play additional random lines from living monsters.");
		RandomMin = ((BaseUnityPlugin)this).Config.Bind<float>("Random", "MinIntervalSeconds", 15f, new ConfigDescription("Minimum silence between random lines.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), new object[0]));
		RandomMax = ((BaseUnityPlugin)this).Config.Bind<float>("Random", "MaxIntervalSeconds", 45f, new ConfigDescription("Maximum silence between random lines.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), new object[0]));
		Volume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "Volume", 1f, new ConfigDescription("Global voice volume. Also respects the game's sound volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		MinDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "MinDistance", 2f, new ConfigDescription("Full-volume distance in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 50f), new object[0]));
		MaxDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "MaxDistance", 25f, new ConfigDescription("Audible distance in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 150f), new object[0]));
		AmbientGap = ((BaseUnityPlugin)this).Config.Bind<float>("Timing", "AmbientGapSeconds", 2f, new ConfigDescription("Minimum silence after a voice finishes before another ambient line.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), new object[0]));
		Verbose = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Log sound bindings and every chosen clip.");
		NetworkDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Network", "StartDelaySeconds", 0.35f, new ConfigDescription("Host only: schedule shared voices this far ahead to absorb network latency.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), new object[0]));
		Network = new NetworkVoiceSync(this);
		harmony = new Harmony("fraer.russianmememonstersounds");
		harmony.PatchAll(typeof(Plugin).Assembly);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Русские мемы | Звуки мобов 1.4.0: loading sound pack.");
	}

	private IEnumerator Start()
	{
		string packFolder = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		string metadataPath = Path.Combine(packFolder, "monsters.json");
		List<string> fingerprints = new List<string>();
		PackDefinition definition;
		try
		{
			definition = JsonConvert.DeserializeObject<PackDefinition>(File.ReadAllText(metadataPath));
			ValidateDefinition(definition);
			fingerprints.Add("1.4.0:" + HashFile(metadataPath));
		}
		catch (Exception ex)
		{
			definition = null;
			((BaseUnityPlugin)this).Logger.LogError((object)("Cannot read monsters.json; original game sounds will be used. " + ex));
		}
		if (definition == null || definition.monsters == null || definition.schema_version != 1)
		{
			FinishSmokeTest(success: false);
			yield break;
		}
		try
		{
			MonsterDefinition[] array = definition.monsters;
			foreach (MonsterDefinition monster in array)
			{
				MonsterRuntime runtime = new MonsterRuntime(monster, ((BaseUnityPlugin)this).Config);
				monsters.Add(runtime);
				try
				{
					string[] array2 = new string[4] { "random", "notice", "attack", "hurt" };
					foreach (string category in array2)
					{
						string folder = Path.Combine(Path.Combine(Path.Combine(packFolder, "audio"), monster.id), category);
						if (!Directory.Exists(folder))
						{
							continue;
						}
						string[] files = Directory.GetFiles(folder, "*.mp3");
						Array.Sort(files, (IComparer<string>?)StringComparer.Ordinal);
						try
						{
							string[] array3 = files;
							foreach (string file in array3)
							{
								UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(new Uri(file).AbsoluteUri, (AudioType)13);
								try
								{
									yield return request.SendWebRequest();
									if ((int)request.result != 1)
									{
										loadFailures++;
										((BaseUnityPlugin)this).Logger.LogError((object)("Cannot load " + file + ": " + request.error));
										continue;
									}
									AudioClip clip = DownloadHandlerAudioClip.GetContent(request);
									if ((Object)(object)clip == (Object)null || clip.samples <= 0)
									{
										loadFailures++;
										((BaseUnityPlugin)this).Logger.LogError((object)("Empty audio clip: " + file));
										continue;
									}
									((Object)clip).name = "RussianMemes/" + monster.id + "/" + category + "/" + Path.GetFileName(file);
									((Object)clip).hideFlags = (HideFlags)32;
									runtime.Pools[category].Add(clip);
									loadedClips.Add(clip);
									clipsByKey.Add(((Object)clip).name, clip);
									fingerprints.Add(((Object)clip).name + ":" + HashFile(file));
								}
								finally
								{
									((IDisposable)request)?.Dispose();
								}
							}
						}
						finally
						{
						}
					}
				}
				finally
				{
				}
				if (runtime.Pools.Values.All((List<AudioClip> pool) => pool.Count == 0))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("No audio files for " + monster.id + "; keeping its original sounds."));
				}
			}
		}
		finally
		{
		}
		using (SHA256 sHA = SHA256.Create())
		{
			PackFingerprint = BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(string.Join("\n", fingerprints.OrderBy<string, string>((string value) => value, StringComparer.Ordinal))))).Replace("-", "").ToLowerInvariant();
		}
		Ready = loadedClips.Count > 0;
		((BaseUnityPlugin)this).Logger.LogInfo((object)("RUSSIAN_MEMES_READY clips=" + loadedClips.Count + " monsters=" + monsters.Count + " failures=" + loadFailures));
		((BaseUnityPlugin)this).Logger.LogInfo((object)("RUSSIAN_MEMES_NETWORK protocol=" + 1 + " pack=" + PackFingerprint));
		if (FinishSmokeTest(Ready && loadFailures == 0))
		{
			yield break;
		}
		while (true)
		{
			Enemy[] array4 = Object.FindObjectsByType<Enemy>((FindObjectsSortMode)0);
			foreach (Enemy enemy in array4)
			{
				Register(enemy);
			}
			ShopKeeper[] array5 = Object.FindObjectsByType<ShopKeeper>((FindObjectsSortMode)0);
			foreach (ShopKeeper source in array5)
			{
				RegisterObject((MonoBehaviour)(object)source);
			}
			ItemGun[] array6 = Object.FindObjectsByType<ItemGun>((FindObjectsSortMode)0);
			foreach (ItemGun source2 in array6)
			{
				RegisterObject((MonoBehaviour)(object)source2);
			}
			yield return (object)new WaitForSeconds(3f);
		}
	}

	private static string HashFile(string file)
	{
		using SHA256 sHA = SHA256.Create();
		using FileStream inputStream = File.OpenRead(file);
		return BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "").ToLowerInvariant();
	}

	private void Update()
	{
		if (Network != null)
		{
			Network.Tick();
		}
	}

	internal IEnumerable<string> EnabledMonsterIds()
	{
		return from monster in monsters
			where monster.Enabled.Value
			select monster.Definition.id;
	}

	internal bool TryClip(string key, out AudioClip clip)
	{
		return clipsByKey.TryGetValue(key, out clip);
	}

	internal void NetworkWarning(string message)
	{
		((BaseUnityPlugin)this).Logger.LogWarning((object)("Network: " + message));
	}

	internal void NetworkInfo(string message)
	{
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Network: " + message));
	}

	internal void ResetNetworkVoices()
	{
		MemeVoiceActor[] array = actors.ToArray();
		foreach (MemeVoiceActor memeVoiceActor in array)
		{
			if ((Object)(object)memeVoiceActor != (Object)null)
			{
				memeVoiceActor.StopNetworkVoice();
			}
		}
	}

	private static void ValidateDefinition(PackDefinition definition)
	{
		if (definition == null || definition.schema_version != 1 || definition.monsters == null)
		{
			throw new InvalidDataException("Unsupported or missing sound pack schema.");
		}
		HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
		MonsterDefinition[] array = definition.monsters;
		foreach (MonsterDefinition monsterDefinition in array)
		{
			if (monsterDefinition == null || string.IsNullOrEmpty(monsterDefinition.id) || !hashSet.Add(monsterDefinition.id) || monsterDefinition.id.IndexOfAny(new char[3] { '/', '\\', '.' }) >= 0 || monsterDefinition.enemy_components == null || monsterDefinition.rules == null)
			{
				throw new InvalidDataException("Invalid or duplicate monster entry.");
			}
			SoundRule[] rules = monsterDefinition.rules;
			foreach (SoundRule soundRule in rules)
			{
				if (soundRule == null || soundRule.fields == null || string.IsNullOrEmpty(soundRule.component) || (soundRule.category != "random" && soundRule.category != "notice" && soundRule.category != "attack" && soundRule.category != "hurt"))
				{
					throw new InvalidDataException("Invalid sound rule for " + monsterDefinition.id);
				}
			}
		}
	}

	internal void Register(Enemy enemy)
	{
		if (Ready && !((Object)(object)enemy == (Object)null) && !((Object)(object)((Component)enemy).GetComponent<MemeVoiceActor>() != (Object)null))
		{
			MonoBehaviour[] componentsInChildren = ((Component)enemy).GetComponentsInChildren<MonoBehaviour>(true);
			HashSet<string> names = new HashSet<string>(from c in componentsInChildren
				where (Object)(object)c != (Object)null
				select ((object)c).GetType().Name);
			MonsterRuntime monsterRuntime = monsters.FirstOrDefault((MonsterRuntime m) => m.Definition.enemy_components.Any(names.Contains));
			if (monsterRuntime != null)
			{
				MemeVoiceActor memeVoiceActor = ((Component)enemy).gameObject.AddComponent<MemeVoiceActor>();
				memeVoiceActor.Initialize(this, enemy, monsterRuntime);
				actors.Add(memeVoiceActor);
				BindSounds(memeVoiceActor, monsterRuntime, componentsInChildren);
			}
		}
	}

	internal void RegisterObject(MonoBehaviour source)
	{
		if (!Ready || (Object)(object)source == (Object)null)
		{
			return;
		}
		PhotonView componentInParent = ((Component)source).GetComponentInParent<PhotonView>();
		GameObject val = (((Object)(object)componentInParent != (Object)null) ? ((Component)componentInParent).gameObject : ((Component)source).gameObject);
		if (!((Object)(object)val.GetComponent<MemeVoiceActor>() != (Object)null))
		{
			MonoBehaviour[] componentsInChildren = val.GetComponentsInChildren<MonoBehaviour>(true);
			HashSet<string> names = new HashSet<string>(from c in componentsInChildren
				where (Object)(object)c != (Object)null
				select ((object)c).GetType().Name);
			MonsterRuntime monsterRuntime = monsters.FirstOrDefault((MonsterRuntime m) => m.Definition.object_components != null && m.Definition.object_components.Any(names.Contains));
			if (monsterRuntime != null)
			{
				MemeVoiceActor memeVoiceActor = val.AddComponent<MemeVoiceActor>();
				memeVoiceActor.InitializeObject(this, monsterRuntime, componentsInChildren);
				actors.Add(memeVoiceActor);
				BindSounds(memeVoiceActor, monsterRuntime, componentsInChildren);
			}
		}
	}

	internal MemeVoiceActor ResolveNetworkActor(PhotonView view, string id)
	{
		MemeVoiceActor component = ((Component)view).GetComponent<MemeVoiceActor>();
		if ((Object)(object)component == (Object)null)
		{
			Enemy component2 = ((Component)view).GetComponent<Enemy>();
			if ((Object)(object)component2 != (Object)null)
			{
				Register(component2);
			}
			else
			{
				MonoBehaviour[] componentsInChildren = ((Component)view).GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour source in componentsInChildren)
				{
					RegisterObject(source);
				}
			}
			component = ((Component)view).GetComponent<MemeVoiceActor>();
		}
		if (!((Object)(object)component != (Object)null) || !(component.Runtime.Definition.id == id))
		{
			return null;
		}
		return component;
	}

	private void BindSounds(MemeVoiceActor actor, MonsterRuntime runtime, MonoBehaviour[] components)
	{
		SoundRule[] rules = runtime.Definition.rules;
		foreach (SoundRule soundRule in rules)
		{
			foreach (MonoBehaviour val in components)
			{
				if ((Object)(object)val == (Object)null || ((object)val).GetType().Name != soundRule.component)
				{
					continue;
				}
				string[] fields = soundRule.fields;
				foreach (string text in fields)
				{
					FieldInfo fieldInfo = AccessTools.Field(((object)val).GetType(), text);
					Sound val2 = (Sound)((fieldInfo == null) ? null : /*isinst with value type is only supported in some contexts*/);
					if (val2 == null)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Unbound sound: " + soundRule.component + "." + text));
						continue;
					}
					if (bindings.TryGetValue(val2, out var value) && (Object)(object)value.Actor != (Object)(object)actor)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Shared Sound instance between enemies: " + soundRule.component + "." + text));
						continue;
					}
					SoundBinding value2 = new SoundBinding(actor, soundRule.category, val2);
					bindings[val2] = value2;
					actor.Bindings.Add(val2);
					if (Verbose.Value)
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)("Bound " + runtime.Definition.id + " " + soundRule.component + "." + text + " -> " + soundRule.category));
					}
				}
			}
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Registered " + runtime.Definition.game_name + " (" + runtime.Definition.id + "), " + actor.Bindings.Count + " sound fields."));
	}

	internal bool HandleOneShot(Sound sound, out AudioSource source)
	{
		source = null;
		if (!CanHandle(sound, out var binding))
		{
			return false;
		}
		source = binding.Actor.Trigger(binding.Category, sound, timedRandom: false);
		return (Object)(object)source != (Object)null;
	}

	internal bool HandleLoop(Sound sound, bool playing)
	{
		if (!CanHandle(sound, out var binding))
		{
			if (bindings.TryGetValue(sound, out binding))
			{
				binding.LoopRequested = false;
			}
			return false;
		}
		if (playing && !binding.LoopRequested)
		{
			binding.Actor.Trigger(binding.Category, sound, timedRandom: false);
		}
		binding.LoopRequested = playing;
		return true;
	}

	private bool CanHandle(Sound sound, out SoundBinding binding)
	{
		binding = null;
		if (!Ready || !ModEnabled.Value || !bindings.TryGetValue(sound, out binding) || (Object)(object)binding.Actor == (Object)null || !binding.Actor.Available)
		{
			return false;
		}
		if (!Network.CanReplace(binding.Actor, binding.Category))
		{
			return false;
		}
		return binding.Actor.Runtime.GetPool(binding.Category).Count > 0;
	}

	internal void Unregister(MemeVoiceActor actor)
	{
		if (Network != null)
		{
			Network.Forget(actor);
		}
		foreach (Sound binding in actor.Bindings)
		{
			if (bindings.TryGetValue(binding, out var value) && (Object)(object)value.Actor == (Object)(object)actor)
			{
				bindings.Remove(binding);
			}
		}
		actors.Remove(actor);
	}

	internal void ResetLoops(MemeVoiceActor actor)
	{
		foreach (Sound binding in actor.Bindings)
		{
			if (bindings.TryGetValue(binding, out var value) && (Object)(object)value.Actor == (Object)(object)actor)
			{
				value.LoopRequested = false;
			}
		}
	}

	internal void LogPick(string monster, string category, AudioClip clip)
	{
		if (Verbose.Value)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)(monster + " / " + category + " -> " + ((Object)clip).name));
		}
	}

	private bool FinishSmokeTest(bool success)
	{
		if (!Environment.GetCommandLineArgs().Contains("--russian-memes-smoke-test"))
		{
			return false;
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)("RUSSIAN_MEMES_SMOKE_TEST " + (success ? "PASS" : "FAIL")));
		Application.Quit((!success) ? 1 : 0);
		return true;
	}

	private void OnDestroy()
	{
		Ready = false;
		if (Network != null)
		{
			Network.Dispose();
		}
		MemeVoiceActor[] array = actors.ToArray();
		foreach (MemeVoiceActor memeVoiceActor in array)
		{
			if ((Object)(object)memeVoiceActor != (Object)null)
			{
				Object.Destroy((Object)(object)memeVoiceActor);
			}
		}
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		foreach (AudioClip loadedClip in loadedClips)
		{
			if ((Object)(object)loadedClip != (Object)null)
			{
				Object.Destroy((Object)(object)loadedClip);
			}
		}
		clipsByKey.Clear();
		if ((Object)(object)Instance == (Object)(object)this)
		{
			Instance = null;
		}
	}
}
internal sealed class MonsterRuntime
{
	internal readonly MonsterDefinition Definition;

	internal readonly ConfigEntry<bool> Enabled;

	internal readonly ConfigEntry<bool> RandomEnabled;

	internal readonly ConfigEntry<float> Volume;

	internal readonly Dictionary<string, List<AudioClip>> Pools = new Dictionary<string, List<AudioClip>>
	{
		{
			"random",
			new List<AudioClip>()
		},
		{
			"notice",
			new List<AudioClip>()
		},
		{
			"attack",
			new List<AudioClip>()
		},
		{
			"hurt",
			new List<AudioClip>()
		}
	};

	internal MonsterRuntime(MonsterDefinition definition, ConfigFile config)
	{
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Expected O, but got Unknown
		Definition = definition;
		string text = "Monster." + definition.id;
		Enabled = config.Bind<bool>(text, "Enabled", true, definition.name_ru + " / " + definition.game_name);
		RandomEnabled = config.Bind<bool>(text, "RandomLines", true, "Enable timed random lines for this monster.");
		Volume = config.Bind<float>(text, "Volume", 1f, new ConfigDescription("Volume multiplier for this monster.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
	}

	internal List<AudioClip> GetPool(string category)
	{
		List<AudioClip> list = Pools[category];
		if (list.Count != 0 || (!(category == "notice") && !(category == "attack")))
		{
			return list;
		}
		return Pools["random"];
	}
}
internal sealed class SoundBinding
{
	internal readonly MemeVoiceActor Actor;

	internal readonly string Category;

	internal bool LoopRequested;

	internal SoundBinding(MemeVoiceActor actor, string category, Sound sound)
	{
		Actor = actor;
		Category = category;
	}
}
internal sealed class VoiceCommand
{
	internal int ViewId;

	internal int Sequence;

	internal int StartTimestamp;

	internal string MonsterId;

	internal string Category;

	internal string ClipKey;

	internal bool Stop;
}
internal static class VoiceProtocol
{
	internal const byte EventCode = 188;

	internal const int ProtocolVersion = 1;

	internal const byte Hello = 0;

	internal const byte State = 1;

	internal const byte Play = 2;

	internal const byte Stop = 3;

	internal const string Marker = "fraer.russianmememonstersounds/voice";

	internal static bool IsAuthority(bool inRoom, bool offline, bool master)
	{
		if (inRoom && !offline)
		{
			return master;
		}
		return true;
	}

	internal static bool AuthorizedSender(int sender, int master, bool authority)
	{
		if (!authority && master > 0)
		{
			return sender == master;
		}
		return false;
	}

	internal static bool TryHeader(object content, out object[] data, out byte kind, out int session, out string pack)
	{
		data = content as object[];
		kind = byte.MaxValue;
		session = 0;
		pack = null;
		if (data == null || data.Length < 5 || !(data[0] is string) || (string)data[0] != "fraer.russianmememonstersounds/voice" || !(data[1] is int) || (int)data[1] != 1 || !(data[2] is byte) || !(data[3] is int) || !(data[4] is string))
		{
			return false;
		}
		kind = (byte)data[2];
		session = (int)data[3];
		pack = (string)data[4];
		if (kind <= 3 && pack.Length == 64)
		{
			if (kind != 0)
			{
				return session > 0;
			}
			return true;
		}
		return false;
	}

	internal static object[] Encode(VoiceCommand command, int session, string pack)
	{
		return new object[11]
		{
			"fraer.russianmememonstersounds/voice",
			1,
			(byte)(command.Stop ? 3 : 2),
			session,
			pack,
			command.ViewId,
			command.MonsterId,
			command.Category,
			command.ClipKey,
			command.Sequence,
			command.StartTimestamp
		};
	}

	internal static bool TryCommand(object content, out VoiceCommand command, out int session, out string pack)
	{
		command = null;
		if (!TryHeader(content, out var data, out var kind, out session, out pack) || (kind != 2 && kind != 3) || data.Length != 11 || !(data[5] is int) || (int)data[5] <= 0 || !(data[6] is string) || !(data[7] is string) || !(data[8] is string) || !(data[9] is int) || (int)data[9] <= 0 || !(data[10] is int))
		{
			return false;
		}
		string text = (string)data[6];
		string text2 = (string)data[7];
		string text3 = (string)data[8];
		if (text.Length == 0 || text.Length > 48)
		{
			return false;
		}
		if (kind == 2 && ((text2 != "random" && text2 != "notice" && text2 != "attack" && text2 != "hurt") || text3.Length > 240 || !text3.StartsWith("RussianMemes/" + text + "/", StringComparison.Ordinal)))
		{
			return false;
		}
		command = new VoiceCommand
		{
			ViewId = (int)data[5],
			MonsterId = text,
			Category = text2,
			ClipKey = text3,
			Sequence = (int)data[9],
			StartTimestamp = (int)data[10],
			Stop = (kind == 3)
		};
		return true;
	}

	internal static double ElapsedSeconds(int now, int start)
	{
		return (double)(now - start) / 1000.0;
	}

	internal static int SampleOffset(int now, int start, int frequency, int samples)
	{
		double num = Math.Max(0.0, ElapsedSeconds(now, start)) * (double)frequency;
		if (!(num >= (double)samples))
		{
			return (int)num;
		}
		return samples;
	}
}
internal sealed class VoiceSequenceTracker
{
	private readonly Dictionary<int, int> received = new Dictionary<int, int>();

	internal bool Accept(int viewId, int sequence)
	{
		if (viewId <= 0 || sequence <= 0 || (received.TryGetValue(viewId, out var value) && sequence <= value))
		{
			return false;
		}
		received[viewId] = sequence;
		return true;
	}

	internal void Clear()
	{
		received.Clear();
	}
}