Decompiled source of HoodwinkVoice v1.0.0

plugins/HoodwinkVoice/HoodwinkVoice.dll

Decompiled 6 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using EntityStates;
using HarmonyLib;
using HoodwinkSurvivor;
using HoodwinkSurvivor.Audio;
using HoodwinkSurvivor.Skills;
using Microsoft.CodeAnalysis;
using RoR2;
using RoR2.ConVar;
using RoR2.SurvivorMannequins;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("HoodwinkVoice")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("HoodwinkVoice")]
[assembly: AssemblyTitle("HoodwinkVoice")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace HoodwinkSurvivor.Audio
{
	internal sealed class NativeAudioClip
	{
		internal readonly float[] Samples;

		internal readonly int Rate;

		internal readonly int Channels;

		internal readonly int Frames;

		private NativeAudioClip(float[] samples, int rate, int channels)
		{
			Samples = samples;
			Rate = rate;
			Channels = channels;
			Frames = samples.Length / channels;
		}

		internal static NativeAudioClip Load(string path)
		{
			using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path));
			Stream baseStream = binaryReader.BaseStream;
			if (baseStream.Length < 44 || baseStream.Length > 67108864 || new string(binaryReader.ReadChars(4)) != "RIFF")
			{
				throw new InvalidDataException("Invalid PCM RIFF header.");
			}
			if ((long)binaryReader.ReadUInt32() + 8L != baseStream.Length || new string(binaryReader.ReadChars(4)) != "WAVE")
			{
				throw new InvalidDataException("Invalid PCM WAVE size.");
			}
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			int num5 = 0;
			byte[] array = null;
			while (baseStream.Position + 8 <= baseStream.Length)
			{
				string text = new string(binaryReader.ReadChars(4));
				uint num6 = binaryReader.ReadUInt32();
				long num7 = baseStream.Position + num6;
				if (num7 > baseStream.Length)
				{
					throw new InvalidDataException("Truncated PCM chunk.");
				}
				if (text == "fmt ")
				{
					if (num6 < 16)
					{
						throw new InvalidDataException("Invalid PCM format chunk.");
					}
					num4 = binaryReader.ReadUInt16();
					num = binaryReader.ReadUInt16();
					num2 = binaryReader.ReadInt32();
					binaryReader.ReadUInt32();
					num5 = binaryReader.ReadUInt16();
					num3 = binaryReader.ReadUInt16();
				}
				else if (text == "data")
				{
					array = binaryReader.ReadBytes(checked((int)num6));
				}
				baseStream.Position = num7 + (num6 & 1);
			}
			if (num4 != 1 || num3 != 16 || num < 1 || num > 2 || num2 < 8000 || num2 > 192000 || num5 != num * 2 || array == null || array.Length == 0 || array.Length % num5 != 0)
			{
				throw new InvalidDataException("Expected nonempty PCM16 mono/stereo WAV.");
			}
			float[] array2 = new float[array.Length / 2];
			for (int i = 0; i < array2.Length; i++)
			{
				array2[i] = (float)(short)(array[i * 2] | (array[i * 2 + 1] << 8)) / 32768f;
			}
			return new NativeAudioClip(array2, num2, num);
		}
	}
	internal sealed class NativePcmOutput : IDisposable
	{
		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		private struct WaveFormat
		{
			internal ushort format;

			internal ushort channels;

			internal uint rate;

			internal uint bytesPerSecond;

			internal ushort blockAlign;

			internal ushort bits;

			internal ushort extra;
		}

		private struct WaveHeader
		{
			internal IntPtr data;

			internal uint length;

			internal uint recorded;

			internal UIntPtr user;

			internal uint flags;

			internal uint loops;

			internal IntPtr next;

			internal UIntPtr reserved;
		}

		private sealed class Buffer
		{
			internal IntPtr data;

			internal IntPtr header;

			internal bool prepared;

			internal bool submitted;
		}

		private sealed class Voice
		{
			internal int handle;

			internal string eventId;

			internal NativeAudioClip clip;

			internal double position;

			internal double step;

			internal float volume;

			internal float left;

			internal float right;

			internal float fade = 1f;

			internal float fadeStep;

			internal float attack = 1f;

			internal float attackStep;

			internal bool loop;

			internal bool protect;
		}

		internal const int OutputRate = 48000;

		internal const int FramesPerBuffer = 480;

		internal const int BufferCount = 4;

		internal const int MaxVoices = 40;

		private const uint Done = 1u;

		private const uint WaveMapper = uint.MaxValue;

		private readonly object gate = new object();

		private readonly List<Voice> voices = new List<Voice>(40);

		private readonly Dictionary<string, int> played = new Dictionary<string, int>(StringComparer.Ordinal);

		private readonly AutoResetEvent wake = new AutoResetEvent(initialState: false);

		private Thread worker;

		private volatile bool stopping;

		private volatile bool deviceOpen;

		private volatile bool failed;

		private bool paused;

		private bool muted;

		private float master = 0.4f;

		private float peak;

		private int nextHandle;

		private int resetSerial;

		private int submittedBuffers;

		private int submittedNonzero;

		private int completedBuffers;

		private string lastError = "";

		internal bool Failed => failed;

		internal bool DeviceOpen => deviceOpen;

		internal string LastError
		{
			get
			{
				lock (gate)
				{
					return lastError;
				}
			}
		}

		internal int VoiceCount
		{
			get
			{
				lock (gate)
				{
					return voices.Count;
				}
			}
		}

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

		internal int SubmittedBuffers => Volatile.Read(in submittedBuffers);

		internal int SubmittedNonzeroBuffers => Volatile.Read(in submittedNonzero);

		internal int CompletedBuffers => Volatile.Read(in completedBuffers);

		internal Dictionary<string, int> PlayedEventCounts
		{
			get
			{
				lock (gate)
				{
					return new Dictionary<string, int>(played);
				}
			}
		}

		internal Dictionary<string, int> ActiveEventCounts
		{
			get
			{
				lock (gate)
				{
					Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
					foreach (Voice voice in voices)
					{
						dictionary.TryGetValue(voice.eventId, out var value);
						dictionary[voice.eventId] = value + 1;
					}
					return dictionary;
				}
			}
		}

		[DllImport("winmm.dll")]
		private static extern uint waveOutOpen(out IntPtr handle, uint device, ref WaveFormat format, IntPtr callback, IntPtr instance, uint flags);

		[DllImport("winmm.dll")]
		private static extern uint waveOutPrepareHeader(IntPtr handle, IntPtr header, uint size);

		[DllImport("winmm.dll")]
		private static extern uint waveOutUnprepareHeader(IntPtr handle, IntPtr header, uint size);

		[DllImport("winmm.dll")]
		private static extern uint waveOutWrite(IntPtr handle, IntPtr header, uint size);

		[DllImport("winmm.dll")]
		private static extern uint waveOutReset(IntPtr handle);

		[DllImport("winmm.dll")]
		private static extern uint waveOutPause(IntPtr handle);

		[DllImport("winmm.dll")]
		private static extern uint waveOutRestart(IntPtr handle);

		[DllImport("winmm.dll")]
		private static extern uint waveOutClose(IntPtr handle);

		internal void Start()
		{
			if (worker == null)
			{
				worker = new Thread(Pump)
				{
					IsBackground = true,
					Name = "Hoodwink PCM output",
					Priority = ThreadPriority.AboveNormal
				};
				worker.Start();
			}
		}

		internal int Play(string eventId, NativeAudioClip clip, float pitch, float volume, float left, float right, bool loop, bool protect, float fadeInSeconds = 0f)
		{
			if (failed || stopping || clip == null)
			{
				return 0;
			}
			lock (gate)
			{
				if (voices.Count == 40)
				{
					int num = voices.FindIndex((Voice v) => !v.protect);
					if (num < 0)
					{
						if (!protect)
						{
							return 0;
						}
						num = 0;
					}
					voices.RemoveAt(num);
				}
				if (++nextHandle <= 0)
				{
					nextHandle = 1;
				}
				voices.Add(new Voice
				{
					handle = nextHandle,
					eventId = eventId,
					clip = clip,
					step = (double)clip.Rate * (double)pitch / 48000.0,
					volume = volume,
					left = left,
					right = right,
					loop = loop,
					protect = protect,
					attack = ((fadeInSeconds > 0f) ? 0f : 1f),
					attackStep = ((fadeInSeconds > 0f) ? (1f / (fadeInSeconds * 48000f)) : 0f)
				});
				played.TryGetValue(eventId, out var value);
				played[eventId] = value + 1;
				wake.Set();
				return nextHandle;
			}
		}

		internal bool IsPlaying(int handle)
		{
			lock (gate)
			{
				return voices.Exists((Voice v) => v.handle == handle);
			}
		}

		internal void SetSpatial(int handle, float left, float right)
		{
			lock (gate)
			{
				Voice voice = voices.Find((Voice v) => v.handle == handle);
				if (voice != null)
				{
					voice.left = left;
					voice.right = right;
				}
			}
		}

		internal void Stop(int handle, float fadeSeconds)
		{
			lock (gate)
			{
				Voice voice = voices.Find((Voice v) => v.handle == handle);
				if (voice != null)
				{
					if (!(fadeSeconds > 0f) || float.IsInfinity(fadeSeconds))
					{
						voices.Remove(voice);
					}
					else
					{
						voice.fadeStep = voice.fade / (Math.Min(fadeSeconds, 10f) * 48000f);
					}
				}
			}
		}

		internal void StopAll()
		{
			lock (gate)
			{
				voices.Clear();
				resetSerial++;
			}
			wake.Set();
		}

		internal void SetControls(float volume, bool pause, bool mute)
		{
			lock (gate)
			{
				master = Math.Max(0f, Math.Min(1f, volume));
				paused = pause;
				muted = mute;
			}
			wake.Set();
		}

		private static void Check(uint code, string operation)
		{
			if (code != 0)
			{
				throw new InvalidOperationException(operation + " returned MMRESULT " + code);
			}
		}

		private void Error(Exception error)
		{
			lock (gate)
			{
				failed = true;
				lastError = error.GetType().Name + ": " + error.Message;
				voices.Clear();
			}
		}

		private void Pump()
		{
			IntPtr handle = IntPtr.Zero;
			Buffer[] array = new Buffer[4];
			uint num = (uint)Marshal.SizeOf(typeof(WaveHeader));
			short[] array2 = new short[960];
			float[] mix = new float[array2.Length];
			bool flag = false;
			bool flag2 = false;
			int num2 = 0;
			try
			{
				WaveFormat format = new WaveFormat
				{
					format = 1,
					channels = 2,
					rate = 48000u,
					bytesPerSecond = 192000u,
					blockAlign = 4,
					bits = 16
				};
				Check(waveOutOpen(out handle, uint.MaxValue, ref format, IntPtr.Zero, IntPtr.Zero, 0u), "waveOutOpen");
				deviceOpen = true;
				for (int i = 0; i < array.Length; i++)
				{
					Buffer buffer = (array[i] = new Buffer());
					buffer.data = Marshal.AllocHGlobal(array2.Length * 2);
					buffer.header = Marshal.AllocHGlobal((int)num);
					Marshal.StructureToPtr(new WaveHeader
					{
						data = buffer.data,
						length = (uint)(array2.Length * 2)
					}, buffer.header, fDeleteOld: false);
					Check(waveOutPrepareHeader(handle, buffer.header, num), "waveOutPrepareHeader");
					buffer.prepared = true;
				}
				while (!stopping)
				{
					bool flag3;
					bool flag4;
					int num3;
					lock (gate)
					{
						flag3 = paused;
						flag4 = muted;
						num3 = resetSerial;
					}
					Buffer[] array3;
					if (num3 != num2 || (flag4 && !flag2))
					{
						Check(waveOutReset(handle), "waveOutReset");
						array3 = array;
						for (int j = 0; j < array3.Length; j++)
						{
							array3[j].submitted = false;
						}
						num2 = num3;
						flag = false;
					}
					flag2 = flag4;
					if (flag3 != flag)
					{
						Check(flag3 ? waveOutPause(handle) : waveOutRestart(handle), flag3 ? "waveOutPause" : "waveOutRestart");
						flag = flag3;
					}
					if (flag3)
					{
						wake.WaitOne(10);
						continue;
					}
					array3 = array;
					foreach (Buffer buffer2 in array3)
					{
						if (buffer2.submitted)
						{
							if ((Marshal.PtrToStructure<WaveHeader>(buffer2.header).flags & 1) == 0)
							{
								continue;
							}
							Interlocked.Increment(ref completedBuffers);
						}
						bool num4 = Mix(mix, array2);
						Marshal.Copy(array2, 0, buffer2.data, array2.Length);
						Check(waveOutWrite(handle, buffer2.header, num), "waveOutWrite");
						buffer2.submitted = true;
						Interlocked.Increment(ref submittedBuffers);
						if (num4)
						{
							Interlocked.Increment(ref submittedNonzero);
						}
					}
					wake.WaitOne(3);
				}
			}
			catch (Exception error)
			{
				Error(error);
			}
			finally
			{
				deviceOpen = false;
				Buffer[] array3;
				if (handle != IntPtr.Zero)
				{
					waveOutReset(handle);
					array3 = array;
					foreach (Buffer buffer3 in array3)
					{
						if (buffer3 != null && buffer3.prepared)
						{
							uint num5 = waveOutUnprepareHeader(handle, buffer3.header, num);
							int num6 = 0;
							while (num5 == 33 && num6 < 50)
							{
								Thread.Sleep(2);
								num5 = waveOutUnprepareHeader(handle, buffer3.header, num);
								num6++;
							}
							buffer3.prepared = num5 != 0;
							if (num5 != 0)
							{
								Error(new InvalidOperationException("waveOutUnprepareHeader returned " + num5));
							}
						}
					}
					uint num7 = waveOutClose(handle);
					if (num7 == 0)
					{
						array3 = array;
						foreach (Buffer buffer4 in array3)
						{
							if (buffer4 != null)
							{
								buffer4.prepared = false;
							}
							else
							{
								Error(new InvalidOperationException("waveOutClose returned " + num7));
							}
						}
					}
				}
				array3 = array;
				foreach (Buffer buffer5 in array3)
				{
					if (buffer5 != null && !buffer5.prepared)
					{
						if (buffer5.header != IntPtr.Zero)
						{
							Marshal.FreeHGlobal(buffer5.header);
						}
						if (buffer5.data != IntPtr.Zero)
						{
							Marshal.FreeHGlobal(buffer5.data);
						}
					}
				}
				lock (gate)
				{
					voices.Clear();
				}
			}
		}

		private bool Mix(float[] mix, short[] pcm)
		{
			Array.Clear(mix, 0, mix.Length);
			lock (gate)
			{
				for (int num = voices.Count - 1; num >= 0; num--)
				{
					Voice voice = voices[num];
					NativeAudioClip clip = voice.clip;
					for (int i = 0; i < 480; i++)
					{
						if (voice.position >= (double)clip.Frames)
						{
							if (!voice.loop)
							{
								break;
							}
							voice.position %= clip.Frames;
						}
						if (voice.fade <= 0f)
						{
							break;
						}
						int num2 = (int)voice.position;
						int num3 = Math.Min(num2 + 1, clip.Frames - 1);
						float num4 = (float)(voice.position - (double)num2);
						float num5 = (muted ? 0f : (master * voice.volume * voice.fade * voice.attack));
						int num6 = num2 * clip.Channels;
						int num7 = num3 * clip.Channels;
						float num8 = clip.Samples[num6] + (clip.Samples[num7] - clip.Samples[num6]) * num4;
						int num9 = ((clip.Channels == 2) ? 1 : 0);
						float num10 = clip.Samples[num6 + num9] + (clip.Samples[num7 + num9] - clip.Samples[num6 + num9]) * num4;
						mix[i * 2] += num8 * num5 * voice.left;
						mix[i * 2 + 1] += num10 * num5 * voice.right;
						voice.position += voice.step;
						voice.fade = Math.Max(0f, voice.fade - voice.fadeStep);
						voice.attack = Math.Min(1f, voice.attack + voice.attackStep);
					}
					if ((!voice.loop && voice.position >= (double)clip.Frames) || voice.fade <= 0f)
					{
						voices.RemoveAt(num);
					}
				}
				bool flag = false;
				for (int j = 0; j < mix.Length; j++)
				{
					float num11 = Math.Max(-1f, Math.Min(1f, mix[j]));
					peak = Math.Max(peak, Math.Abs(num11));
					pcm[j] = (short)Math.Round(num11 * 32767f);
					flag |= pcm[j] != 0;
				}
				return flag;
			}
		}

		public void Dispose()
		{
			if (!stopping)
			{
				stopping = true;
				wake.Set();
				if (worker != null && worker != Thread.CurrentThread && !worker.Join(2500))
				{
					Error(new TimeoutException("PCM output thread has not exited; native buffers remain owned until worker cleanup."));
				}
				else
				{
					wake.Dispose();
				}
			}
		}
	}
}
namespace HoodwinkVoice
{
	internal sealed class VoiceAudio : IDisposable
	{
		[Serializable]
		private sealed class EventFile
		{
			public string language = "";

