Decompiled source of Poltergeist Manifest Voice v1.1.0

BepInEx/plugins/PoltergeistManifestVoice/PoltergeistManifestVoice.dll

Decompiled 4 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Poltergeist;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[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("PoltergeistManifestVoice")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("PoltergeistManifestVoice")]
[assembly: AssemblyTitle("PoltergeistManifestVoice")]
[assembly: AssemblyVersion("1.1.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 PoltergeistManifestVoice
{
	internal static class GameAccess
	{
		internal static Type StartOfRoundType;

		internal static Type PlayerType;

		private static Func<object> sorInstance;

		private static Func<object, object> allPlayers;

		private static Func<object, object> localPlayer;

		private static Func<object, object> isDead;

		private static Func<object, object> playerClientId;

		private static Func<object, object> actualClientId;

		private static Func<object, object> voiceSource;

		private static Func<object, object> voiceSettings;

		private static Func<object, object> voiceState;

		private static MethodInfo updateVoiceEffects;

		private static readonly Dictionary<Type, Action<object, object>> set2DSetters = new Dictionary<Type, Action<object, object>>();

		private static readonly Dictionary<Type, Action<object, object>> volumeSetters = new Dictionary<Type, Action<object, object>>();

		internal static object StartOfRound => sorInstance();

		internal static bool Init()
		{
			StartOfRoundType = AccessTools.TypeByName("StartOfRound");
			PlayerType = AccessTools.TypeByName("GameNetcodeStuff.PlayerControllerB");
			if (StartOfRoundType == null || PlayerType == null)
			{
				return false;
			}
			sorInstance = StaticGetter(StartOfRoundType, "Instance");
			allPlayers = Getter(StartOfRoundType, "allPlayerScripts");
			localPlayer = Getter(StartOfRoundType, "localPlayerController");
			isDead = Getter(PlayerType, "isPlayerDead");
			playerClientId = Getter(PlayerType, "playerClientId");
			actualClientId = Getter(PlayerType, "actualClientId");
			voiceSource = Getter(PlayerType, "currentVoiceChatAudioSource");
			voiceSettings = Getter(PlayerType, "currentVoiceChatIngameSettings");
			voiceState = Getter(PlayerType, "voicePlayerState");
			updateVoiceEffects = AccessTools.Method(StartOfRoundType, "UpdatePlayerVoiceEffects", (Type[])null, (Type[])null);
			if (sorInstance != null && allPlayers != null && localPlayer != null && isDead != null && playerClientId != null && actualClientId != null && voiceSource != null && voiceSettings != null && voiceState != null)
			{
				return updateVoiceEffects != null;
			}
			return false;
		}

		internal static Component LocalPlayer(object sor)
		{
			object obj = localPlayer(sor);
			return (Component)((obj is Component) ? obj : null);
		}

		internal static Array AllPlayers(object sor)
		{
			return allPlayers(sor) as Array;
		}

		internal static void RefreshVanillaVoiceEffects(object sor)
		{
			try
			{
				updateVoiceEffects.Invoke(sor, null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("UpdatePlayerVoiceEffects failed: " + (ex.InnerException?.Message ?? ex.Message)));
			}
		}

		internal static bool IsDead(object player)
		{
			return (bool)isDead(player);
		}

		internal static ulong PlayerIndex(object player)
		{
			return (ulong)playerClientId(player);
		}

		internal static ulong NetClientId(object player)
		{
			return (ulong)actualClientId(player);
		}

		internal static AudioSource VoiceSource(object player)
		{
			object obj = voiceSource(player);
			return (AudioSource)((obj is AudioSource) ? obj : null);
		}

		internal static object VoiceSettings(object player)
		{
			return voiceSettings(player);
		}

		internal static object VoiceState(object player)
		{
			return voiceState(player);
		}

		internal static void SetVoice2D(object settings, bool value)
		{
			if (settings != null)
			{
				CachedSetter(set2DSetters, settings.GetType(), "set2D")?.Invoke(settings, value);
			}
		}

		internal static void SetVoiceVolume(object voicePlayerState, float volume)
		{
			if (voicePlayerState != null)
			{
				CachedSetter(volumeSetters, voicePlayerState.GetType(), "Volume")?.Invoke(voicePlayerState, volume);
			}
		}

		private static Func<object> StaticGetter(Type t, string name)
		{
			FieldInfo f = AccessTools.Field(t, name);
			if (f != null && f.IsStatic)
			{
				return () => f.GetValue(null);
			}
			PropertyInfo p = AccessTools.Property(t, name);
			if (p != null)
			{
				MethodInfo? getMethod = p.GetGetMethod(nonPublic: true);
				if ((object)getMethod != null && getMethod.IsStatic)
				{
					return () => p.GetValue(null);
				}
			}
			Plugin.Log.LogError((object)("Missing static member " + t.Name + "." + name));
			return null;
		}

		private static Func<object, object> Getter(Type t, string name)
		{
			FieldInfo f = AccessTools.Field(t, name);
			if (f != null)
			{
				return (object o) => f.GetValue(o);
			}
			PropertyInfo p = AccessTools.Property(t, name);
			if (p != null)
			{
				return (object o) => p.GetValue(o);
			}
			Plugin.Log.LogError((object)("Missing member " + t.Name + "." + name));
			return null;
		}

		private static Action<object, object> CachedSetter(Dictionary<Type, Action<object, object>> cache, Type t, string name)
		{
			if (cache.TryGetValue(t, out var value))
			{
				return value;
			}
			FieldInfo f = AccessTools.Field(t, name);
			PropertyInfo p = ((f == null) ? AccessTools.Property(t, name) : null);
			if (f != null)
			{
				value = delegate(object o, object v)
				{
					f.SetValue(o, v);
				};
			}
			else if (p != null && p.CanWrite)
			{
				value = delegate(object o, object v)
				{
					p.SetValue(o, v);
				};
			}
			else
			{
				Plugin.Log.LogWarning((object)("Missing member " + t.Name + "." + name));
			}
			cache[t] = value;
			return value;
		}
	}
	internal class GhostPitchFilter : MonoBehaviour
	{
		private const int BUFFER = 4096;

		private const int WINDOW = 1600;

		private static readonly float[] Gain = BuildGain();

		private volatile float ratio = 1f;

		private volatile bool active;

		private volatile bool resetPending = true;

		private float[][] buf;

		private int channels;

		private int write;

		private float delay;

		internal void SetPitch(float pitch)
		{
			ratio = pitch;
			active = true;
		}

		internal void Bypass()
		{
			if (active)
			{
				active = false;
				resetPending = true;
			}
		}

		private static float[] BuildGain()
		{
			float[] array = new float[1600];
			for (int i = 0; i < 1600; i++)
			{
				double num = Math.Sin(Math.PI * (double)i / 1600.0);
				array[i] = (float)(num * num);
			}
			return array;
		}

		private void OnAudioFilterRead(float[] data, int ch)
		{
			if (!active || ch <= 0)
			{
				return;
			}
			if (buf == null || channels != ch || resetPending)
			{
				if (buf == null || channels != ch)
				{
					buf = new float[ch][];
					for (int i = 0; i < ch; i++)
					{
						buf[i] = new float[4096];
					}
					channels = ch;
				}
				else
				{
					for (int j = 0; j < ch; j++)
					{
						Array.Clear(buf[j], 0, 4096);
					}
				}
				write = 0;
				delay = 0f;
				resetPending = false;
			}
			float num = 1f - ratio;
			int num2 = data.Length / ch;
			for (int k = 0; k < num2; k++)
			{
				int num3 = k * ch;
				for (int l = 0; l < ch; l++)
				{
					buf[l][write] = data[num3 + l];
				}
				float num4 = delay;
				float num5 = num4 + 800f;
				if (num5 >= 1600f)
				{
					num5 -= 1600f;
				}
				float num6 = Gain[(int)num4];
				float num7 = Gain[(int)num5];
				for (int m = 0; m < ch; m++)
				{
					float[] b = buf[m];
					data[num3 + m] = Tap(b, (float)write - num4) * num6 + Tap(b, (float)write - num5) * num7;
				}
				write = (write + 1) & 0xFFF;
				delay += num;
				if (delay >= 1600f)
				{
					delay -= 1600f;
				}
				else if (delay < 0f)
				{
					delay += 1600f;
				}
			}
		}

		private static float Tap(float[] b, float pos)
		{
			if (pos < 0f)
			{
				pos += 4096f;
			}
			int num = (int)pos;
			float num2 = pos - (float)num;
			num &= 0xFFF;
			int num3 = (num + 1) & 0xFFF;
			return b[num] + (b[num3] - b[num]) * num2;
		}
	}
	internal static class Net
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnHello;

			public static HandleNamedMessageDelegate <1>__OnConfig;

			public static HandleNamedMessageDelegate <2>__OnPitch;
		}

		private const string MSG_HELLO = "PoltergeistManifestVoice.Hello";

		private const string MSG_CONFIG = "PoltergeistManifestVoice.Config";

		private const string MSG_PITCH = "PoltergeistManifestVoice.Pitch";

		private static readonly Dictionary<ulong, float> pitches = new Dictionary<ulong, float>();

		private static float? hostRange;

		private static CustomMessagingManager registeredOn;

		private static NetworkManager NM => NetworkManager.Singleton;

		private static bool IsServer
		{
			get
			{
				if ((Object)(object)NM != (Object)null)
				{
					return NM.IsServer;
				}
				return false;
			}
		}

		internal static float HearingRange
		{
			get
			{
				if (!IsServer && hostRange.HasValue)
				{
					return hostRange.Value;
				}
				return Plugin.HearingRange.Value;
			}
		}

		internal static float PitchFor(ulong clientId)
		{
			if (!pitches.TryGetValue(clientId, out var value))
			{
				return 1f;
			}
			return value;
		}

		internal static void Setup()
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Expected O, but got Unknown
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Expected O, but got Unknown
			NetworkManager nM = NM;
			if (!((Object)(object)nM == (Object)null) && nM.IsListening && nM.CustomMessagingManager != null)
			{
				CustomMessagingManager customMessagingManager = nM.CustomMessagingManager;
				if (registeredOn != customMessagingManager)
				{
					pitches.Clear();
					hostRange = null;
				}
				customMessagingManager.UnregisterNamedMessageHandler("PoltergeistManifestVoice.Hello");
				customMessagingManager.UnregisterNamedMessageHandler("PoltergeistManifestVoice.Config");
				customMessagingManager.UnregisterNamedMessageHandler("PoltergeistManifestVoice.Pitch");
				object obj = <>O.<0>__OnHello;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnHello;
					<>O.<0>__OnHello = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltergeistManifestVoice.Hello", (HandleNamedMessageDelegate)obj);
				object obj2 = <>O.<1>__OnConfig;
				if (obj2 == null)
				{
					HandleNamedMessageDelegate val2 = OnConfig;
					<>O.<1>__OnConfig = val2;
					obj2 = (object)val2;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltergeistManifestVoice.Config", (HandleNamedMessageDelegate)obj2);
				object obj3 = <>O.<2>__OnPitch;
				if (obj3 == null)
				{
					HandleNamedMessageDelegate val3 = OnPitch;
					<>O.<2>__OnPitch = val3;
					obj3 = (object)val3;
				}
				customMessagingManager.RegisterNamedMessageHandler("PoltergeistManifestVoice.Pitch", (HandleNamedMessageDelegate)obj3);
				registeredOn = customMessagingManager;
				if (!nM.IsServer)
				{
					Send("PoltergeistManifestVoice.Hello", 0uL, new byte[1]);
				}
			}
		}

		internal static void SendOwnPitch(float pitch)
		{
			NetworkManager nM = NM;
			if (!((Object)(object)nM == (Object)null) && nM.IsListening && registeredOn != null)
			{
				ulong localClientId = nM.LocalClientId;
				pitches[localClientId] = pitch;
				byte[] payload = PitchPayload(localClientId, pitch);
				if (nM.IsServer)
				{
					SendToAllClients("PoltergeistManifestVoice.Pitch", payload);
				}
				else
				{
					Send("PoltergeistManifestVoice.Pitch", 0uL, payload);
				}
			}
		}

		internal static void BroadcastConfig()
		{
			if (IsServer && registeredOn != null)
			{
				SendToAllClients("PoltergeistManifestVoice.Config", BitConverter.GetBytes(Plugin.HearingRange.Value));
			}
		}

		private static void OnHello(ulong sender, FastBufferReader reader)
		{
			if (!IsServer)
			{
				return;
			}
			Send("PoltergeistManifestVoice.Config", sender, BitConverter.GetBytes(Plugin.HearingRange.Value));
			foreach (KeyValuePair<ulong, float> pitch in pitches)
			{
				Send("PoltergeistManifestVoice.Pitch", sender, PitchPayload(pitch.Key, pitch.Value));
			}
		}

		private static void OnConfig(ulong sender, FastBufferReader reader)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (IsServer || sender != 0L)
			{
				return;
			}
			byte[] array = Read(reader, 4);
			if (array != null)
			{
				float num = BitConverter.ToSingle(array, 0);
				if (!float.IsNaN(num) && !(num <= 0f))
				{
					hostRange = num;
					Plugin.Log.LogInfo((object)$"Hearing range synced from host: {num}m");
				}
			}
		}

		private static void OnPitch(ulong sender, FastBufferReader reader)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			byte[] array = Read(reader, 12);
			if (array == null)
			{
				return;
			}
			ulong key = BitConverter.ToUInt64(array, 0);
			float num = Plugin.ClampPitch(BitConverter.ToSingle(array, 8));
			if (IsServer)
			{
				key = sender;
				pitches[key] = num;
				byte[] payload = PitchPayload(key, num);
				{
					foreach (ulong connectedClientsId in NM.ConnectedClientsIds)
					{
						if (connectedClientsId != NM.LocalClientId && connectedClientsId != sender)
						{
							Send("PoltergeistManifestVoice.Pitch", connectedClientsId, payload);
						}
					}
					return;
				}
			}
			if (sender == 0L)
			{
				pitches[key] = num;
			}
		}

		private static byte[] PitchPayload(ulong clientId, float pitch)
		{
			byte[] array = new byte[12];
			BitConverter.GetBytes(clientId).CopyTo(array, 0);
			BitConverter.GetBytes(pitch).CopyTo(array, 8);
			return array;
		}

		private static byte[] Read(FastBufferReader reader, int size)
		{
			try
			{
				if (((FastBufferReader)(ref reader)).Length - ((FastBufferReader)(ref reader)).Position < size)
				{
					return null;
				}
				byte[] result = new byte[size];
				((FastBufferReader)(ref reader)).ReadBytesSafe(ref result, size, 0);
				return result;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Bad message: " + ex.Message));
				return null;
			}
		}

		private static void SendToAllClients(string msg, byte[] payload)
		{
			NetworkManager nM = NM;
			foreach (ulong connectedClientsId in nM.ConnectedClientsIds)
			{
				if (connectedClientsId != nM.LocalClientId)
				{
					Send(msg, connectedClientsId, payload);
				}
			}
		}

		private unsafe static void Send(string msg, ulong target, byte[] payload)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(payload.Length, (Allocator)2, -1);
				try
				{
					((FastBufferWriter)(ref val)).WriteBytesSafe(payload, payload.Length, 0);
					NM.CustomMessagingManager.SendNamedMessage(msg, target, val, (NetworkDelivery)3);
				}
				finally
				{
					((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Failed to send " + msg + ": " + ex.Message));
			}
		}
	}
	internal static class Patches
	{
		[HarmonyPatch]
		internal static class StartOfRoundStart
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.Method(GameAccess.StartOfRoundType, "Start", (Type[])null, (Type[])null);
			}

			private static void Postfix()
			{
				Net.Setup();
				Net.BroadcastConfig();
				VoiceController.Instance?.OnSessionStart();
			}
		}

		[HarmonyPatch]
		internal static class UpdatePlayerVoiceEffects
		{
			private static MethodBase TargetMethod()
			{
				return AccessTools.Method(GameAccess.StartOfRoundType, "UpdatePlayerVoiceEffects", (Type[])null, (Type[])null);
			}

			private static void Postfix()
			{
				VoiceController.Instance?.ReapplyActive();
			}
		}
	}
	[BepInPlugin("PoltergeistManifestVoice", "Poltergeist Manifest Voice", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "PoltergeistManifestVoice";

		public const string NAME = "Poltergeist Manifest Voice";

		public const string VERSION = "1.1.0";

		public const float MIN_PITCH = 0.5f;

		public const float MAX_PITCH = 2f;

		public const float RANDOM_DEADZONE = 0.15f;

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> HearingRange;

		internal static ConfigEntry<float> Pitch;

		internal static ConfigEntry<bool> RandomPitch;

		private void Awake()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			HearingRange = ((BaseUnityPlugin)this).Config.Bind<float>("Synced", "Hearing Range", 20f, new ConfigDescription("How close (in metres) a living player must be to a manifesting ghost to hear its voice.\nThe host's value is used for everyone in the lobby.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 200f), Array.Empty<object>()));
			Pitch = ((BaseUnityPlugin)this).Config.Bind<float>("Client-Side", "Voice Pitch", 1f, new ConfigDescription("How your ghost voice sounds to the living while you manifest.\n1.0 = your normal voice. Above 1 = higher (eerie, childlike). Below 1 = lower (deep, demonic).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 2f), Array.Empty<object>()));
			RandomPitch = ((BaseUnityPlugin)this).Config.Bind<bool>("Client-Side", "Random Pitch", false, "If enabled, Voice Pitch is ignored and each manifest picks a random pitch between " + $"{0.5f} and {2f} (never close to your normal voice).");
			HearingRange.SettingChanged += delegate
			{
				Net.BroadcastConfig();
			};
			Pitch.SettingChanged += delegate
			{
				VoiceController.Instance?.AnnounceOwnPitch(reroll: true);
			};
			RandomPitch.SettingChanged += delegate
			{
				VoiceController.Instance?.AnnounceOwnPitch(reroll: true);
			};
			if (!GameAccess.Init())
			{
				Log.LogError((object)"Could not find the game members this addon needs; it will stay inactive.");
				return;
			}
			Harmony val = new Harmony("PoltergeistManifestVoice");
			val.PatchAll(typeof(Patches.StartOfRoundStart));
			val.PatchAll(typeof(Patches.UpdatePlayerVoiceEffects));
			GameObject val2 = new GameObject("PoltergeistManifestVoice")
			{
				hideFlags = (HideFlags)61
			};
			Object.DontDestroyOnLoad((Object)val2);
			val2.AddComponent<VoiceController>();
			Log.LogInfo((object)"Poltergeist Manifest Voice v1.1.0 loaded");
		}

		internal static float ClampPitch(float p)
		{
			if (!float.IsNaN(p))
			{
				if (!(p < 0.5f))
				{
					if (!(p > 2f))
					{
						return p;
					}
					return 2f;
				}
				return 0.5f;
			}
			return 1f;
		}
	}
	internal class VoiceController : MonoBehaviour
	{
		private struct ActiveVoice
		{
			public object Player;

			public GhostHead Head;

			public float Volume;

			public float Pitch;
		}

		private const float HEAD_REFRESH_INTERVAL = 1f;

		private const float EDGE_FADE = 0.15f;

		private const float REROLL_DELAY = 1.5f;

		private GhostHead[] heads = Array.Empty<GhostHead>();

		private float nextHeadRefresh;

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

		private Dictionary<int, ActiveVoice> nextActive = new Dictionary<int, ActiveVoice>();

		private static readonly Random rng = new Random();

		private float ownPitch = 1f;

		private bool lastLocalDead;

		private bool lastOwnManifest;

		private float rerollAt = -1f;

		internal static VoiceController Instance { get; private set; }

		private void Awake()
		{
			Instance = this;
		}

		internal void OnSessionStart()
		{
			active.Clear();
			heads = Array.Empty<GhostHead>();
			nextHeadRefresh = 0f;
			lastLocalDead = false;
			lastOwnManifest = false;
			rerollAt = -1f;
			AnnounceOwnPitch(reroll: true);
		}

		internal void AnnounceOwnPitch(bool reroll)
		{
			if (reroll)
			{
				ownPitch = (Plugin.RandomPitch.Value ? RandomPitch() : Plugin.ClampPitch(Plugin.Pitch.Value));
			}
			Net.SendOwnPitch(ownPitch);
		}

		private static float RandomPitch()
		{
			float num = 1.15f;
			float num2 = 0.85f - 0.5f;
			float num3 = 2f - num;
			float num4 = (float)rng.NextDouble() * (num2 + num3);
			if (!(num4 < num2))
			{
				return num + (num4 - num2);
			}
			return 0.5f + num4;
		}

		private void SpeakerTick(bool localDead)
		{
			GhostHead val = (((Object)(object)SpectatorCamController.instance != (Object)null) ? SpectatorCamController.instance.head : null);
			bool flag = localDead && (Object)(object)val != (Object)null && val.IsManifesting();
			if (localDead && !lastLocalDead)
			{
				AnnounceOwnPitch(reroll: true);
			}
			if (lastOwnManifest && !flag && Plugin.RandomPitch.Value)
			{
				rerollAt = Time.time + 1.5f;
			}
			if (rerollAt > 0f && Time.time >= rerollAt && !flag)
			{
				rerollAt = -1f;
				AnnounceOwnPitch(reroll: true);
			}
			lastLocalDead = localDead;
			lastOwnManifest = flag;
		}

		private void LateUpdate()
		{
			object startOfRound = GameAccess.StartOfRound;
			Component val = ((startOfRound != null) ? GameAccess.LocalPlayer(startOfRound) : null);
			if ((Object)(object)val == (Object)null)
			{
				active.Clear();
				return;
			}
			bool flag = GameAccess.IsDead(val);
			SpeakerTick(flag);
			Array array = GameAccess.AllPlayers(startOfRound);
			nextActive.Clear();
			if (!flag && array != null)
			{
				CollectAudibleGhosts(val, array);
			}
			bool flag2 = false;
			foreach (KeyValuePair<int, ActiveVoice> item in active)
			{
				if (!nextActive.ContainsKey(item.Key))
				{
					Silence(item.Value.Player);
					flag2 = true;
				}
			}
			Dictionary<int, ActiveVoice> dictionary = nextActive;
			Dictionary<int, ActiveVoice> dictionary2 = active;
			active = dictionary;
			nextActive = dictionary2;
			if (flag2)
			{
				GameAccess.RefreshVanillaVoiceEffects(startOfRound);
			}
			ReapplyActive();
		}

		private void CollectAudibleGhosts(Component local, Array players)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			RefreshHeads();
			float hearingRange = Net.HearingRange;
			float num = hearingRange * 0.85f;
			Vector3 position = local.transform.position;
			GhostHead[] array = heads;
			foreach (GhostHead val in array)
			{
				if ((Object)(object)val == (Object)null || !val.IsManifesting())
				{
					continue;
				}
				object obj = FindDeadPlayerFor(((NetworkBehaviour)val).OwnerClientId, players, local);
				if (obj != null)
				{
					Vector3 position2 = ((Component)val).transform.position;
					float num2 = position2.x - position.x;
					float num3 = position2.y - position.y;
					float num4 = position2.z - position.z;
					float num5 = (float)Math.Sqrt(num2 * num2 + num3 * num3 + num4 * num4);
					if (!(num5 > hearingRange))
					{
						float volume = ((num5 <= num) ? 1f : (1f - (num5 - num) / (hearingRange - num)));
						int key = (int)GameAccess.PlayerIndex(obj);
						ActiveVoice value;
						float pitch = ((active.TryGetValue(key, out value) && (Object)(object)value.Head == (Object)(object)val) ? value.Pitch : Net.PitchFor(((NetworkBehaviour)val).OwnerClientId));
						nextActive[key] = new ActiveVoice
						{
							Player = obj,
							Head = val,
							Volume = volume,
							Pitch = pitch
						};
					}
				}
			}
		}

		private static object FindDeadPlayerFor(ulong netClientId, Array players, Component local)
		{
			foreach (object player in players)
			{
				if (player != null && player != local && GameAccess.IsDead(player) && GameAccess.NetClientId(player) == netClientId)
				{
					return player;
				}
			}
			return null;
		}

		private void RefreshHeads()
		{
			if (!(Time.time < nextHeadRefresh))
			{
				nextHeadRefresh = Time.time + 1f;
				heads = Object.FindObjectsOfType<GhostHead>();
			}
		}

		internal void ReapplyActive()
		{
			foreach (ActiveVoice value in active.Values)
			{
				MakeAudible(value);
			}
		}

		private static void MakeAudible(ActiveVoice v)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)v.Head == (Object)null)
			{
				return;
			}
			AudioSource val = GameAccess.VoiceSource(v.Player);
			if (!((Object)(object)val == (Object)null))
			{
				((Component)val).transform.position = ((Component)v.Head).transform.position;
				val.spatialBlend = 1f;
				val.panStereo = 0f;
				AudioLowPassFilter component = ((Component)val).GetComponent<AudioLowPassFilter>();
				if ((Object)(object)component != (Object)null)
				{
					((Behaviour)component).enabled = false;
				}
				AudioHighPassFilter component2 = ((Component)val).GetComponent<AudioHighPassFilter>();
				if ((Object)(object)component2 != (Object)null)
				{
					((Behaviour)component2).enabled = false;
				}
				GameAccess.SetVoice2D(GameAccess.VoiceSettings(v.Player), value: false);
				GameAccess.SetVoiceVolume(GameAccess.VoiceState(v.Player), v.Volume);
				if (Math.Abs(v.Pitch - 1f) < 0.01f)
				{
					PitchFilterFor(val, create: false)?.Bypass();
				}
				else
				{
					PitchFilterFor(val, create: true).SetPitch(v.Pitch);
				}
			}
		}

		private static void Silence(object player)
		{
			if (player != null)
			{
				GameAccess.SetVoiceVolume(GameAccess.VoiceState(player), GameAccess.IsDead(player) ? 0f : 1f);
				AudioSource val = GameAccess.VoiceSource(player);
				if ((Object)(object)val != (Object)null)
				{
					PitchFilterFor(val, create: false)?.Bypass();
				}
			}
		}

		private static GhostPitchFilter PitchFilterFor(AudioSource src, bool create)
		{
			GhostPitchFilter ghostPitchFilter = ((Component)src).GetComponent<GhostPitchFilter>();
			if ((Object)(object)ghostPitchFilter == (Object)null && create)
			{
				ghostPitchFilter = ((Component)src).gameObject.AddComponent<GhostPitchFilter>();
			}
			return ghostPitchFilter;
		}
	}
}