Decompiled source of EnemySoundboard v1.4.0

plugins/EnemySoundboard.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice;
using Photon.Voice.PUN;
using Photon.Voice.Unity;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 EnemySoundboard
{
	public sealed class PcmPlayback
	{
		private readonly object gate = new object();

		private float[] data;

		private int offset;

		private bool finished;

		public bool Active
		{
			get
			{
				lock (gate)
				{
					return data != null;
				}
			}
		}

		public bool Finished
		{
			get
			{
				lock (gate)
				{
					return finished;
				}
			}
		}

		public void Begin(float[] samples)
		{
			lock (gate)
			{
				data = samples;
				offset = 0;
				finished = false;
			}
		}

		public void Stop()
		{
			lock (gate)
			{
				data = null;
				offset = 0;
				finished = false;
			}
		}

		public void Fill(float[] buffer)
		{
			lock (gate)
			{
				if (data != null)
				{
					for (int i = 0; i < buffer.Length; i++)
					{
						buffer[i] = ((offset < data.Length) ? data[offset++] : 0f);
					}
					finished = offset >= data.Length;
				}
			}
		}

		public void Fill(short[] buffer)
		{
			lock (gate)
			{
				if (data != null)
				{
					for (int i = 0; i < buffer.Length; i++)
					{
						buffer[i] = (short)((offset < data.Length) ? ((short)(Math.Max(-1f, Math.Min(1f, data[offset++])) * 32767f)) : 0);
					}
					finished = offset >= data.Length;
				}
			}
		}

		public static float[] Convert(float[] input, int inputRate, int inputChannels, int outputRate, int outputChannels, float gain)
		{
			if (inputRate <= 0 || inputChannels <= 0 || outputRate <= 0 || outputChannels <= 0 || input.Length < inputChannels)
			{
				throw new ArgumentException("Invalid PCM format");
			}
			int num = input.Length / inputChannels;
			int num2 = (int)Math.Ceiling((double)num * (double)outputRate / (double)inputRate);
			float[] array = new float[checked(num2 * outputChannels)];
			for (int i = 0; i < num2; i++)
			{
				double num3 = (double)i * (double)inputRate / (double)outputRate;
				int num4 = Math.Min((int)num3, num - 1);
				int num5 = Math.Min(num4 + 1, num - 1);
				float num6 = (float)(num3 - (double)num4);
				float num7 = 0f;
				for (int j = 0; j < inputChannels; j++)
				{
					num7 += input[num4 * inputChannels + j] * (1f - num6) + input[num5 * inputChannels + j] * num6;
				}
				num7 = Math.Max(-1f, Math.Min(1f, num7 / (float)inputChannels * gain));
				for (int k = 0; k < outputChannels; k++)
				{
					array[i * outputChannels + k] = num7;
				}
			}
			return array;
		}
	}
	public sealed class AudioRelayBuffer
	{
		private readonly object gate = new object();

		private readonly float[] ring = new float[384000];

		private int read;

		private int write;

		private int count;

		private int rate;

		private int channels;

		private double phase;

		private float gain;

		private bool active;

		private long received;

		private float peak;

		public bool Active
		{
			get
			{
				lock (gate)
				{
					return active;
				}
			}
		}

		public float Peak
		{
			get
			{
				lock (gate)
				{
					return peak;
				}
			}
		}

		public long Received
		{
			get
			{
				lock (gate)
				{
					return received;
				}
			}
		}

		public int Buffered
		{
			get
			{
				lock (gate)
				{
					return count;
				}
			}
		}

		public void Begin(int outputRate, int outputChannels, float volume)
		{
			if (outputRate <= 0 || outputChannels < 1 || outputChannels > 2)
			{
				throw new ArgumentException("Unsupported voice format");
			}
			lock (gate)
			{
				rate = outputRate;
				channels = outputChannels;
				gain = volume;
				read = (write = (count = 0));
				phase = 0.0;
				received = 0L;
				peak = 0f;
				active = true;
			}
		}

		public void Stop()
		{
			lock (gate)
			{
				active = false;
				read = (write = (count = 0));
			}
		}

		public void Push(float[] data, int inputChannels, int inputRate)
		{
			lock (gate)
			{
				if (!active || inputChannels < 1 || inputRate < 1)
				{
					return;
				}
				int num = data.Length / inputChannels;
				double num2 = (double)inputRate / (double)rate;
				while (phase < (double)num)
				{
					int num3 = (int)phase;
					int num4 = Math.Min(num3 + 1, num - 1);
					float num5 = (float)(phase - (double)num3);
					float num6 = 0f;
					for (int i = 0; i < inputChannels; i++)
					{
						num6 += data[num3 * inputChannels + i] * (1f - num5) + data[num4 * inputChannels + i] * num5;
					}
					num6 = num6 / (float)inputChannels * gain;
					if (float.IsNaN(num6) || float.IsInfinity(num6))
					{
						num6 = 0f;
					}
					num6 = Math.Max(-1f, Math.Min(1f, num6));
					peak = Math.Max(peak, Math.Abs(num6));
					if (count + channels > ring.Length)
					{
						read = (read + channels) % ring.Length;
						count -= channels;
					}
					for (int j = 0; j < channels; j++)
					{
						ring[write] = num6;
						write = (write + 1) % ring.Length;
						count++;
						received++;
					}
					phase += num2;
				}
				phase -= num;
			}
		}

		public bool ReadFrame(float[] frame)
		{
			lock (gate)
			{
				if (!active || count < frame.Length)
				{
					return false;
				}
				Fill(frame);
				return true;
			}
		}

		public void Fill(float[] buffer)
		{
			lock (gate)
			{
				if (!active)
				{
					return;
				}
				for (int i = 0; i < buffer.Length; i++)
				{
					buffer[i] = ((count > 0) ? ring[read] : 0f);
					if (count > 0)
					{
						read = (read + 1) % ring.Length;
						count--;
					}
				}
			}
		}

		public void Fill(short[] buffer)
		{
			lock (gate)
			{
				if (!active)
				{
					return;
				}
				for (int i = 0; i < buffer.Length; i++)
				{
					buffer[i] = (short)((count > 0) ? ((short)(ring[read] * 32767f)) : 0);
					if (count > 0)
					{
						read = (read + 1) % ring.Length;
						count--;
					}
				}
			}
		}
	}
	public static class SoundCatalogRules
	{
		public static string Category(string action, string clipName)
		{
			return Match(action) ?? Match(clipName) ?? "Inne";
		}

		private static string Match(string value)
		{
			string input = Regex.Replace(value ?? "", "([a-z])([A-Z])", "$1 $2").ToLowerInvariant();
			if (Regex.IsMatch(input, "death|dead|die|dying"))
			{
				return "Smierc";
			}
			if (Regex.IsMatch(input, "hurt|damage|pain|stun"))
			{
				return "Bol / obrazenia";
			}
			if (Regex.IsMatch(input, "attack|bite|slash|punch|kick|hit|shoot|grab|throw|tongue"))
			{
				return "Atak";
			}
			if (Regex.IsMatch(input, "alert|aggro|notice|detect|scream|roar|chase"))
			{
				return "Alarm / krzyk";
			}
			if (Regex.IsMatch(input, "footstep|step|walk|jump|land|crawl|move|\\brun\\b"))
			{
				return "Ruch";
			}
			if (Regex.IsMatch(input, "idle|voice|vocal|breath|growl|chatter|laugh|snore|talk"))
			{
				return "Odglosy";
			}
			return null;
		}

		public static bool HasAudibleSamples(float[] samples)
		{
			bool result = false;
			foreach (float num in samples)
			{
				if (float.IsNaN(num) || float.IsInfinity(num))
				{
					return false;
				}
				if (Math.Abs(num) > 1E-06f)
				{
					result = true;
				}
			}
			return result;
		}
	}
	[BepInPlugin("local.repo.enemysoundboard", "Enemy Soundboard Host", "1.4.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal static Plugin Instance;

		internal static ConfigEntry<KeyCode> MenuKey;

		private Harmony harmony;

		private GameObject ui;

		private void Awake()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			Instance = this;
			MenuKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "MenuKey", (KeyCode)264, "Open/close the sound menu. Arrows: select; Enter: play; Backspace: stop; F5: refresh.");
			harmony = new Harmony("local.repo.enemysoundboard");
			harmony.PatchAll();
			ui = new GameObject("EnemySoundboardUI");
			Object.DontDestroyOnLoad((Object)(object)ui);
			ui.AddComponent<SoundboardUI>();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Enemy Soundboard ready. NumPad8 menu; host voice proximity transport.");
		}

		internal static void Log(string message)
		{
			((BaseUnityPlugin)Instance).Logger.LogInfo((object)message);
		}

		private void OnDestroy()
		{
			if (Object.op_Implicit((Object)(object)ui))
			{
				Object.Destroy((Object)(object)ui);
			}
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			Instance = null;
		}
	}
	public sealed class SoundboardUI : MonoBehaviour
	{
		private sealed class Entry
		{
			public string Label;

			public string Enemy;

			public string Category;

			public AudioClip Clip;

			public float Volume;
		}

		private sealed class SoundInput : IAudioReader<float>, IDataReader<float>, IDisposable, IAudioDesc
		{
			private readonly AudioRelayBuffer buffer;

			public int SamplingRate { get; }

			public int Channels => 1;

			public string Error => null;

			public SoundInput(AudioRelayBuffer buffer, int rate)
			{
				this.buffer = buffer;
				SamplingRate = rate;
			}

			public bool Read(float[] samples)
			{
				return buffer.ReadFrame(samples);
			}

			public void Dispose()
			{
			}
		}

		internal static SoundboardUI Instance;

		private readonly List<Entry> entries = new List<Entry>();

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

		private readonly List<Entry> filtered = new List<Entry>();

		private int tab;

		private int kind;

		private Vector2 tabScroll;

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

		private readonly List<Entry> candidates = new List<Entry>();

		private readonly Dictionary<int, bool> availability = new Dictionary<int, bool>();

		private bool catalogStarted;

		private float nextCatalogCheck;

		private int setupCount;

		private Entry playing;

		private int dspRate;

		private float playStarted;

		private bool audioDiagnosticDone;

		private volatile bool audioDiagnosticRunning;

		private volatile float localGain = 1f;

		private Coroutine scanRoutine;

		private bool scanning;

		private int skipped;

		private GUIStyle titleStyle;

		private GUIStyle labelStyle;

		private GUIStyle smallStyle;

		private GUIStyle tabStyle;

		private GUIStyle activeTabStyle;

		private GUIStyle rowStyle;

		private GUIStyle activeRowStyle;

		private Texture2D panelTexture;

		private Texture2D normalTexture;

		private Texture2D activeTexture;

		private Texture2D hoverTexture;

		private static readonly Color Accent = new Color(1f, 0.77f, 0.19f);

		private readonly AudioRelayBuffer playback = new AudioRelayBuffer();

		private LocalVoice voice;

		private Recorder recorder;

		private WebRtcAudioDsp dsp;

		private Func<IAudioDesc> savedFactory;

		private InputSourceType savedSource;

		private bool savedTransmit;

		private bool savedDetection;

		private bool savedRecording;

		private bool savedDsp;

		private bool open;

		private int selected;

		private int lastFrame = -1;

		private int initialFrames;

		private float deadline;

		private float drainUntil;

		private SoundInput input;

		private string status = "Wejdz do rozgrywki jako gospodarz.";

		private AudioSource preview;

		private static readonly FieldInfo VoiceField = AccessTools.Field(typeof(Recorder), "voice");

		private static readonly FieldInfo InputField = AccessTools.Field(typeof(Recorder), "inputSource");

		private static readonly FieldInfo RecorderField = AccessTools.Field(typeof(PlayerVoiceChat), "recorder");

		private static readonly FieldInfo DeadField = AccessTools.Field(typeof(PlayerAvatar), "deadSet");

		private static string NiceName(string value)
		{
			value = value.Replace("(Clone)", "").Replace("Enemy", "").Replace("Prefab", "");
			value = Regex.Replace(value, "([a-z])([A-Z])", "$1 $2");
			return Regex.Replace(value.Replace('_', ' ').Replace('-', ' '), "\\s+", " ").Trim();
		}

		private void SelectTab(int index)
		{
			tab = Mathf.Clamp(index, 0, Math.Max(0, enemies.Count - 1));
			kinds.Clear();
			if (enemies.Count > 0)
			{
				kinds.AddRange((from e in entries
					where e.Enemy == enemies[tab]
					select e.Category).Distinct().OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase));
			}
			SelectKind(0);
			tabScroll.y = Math.Max(0, tab / 3 * 32 - 32);
		}

		private void SelectKind(int index)
		{
			kind = Mathf.Clamp(index, 0, Math.Max(0, kinds.Count - 1));
			selected = 0;
			filtered.Clear();
			if (enemies.Count > 0 && kinds.Count > 0)
			{
				filtered.AddRange(entries.Where((Entry e) => e.Enemy == enemies[tab] && e.Category == kinds[kind]));
			}
		}

		private void RebuildTabs()
		{
			string item = ((enemies.Count > 0) ? enemies[tab] : null);
			string item2 = ((kinds.Count > 0) ? kinds[kind] : null);
			enemies.Clear();
			enemies.AddRange(entries.Select((Entry e) => e.Enemy).Distinct().OrderBy<string, string>((string x) => x, StringComparer.OrdinalIgnoreCase));
			SelectTab(Math.Max(0, enemies.IndexOf(item)));
			SelectKind(Math.Max(0, kinds.IndexOf(item2)));
		}

		private bool HostAlive()
		{
			if (Object.op_Implicit((Object)(object)PlayerAvatar.instance) && (!PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient))
			{
				return !(bool)DeadField.GetValue(PlayerAvatar.instance);
			}
			return false;
		}

		private void Awake()
		{
			Instance = this;
			preview = ((Component)this).gameObject.AddComponent<AudioSource>();
			preview.playOnAwake = false;
			preview.spatialBlend = 0f;
			dspRate = AudioSettings.outputSampleRate;
			nextCatalogCheck = Time.realtimeSinceStartup + 2f;
		}

		private void OnAudioFilterRead(float[] data, int channels)
		{
			playback.Push(data, channels, dspRate);
			if (audioDiagnosticRunning)
			{
				Array.Clear(data, 0, data.Length);
				return;
			}
			for (int i = 0; i < data.Length; i++)
			{
				data[i] *= localGain;
			}
		}

		private void Update()
		{
			Tick();
		}

		internal void Tick()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			if (lastFrame == Time.frameCount)
			{
				return;
			}
			lastFrame = Time.frameCount;
			if (Object.op_Implicit((Object)(object)recorder))
			{
				TickTransmission();
			}
			if (!scanning && Time.realtimeSinceStartup >= nextCatalogCheck)
			{
				nextCatalogCheck = Time.realtimeSinceStartup + 10f;
				int num = Resources.FindObjectsOfTypeAll<EnemySetup>().Length;
				if (!catalogStarted || num > setupCount)
				{
					setupCount = num;
					Refresh();
				}
			}
			if (Input.GetKeyDown(Plugin.MenuKey.Value))
			{
				open = !open;
			}
			if (!open)
			{
				return;
			}
			if (Input.GetKeyDown((KeyCode)27))
			{
				open = false;
				return;
			}
			if (Input.GetKeyDown((KeyCode)286))
			{
				Refresh();
			}
			if (Input.GetKeyDown((KeyCode)9))
			{
				SelectKind((kinds.Count != 0) ? ((kind + ((!Input.GetKey((KeyCode)304) && !Input.GetKey((KeyCode)303)) ? 1 : (kinds.Count - 1))) % kinds.Count) : 0);
			}
			if (Input.GetKeyDown((KeyCode)276))
			{
				SelectTab(tab - 1);
			}
			if (Input.GetKeyDown((KeyCode)275))
			{
				SelectTab(tab + 1);
			}
			if (Input.GetKeyDown((KeyCode)273))
			{
				selected = Math.Max(0, selected - 1);
			}
			if (Input.GetKeyDown((KeyCode)274))
			{
				selected = Math.Min(filtered.Count - 1, selected + 1);
			}
			if (Input.GetKeyDown((KeyCode)280))
			{
				selected = Math.Max(0, selected - 12);
			}
			if (Input.GetKeyDown((KeyCode)281))
			{
				selected = Math.Min(filtered.Count - 1, selected + 12);
			}
			if (Input.GetKeyDown((KeyCode)8))
			{
				Stop();
			}
			if ((Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271)) && selected >= 0 && selected < filtered.Count)
			{
				Play(filtered[selected]);
			}
		}

		private void Refresh()
		{
			if (!scanning)
			{
				catalogStarted = true;
				scanning = true;
				scanRoutine = ((MonoBehaviour)this).StartCoroutine(BuildCatalog());
			}
		}

		private IEnumerator BuildCatalog()
		{
			yield return null;
			Stopwatch timer = Stopwatch.StartNew();
			HashSet<string> seen = new HashSet<string>();
			foreach (Entry entry in entries)
			{
				if (Object.op_Implicit((Object)(object)entry.Clip))
				{
					seen.Add(entry.Enemy + ":" + ((Object)entry.Clip).GetInstanceID());
				}
			}
			candidates.Clear();
			skipped = 0;
			EnemySetup[] setups = Resources.FindObjectsOfTypeAll<EnemySetup>();
			setupCount = setups.Length;
			for (int n = 0; n < setups.Length; n++)
			{
				EnemySetup val = setups[n];
				if (!Object.op_Implicit((Object)(object)val) || val.spawnObjects == null)
				{
					continue;
				}
				status = "Przygotowanie katalogu: " + (n + 1) + " / " + setups.Length;
				foreach (PrefabRef spawnObject in val.spawnObjects)
				{
					if (spawnObject == null)
					{
						continue;
					}
					try
					{
						GameObject prefab = ((PrefabRef<GameObject>)(object)spawnObject).Prefab;
						if (Object.op_Implicit((Object)(object)prefab))
						{
							Scan(prefab.GetComponentsInChildren<MonoBehaviour>(true), NiceName(((Object)prefab).name), seen);
						}
					}
					catch (Exception ex)
					{
						Plugin.Log("Prefab skipped: " + ex.Message);
					}
					yield return null;
				}
			}
			if (setups.Length == 0)
			{
				EnemyParent[] array = Resources.FindObjectsOfTypeAll<EnemyParent>();
				foreach (EnemyParent val2 in array)
				{
					if (Object.op_Implicit((Object)(object)val2))
					{
						Scan(((Component)val2).GetComponentsInChildren<MonoBehaviour>(true), NiceName(((Object)((Component)val2).gameObject).name), seen);
					}
					yield return null;
				}
			}
			foreach (Entry candidate in candidates)
			{
				if (Object.op_Implicit((Object)(object)candidate.Clip))
				{
					entries.Add(candidate);
				}
			}
			entries.RemoveAll((Entry e) => !Object.op_Implicit((Object)(object)e.Clip));
			entries.Sort((Entry a, Entry b) => StringComparer.OrdinalIgnoreCase.Compare(a.Label, b.Label));
			RebuildTabs();
			scanning = false;
			scanRoutine = null;
			nextCatalogCheck = Time.realtimeSinceStartup + 10f;
			status = entries.Count + " dzwiekow / " + enemies.Count + " przeciwnikow";
			Plugin.Log("Catalog ready in " + timer.ElapsedMilliseconds + " ms: " + status + "; skipped invalid: " + skipped + ". Native Unity audio decoding enabled.");
			if (!audioDiagnosticDone && Environment.GetCommandLineArgs().Contains("--enemy-soundboard-audio-test"))
			{
				audioDiagnosticDone = true;
				((MonoBehaviour)this).StartCoroutine(AudioDiagnostic());
			}
		}

		private IEnumerator AudioDiagnostic()
		{
			audioDiagnosticRunning = true;
			foreach (Entry entry in entries.Where((Entry e) => Object.op_Implicit((Object)(object)e.Clip) && (int)e.Clip.loadType > 0).Take(3))
			{
				dspRate = AudioSettings.outputSampleRate;
				playback.Begin(48000, 1, 1f);
				preview.clip = entry.Clip;
				preview.volume = 1f;
				preview.Play();
				yield return (object)new WaitForSecondsRealtime(Mathf.Min(2f, entry.Clip.length + 0.2f));
				Plugin.Log("Native decode probe: " + entry.Enemy + " / " + ((Object)entry.Clip).name + " / " + ((object)entry.Clip.loadType/*cast due to .constrained prefix*/).ToString() + " samples=" + playback.Received + " peak=" + playback.Peak);
				preview.Stop();
				playback.Stop();
				yield return null;
			}
			audioDiagnosticRunning = false;
		}

		private void HideUnavailable(Entry entry)
		{
			entries.RemoveAll((Entry e) => !Object.op_Implicit((Object)(object)e.Clip) || (Object)(object)e.Clip == (Object)(object)entry.Clip);
			RebuildTabs();
			status = "Niedostepny dzwiek zostal ukryty. F5 odswieza liste.";
		}

		private void Scan(IEnumerable<MonoBehaviour> components, string enemy, HashSet<string> seen)
		{
			if (string.IsNullOrWhiteSpace(enemy))
			{
				return;
			}
			foreach (MonoBehaviour component in components)
			{
				if (!Object.op_Implicit((Object)(object)component) || !((object)component).GetType().Name.StartsWith("Enemy"))
				{
					continue;
				}
				FieldInfo[] fields = ((object)component).GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (fieldInfo.FieldType == typeof(Sound))
					{
						object? value = fieldInfo.GetValue(component);
						Sound val = (Sound)((value is Sound) ? value : null);
						if (val?.Sounds != null)
						{
							AudioClip[] sounds = val.Sounds;
							foreach (AudioClip clip in sounds)
							{
								Add(clip, enemy, fieldInfo.Name, val.Volume, seen);
							}
						}
					}
					else if (fieldInfo.FieldType == typeof(AudioClip))
					{
						object? value2 = fieldInfo.GetValue(component);
						Add((AudioClip)((value2 is AudioClip) ? value2 : null), enemy, fieldInfo.Name, 1f, seen);
					}
					else if (fieldInfo.FieldType == typeof(AudioClip[]))
					{
						if (fieldInfo.GetValue(component) is AudioClip[] array)
						{
							AudioClip[] sounds = array;
							foreach (AudioClip clip2 in sounds)
							{
								Add(clip2, enemy, fieldInfo.Name, 1f, seen);
							}
						}
					}
					else if (fieldInfo.FieldType == typeof(Sound[]))
					{
						if (!(fieldInfo.GetValue(component) is Sound[] array2))
						{
							continue;
						}
						Sound[] array3 = array2;
						foreach (Sound val2 in array3)
						{
							if (val2?.Sounds != null)
							{
								AudioClip[] sounds = val2.Sounds;
								foreach (AudioClip clip3 in sounds)
								{
									Add(clip3, enemy, fieldInfo.Name, val2.Volume, seen);
								}
							}
						}
					}
					else
					{
						if (!typeof(ScriptableObject).IsAssignableFrom(fieldInfo.FieldType) || !fieldInfo.FieldType.Name.StartsWith("Enemy"))
						{
							continue;
						}
						object value3 = fieldInfo.GetValue(component);
						if (value3 == null)
						{
							continue;
						}
						FieldInfo[] fields2 = value3.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
						foreach (FieldInfo fieldInfo2 in fields2)
						{
							if (fieldInfo2.FieldType == typeof(AudioClip[]) && fieldInfo2.GetValue(value3) is AudioClip[] array4)
							{
								AudioClip[] sounds = array4;
								foreach (AudioClip clip4 in sounds)
								{
									Add(clip4, enemy, fieldInfo.Name, 1f, seen);
								}
							}
						}
					}
				}
			}
		}

		private void Add(AudioClip clip, string enemy, string action, float volume, HashSet<string> seen)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Invalid comparison between Unknown and I4
			//IL_00a2: 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_00b0: Invalid comparison between Unknown and I4
			if (!Object.op_Implicit((Object)(object)clip) || clip.length <= 0f || clip.length > 60f || clip.samples <= 0 || clip.channels <= 0 || clip.frequency <= 0 || (int)clip.loadState == 3)
			{
				skipped++;
			}
			else
			{
				if (!seen.Add(enemy + ":" + ((Object)clip).GetInstanceID()))
				{
					return;
				}
				if (!availability.TryGetValue(((Object)clip).GetInstanceID(), out var value))
				{
					value = true;
					if ((int)clip.loadType == 0 && (int)clip.loadState == 2 && (long)clip.samples * (long)clip.channels <= 1000000)
					{
						float[] array = new float[clip.samples * clip.channels];
						if (clip.GetData(array, 0))
						{
							value = SoundCatalogRules.HasAudibleSamples(array);
						}
					}
					availability[((Object)clip).GetInstanceID()] = value;
				}
				if (!value)
				{
					skipped++;
					return;
				}
				string label = NiceName(action).Replace("sound", "").Replace("Sound", "").Trim();
				if (label.Length == 0)
				{
					label = "Dzwiek";
				}
				int num = candidates.Count((Entry e) => e.Enemy == enemy && e.Label.StartsWith(label + "  #")) + 1;
				candidates.Add(new Entry
				{
					Clip = clip,
					Enemy = enemy,
					Category = SoundCatalogRules.Category(action, ((Object)clip).name),
					Label = label + "  #" + num,
					Volume = Mathf.Clamp(volume, 0.05f, 1f)
				});
			}
		}

		private void Play(Entry entry)
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Invalid comparison between Unknown and I4
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Expected I4, but got Unknown
			Stop();
			if (!HostAlive())
			{
				status = "Dostepne dla zywego gospodarza w rozgrywce.";
				return;
			}
			if (Object.op_Implicit((Object)(object)DataDirector.instance) && (bool)AccessTools.Field(typeof(DataDirector), "toggleMute").GetValue(DataDirector.instance))
			{
				status = "Wlacz czat glosowy w grze (jest wyciszony).";
				return;
			}
			PlayerVoiceChat instance = PlayerVoiceChat.instance;
			PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
			Recorder val = (Recorder)(Object.op_Implicit((Object)(object)instance) ? /*isinst with value type is only supported in some contexts*/: null);
			if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)existingInstance))
			{
				LoadBalancingTransport client = ((VoiceConnection)existingInstance).Client;
				if (client != null && ((LoadBalancingClient)client).InRoom)
				{
					if (!Object.op_Implicit((Object)(object)entry.Clip) || (int)entry.Clip.loadState == 3)
					{
						HideUnavailable(entry);
						return;
					}
					savedSource = val.SourceType;
					savedFactory = val.InputFactory;
					savedTransmit = val.TransmitEnabled;
					savedDetection = val.VoiceDetection;
					savedRecording = val.RecordingEnabled;
					dsp = ((Component)val).GetComponent<WebRtcAudioDsp>();
					savedDsp = Object.op_Implicit((Object)(object)dsp) && ((Behaviour)dsp).enabled;
					recorder = val;
					try
					{
						int num = (int)recorder.SamplingRate;
						dspRate = AudioSettings.outputSampleRate;
						playback.Begin(num, 1, entry.Volume);
						input = new SoundInput(playback, num);
						playing = entry;
						deadline = Time.realtimeSinceStartup + 3f;
						drainUntil = 0f;
						if (savedDsp)
						{
							((Behaviour)dsp).enabled = false;
						}
						recorder.TransmitEnabled = false;
						recorder.VoiceDetection = false;
						SoundInput soundInput = input;
						recorder.InputFactory = () => (IAudioDesc)(object)soundInput;
						recorder.SourceType = (InputSourceType)2;
						recorder.RecordingEnabled = true;
						status = "Uruchamianie transmisji...";
						return;
					}
					catch (Exception ex)
					{
						Stop();
						status = "Blad transmisji: " + ex.Message;
						Plugin.Log(ex.ToString());
						return;
					}
				}
			}
			status = "Czat glosowy nie jest jeszcze polaczony.";
		}

		private void TickTransmission()
		{
			if (!HostAlive() || !Object.op_Implicit((Object)(object)PlayerVoiceChat.instance) || RecorderField.GetValue(PlayerVoiceChat.instance) != recorder)
			{
				Stop();
				return;
			}
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			object? value = VoiceField.GetValue(recorder);
			LocalVoice val = (LocalVoice)((value is LocalVoice) ? value : null);
			if (InputField.GetValue(recorder) != input || val == null || (object)val == LocalVoiceAudioDummy.Dummy)
			{
				if (realtimeSinceStartup >= deadline)
				{
					Stop();
					status = "Czat glosowy nie uruchomil zrodla dzwieku.";
					Plugin.Log(status);
				}
				return;
			}
			if (voice == null)
			{
				voice = val;
				initialFrames = voice.FramesSent;
				Entry entry = playing;
				playStarted = realtimeSinceStartup;
				deadline = realtimeSinceStartup + entry.Clip.length + 3f;
				preview.clip = entry.Clip;
				localGain = entry.Volume;
				preview.volume = 1f;
				recorder.TransmitEnabled = true;
				preview.Play();
				status = entry.Enemy + " / " + entry.Label;
				Plugin.Log("Voice source ready: " + status);
			}
			else if (voice != val)
			{
				Stop();
				status = "Kanal glosowy zostal przelaczony.";
				return;
			}
			if (!preview.isPlaying && realtimeSinceStartup > playStarted + 0.25f && drainUntil == 0f)
			{
				drainUntil = realtimeSinceStartup + 0.35f;
			}
			if (realtimeSinceStartup >= deadline || (drainUntil > 0f && realtimeSinceStartup >= drainUntil))
			{
				int num = voice.FramesSent - initialFrames;
				Entry entry2 = playing;
				bool flag = playback.Received > 0 && playback.Peak <= 1E-06f;
				Plugin.Log("Voice clip finished: sent frames=" + num + ", decoded samples=" + playback.Received + ", targets=" + ((voice.TargetPlayers == null) ? "room" : voice.TargetPlayers.Length.ToString()));
				Stop();
				if (flag)
				{
					HideUnavailable(entry2);
				}
				else if (num <= 0)
				{
					status = "Czat glosowy nie wyslal dzwieku. Sprawdz polaczenie.";
				}
			}
		}

		internal void KeepTransmitting(PlayerVoiceChat chat)
		{
			if (Object.op_Implicit((Object)(object)recorder) && RecorderField.GetValue(chat) == recorder)
			{
				recorder.TransmitEnabled = voice != null;
			}
		}

		private void Stop()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)preview))
			{
				preview.Stop();
			}
			playback.Stop();
			if (Object.op_Implicit((Object)(object)recorder))
			{
				recorder.TransmitEnabled = false;
				recorder.SourceType = savedSource;
				recorder.InputFactory = savedFactory;
				recorder.VoiceDetection = savedDetection;
				if (Object.op_Implicit((Object)(object)dsp))
				{
					((Behaviour)dsp).enabled = savedDsp;
				}
				recorder.RecordingEnabled = savedRecording;
				recorder.TransmitEnabled = savedTransmit;
			}
			playing = null;
			voice = null;
			recorder = null;
			dsp = null;
			input = null;
		}

		private void OnDisable()
		{
			Stop();
			if (scanRoutine != null)
			{
				((MonoBehaviour)this).StopCoroutine(scanRoutine);
			}
			scanRoutine = null;
			scanning = false;
		}

		private void OnDestroy()
		{
			Stop();
			Texture2D[] array = (Texture2D[])(object)new Texture2D[4] { panelTexture, normalTexture, activeTexture, hoverTexture };
			foreach (Texture2D val in array)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					Object.Destroy((Object)(object)val);
				}
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private static Texture2D Flat(Color color)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			Texture2D val = new Texture2D(1, 1);
			val.SetPixel(0, 0, color);
			val.Apply();
			return val;
		}

		private void BuildStyles()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Expected O, but got Unknown
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Expected O, but got Unknown
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Expected O, but got Unknown
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Expected O, but got Unknown
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Expected O, but got Unknown
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_023d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_0251: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Expected O, but got Unknown
			//IL_0266: Expected O, but got Unknown
			//IL_026d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Expected O, but got Unknown
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			if (titleStyle == null)
			{
				panelTexture = Flat(new Color(0.055f, 0.063f, 0.067f, 0.97f));
				normalTexture = Flat(new Color(0.105f, 0.12f, 0.12f));
				activeTexture = Flat(new Color(0.29f, 0.255f, 0.12f));
				hoverTexture = Flat(new Color(0.19f, 0.21f, 0.19f));
				titleStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 27,
					fontStyle = (FontStyle)1
				};
				titleStyle.normal.textColor = Accent;
				labelStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 17,
					fontStyle = (FontStyle)1
				};
				labelStyle.normal.textColor = new Color(0.9f, 0.92f, 0.84f);
				smallStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 13,
					wordWrap = true
				};
				smallStyle.normal.textColor = new Color(0.64f, 0.7f, 0.66f);
				tabStyle = new GUIStyle(GUI.skin.button)
				{
					fontSize = 14,
					fontStyle = (FontStyle)1,
					alignment = (TextAnchor)4,
					padding = new RectOffset(5, 5, 4, 4),
					clipping = (TextClipping)1
				};
				tabStyle.normal.background = normalTexture;
				tabStyle.normal.textColor = new Color(0.8f, 0.85f, 0.8f);
				tabStyle.hover.background = hoverTexture;
				tabStyle.active.background = activeTexture;
				activeTabStyle = new GUIStyle(tabStyle);
				activeTabStyle.normal.background = activeTexture;
				activeTabStyle.normal.textColor = Accent;
				rowStyle = new GUIStyle(tabStyle)
				{
					alignment = (TextAnchor)3,
					fontSize = 15,
					padding = new RectOffset(12, 8, 4, 4)
				};
				activeRowStyle = new GUIStyle(rowStyle);
				activeRowStyle.normal.background = activeTexture;
				activeRowStyle.normal.textColor = Accent;
			}
		}

		private void OnGUI()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_020b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0242: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0357: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_056a: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0602: Unknown result type (might be due to invalid IL or missing references)
			//IL_0617: Unknown result type (might be due to invalid IL or missing references)
			//IL_061d: Unknown result type (might be due to invalid IL or missing references)
			if (!open)
			{
				return;
			}
			BuildStyles();
			Matrix4x4 matrix = GUI.matrix;
			Color color = GUI.color;
			int depth = GUI.depth;
			float num = Mathf.Clamp((float)Screen.height / 1080f, 0.6f, 1.3f);
			GUI.matrix = Matrix4x4.Scale(new Vector3(num, num, 1f));
			GUI.depth = -100;
			float num2 = Mathf.Min(510f, (float)Screen.width / num - 32f);
			float num3 = Mathf.Min(790f, (float)Screen.height / num - 48f);
			float num4 = (float)Screen.width / num - num2 - 20f;
			float num5 = 24f;
			GUI.DrawTexture(new Rect(num4, num5, num2, num3), (Texture)(object)panelTexture);
			GUI.color = Accent;
			GUI.DrawTexture(new Rect(num4, num5, 4f, num3), (Texture)(object)Texture2D.whiteTexture);
			GUI.DrawTexture(new Rect(num4, num5, num2, 3f), (Texture)(object)Texture2D.whiteTexture);
			GUI.color = Color.white;
			GUI.Label(new Rect(num4 + 20f, num5 + 14f, num2 - 40f, 36f), "ENEMY SOUNDBOARD", titleStyle);
			GUI.Label(new Rect(num4 + 20f, num5 + 52f, num2 - 40f, 25f), "WYBIERZ PRZECIWNIKA", smallStyle);
			float num6 = Mathf.Min(132f, Mathf.Max(34f, Mathf.Ceil((float)enemies.Count / 3f) * 32f));
			Rect val = default(Rect);
			((Rect)(ref val))..ctor(num4 + 18f, num5 + 80f, num2 - 36f, num6);
			tabScroll = GUI.BeginScrollView(val, tabScroll, new Rect(0f, 0f, num2 - 56f, Mathf.Max(num6, Mathf.Ceil((float)enemies.Count / 3f) * 32f)), false, false);
			float num7 = (num2 - 64f) / 3f;
			for (int i = 0; i < enemies.Count; i++)
			{
				if (GUI.Button(new Rect((float)(i % 3) * (num7 + 4f), (float)(i / 3 * 32), num7, 28f), enemies[i], (i == tab) ? activeTabStyle : tabStyle))
				{
					SelectTab(i);
				}
			}
			GUI.EndScrollView();
			float num8 = num5 + 96f + num6;
			GUI.Label(new Rect(num4 + 20f, num8, num2 - 40f, 28f), (enemies.Count > 0) ? enemies[tab].ToUpperInvariant() : "BRAK PRZECIWNIKOW", labelStyle);
			float num9 = Mathf.Ceil((float)kinds.Count / 3f) * 30f;
			float num10 = (num2 - 44f) / 3f;
			for (int j = 0; j < kinds.Count; j++)
			{
				if (GUI.Button(new Rect(num4 + 18f + (float)(j % 3) * (num10 + 4f), num8 + 34f + (float)(j / 3 * 30), num10, 26f), kinds[j], (j == kind) ? activeTabStyle : tabStyle))
				{
					SelectKind(j);
				}
			}
			float num11 = num8 + 44f + num9;
			GUI.Label(new Rect(num4 + 20f, num11, num2 - 40f, 22f), filtered.Count + " dzwiekow", smallStyle);
			num11 += 28f;
			int num12 = Math.Max(1, (int)((num5 + num3 - 120f - num11) / 34f));
			int num13 = Mathf.Clamp(selected - num12 / 2, 0, Math.Max(0, filtered.Count - num12));
			for (int k = num13; k < Math.Min(filtered.Count, num13 + num12); k++)
			{
				Entry entry = filtered[k];
				if (Object.op_Implicit((Object)(object)entry.Clip))
				{
					string text = ((k == selected) ? ">  " : "    ") + entry.Label + "   (" + entry.Clip.length.ToString("0.0") + " s)";
					if (GUI.Button(new Rect(num4 + 18f, num11 + (float)((k - num13) * 34), num2 - 36f, 30f), text, (k == selected) ? activeRowStyle : rowStyle))
					{
						selected = k;
						Play(entry);
						break;
					}
				}
			}
			if (filtered.Count == 0)
			{
				GUI.Label(new Rect(num4 + 20f, num11, num2 - 40f, 65f), scanning ? "Sprawdzanie dostepnosci nagran..." : "Brak dostepnych nagran. Katalog przygotowuje sie w tle.", smallStyle);
			}
			GUI.Label(new Rect(num4 + 20f, num5 + num3 - 112f, num2 - 40f, 40f), (playback.Active ? "ODTWARZANIE  /  " : "") + status, smallStyle);
			GUI.Label(new Rect(num4 + 20f, num5 + num3 - 68f, num2 - 40f, 55f), "LEWO / PRAWO  przeciwnik     TAB  rodzaj\nGORA / DOL  dzwiek     ENTER  odtworz\nBACKSPACE  stop     NUMPAD 8  zamknij     F5  odswiez", smallStyle);
			GUI.matrix = matrix;
			GUI.color = color;
			GUI.depth = depth;
		}
	}
	[HarmonyPatch(typeof(GameDirector), "Update")]
	internal static class FramePatch
	{
		private static void Postfix()
		{
			SoundboardUI.Instance?.Tick();
		}
	}
	[HarmonyPatch(typeof(PlayerVoiceChat), "TransmitEnabledTick")]
	internal static class TransmitPatch
	{
		private static void Postfix(PlayerVoiceChat __instance)
		{
			SoundboardUI.Instance?.KeepTransmitting(__instance);
		}
	}
}