			public EventDef[] events = Array.Empty<EventDef>();
		}

		[Serializable]
		internal sealed class EventDef
		{
			public string id = "";

			public string[] clips = Array.Empty<string>();

			public float volume = 1f;

			public float pitchMin = 1f;

			public float pitchMax = 1f;

			[NonSerialized]
			internal NativeAudioClip[] loaded;

			[NonSerialized]
			internal int lastVariant = -1;
		}

		private readonly Dictionary<string, EventDef> events = new Dictionary<string, EventDef>(StringComparer.Ordinal);

		private readonly NativePcmOutput output;

		private readonly ManualLogSource log;

		private readonly Random random = new Random();

		private string reportedError = "";

		private float nextSettingsRead;

		private float master = 1f;

		private float sfx = 1f;

		private bool focusedOnly;

		internal int ClipCount { get; }

		internal int EventCount => events.Count;

		internal bool IsPlaying(int handle)
		{
			return output.IsPlaying(handle);
		}

		internal bool HasEvent(string cue)
		{
			if (cue != null)
			{
				return events.ContainsKey(cue);
			}
			return false;
		}

		internal VoiceAudio(string directory, ManualLogSource logger)
		{
			//IL_02c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Invalid comparison between Unknown and I4
			log = logger;
			if (Environment.OSVersion.Platform != PlatformID.Win32NT)
			{
				throw new PlatformNotSupportedException("Hoodwink voice output requires Windows.");
			}
			EventFile eventFile = JsonUtility.FromJson<EventFile>(File.ReadAllText(Path.Combine(directory, "voice_events.json")));
			if (eventFile?.events == null || eventFile.language != "en" || eventFile.events.Length < 1 || eventFile.events.Length > 64)
			{
				throw new InvalidDataException("Invalid English voice event map.");
			}
			Dictionary<string, NativeAudioClip> dictionary = new Dictionary<string, NativeAudioClip>(StringComparer.Ordinal);
			EventDef[] array = eventFile.events;
			foreach (EventDef eventDef in array)
			{
				if (string.IsNullOrEmpty(eventDef.id) || events.ContainsKey(eventDef.id) || eventDef.clips == null || eventDef.clips.Length < 1 || eventDef.clips.Length > 32 || !VoicePolicy.Rules.ContainsKey(eventDef.id) || !Finite(eventDef.volume) || eventDef.volume < 0f || eventDef.volume > 4f || !Finite(eventDef.pitchMin) || !Finite(eventDef.pitchMax) || eventDef.pitchMin < 0.1f || eventDef.pitchMax > 4f || eventDef.pitchMin > eventDef.pitchMax)
				{
					throw new InvalidDataException("Invalid voice descriptor: " + eventDef.id);
				}
				eventDef.loaded = new NativeAudioClip[eventDef.clips.Length];
				for (int j = 0; j < eventDef.clips.Length; j++)
				{
					string text = eventDef.clips[j];
					if (text != Path.GetFileName(text) || !text.StartsWith("voice_hw_", StringComparison.Ordinal) || !text.EndsWith(".wav", StringComparison.OrdinalIgnoreCase))
					{
						throw new InvalidDataException("Invalid voice filename.");
					}
					if (!dictionary.TryGetValue(text, out var value))
					{
						value = NativeAudioClip.Load(Path.Combine(directory, text));
						dictionary.Add(text, value);
					}
					eventDef.loaded[j] = value;
				}
				events.Add(eventDef.id, eventDef);
			}
			if (events.Count != VoicePolicy.Rules.Count)
			{
				throw new InvalidDataException("Missing expected voice response group.");
			}
			ClipCount = dictionary.Count;
			output = new NativePcmOutput();
			if ((int)SystemInfo.graphicsDeviceType != 4)
			{
				output.Start();
			}
			Update();
		}

		internal int Play(string cue)
		{
			if (!events.TryGetValue(cue, out var value))
			{
				return 0;
			}
			int num = 0;
			if (value.loaded.Length > 1)
			{
				num = random.Next(value.loaded.Length - ((value.lastVariant >= 0) ? 1 : 0));
				if (value.lastVariant >= 0 && num >= value.lastVariant)
				{
					num++;
				}
			}
			float pitch = value.pitchMin + (value.pitchMax - value.pitchMin) * (float)random.NextDouble();
			int num2 = output.Play(cue, value.loaded[num], pitch, value.volume, 1f, 1f, loop: false, protect: false);
			if (num2 != 0)
			{
				value.lastVariant = num;
			}
			return num2;
		}

		internal void Stop(int handle)
		{
			output.Stop(handle, 0f);
		}

		internal void StopAll()
		{
			output.StopAll();
		}

		internal void Update()
		{
			if (Time.unscaledTime >= nextSettingsRead)
			{
				master = Mathf.Clamp01(Setting("volume_master", master * 100f) / 100f);
				sfx = Mathf.Clamp01(Setting("volume_sfx", sfx * 100f) / 100f);
				focusedOnly = Setting("audio_focused_only", focusedOnly ? 1 : 0) != 0f;
				nextSettingsRead = Time.unscaledTime + 0.1f;
			}
			bool pause = PauseManager.isPaused || Time.timeScale <= 0.0001f;
			bool mute = !VoicePlugin.Enabled.Value || (focusedOnly && !Application.isFocused);
			output.SetControls(master * sfx * 0.4f * VoicePlugin.Volume.Value, pause, mute);
			string lastError = output.LastError;
			if (lastError.Length > 0 && lastError != reportedError)
			{
				reportedError = lastError;
				log.LogWarning((object)("Hoodwink voice output: " + lastError));
			}
		}

		private static float Setting(string name, float previous)
		{
			Console instance = Console.instance;
			BaseConVar val = (Object.op_Implicit((Object)(object)instance) ? instance.FindConVar(name) : null);
			if (val == null || !float.TryParse(val.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || !Finite(result))
			{
				return previous;
			}
			return result;
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}

		public void Dispose()
		{
			output.Dispose();
		}
	}
	public sealed class VoiceBody : MonoBehaviour
	{
		private CharacterBody body;

		private bool subscribed;

		private bool announced;

		private bool deathReported;

		private bool hasHealth;

		private bool wasAlive;

		private bool moving;

		private bool movementRequested;

		private float previousLevel;

		private float movementStarted;

		private void OnEnable()
		{
			body = ((Component)this).GetComponent<CharacterBody>();
			announced = (deathReported = (hasHealth = (wasAlive = (moving = (movementRequested = false)))));
			previousLevel = (Object.op_Implicit((Object)(object)body) ? body.level : 0f);
			if (Object.op_Implicit((Object)(object)body) && !subscribed)
			{
				body.onSkillActivatedAuthority += OnSkill;
				subscribed = true;
			}
		}

		private void Update()
		{
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)body) || !VoiceOwnership.IsLocalBody(body) || !Object.op_Implicit((Object)(object)body.healthComponent))
			{
				return;
			}
			bool alive = body.healthComponent.alive;
			if (!announced && alive)
			{
				announced = true;
				previousLevel = body.level;
				VoiceRuntime.Emit(VoiceHooks.BeginLocalBody(body) ? "respawn" : "spawn", ((Component)this).transform);
			}
			if (hasHealth && wasAlive && !alive)
			{
				ReportDeath();
			}
			hasHealth = true;
			wasAlive = alive;
			if (!alive || !announced || Time.timeScale <= 0f || Time.deltaTime <= 0f)
			{
				moving = (movementRequested = false);
				return;
			}
			if (body.level > previousLevel + 0.01f)
			{
				VoiceRuntime.Emit("levelup", ((Component)this).transform);
			}
			previousLevel = body.level;
			CharacterMotor characterMotor = body.characterMotor;
			Vector3 val = (Object.op_Implicit((Object)(object)characterMotor) ? characterMotor.velocity : Vector3.zero);
			if (Object.op_Implicit((Object)(object)characterMotor) && characterMotor.isGrounded && Object.op_Implicit((Object)(object)body.inputBank) && ((Vector3)(ref body.inputBank.moveVector)).sqrMagnitude > 0.04f)
			{
				Vector2 val2 = new Vector2(val.x, val.z);
				if (((Vector2)(ref val2)).sqrMagnitude > 0.25f)
				{
					if (!moving)
					{
						moving = true;
						movementStarted = Time.time;
						movementRequested = false;
					}
					if (!movementRequested && Time.time - movementStarted >= 0.35f)
					{
						movementRequested = true;
						VoiceRuntime.Emit("move", ((Component)this).transform);
					}
					return;
				}
			}
			moving = (movementRequested = false);
		}

		private void OnSkill(GenericSkill skill)
		{
			if (Object.op_Implicit((Object)(object)skill) && VoiceOwnership.IsLocalBody(body) && Object.op_Implicit((Object)(object)body.healthComponent) && body.healthComponent.alive && Object.op_Implicit((Object)(object)body.skillLocator))
			{
				if ((Object)(object)skill == (Object)(object)body.skillLocator.primary)
				{
					VoiceRuntime.Emit("attack", ((Component)this).transform);
				}
				else if ((Object)(object)skill == (Object)(object)body.skillLocator.utility)
				{
					VoiceRuntime.Emit("scurry", ((Component)this).transform);
				}
				else if ((Object)(object)skill == (Object)(object)body.skillLocator.special)
				{
					VoiceRuntime.Emit("r_charge", ((Component)this).transform);
				}
			}
		}

		internal void ReportDeath()
		{
			if (!deathReported && VoiceOwnership.IsLocalBody(body))
			{
				deathReported = true;
				VoiceHooks.RememberDeath(body);
				VoiceRuntime.Emit("death", VoiceOwnership.DeathContext(body));
			}
		}

		private void OnDisable()
		{
			if (Object.op_Implicit((Object)(object)body) && subscribed)
			{
				body.onSkillActivatedAuthority -= OnSkill;
			}
			subscribed = false;
			moving = (movementRequested = false);
		}
	}
	internal sealed class VoiceDirector : IDisposable
	{
		private sealed class Pending
		{
			internal string Cue = "";

			internal Transform Context;

			internal float Due;
		}

		private readonly VoiceAudio audio;

		private readonly VoicePolicy policy = new VoicePolicy();

		private readonly Random random = new Random();

		private readonly List<Pending> pending = new List<Pending>(8);

		private readonly ManualLogSource log;

		private int handle;

		private int priority;

		private bool enabledLast = true;

		internal int ClipCount => audio.ClipCount;

		internal int EventCount => audio.EventCount;

		internal VoiceDirector(string directory, ManualLogSource logger)
		{
			log = logger;
			audio = new VoiceAudio(directory, logger);
		}

		internal void Request(string cue, Transform context, float delay)
		{
			if (!VoicePlugin.Enabled.Value || !Object.op_Implicit((Object)(object)context) || !((Component)context).gameObject.activeInHierarchy || !audio.HasEvent(cue) || float.IsNaN(delay) || float.IsInfinity(delay) || delay < 0f)
			{
				return;
			}
			if (delay > 0f)
			{
				for (int i = 0; i < pending.Count; i++)
				{
					if (pending[i].Cue == cue && (Object)(object)pending[i].Context == (Object)(object)context)
					{
						return;
					}
				}
				if (pending.Count < 8)
				{
					pending.Add(new Pending
					{
						Cue = cue,
						Context = context,
						Due = Time.unscaledTime + delay
					});
				}
			}
			else
			{
				TryPlay(cue);
			}
		}

		private void UpdateCompletion()
		{
			if (handle != 0 && !audio.IsPlaying(handle))
			{
				handle = (priority = 0);
				policy.Finished(Time.unscaledTime, VoicePlugin.MinimumGap.Value);
			}
		}

		private void TryPlay(string cue)
		{
			if (PauseManager.isPaused || Time.timeScale <= 0.0001f)
			{
				return;
			}
			UpdateCompletion();
			float unscaledTime = Time.unscaledTime;
			bool flag = handle != 0 && audio.IsPlaying(handle);
			if (!policy.CanStart(cue, unscaledTime, VoicePlugin.ChatterFrequency.Value, flag, priority, random.NextDouble(), out var rule))
			{
				return;
			}
			if (flag)
			{
				audio.Stop(handle);
			}
			int num = audio.Play(cue);
			if (num != 0)
			{
				handle = num;
				priority = rule.Priority;
				policy.Commit(cue, unscaledTime);
				if (VoicePlugin.LogVoiceEvents.Value)
				{
					log.LogInfo((object)("[HoodwinkVoice] " + cue));
				}
			}
		}

		internal void Update()
		{
			audio.Update();
			if (!VoicePlugin.Enabled.Value)
			{
				if (enabledLast)
				{
					StopAll();
				}
				enabledLast = false;
				return;
			}
			enabledLast = true;
			if (PauseManager.isPaused || Time.timeScale <= 0.0001f)
			{
				return;
			}
			UpdateCompletion();
			for (int num = this.pending.Count - 1; num >= 0; num--)
			{
				Pending pending = this.pending[num];
				if (!Object.op_Implicit((Object)(object)pending.Context) || !((Component)pending.Context).gameObject.activeInHierarchy || Time.unscaledTime > pending.Due + 2f)
				{
					this.pending.RemoveAt(num);
				}
				else if (!(Time.unscaledTime < pending.Due))
				{
					this.pending.RemoveAt(num);
					TryPlay(pending.Cue);
				}
			}
		}

		internal void StopAll()
		{
			audio.StopAll();
			pending.Clear();
			handle = (priority = 0);
			policy.Reset();
		}

		public void Dispose()
		{
			StopAll();
			audio.Dispose();
		}
	}
	public static class VoiceOwnership
	{
		public static bool IsHoodwink(CharacterBody body)
		{
			if (Object.op_Implicit((Object)(object)body))
			{
				return Object.op_Implicit((Object)(object)((Component)body).GetComponent<HoodwinkAcornPassive>());
			}
			return false;
		}

		public static bool IsLocalBody(CharacterBody body)
		{
			if (!IsHoodwink(body))
			{
				return false;
			}
			CharacterMaster master = body.master;
			foreach (LocalUser readOnlyLocalUsers in LocalUserManager.readOnlyLocalUsersList)
			{
				if (readOnlyLocalUsers != null && ((Object)(object)readOnlyLocalUsers.cachedBody == (Object)(object)body || (Object.op_Implicit((Object)(object)master) && (Object)(object)readOnlyLocalUsers.cachedMaster == (Object)(object)master)))
				{
					return true;
				}
			}
			return false;
		}

		internal static bool AreEnemies(CharacterBody attacker, CharacterBody victim)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)attacker) && Object.op_Implicit((Object)(object)victim) && (Object)(object)attacker != (Object)(object)victim && Object.op_Implicit((Object)(object)attacker.teamComponent) && Object.op_Implicit((Object)(object)victim.teamComponent))
			{
				TeamMask enemyTeams = TeamMask.GetEnemyTeams(attacker.teamComponent.teamIndex);
				return ((TeamMask)(ref enemyTeams)).HasTeam(victim.teamComponent.teamIndex);
			}
			return false;
		}

		internal static Transform DeathContext(CharacterBody body)
		{
			if (!Object.op_Implicit((Object)(object)body) || !Object.op_Implicit((Object)(object)body.master))
			{
				if (!Object.op_Implicit((Object)(object)body))
				{
					return null;
				}
				return ((Component)body).transform;
			}
			return ((Component)body.master).transform;
		}
	}
	public static class VoiceHooks
	{
		private const string HarmonyId = "local.hoodwink.voice.events";

		private static Harmony patches;

		private static bool installed;

		private static readonly HashSet<int> deadMasters = new HashSet<int>();

		private static readonly HashSet<int> localHoodwinkMasters = new HashSet<int>();

		public static void Install()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			if (installed)
			{
				return;
			}
			installed = true;
			try
			{
				patches = new Harmony("local.hoodwink.voice.events");
				patches.Patch((MethodBase)AccessTools.Method(typeof(HoodwinkAnimationController), "BeginDisplayEntrance", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(VoiceHooks), "AfterEntrance", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				patches.Patch((MethodBase)AccessTools.Method(typeof(FireSharpshooter), "OnEnter", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(VoiceHooks), "AfterUltimateFire", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(AcornShot), "FireOnCriticalHit", (Type[])null, (Type[])null);
				if (methodInfo == null)
				{
					throw new MissingMethodException(typeof(AcornShot).FullName, "FireOnCriticalHit");
				}
				patches.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(VoiceHooks), "AfterAcorn", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				CharacterBody.onBodyStartGlobal += OnBodyStart;
				GlobalEventManager.onServerDamageDealt += OnServerDamage;
				GlobalEventManager.onClientDamageNotified += OnClientDamage;
				GlobalEventManager.onCharacterDeathServer += OnServerDeath;
				Run.onRunStartGlobal += OnRunStart;
				Run.onRunDestroyGlobal += OnRunDestroy;
				Run.onClientGameOverGlobal += OnGameOver;
				foreach (CharacterBody readOnlyInstances in CharacterBody.readOnlyInstancesList)
				{
					OnBodyStart(readOnlyInstances);
				}
			}
			catch
			{
				Uninstall();
				throw;
			}
		}

		public static void Uninstall()
		{
			if (!installed)
			{
				return;
			}
			installed = false;
			CharacterBody.onBodyStartGlobal -= OnBodyStart;
			GlobalEventManager.onServerDamageDealt -= OnServerDamage;
			GlobalEventManager.onClientDamageNotified -= OnClientDamage;
			GlobalEventManager.onCharacterDeathServer -= OnServerDeath;
			Run.onRunStartGlobal -= OnRunStart;
			Run.onRunDestroyGlobal -= OnRunDestroy;
			Run.onClientGameOverGlobal -= OnGameOver;
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			patches = null;
			VoiceBody voiceBody = default(VoiceBody);
			foreach (CharacterBody readOnlyInstances in CharacterBody.readOnlyInstancesList)
			{
				if (Object.op_Implicit((Object)(object)readOnlyInstances) && ((Component)readOnlyInstances).TryGetComponent<VoiceBody>(ref voiceBody))
				{
					Object.Destroy((Object)(object)voiceBody);
				}
			}
			ResetRun();
		}

		private static void OnBodyStart(CharacterBody body)
		{
			if (VoiceOwnership.IsHoodwink(body) && !Object.op_Implicit((Object)(object)((Component)body).GetComponent<VoiceBody>()))
			{
				((Component)body).gameObject.AddComponent<VoiceBody>();
			}
		}

		internal static bool BeginLocalBody(CharacterBody body)
		{
			CharacterMaster val = (Object.op_Implicit((Object)(object)body) ? body.master : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return false;
			}
			int instanceID = ((Object)val).GetInstanceID();
			localHoodwinkMasters.Add(instanceID);
			return deadMasters.Remove(instanceID);
		}

		internal static void RememberDeath(CharacterBody body)
		{
			if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.master))
			{
				int instanceID = ((Object)body.master).GetInstanceID();
				localHoodwinkMasters.Add(instanceID);
				deadMasters.Add(instanceID);
			}
		}

		private static VoiceBody EnsureBody(CharacterBody body)
		{
			if (!Object.op_Implicit((Object)(object)body))
			{
				return null;
			}
			VoiceBody component = ((Component)body).GetComponent<VoiceBody>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return ((Component)body).gameObject.AddComponent<VoiceBody>();
			}
			return component;
		}

		private static void AfterEntrance(HoodwinkAnimationController __instance, bool __result)
		{
			if (installed && __result && Object.op_Implicit((Object)(object)__instance))
			{
				SurvivorMannequinSlotController componentInParent = ((Component)__instance).GetComponentInParent<SurvivorMannequinSlotController>();
				if (Object.op_Implicit((Object)(object)componentInParent) && Object.op_Implicit((Object)(object)componentInParent.networkUser) && componentInParent.networkUser.localUser != null)
				{
					VoiceRuntime.Emit("select", ((Component)__instance).transform, 1.0666667f);
				}
			}
		}

		private static void AfterUltimateFire(FireSharpshooter __instance)
		{
			if (installed && __instance != null && Object.op_Implicit((Object)(object)((EntityState)__instance).outer))
			{
				CharacterBody component = ((Component)((EntityState)__instance).outer).GetComponent<CharacterBody>();
				if (VoiceOwnership.IsLocalBody(component))
				{
					VoiceRuntime.Emit("r_fire", ((Component)component).transform);
				}
			}
		}

		private static void AfterAcorn(CharacterBody owner, float baseDamage)
		{
			if (installed && NetworkServer.active && VoiceOwnership.IsLocalBody(owner) && Object.op_Implicit((Object)(object)owner.healthComponent) && owner.healthComponent.alive && !float.IsNaN(baseDamage) && !float.IsInfinity(baseDamage) && !(baseDamage <= 0f))
			{
				VoiceRuntime.Emit("acorn", ((Component)owner).transform);
			}
		}

		internal static bool ValidDamage(float damage, bool rejected, bool dot, bool delayed, bool silent)
		{
			if (damage > 0f && !float.IsNaN(damage) && !float.IsInfinity(damage) && !rejected && !dot && !delayed)
			{
				return !silent;
			}
			return false;
		}

		private static bool IsDot(DamageTypeCombo type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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_0017: Invalid comparison between Unknown and I4
			if ((int)type.damageSource != 32)
			{
				return (type.damageType & 0x4000000) > 0;
			}
			return true;
		}

		private static bool IsSilent(DamageTypeCombo type)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			return (type.damageType & 0x800) > 0;
		}

		private static void OnServerDamage(DamageReport report)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_0030: 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_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Invalid comparison between Unknown and I4
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Invalid comparison between Unknown and I4
			if (!installed || report == null || report.damageInfo == null)
			{
				return;
			}
			DamageInfo damageInfo = report.damageInfo;
			if (!ValidDamage(report.damageDealt, damageInfo.rejected, (int)report.dotType != -1 || IsDot(damageInfo.damageType), damageInfo.delayedDamageSecondHalf, IsSilent(damageInfo.damageType)))
			{
				return;
			}
			if (VoiceOwnership.IsLocalBody(report.victimBody) && (Object)(object)report.attackerBody != (Object)(object)report.victimBody && Object.op_Implicit((Object)(object)report.victim) && report.victim.alive)
			{
				VoiceRuntime.Emit("hurt", ((Component)report.victimBody).transform);
			}
			if (VoiceOwnership.IsLocalBody(report.attackerBody) && VoiceOwnership.AreEnemies(report.attackerBody, report.victimBody) && Object.op_Implicit((Object)(object)damageInfo.inflictor) && !(damageInfo.procCoefficient <= 0f) && ((ProcChainMask)(ref damageInfo.procChainMask)).Equals(default(ProcChainMask)))
			{
				if ((int)damageInfo.damageType.damageSource == 2 && Object.op_Implicit((Object)(object)damageInfo.inflictor.GetComponent<HoodwinkNetProjectile>()))
				{
					VoiceRuntime.Emit("net_hit", ((Component)report.attackerBody).transform);
				}
				else if ((int)damageInfo.damageType.damageSource == 8 && Object.op_Implicit((Object)(object)damageInfo.inflictor.GetComponent<HoodwinkSharpshooterProjectile>()))
				{
					VoiceRuntime.Emit("r_hit", ((Component)report.attackerBody).transform);
				}
			}
		}

		private static void OnClientDamage(DamageDealtMessage message)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Invalid comparison between Unknown and I4
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Invalid comparison between Unknown and I4
			if (!installed || NetworkServer.active || message == null || !ValidDamage(message.damage, rejected: false, IsDot(message.damageType), message.delayedHit, message.isSilent))
			{
				return;
			}
			CharacterBody val = (Object.op_Implicit((Object)(object)message.victim) ? message.victim.GetComponent<CharacterBody>() : null);
			CharacterBody val2 = (Object.op_Implicit((Object)(object)message.attacker) ? message.attacker.GetComponent<CharacterBody>() : null);
			if (VoiceOwnership.IsLocalBody(val) && (Object)(object)val2 != (Object)(object)val && Object.op_Implicit((Object)(object)val.healthComponent) && val.healthComponent.alive)
			{
				VoiceRuntime.Emit("hurt", ((Component)val).transform);
			}
			if (VoiceOwnership.IsLocalBody(val2) && VoiceOwnership.AreEnemies(val2, val))
			{
				if ((int)message.damageType.damageSource == 2)
				{
					VoiceRuntime.Emit("net_hit", ((Component)val2).transform);
				}
				else if ((int)message.damageType.damageSource == 8)
				{
					VoiceRuntime.Emit("r_hit", ((Component)val2).transform);
				}
			}
		}

		private static void OnServerDeath(DamageReport report)
		{
			if (installed && report != null)
			{
				if (VoiceOwnership.IsLocalBody(report.victimBody))
				{
					EnsureBody(report.victimBody)?.ReportDeath();
				}
				if (VoiceOwnership.IsLocalBody(report.attackerBody) && VoiceOwnership.AreEnemies(report.attackerBody, report.victimBody))
				{
					VoiceRuntime.Emit("kill", ((Component)report.attackerBody).transform);
				}
			}
		}

		private static void OnGameOver(Run run, RunReport report)
		{
			if (!installed || report == null || !Object.op_Implicit((Object)(object)report.gameEnding))
			{
				return;
			}
			foreach (LocalUser readOnlyLocalUsers in LocalUserManager.readOnlyLocalUsersList)
			{
				CharacterMaster val = ((readOnlyLocalUsers != null) ? readOnlyLocalUsers.cachedMaster : null);
				if (Object.op_Implicit((Object)(object)val) && localHoodwinkMasters.Contains(((Object)val).GetInstanceID()))
				{
					VoiceRuntime.Emit(report.gameEnding.isWin ? "victory" : "defeat", Object.op_Implicit((Object)(object)run) ? ((Component)run).transform : ((Component)val).transform);
					break;
				}
			}
		}

		private static void ResetRun()
		{
			deadMasters.Clear();
			localHoodwinkMasters.Clear();
			VoiceRuntime.StopAll();
		}

		private static void OnRunStart(Run run)
		{
			ResetRun();
			foreach (CharacterBody readOnlyInstances in CharacterBody.readOnlyInstancesList)
			{
				if (VoiceOwnership.IsLocalBody(readOnlyInstances))
				{
					BeginLocalBody(readOnlyInstances);
				}
			}
		}

		private static void OnRunDestroy(Run run)
		{
			ResetRun();
		}
	}
	[BepInPlugin("local.hoodwink.voice", "Hoodwink Voice", "1.0.0")]
	[BepInDependency("local.hoodwink.survivor", "1.0.0")]
	public sealed class VoicePlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "local.hoodwink.voice";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> LogVoiceEvents;

		internal static ConfigEntry<float> Volume;

		internal static ConfigEntry<float> ChatterFrequency;

		internal static ConfigEntry<float> MinimumGap;

		private VoiceDirector? director;

		private void Awake()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Invalid comparison between Unknown and I4
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable original English Hoodwink voice lines. Skill sounds remain in the main mod.");
			Volume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "Volume", 1.7f, new ConfigDescription("Voice volume relative to the original voice master; game master/SFX volume, pause and focus mute also apply.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			ChatterFrequency = ((BaseUnityPlugin)this).Config.Bind<float>("Voice", "ChatterFrequency", 1f, new ConfigDescription("Probability multiplier. 0 silences voice requests; cooldowns and exclusive playback still apply.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>()));
			MinimumGap = ((BaseUnityPlugin)this).Config.Bind<float>("Voice", "MinimumGap", 1.5f, new ConfigDescription("Minimum quiet time after a line finishes. Death and run outcome can interrupt lower-priority lines.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 10f), Array.Empty<object>()));
			LogVoiceEvents = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogVoiceEvents", false, "Log successful voice playback only; no automatic capture or per-frame diagnostic output.");
			if ((int)SystemInfo.graphicsDeviceType == 4)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Hoodwink Voice is local client audio; skipping the headless server.");
				((Behaviour)this).enabled = false;
				return;
			}
			try
			{
				string directory = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Assets", "en");
				director = new VoiceDirector(directory, ((BaseUnityPlugin)this).Logger);
				VoiceRuntime.Director = director;
				SceneManager.activeSceneChanged += OnSceneChanged;
				Run.onRunDestroyGlobal += OnRunDestroyed;
				VoiceHooks.Install();
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Hoodwink Voice 1.0.0 ready: {director.ClipCount} English lines, {director.EventCount} response groups. Main mod unchanged.");
			}
			catch (Exception ex)
			{
				SceneManager.activeSceneChanged -= OnSceneChanged;
				Run.onRunDestroyGlobal -= OnRunDestroyed;
				VoiceHooks.Uninstall();
				director?.Dispose();
				director = null;
				VoiceRuntime.Director = null;
				((BaseUnityPlugin)this).Logger.LogError((object)("Hoodwink Voice disabled: " + ex));
				((Behaviour)this).enabled = false;
			}
		}

		private void Update()
		{
			director?.Update();
		}

		private static void OnSceneChanged(Scene previous, Scene next)
		{
			VoiceRuntime.StopAll();
		}

		private static void OnRunDestroyed(Run run)
		{
			VoiceRuntime.StopAll();
		}

		private void OnDestroy()
		{
			SceneManager.activeSceneChanged -= OnSceneChanged;
			Run.onRunDestroyGlobal -= OnRunDestroyed;
			VoiceHooks.Uninstall();
			VoiceRuntime.Director = null;
			director?.Dispose();
			director = null;
		}
	}
	internal static class VoiceRuntime
	{
		internal static VoiceDirector? Director;

		internal static void Emit(string cue, Transform context, float delay = 0f)
		{
			Director?.Request(cue, context, delay);
		}

		internal static void StopAll()
		{
			Director?.StopAll();
		}
	}
	internal sealed class VoicePolicy
	{
		internal readonly struct Rule
		{
			internal readonly float Chance;

			internal readonly float Cooldown;

			internal readonly int Priority;

			internal readonly bool Interrupt;

			internal Rule(float chance, float cooldown, int priority, bool interrupt = false)
			{
				Chance = chance;
				Cooldown = cooldown;
				Priority = priority;
				Interrupt = interrupt;
			}
		}

		internal static readonly Dictionary<string, Rule> Rules = new Dictionary<string, Rule>(StringComparer.Ordinal)
		{
			["select"] = new Rule(1f, 2f, 90),
			["spawn"] = new Rule(1f, 8f, 65),
			["respawn"] = new Rule(1f, 8f, 70),
			["move"] = new Rule(0.65f, 20f, 5),
			["attack"] = new Rule(0.25f, 8f, 10),
			["acorn"] = new Rule(0.65f, 10f, 25),
			["scurry"] = new Rule(0.8f, 10f, 30),
			["r_charge"] = new Rule(0.55f, 20f, 35),
			["r_fire"] = new Rule(1f, 6f, 45),
			["net_hit"] = new Rule(0.75f, 10f, 40),
			["r_hit"] = new Rule(0.75f, 10f, 45),
			["kill"] = new Rule(0.5f, 8f, 55),
			["hurt"] = new Rule(0.35f, 7f, 75),
			["death"] = new Rule(1f, 2f, 100, interrupt: true),
			["levelup"] = new Rule(0.7f, 15f, 50),
			["victory"] = new Rule(1f, 30f, 98, interrupt: true),
			["defeat"] = new Rule(1f, 30f, 99, interrupt: true)
		};

		private readonly Dictionary<string, float> lastPlayed = new Dictionary<string, float>(StringComparer.Ordinal);

		private float availableAt;

		internal bool CanStart(string cue, float now, float frequency, bool busy, int activePriority, double randomRoll, out Rule rule)
		{
			rule = default(Rule);
			if (cue == null || !Rules.TryGetValue(cue, out rule) || !Finite(now) || !Finite(frequency) || frequency <= 0f || randomRoll < 0.0 || randomRoll >= 1.0 || double.IsNaN(randomRoll))
			{
				return false;
			}
			if (lastPlayed.TryGetValue(cue, out var value) && now < value + rule.Cooldown)
			{
				return false;
			}
			bool flag = rule.Interrupt && rule.Priority > activePriority;
			if (busy && !flag)
			{
				return false;
			}
			if (!busy && now < availableAt && !rule.Interrupt)
			{
				return false;
			}
			return randomRoll < (double)Math.Min(1f, rule.Chance * frequency);
		}

		internal void Commit(string cue, float now)
		{
			lastPlayed[cue] = now;
		}

		internal void Finished(float now, float minimumGap)
		{
			availableAt = now + Math.Max(0f, minimumGap);
		}

		internal void Reset()
		{
			lastPlayed.Clear();
			availableAt = 0f;
		}

		private static bool Finite(float value)
		{
			if (!float.IsNaN(value))
			{
				return !float.IsInfinity(value);
			}
			return false;
		}
	}
}