Decompiled source of UltraVox v1.0.0

UltraVox.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[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("UltraVox")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a5239e9aa2a06076cb2fefe35c04a0423cf7e0ca")]
[assembly: AssemblyProduct("UltraVox")]
[assembly: AssemblyTitle("UltraVox")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace UltraVox;

internal static class DualBosses
{
	private class Boss
	{
		public string Pair;

		public int Number;

		public string Color;
	}

	private class DownWatch : MonoBehaviour
	{
		public EnemyVoice Voice;

		public EnemyIdentifier Eid;

		public Boss Boss;

		private Enemy enemy;

		private bool down;

		private void Start()
		{
			enemy = ((Component)this).GetComponent<Enemy>();
		}

		private void Update()
		{
			if (!((Object)(object)enemy == (Object)null) && !((Object)(object)Eid == (Object)null) && !Eid.dead)
			{
				bool flag = enemy.health <= 0f && (Object)(object)enemy.symbiote != (Object)null && enemy.symbiote.health > 0f;
				if (flag && !down)
				{
					Voice.StopTalking("its downed line plays instead");
					Voice.Mute(4f);
					StandIn(Eid, Boss).Say($"Down_{Boss.Number}", interrupt: true);
				}
				if (enemy.health > 0f)
				{
					down = false;
				}
				else if (flag)
				{
					down = true;
				}
			}
		}
	}

	private static readonly Dictionary<string, Boss> Named = new Dictionary<string, Boss>
	{
		["AGONY"] = new Boss
		{
			Pair = "SwordsmachineDual",
			Number = 1,
			Color = "DualRed"
		},
		["TUNDRA"] = new Boss
		{
			Pair = "SwordsmachineDual",
			Number = 2,
			Color = "DualBlue"
		},
		["ANGRY"] = new Boss
		{
			Pair = "SisyphusDual",
			Number = 1,
			Color = "DualRed"
		},
		["RUDE"] = new Boss
		{
			Pair = "SisyphusDual",
			Number = 2,
			Color = "DualBlue"
		},
		["AGONIS"] = new Boss
		{
			Pair = "FerrymanDual",
			Number = 1,
			Color = "DualRed"
		},
		["RUDRAKSHA"] = new Boss
		{
			Pair = "FerrymanDual",
			Number = 2,
			Color = "DualBlue"
		}
	};

	private const string Red = "DualRed";

	private const string Blue = "DualBlue";

	private const float PartnerWait = 0.3f;

	private const float LoadingWait = 3f;

	private const float SpawnQuiet = 3f;

	private const float SpawnAgainAfter = 10f;

	private static readonly Dictionary<EnemyIdentifier, Boss> present = new Dictionary<EnemyIdentifier, Boss>();

	private static readonly Dictionary<string, float> spawnSaidAt = new Dictionary<string, float>();

	private static readonly HashSet<string> spawnPending = new HashSet<string>();

	private const float DownQuiet = 4f;

	public static void OnSceneLoaded()
	{
		present.Clear();
		spawnSaidAt.Clear();
		spawnPending.Clear();
		EnemyIdentifier[] array = Object.FindObjectsOfType<EnemyIdentifier>(true);
		for (int i = 0; i < array.Length; i++)
		{
			Boss boss = Identify(array[i]);
			if (boss != null)
			{
				VoiceBank.Request(boss.Pair);
			}
		}
	}

	private static Boss Identify(EnemyIdentifier eid)
	{
		BossHealthBar component = ((Component)eid).GetComponent<BossHealthBar>();
		string text = (((Object)(object)component != (Object)null && component.bossName != null) ? component.bossName.ToUpperInvariant() : "");
		string text2 = ((Object)eid).name.ToUpperInvariant();
		foreach (KeyValuePair<string, Boss> item in Named)
		{
			if (text.Contains("\"" + item.Key + "\"") || text2.EndsWith(" " + item.Key))
			{
				return item.Value;
			}
		}
		return null;
	}

	public static void SetUp(EnemyVoice voice, EnemyIdentifier eid)
	{
		Boss boss = Identify(eid);
		if (boss != null)
		{
			voice.SubtitleColor = boss.Color;
			voice.SkipSpawnLine("one of the dual bosses says the pair's spawn line");
			present[eid] = boss;
			VoiceBank.Request(boss.Pair);
			voice.Report("Clue", $"dual boss: {boss.Pair} #{boss.Number}");
			DownWatch downWatch = default(DownWatch);
			if (!((Component)eid).TryGetComponent<DownWatch>(ref downWatch))
			{
				downWatch = ((Component)eid).gameObject.AddComponent<DownWatch>();
			}
			downWatch.Voice = voice;
			downWatch.Eid = eid;
			downWatch.Boss = boss;
			if ((!spawnSaidAt.TryGetValue(boss.Pair, out var value) || !(Time.time - value < 10f)) && spawnPending.Add(boss.Pair))
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(SpawnLine(boss.Pair));
			}
		}
	}

	private static IEnumerator SpawnLine(string pair)
	{
		yield return (object)new WaitForSeconds(0.3f);
		spawnPending.Remove(pair);
		spawnSaidAt[pair] = Time.time;
		List<EnemyIdentifier> list = new List<EnemyIdentifier>();
		foreach (KeyValuePair<EnemyIdentifier, Boss> item in present)
		{
			if (item.Value.Pair == pair && Alive(item.Key))
			{
				list.Add(item.Key);
			}
		}
		if (list.Count == 0)
		{
			yield break;
		}
		EnemyIdentifier speaker = list[Random.Range(0, list.Count)];
		foreach (EnemyIdentifier item2 in list)
		{
			EnemyVoice.For(item2).Mute(3f);
		}
		EnemyVoice voice = StandIn(speaker, present[speaker]);
		float giveUp = Time.time + 3f;
		while (!voice.Say($"Spawn_{present[speaker].Number}", interrupt: true, Time.time < giveUp) && Time.time < giveUp)
		{
			yield return null;
		}
	}

	private static bool Alive(EnemyIdentifier eid)
	{
		if ((Object)(object)eid != (Object)null)
		{
			return !eid.dead;
		}
		return false;
	}

	private static EnemyVoice StandIn(EnemyIdentifier eid, Boss boss)
	{
		//IL_0010: 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_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		//IL_0042: Expected O, but got Unknown
		GameObject val = new GameObject("UltraVox " + boss.Pair);
		val.transform.position = ((Component)eid).transform.position;
		Object.Destroy((Object)val, 15f);
		EnemyVoice enemyVoice = EnemyVoice.ForStandIn(val, boss.Pair);
		enemyVoice.SubtitleColor = boss.Color;
		return enemyVoice;
	}
}
internal class EarthmoverMoments : MonoBehaviour
{
	private static readonly Dictionary<string, string> Triggers = new Dictionary<string, string>
	{
		["Centaur Full"] = "Detected",
		["FakeExplosionSpawner"] = "Interrupted",
		["EntryTrigger"] = "InteriorBreach",
		["Forcefield/Deactivator"] = "ShieldDown",
		["BrainFightTrigger"] = "CoreBattle",
		["EscapeFightStart"] = "SecurityTeam"
	};

	private static readonly Dictionary<string, float> Delays = new Dictionary<string, float>
	{
		["Detected"] = 1f,
		["Interrupted"] = 2f
	};

	private static readonly HashSet<string> Screeches = new HashSet<string> { "CentaurSpotted", "CentaurHurt" };

	private const float ScreechVolume = 0.63f;

	private const string EarthmoverLoads = "Centaur Full";

	private const string Interrupted = "Interrupted";

	private const string Exploding = "Exploding";

	private const string ExplosionTrigger = "CountdownEnd";

	private static EarthmoverMoments instance;

	private readonly Queue<string> pending = new Queue<string>();

	private EnemyVoice voice;

	public static bool InLevel
	{
		get
		{
			if ((Object)(object)instance != (Object)null)
			{
				return VoiceBank.CurrentLevel == "7-4";
			}
			return false;
		}
	}

	public static void OnSceneLoaded()
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		if (VoiceBank.CurrentLevel == "7-4")
		{
			instance = new GameObject("UltraVox Earthmover").AddComponent<EarthmoverMoments>();
		}
	}

	private void Awake()
	{
		voice = EnemyVoice.ForStandIn(((Component)this).gameObject, "Centaur");
	}

	public static void Moment(string line, string what)
	{
		if (InLevel && SpecialMoments.FirstTime("Earthmover " + line))
		{
			instance.voice.Report(line, what);
			if (Delays.TryGetValue(line, out var value))
			{
				((MonoBehaviour)instance).StartCoroutine(instance.SpeakAfter(value, line));
			}
			else
			{
				instance.Speak(line);
			}
		}
	}

	private IEnumerator SpeakAfter(float delay, string line)
	{
		yield return (object)new WaitForSeconds(delay);
		ModLog.Guard("Earthmover", delegate
		{
			Speak(line);
		});
	}

	private void TurnDownScreeches()
	{
		AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true);
		foreach (AudioSource val in array)
		{
			if ((Object)(object)val.clip != (Object)null && Screeches.Contains(((Object)val.clip).name))
			{
				val.volume *= 0.63f;
				voice.Report("Clue", "turned down " + ((Object)val.clip).name + " on '" + PathOf(((Component)val).transform) + "'");
			}
		}
	}

	private void Speak(string line)
	{
		if (line == "Interrupted" || line == "Exploding")
		{
			pending.Clear();
			voice.Say(line, interrupt: true);
		}
		else
		{
			pending.Enqueue(line);
		}
	}

	public static void TriggerFired(ObjectActivator trigger)
	{
		string text = PathOf(((Component)trigger).transform);
		if (Plugin.LogVoiceEvents.Value)
		{
			instance.voice.Report("Clue", "7-4 activates '" + text + "'");
		}
		if (((Object)trigger).name == "Centaur Full" && SpecialMoments.FirstTime("Earthmover screech"))
		{
			instance.TurnDownScreeches();
		}
		if (Triggers.TryGetValue(text, out var value) || Triggers.TryGetValue(((Object)trigger).name, out value))
		{
			Moment(value, "'" + text + "' activates");
		}
		else if (((Object)trigger).name == "CountdownEnd")
		{
			instance.pending.Clear();
			instance.voice.StopTalking("the Earthmover explodes");
		}
	}

	public static void EnemyDied(EnemyIdentifier eid)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Invalid comparison between Unknown and I4
		if ((int)eid.enemyType == 35 && ((Object)eid).name == "Brain")
		{
			Moment("SelfDestruct", "the brain dies");
		}
	}

	public static void CountdownSet(Countdown timer, float seconds)
	{
		if (Plugin.LogVoiceEvents.Value)
		{
			instance.voice.Report("Clue", $"countdown '{PathOf(((Component)timer).transform)}' set to {seconds:0.00} s");
		}
		if (((Object)timer).name == "Countdown")
		{
			Moment("Exploding", $"the countdown is set to {seconds:0.00} s");
		}
	}

	private void Update()
	{
		ModLog.Guard("Earthmover", delegate
		{
			if (pending.Count > 0 && !voice.IsTalking)
			{
				voice.Say(pending.Dequeue(), interrupt: true);
			}
		});
	}

	public static string PathOf(Transform t)
	{
		if (!((Object)(object)t.parent != (Object)null))
		{
			return ((Object)t).name;
		}
		return ((Object)t.parent).name + "/" + ((Object)t).name;
	}
}
[HarmonyPatch(typeof(ObjectActivator), "Activate", new Type[] { typeof(bool) })]
internal static class EarthmoverTriggers
{
	private static void Postfix(ObjectActivator __instance)
	{
		ModLog.Guard("Earthmover trigger", delegate
		{
			if (EarthmoverMoments.InLevel)
			{
				EarthmoverMoments.TriggerFired(__instance);
			}
		});
	}
}
[HarmonyPatch(typeof(HookPoint), "SwitchPulled")]
internal static class EarthmoverSwitchPulled
{
	private static void Postfix(HookPoint __instance)
	{
		ModLog.Guard("Earthmover switch", delegate
		{
			EarthmoverMoments.Moment("BloodTanks", "switch hookpoint '" + EarthmoverMoments.PathOf(((Component)__instance).transform) + "' pulled");
		});
	}
}
[HarmonyPatch(typeof(EnemyIdentifier), "Start")]
internal static class EarthmoverSecuritySystem
{
	private static void Postfix(EnemyIdentifier __instance)
	{
		ModLog.Guard("Earthmover security system", delegate
		{
			if (EarthmoverMoments.InLevel)
			{
				Transform parent = ((Component)__instance).transform.parent;
				while ((Object)(object)parent != (Object)null)
				{
					if (((Object)parent).name == "SecuritySystem")
					{
						EarthmoverMoments.Moment("SecuritySystem", "'" + ((Object)__instance).name + "' appears");
						break;
					}
					parent = parent.parent;
				}
			}
		});
	}
}
[HarmonyPatch(typeof(Countdown), "ChangeTime")]
internal static class EarthmoverCountdownSet
{
	private static void Postfix(Countdown __instance, float newTime)
	{
		ModLog.Guard("Earthmover countdown", delegate
		{
			if (EarthmoverMoments.InLevel)
			{
				EarthmoverMoments.CountdownSet(__instance, newTime);
			}
		});
	}
}
internal class EnemyVoice : MonoBehaviour
{
	private class TypeState
	{
		public EnemyVoice Speaker;

		public float QuietUntil;
	}

	private const float PauseAfterLine = 1f;

	private const float ApproachedDistance = 12f;

	private const float ApproachedCooldown = 20f;

	private const float SpawnLineWait = 3f;

	private const float SpawnBusyWait = 1f;

	private const float StatueHandoff = 1.5f;

	private const int MaxSubtitles = 5;

	private const float SpawnFirstLimit = 5f;

	private const float DuckedVolume = 0.4f;

	private static readonly HashSet<string> Omniscient = new HashSet<string> { "Minos", "Leviathan", "Geryon", "Centaur", "Wicked", "HellItself" };

	private static readonly HashSet<string> DuckOwnSounds = new HashSet<string> { "Mindflayer", "MindflayerMale", "Sisyphus", "Geryon" };

	private static readonly HashSet<string> DeathFromBody = new HashSet<string> { "Geryon" };

	private static readonly Dictionary<string, float> ChatterSooner = new Dictionary<string, float>
	{
		["V2"] = 2.8f,
		["V2Second"] = 2.8f
	};

	internal static float StatueWokeAt = -100f;

	internal static float IdolAppearedAt = -100f;

	private static readonly Dictionary<string, TypeState> types = new Dictionary<string, TypeState>();

	private static GameObject player;

	private EnemyIdentifier eid;

	private bool standIn;

	private string enemyName;

	private AudioSource source;

	private AudioSource speaking;

	private float nextChatter;

	private float nextApproached;

	private float mutedUntil;

	private float spawnLineUntil = -1f;

	private float spawnBusyUntil = -1f;

	private int spawnFrame;

	private float spawnNotBefore;

	private string skipSpawnReason;

	private string spawnEvent = "Spawn";

	private bool guardsFerryman;

	private bool waitingForBossBar;

	private float spawnFirstUntil = -1f;

	private readonly Dictionary<AudioSource, float> ducked = new Dictionary<AudioSource, float>();

	private string nearEvent;

	private float nearDistance;

	private bool chatterOff;

	private string silentReason;

	private string subtitleColor;

	private const string SourceName = "UltraVox Voice";

	public bool Spoke { get; set; }

	private bool IsOmniscient
	{
		get
		{
			if (!Omniscient.Contains(enemyName) && (!(enemyName == "HideousMass") || !(VoiceBank.CurrentLevel == "1-3")))
			{
				if (enemyName == "ShopTerminal")
				{
					return VoiceBank.CurrentLevel == "Endless";
				}
				return false;
			}
			return true;
		}
	}

	private bool Gone
	{
		get
		{
			if (!standIn)
			{
				if (!((Object)(object)eid == (Object)null))
				{
					return eid.dead;
				}
				return true;
			}
			return false;
		}
	}

	public string EnemyName => enemyName;

	public string SubtitleColor
	{
		set
		{
			subtitleColor = value;
		}
	}

	public bool ChatterOff
	{
		set
		{
			chatterOff = value;
		}
	}

	private bool SpawnComesFirst
	{
		get
		{
			if (Time.time < spawnFirstUntil)
			{
				if (!VoiceBank.HasEvent(enemyName, spawnEvent))
				{
					return VoiceBank.HasEvent(enemyName, spawnEvent + "@" + VoiceBank.CurrentLevel);
				}
				return true;
			}
			return false;
		}
	}

	private bool GuardsFerryman
	{
		get
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Invalid comparison between Unknown and I4
			if (guardsFerryman || enemyName != "Idol")
			{
				return guardsFerryman;
			}
			Idol component = ((Component)this).GetComponent<Idol>();
			guardsFerryman = (Object)(object)component != (Object)null && (((Object)(object)component.overrideTarget != (Object)null && (int)component.overrideTarget.enemyType == 26) || ((Object)(object)component.target != (Object)null && (int)component.target.enemyType == 26));
			return guardsFerryman;
		}
	}

	public bool IsTalking
	{
		get
		{
			if ((Object)(object)speaking != (Object)null)
			{
				return speaking.isPlaying;
			}
			return false;
		}
	}

	public static EnemyVoice For(EnemyIdentifier eid)
	{
		FerrymanFake component = ((Component)eid).GetComponent<FerrymanFake>();
		if ((Object)(object)component != (Object)null)
		{
			return SpecialMoments.DockFerryman(component);
		}
		EnemyVoice enemyVoice = ((Component)eid).GetComponent<EnemyVoice>();
		if ((Object)(object)enemyVoice == (Object)null)
		{
			enemyVoice = ((Component)eid).gameObject.AddComponent<EnemyVoice>();
		}
		if (!enemyVoice.standIn && (Object)(object)enemyVoice.eid != (Object)(object)eid)
		{
			enemyVoice.Setup(eid, VoiceName(eid));
		}
		return enemyVoice;
	}

	public static EnemyVoice ForStandIn(GameObject obj, string enemyName, Action<EnemyVoice> onSetup = null)
	{
		EnemyVoice enemyVoice = obj.GetComponent<EnemyVoice>();
		if ((Object)(object)enemyVoice == (Object)null)
		{
			enemyVoice = obj.AddComponent<EnemyVoice>();
		}
		if (!enemyVoice.standIn || enemyVoice.enemyName != enemyName)
		{
			enemyVoice.standIn = true;
			enemyVoice.Setup(null, enemyName);
			onSetup?.Invoke(enemyVoice);
		}
		return enemyVoice;
	}

	private void Setup(EnemyIdentifier owner, string name)
	{
		eid = owner;
		enemyName = name;
		speaking = null;
		ducked.Clear();
		chatterOff = false;
		silentReason = (((Object)(object)owner != (Object)null) ? SilentReason(owner) : null);
		if (name == "Idol")
		{
			IdolAppearedAt = Time.time;
		}
		spawnFirstUntil = (standIn ? (-1f) : (Time.time + 5f));
		Transform val = ((Component)this).transform.Find("UltraVox Voice");
		source = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<AudioSource>() : null);
		ScheduleChatter();
		VoiceBank.Request(enemyName);
		Report("Voice", "set up on '" + ((Object)((Component)this).gameObject).name + "'" + (standIn ? " (stand-in)" : "") + ((silentReason != null) ? (" (silent: " + silentReason + ")") : ""));
		subtitleColor = null;
		if ((Object)(object)owner != (Object)null)
		{
			DualBosses.SetUp(this, owner);
		}
	}

	private static string SilentReason(EnemyIdentifier eid)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: 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_0009: Invalid comparison between Unknown and I4
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Invalid comparison between Unknown and I4
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0013: Invalid comparison between Unknown and I4
		EnemyType enemyType = eid.enemyType;
		if ((int)enemyType != 5)
		{
			if ((int)enemyType != 10)
			{
				if ((int)enemyType == 35)
				{
					return "part of the Earthmover, which speaks through the level";
				}
			}
			else if ((Object)(object)((Component)eid).GetComponent<Wicked>() == (Object)null)
			{
				return "level script object, not Something Wicked";
			}
		}
		else if ((Object)(object)((Component)eid).GetComponent<Mindflayer>() == (Object)null)
		{
			return "not a real Mindflayer";
		}
		return null;
	}

	private static string VoiceName(EnemyIdentifier eid)
	{
		Mindflayer component = ((Component)eid).GetComponent<Mindflayer>();
		if ((Object)(object)component != (Object)null && (((Object)(object)component.smr != (Object)null && (Object)(object)component.maleMesh != (Object)null && (Object)(object)component.smr.sharedMesh == (Object)(object)component.maleMesh) || Plugin.AlwaysMaleMindflayer.Value))
		{
			return "MindflayerMale";
		}
		V2 component2 = ((Component)eid).GetComponent<V2>();
		if ((Object)(object)component2 != (Object)null && component2.secondEncounter)
		{
			return "V2Second";
		}
		return ((object)Unsafe.As<EnemyType, EnemyType>(ref eid.enemyType)/*cast due to .constrained prefix*/).ToString();
	}

	public void QueueSpawnLine()
	{
		if (!standIn)
		{
			string text = skipSpawnReason;
			skipSpawnReason = null;
			if (text == null && enemyName == "Cerberus" && Time.time - StatueWokeAt < 1.5f)
			{
				text = "woke up from a statue, which already spoke";
			}
			if (text == null && (Object)(object)((Component)this).GetComponent<MinosArm>() != (Object)null)
			{
				text = "the arm in the 2-4 hallway has its own line when it first attacks";
			}
			if (text != null)
			{
				Report("Spawn", "skipped: " + text);
				spawnFirstUntil = -1f;
			}
			else if (WaitsForBossBar())
			{
				waitingForBossBar = true;
				spawnFirstUntil = -1f;
				Report("Spawn", "waiting for its boss health bar to appear");
			}
			else
			{
				StartSpawnLine();
			}
		}
	}

	private void StartSpawnLine()
	{
		spawnFirstUntil = Time.time + 5f;
		spawnFrame = Time.frameCount;
		spawnLineUntil = Time.time + 3f;
		spawnBusyUntil = Time.time + 1f;
	}

	public void SkipSpawnLine(string reason)
	{
		if (spawnLineUntil > 0f)
		{
			spawnLineUntil = (spawnFirstUntil = -1f);
			Report(spawnEvent, "skipped: " + reason);
		}
		else
		{
			skipSpawnReason = reason;
		}
	}

	public void SpawnAs(string evt)
	{
		spawnEvent = evt;
	}

	public void DelaySpawnLine(float seconds)
	{
		spawnNotBefore = Time.realtimeSinceStartup + seconds;
	}

	private bool WaitsForBossBar()
	{
		if (enemyName != "MirrorReaper" || VoiceBank.CurrentLevel != "8-2")
		{
			return false;
		}
		BossHealthBar component = ((Component)this).GetComponent<BossHealthBar>();
		if (!((Object)(object)component == (Object)null))
		{
			return !((Behaviour)component).isActiveAndEnabled;
		}
		return true;
	}

	public void OnBossBarShown()
	{
		if (waitingForBossBar)
		{
			waitingForBossBar = false;
			StartSpawnLine();
		}
	}

	public void Mute(float seconds)
	{
		mutedUntil = Time.time + seconds;
	}

	public void SayWhenNear(string evt, float distance)
	{
		nearEvent = evt;
		nearDistance = distance;
	}

	public bool Say(string evt, bool interrupt = false, bool routine = false, bool overlap = false, bool cutOff = false)
	{
		string text = WhyNot(interrupt, overlap || cutOff);
		if (text == null && nearEvent != null && evt != nearEvent && !interrupt)
		{
			text = "saves its " + nearEvent + " line for when the player comes near";
		}
		if (text == null && evt != spawnEvent && SpawnComesFirst)
		{
			text = "its spawn line comes first";
		}
		VoiceBank.Line line = null;
		if (text == null)
		{
			line = VoiceBank.Pick(enemyName, evt);
			if (line == null)
			{
				text = ((VoiceBank.HasEvent(enemyName, evt) || VoiceBank.HasLine(enemyName, evt)) ? "line still loading" : "no lines for this event");
			}
		}
		if (text != null)
		{
			if (!routine)
			{
				Report(evt, "skipped: " + text);
			}
			return false;
		}
		if (cutOff)
		{
			EnemyVoice speaker = TypeOf(enemyName).Speaker;
			if ((Object)(object)speaker != (Object)null && (Object)(object)speaker != (Object)(object)this && speaker.IsTalking)
			{
				speaker.speaking.Stop();
			}
		}
		AudioSource src;
		if (standIn)
		{
			if ((Object)(object)speaking != (Object)null)
			{
				speaking.Stop();
			}
			src = Detached(line);
		}
		else
		{
			if ((Object)(object)source == (Object)null)
			{
				source = CreateSource(((Component)this).transform, IsOmniscient);
			}
			src = source;
		}
		Play(src, line);
		Report(evt, "played " + ((Object)line.Clip).name);
		ScheduleChatter();
		return true;
	}

	public bool SayDetached(string evt)
	{
		string text = WhyNot(interrupt: true);
		VoiceBank.Line line = ((text == null) ? VoiceBank.Pick(enemyName, evt) : null);
		if (line == null)
		{
			Report(evt, "skipped: " + (text ?? "no lines for this event, or still loading"));
			return false;
		}
		Play(Detached(line), line);
		Report(evt, "played " + ((Object)line.Clip).name);
		return true;
	}

	public void SayOutsideGame(string evt, bool subtitle = true)
	{
		string text = WhyNot(interrupt: true);
		VoiceBank.Line line = ((text == null) ? VoiceBank.Pick(enemyName, evt) : null);
		if (line == null)
		{
			Report(evt, "skipped: " + (text ?? "no lines for this event, or still loading"));
			return;
		}
		AudioSource val = Detached(line);
		val.outputAudioMixerGroup = null;
		Play(val, line, subtitle);
		AudioMixerController instance = MonoSingleton<AudioMixerController>.Instance;
		if ((Object)(object)instance != (Object)null)
		{
			val.volume *= instance.sfxVolume;
		}
		Report(evt, "played " + ((Object)line.Clip).name + (subtitle ? "" : " (no subtitle)"));
		Subtitle val2 = ((subtitle && Time.timeScale == 0f) ? NewestSubtitle() : null);
		if ((Object)(object)val2 != (Object)null)
		{
			((MonoBehaviour)this).StartCoroutine(HoldSubtitle(val2, line.Clip.length));
		}
	}

	private static Subtitle NewestSubtitle()
	{
		SubtitleController instance = MonoSingleton<SubtitleController>.Instance;
		Transform val = (((Object)(object)instance != (Object)null) ? Traverse.Create((object)instance).Field<Transform>("container").Value : null);
		Subtitle[] array = (Subtitle[])(((Object)(object)val != (Object)null) ? ((Array)((Component)val).GetComponentsInChildren<Subtitle>()) : ((Array)new Subtitle[0]));
		if (array.Length == 0)
		{
			return null;
		}
		return array[^1];
	}

	private static IEnumerator HoldSubtitle(Subtitle subtitle, float seconds)
	{
		Traverse.Create((object)subtitle).Field("currentAlpha").SetValue((object)1f);
		yield return (object)new WaitForSecondsRealtime(seconds);
		if ((Object)(object)subtitle != (Object)null)
		{
			MonoSingleton<SubtitleController>.Instance.NotifyHoldEnd(subtitle);
			Object.Destroy((Object)(object)((Component)subtitle).gameObject);
		}
	}

	private AudioSource Detached(VoiceBank.Line line)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		AudioSource obj = CreateSource(null, IsOmniscient);
		((Component)obj).transform.position = ((Component)this).transform.position;
		Object.Destroy((Object)(object)((Component)obj).gameObject, line.Clip.length + 0.5f);
		return obj;
	}

	public void Report(string evt, string outcome)
	{
		if (Plugin.LogVoiceEvents.Value)
		{
			Plugin.Log.LogInfo((object)$"{Time.timeSinceLevelLoad,6:0.0}s  {enemyName} #{(((Object)(object)eid != (Object)null) ? ((Object)eid).GetInstanceID() : ((Object)((Component)this).gameObject).GetInstanceID())} {evt}: {outcome}");
		}
	}

	private string WhyNot(bool interrupt, bool overlap = false)
	{
		if (!Plugin.Enabled.Value)
		{
			return "voices are off";
		}
		if (silentReason != null)
		{
			return silentReason;
		}
		if (!VoiceBank.IsEnabled(enemyName))
		{
			return "this enemy is off or has no voice files";
		}
		if (Time.time < mutedUntil)
		{
			return "muted";
		}
		if (GuardsFerryman)
		{
			return "Idols guarding the Ferryman stay quiet";
		}
		if (!overlap && !MayTalk(interrupt))
		{
			return "another line of this enemy type is playing or just ended";
		}
		return null;
	}

	public void StopTalking(string why)
	{
		if (IsTalking)
		{
			speaking.Stop();
			TypeOf(enemyName).QuietUntil = Time.time;
			Report("Stop", why);
		}
	}

	public void SayAfter(string evt, float pause)
	{
		((MonoBehaviour)this).StartCoroutine(SayAfterRoutine(evt, pause));
	}

	private IEnumerator SayAfterRoutine(string evt, float pause)
	{
		yield return (object)new WaitForSeconds(0.2f);
		float giveUp = Time.time + 6f;
		while (IsTalking && Time.time < giveUp)
		{
			yield return null;
		}
		yield return (object)new WaitForSeconds(pause);
		if (!Gone)
		{
			Say(evt, interrupt: true);
		}
	}

	public void OnDeath()
	{
		if (spawnLineUntil > 0f)
		{
			spawnLineUntil = -1f;
			Report(spawnEvent, "skipped: died before it could speak (" + (WhyNot(interrupt: false) ?? "line still loading") + ")");
		}
		if ((Object)(object)((Component)this).GetComponent<MinosArm>() != (Object)null)
		{
			Report("Death", "skipped: Minos's arm only retreats; its death line is for the boss");
			return;
		}
		if ((Object)(object)((Component)this).GetComponent<V2>() != (Object)null)
		{
			Report("Death", "skipped: V2's knockdown has its own lines");
			return;
		}
		if (enemyName == "Geryon")
		{
			GeryonImpaled.Died(this);
		}
		if (!DeathFromBody.Contains(enemyName))
		{
			if ((Object)(object)source != (Object)null)
			{
				source.Stop();
			}
			SayDetached("Death");
			return;
		}
		string text = WhyNot(interrupt: true);
		VoiceBank.Line line = ((text == null) ? VoiceBank.Pick(enemyName, "Death") : null);
		if (line == null)
		{
			Report("Death", "skipped: " + (text ?? "no lines for this event, or still loading"));
			return;
		}
		if ((Object)(object)source == (Object)null)
		{
			source = CreateSource(((Component)this).transform, IsOmniscient);
		}
		Play(source, line);
		Report("Death", "played " + ((Object)line.Clip).name);
	}

	private void Update()
	{
		if (Gone)
		{
			return;
		}
		ModLog.Guard("EnemyVoice.Update", delegate
		{
			if (spawnLineUntil > 0f && Time.frameCount > spawnFrame && Time.realtimeSinceStartup >= spawnNotBefore)
			{
				if (Say(spawnEvent, interrupt: false, routine: true))
				{
					spawnLineUntil = (spawnFirstUntil = -1f);
				}
				else
				{
					string text = WhyNot(interrupt: false);
					if (Time.time > spawnLineUntil || (text != null && Time.time > spawnBusyUntil))
					{
						spawnLineUntil = (spawnFirstUntil = -1f);
						if (VoiceBank.HasEvent(enemyName, spawnEvent) || VoiceBank.HasEvent(enemyName, spawnEvent + "@" + VoiceBank.CurrentLevel))
						{
							Report(spawnEvent, string.Format("skipped: {0} (gave up after {1} s)", text ?? "line still loading", (text != null) ? 1f : 3f));
						}
					}
				}
			}
			if (nearEvent != null && PlayerWithin(nearDistance))
			{
				string evt = nearEvent;
				nearEvent = null;
				if (!Say(evt, interrupt: true, routine: true))
				{
					nearEvent = evt;
				}
			}
			if (!standIn)
			{
				if (Time.time >= nextApproached && VoiceBank.HasEvent(enemyName, "Approached") && PlayerWithin(12f))
				{
					Say("Approached", interrupt: false, routine: true);
					nextApproached = Time.time + 20f;
				}
				if (!chatterOff && Time.time >= nextChatter)
				{
					Say("Chatter", interrupt: false, routine: true);
					ScheduleChatter();
				}
			}
		});
	}

	private bool MayTalk(bool interrupt)
	{
		TypeState typeState = TypeOf(enemyName);
		if ((Object)(object)typeState.Speaker != (Object)null && typeState.Speaker.IsTalking)
		{
			if (interrupt)
			{
				return (Object)(object)typeState.Speaker == (Object)(object)this;
			}
			return false;
		}
		if (!interrupt)
		{
			return Time.time >= typeState.QuietUntil;
		}
		return true;
	}

	private static TypeState TypeOf(string enemyName)
	{
		if (!types.TryGetValue(enemyName, out var value))
		{
			value = (types[enemyName] = new TypeState());
		}
		return value;
	}

	private bool PlayerWithin(float distance)
	{
		//IL_0033: 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)
		if ((Object)(object)player == (Object)null)
		{
			player = GameObject.FindWithTag("Player");
		}
		if ((Object)(object)player != (Object)null)
		{
			return Vector3.Distance(player.transform.position, ((Component)this).transform.position) < distance;
		}
		return false;
	}

	private void ScheduleChatter()
	{
		ChatterSooner.TryGetValue(enemyName, out var value);
		float num = Mathf.Max(1f, Plugin.ChatterSeconds.Value - value);
		nextChatter = Time.time + Random.Range(num * 0.5f, num * 1.5f);
	}

	private static AudioSource CreateSource(Transform parent, bool omniscient)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		GameObject val = new GameObject("UltraVox Voice");
		if ((Object)(object)parent != (Object)null)
		{
			val.transform.SetParent(parent, false);
		}
		AudioSource val2 = val.AddComponent<AudioSource>();
		val2.playOnAwake = false;
		val2.spatialBlend = (omniscient ? 0f : 1f);
		val2.rolloffMode = (AudioRolloffMode)1;
		val2.minDistance = 25f;
		val2.maxDistance = 150f;
		val2.dopplerLevel = 0f;
		if (omniscient)
		{
			val2.bypassReverbZones = true;
			val2.reverbZoneMix = 0f;
			val2.bypassListenerEffects = true;
		}
		AudioMixerController instance = MonoSingleton<AudioMixerController>.Instance;
		if ((Object)(object)instance != (Object)null)
		{
			val2.outputAudioMixerGroup = instance.allGroup;
		}
		return val2;
	}

	private void Play(AudioSource src, VoiceBank.Line line, bool subtitle = true)
	{
		src.Stop();
		src.clip = line.Clip;
		src.volume = Plugin.Volume.Value;
		src.Play();
		speaking = src;
		TypeState typeState = TypeOf(enemyName);
		typeState.Speaker = this;
		typeState.QuietUntil = Time.time + line.Clip.length + 1f;
		if (subtitle && Plugin.Subtitles.Value && line.Subtitle != null)
		{
			ShowSubtitle(SubtitleColors.Paint(subtitleColor ?? enemyName, Path.GetFileNameWithoutExtension(((Object)line.Clip).name), line.Subtitle), IsOmniscient ? null : src);
		}
		if (DuckOwnSounds.Contains(enemyName) && ((Behaviour)this).isActiveAndEnabled)
		{
			((MonoBehaviour)this).StartCoroutine(DuckWhilePlaying(src));
		}
	}

	private IEnumerator DuckWhilePlaying(AudioSource line)
	{
		AudioSource[] componentsInChildren = ((Component)this).GetComponentsInChildren<AudioSource>(true);
		foreach (AudioSource val in componentsInChildren)
		{
			if (!((Object)(object)val == (Object)null) && !(((Object)val).name == "UltraVox Voice") && !ducked.ContainsKey(val))
			{
				ducked[val] = val.volume;
				val.volume *= 0.4f;
			}
		}
		while ((Object)(object)line != (Object)null && line.isPlaying)
		{
			yield return null;
		}
		if ((Object)(object)line != (Object)null && (Object)(object)speaking != (Object)(object)line)
		{
			yield break;
		}
		foreach (KeyValuePair<AudioSource, float> item in ducked)
		{
			if ((Object)(object)item.Key != (Object)null)
			{
				item.Key.volume = item.Value;
			}
		}
		ducked.Clear();
	}

	private static void ShowSubtitle(string text, AudioSource src)
	{
		SubtitleController instance = MonoSingleton<SubtitleController>.Instance;
		if (!((Object)(object)instance == (Object)null))
		{
			instance.DisplaySubtitle(text, src, false);
			LimitSubtitles(instance);
		}
	}

	private static void LimitSubtitles(SubtitleController controller)
	{
		Transform value = Traverse.Create((object)controller).Field<Transform>("container").Value;
		if ((Object)(object)value == (Object)null)
		{
			return;
		}
		List<Subtitle> list = (from s in ((Component)value).GetComponentsInChildren<Subtitle>()
			where !Traverse.Create((object)s).Field<bool>("isFadingOut").Value
			select s).ToList();
		for (int num = 0; num < list.Count - 5; num++)
		{
			Subtitle val = list[num];
			Traverse.Create((object)val).Field("isFadingIn").SetValue((object)false);
			Traverse.Create((object)val).Field("isFadingOut").SetValue((object)true);
			controller.NotifyHoldEnd(val);
			if ((Object)(object)val.nextInChain != (Object)null)
			{
				val.nextInChain.ContinueChain();
			}
		}
	}
}
internal static class EventHooks
{
	private class Hook
	{
		public Type Type;

		public string Method;

		public Type[] Args;

		public string Event;

		public float Chance = 1f;

		public bool Interrupt;

		public Func<Component, bool> When;

		public string Became;

		public float Near;

		public float After = -1f;

		public bool Overlap;
	}

	private const float IdolsAppearing = 1f;

	private static readonly Hook[] Table = new Hook[51]
	{
		H(typeof(ZombieMelee), "Swing", "Attack", 0.5f),
		H(typeof(ZombieMelee), "JumpAttack", "Attack", 0.5f),
		H(typeof(Streetcleaner), "StartFire", "Burning", 0.75f),
		H(typeof(Streetcleaner), "Dodge", "Dodging", 0.5f),
		H(typeof(Streetcleaner), "DeflectShot", "Blocking"),
		H(typeof(StatueBoss), "Throw", "Throwing", 0.6f),
		H(typeof(StatueBoss), "Stomp", "Stomping", 0.6f),
		H(typeof(StatueBoss), "Tackle", "Dashing", 0.6f),
		H(typeof(StatueBoss), "Enrage", "Enraged", 1f, interrupt: true, null, null, "enraged", 0f, -1f, overlap: true),
		H(typeof(Mass), "ReadySpear", "Hookshot"),
		H(typeof(Mindflayer), "MeleeAttack", "Swipe", 0.75f),
		H(typeof(Mindflayer), "Enrage", "Enraged", 1f, interrupt: true, null, null, "enraged"),
		H(typeof(Drone), "Enrage", "Enraged", 1f, interrupt: true, null, null, "isEnraged"),
		H(typeof(Drone), "DodgeLaugh", "Dodging", 0.75f),
		H(typeof(Stalker), "Countdown", "Detonate", 1f, interrupt: true),
		H(typeof(Sisyphus), "GotParried", "Parried", 1f, interrupt: true),
		H(typeof(Turret), "LodgeFoot", "Anchor", 0.75f, interrupt: false, null, null, "lodged"),
		H(typeof(Turret), "Shoot", "Firing", 0.75f, interrupt: true),
		H(typeof(Turret), "Interrupt", "Interrupted", 1f, interrupt: true),
		H(typeof(Turret), "Kick", "Kick", 1f, interrupt: true),
		H(typeof(Idol), "ChangeTarget", "Protecting", 0.75f, interrupt: false, (Component c) => VoiceBank.CurrentLevel != "7-4" || Time.time - EnemyVoice.IdolAppearedAt > 1f),
		H(typeof(Ferryman), "GotParried", "Parried", 1f, interrupt: true),
		H(typeof(Ferryman), "LightningBoltWindup", "Lightning"),
		H(typeof(Ferryman), "PhaseChange", "Phase2", 1f, interrupt: true, null, null, "inPhaseChange"),
		H(typeof(Gutterman), "ShieldBash", "ShieldBash", 0.6f),
		H(typeof(Gutterman), "ShieldBreak", "ShieldBreak", 1f, interrupt: true),
		H(typeof(Gutterman), "GotParried", "Parried", 1f, interrupt: true),
		H(typeof(Guttertank), "PrepRocket", "Shoot", 0.75f),
		H(typeof(Guttertank), "Punch", "Punch", 0.5f),
		H(typeof(Guttertank), "TargetBeenHit", "PunchHit", 1f, interrupt: true),
		H(typeof(Guttertank), "FallImpact", "Tripped", 1f, interrupt: true),
		H(typeof(Guttertank), "PunchStop", "PunchMiss", 0.75f, interrupt: false, (Component c) => !Traverse.Create((object)c).Field<bool>("punchHit").Value, null, null, 0f, 0.45f),
		H(typeof(Guttertank), "PlaceMine", "Landmine", 0.75f),
		H(typeof(Deathcatcher), "Opened", "Opening"),
		H(typeof(Deathcatcher), "RespawnPuppets", "Reviving"),
		H(typeof(MaliciousFace), "Enrage", "Enraged", 1f, interrupt: true, null, null, "isEnraged"),
		H(typeof(SwordsMachine), "Combo", "Combo", 0.6f),
		H(typeof(SwordsMachine), "RunningSwing", "Lunge", 0.6f),
		H(typeof(SwordsMachine), "SwordThrow", "ThrowShoot", 0.6f),
		H(typeof(EnemyShotgun), "Fire", "ThrowShoot", 0.4f),
		H(typeof(SwordsMachine), "Enrage", "Enraged", 1f, interrupt: true, null, null, "enraged"),
		H(typeof(SwordsMachine), "EndFirstPhase", "Knocked", 1f, interrupt: true),
		H(typeof(LeviathanHead), "Roar", "Battlecry"),
		H(typeof(LeviathanController), "BeginMainPhase", "Phase2", 1f, interrupt: true, null, null, "secondPhase"),
		H(typeof(MirrorReaper), "TeleportNow", "MirrorEnter", 1f, interrupt: true, null, null, "inMirrorPhase"),
		H(typeof(MinosBoss), "GotParried", "Parried", 1f, interrupt: true),
		H(typeof(MinosBoss), "PhaseChange", "Phase2", 1f, interrupt: true),
		H(typeof(V2), "InstaEnrage", "StopHitting", 1f, interrupt: true, null, null, "enraged"),
		H(typeof(V2), "Enrage", "Enraged", 1f, interrupt: true, null, Type.EmptyTypes, "enraged"),
		H(typeof(Geryon), "Stun", "Overheat"),
		H(typeof(Geryon), "Update", "Enraged", 1f, interrupt: true, null, null, "secondPhase")
	};

	private static readonly Dictionary<MethodBase, Hook> byMethod = new Dictionary<MethodBase, Hook>();

	private static Hook H(Type type, string method, string evt, float chance = 1f, bool interrupt = false, Func<Component, bool> when = null, Type[] args = null, string became = null, float near = 0f, float after = -1f, bool overlap = false)
	{
		return new Hook
		{
			Type = type,
			Method = method,
			Event = evt,
			Chance = chance,
			Interrupt = interrupt,
			When = when,
			Args = args,
			Became = became,
			Near = near,
			After = after,
			Overlap = overlap
		};
	}

	public static void Apply(Harmony harmony)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Expected O, but got Unknown
		HarmonyMethod val = new HarmonyMethod(typeof(EventHooks), "Prefix", (Type[])null);
		HarmonyMethod val2 = new HarmonyMethod(typeof(EventHooks), "Postfix", (Type[])null);
		Hook[] table = Table;
		foreach (Hook hook in table)
		{
			MethodInfo methodInfo = null;
			try
			{
				methodInfo = AccessTools.Method(hook.Type, hook.Method, hook.Args, (Type[])null);
			}
			catch (AmbiguousMatchException)
			{
			}
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)("Game method " + hook.Type.Name + "." + hook.Method + " not found (or ambiguous); '" + hook.Event + "' lines for it are off"));
			}
			else if (!byMethod.ContainsKey(methodInfo))
			{
				byMethod[methodInfo] = hook;
				harmony.Patch((MethodBase)methodInfo, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}
	}

	private static bool ReadBool(object instance, string name)
	{
		Traverse val = Traverse.Create(instance);
		Traverse val2 = val.Field(name);
		return (val2.FieldExists() ? val2 : val.Property(name, (object[])null)).GetValue<bool>();
	}

	private static void Prefix(object __instance, MethodBase __originalMethod, out bool __state)
	{
		bool before = false;
		ModLog.Guard(__originalMethod.DeclaringType.Name + "." + __originalMethod.Name + " (before)", delegate
		{
			if (byMethod.TryGetValue(__originalMethod, out var value) && value.Became != null)
			{
				before = ReadBool(__instance, value.Became);
			}
		});
		__state = before;
	}

	private static void Postfix(object __instance, MethodBase __originalMethod, bool __state)
	{
		ModLog.Guard(__originalMethod.DeclaringType.Name + "." + __originalMethod.Name, delegate
		{
			if (byMethod.TryGetValue(__originalMethod, out var value))
			{
				object obj = __instance;
				Component val = (Component)((obj is Component) ? obj : null);
				if (val != null && !(value.Became != null && __state))
				{
					bool flag = value.Became == null || ReadBool(val, value.Became);
					if (flag || !(value.Method == "Update"))
					{
						EnemyIdentifier val2 = val.GetComponentInParent<EnemyIdentifier>();
						if ((Object)(object)val2 == (Object)null)
						{
							val2 = val.GetComponentInChildren<EnemyIdentifier>();
						}
						if ((Object)(object)val2 == (Object)null)
						{
							Plugin.Log.LogWarning((object)(__originalMethod.DeclaringType.Name + "." + __originalMethod.Name + ": no enemy found for '" + value.Event + "'"));
						}
						else if (!val2.dead)
						{
							EnemyVoice enemyVoice = EnemyVoice.For(val2);
							if (VoiceBank.HasEvent(enemyVoice.EnemyName, value.Event) || VoiceBank.HasLine(enemyVoice.EnemyName, value.Event))
							{
								string evt = value.Event + " (" + __originalMethod.DeclaringType.Name + "." + __originalMethod.Name + ")";
								if (!flag)
								{
									enemyVoice.Report(evt, "skipped: " + value.Became + " didn't change");
								}
								else if (value.When != null && !value.When(val))
								{
									enemyVoice.Report(evt, "skipped: condition not met");
								}
								else if (Random.value > value.Chance)
								{
									enemyVoice.Report(evt, $"skipped by chance ({value.Chance:P0})");
								}
								else if (value.Near > 0f)
								{
									enemyVoice.SayWhenNear(value.Event, value.Near);
								}
								else if (value.After >= 0f)
								{
									enemyVoice.SayAfter(value.Event, value.After);
								}
								else
								{
									enemyVoice.Say(value.Event, value.Interrupt, routine: false, value.Overlap);
								}
							}
						}
					}
				}
			}
		});
	}
}
[HarmonyPatch(typeof(EnemyIdentifier), "Start")]
internal static class SpawnHook
{
	private static void Postfix(EnemyIdentifier __instance)
	{
		ModLog.Guard("Spawn", delegate
		{
			EnemyVoice.For(__instance).QueueSpawnLine();
		});
	}
}
[HarmonyPatch(typeof(EnemyIdentifier), "Death", new Type[] { typeof(bool) })]
internal static class DeathHook
{
	private static void Prefix(EnemyIdentifier __instance, out bool __state)
	{
		__state = __instance.dead;
	}

	private static void Postfix(EnemyIdentifier __instance, bool __state)
	{
		ModLog.Guard("Death", delegate
		{
			if (!__state && __instance.dead)
			{
				EnemyVoice.For(__instance).OnDeath();
				if (EarthmoverMoments.InLevel)
				{
					EarthmoverMoments.EnemyDied(__instance);
				}
			}
		});
	}
}
[HarmonyPatch(typeof(Guttertank), "Start")]
internal static class GuttertankWallBreakHook
{
	private static void Prefix(Guttertank __instance)
	{
		ModLog.Guard("Guttertank wall break", delegate
		{
			EnemyIdentifier component = ((Component)__instance).GetComponent<EnemyIdentifier>();
			if (__instance.punchOnSpawn && (Object)(object)component != (Object)null)
			{
				EnemyVoice.For(component).Mute(4f);
			}
		});
	}
}
[HarmonyPatch(typeof(Turret), "Update")]
internal static class TurretSightLostHook
{
	private class Sight
	{
		public bool Saw;

		public float LostAt = -1f;

		public float NextLine;

		public EnemyIdentifier Eid;
	}

	private const float LostFor = 1f;

	private const float Cooldown = 3f;

	private static readonly ConditionalWeakTable<Turret, Sight> sights = new ConditionalWeakTable<Turret, Sight>();

	private static readonly Func<Turret, bool> hasVision = AccessTools.MethodDelegate<Func<Turret, bool>>(AccessTools.PropertyGetter(typeof(Turret), "hasVision"), (object)null, true);

	private static readonly FieldRef<Turret, Enemy> mach = AccessTools.FieldRefAccess<Turret, Enemy>("mach");

	private static void Postfix(Turret __instance)
	{
		ModLog.Guard("Turret.Update", delegate
		{
			Sight orCreateValue = sights.GetOrCreateValue(__instance);
			Enemy val = mach.Invoke(__instance);
			if ((Object)(object)orCreateValue.Eid == (Object)null)
			{
				orCreateValue.Eid = ((Component)__instance).GetComponent<EnemyIdentifier>();
			}
			EnemyIdentifier eid = orCreateValue.Eid;
			if ((Object)(object)eid == (Object)null || eid.dead || eid.target == null || (Object)(object)val == (Object)null || !val.grounded || val.limp)
			{
				orCreateValue.Saw = false;
				orCreateValue.LostAt = -1f;
			}
			else if (hasVision(__instance))
			{
				orCreateValue.Saw = true;
				orCreateValue.LostAt = -1f;
			}
			else if (orCreateValue.Saw)
			{
				if (orCreateValue.LostAt < 0f)
				{
					orCreateValue.LostAt = Time.time;
				}
				else if (Time.time - orCreateValue.LostAt >= 1f)
				{
					orCreateValue.Saw = false;
					if (Time.time >= orCreateValue.NextLine)
					{
						orCreateValue.NextLine = Time.time + 3f;
						EnemyVoice.For(eid).Say("SightLost", interrupt: false, routine: false, overlap: false, cutOff: true);
					}
				}
			}
		});
	}
}
internal static class HellItself
{
	public const string Name = "HellItself";

	private const float LoadingWait = 5f;

	private const float BossDoorWait = 20f;

	private const float CurtainCallDelay = 2f;

	private const float ApplauseVolume = 0.5f;

	private static readonly HashSet<string> Levels = new HashSet<string>
	{
		"0-1", "0-5", "1-1", "1-4", "2-1", "2-4", "3-1", "3-2", "4-1", "4-4",
		"5-1", "5-4", "6-1", "6-2", "7-1", "7-3", "7-4", "8-1", "8-3", "8-4",
		"P-1", "P-2"
	};

	private static readonly Dictionary<string, (EnemyType Boss, string Event)> BossDoors = new Dictionary<string, (EnemyType, string)>
	{
		["0-1"] = ((EnemyType)4, "FinalDoor"),
		["0-5"] = ((EnemyType)0, "Gates")
	};

	private static float bossDiedAt = -1f;

	private static bool InLevel => Levels.Contains(VoiceBank.CurrentLevel);

	public static void OnSceneLoaded()
	{
		bossDiedAt = -1f;
		if (InLevel)
		{
			VoiceBank.Request("HellItself");
		}
	}

	public static void Say(string evt, string clue, float delay = 0f, bool subtitle = true)
	{
		if (InLevel && SpecialMoments.FirstTime("Hell itself " + evt))
		{
			((MonoBehaviour)Plugin.Instance).StartCoroutine(Speak(evt, clue, delay, subtitle));
		}
	}

	private static IEnumerator Speak(string evt, string clue, float delay, bool subtitle)
	{
		if (delay > 0f)
		{
			yield return (object)new WaitForSeconds(delay);
		}
		float giveUp = Time.realtimeSinceStartup + 5f;
		while (!VoiceBank.IsLoaded("HellItself") && Time.realtimeSinceStartup < giveUp)
		{
			yield return null;
		}
		EnemyVoice enemyVoice = EnemyVoice.ForStandIn(new GameObject("UltraVox Hell Itself"), "HellItself");
		Object.Destroy((Object)(object)((Component)enemyVoice).gameObject, 30f);
		enemyVoice.Report("Clue", clue);
		enemyVoice.SayOutsideGame(evt, subtitle);
	}

	public static void LevelStarted(string how)
	{
		if (InLevel && VoiceBank.HasUnplayedLevelLine("HellItself", "Door"))
		{
			Say("Door", "level start (" + how + ")");
		}
	}

	public static void EnemyDied(EnemyIdentifier eid)
	{
		//IL_0014: 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_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		if (!BossDoors.TryGetValue(VoiceBank.CurrentLevel, out (EnemyType, string) value) || eid.enemyType != value.Item1)
		{
			return;
		}
		EnemyIdentifier[] array = Object.FindObjectsOfType<EnemyIdentifier>();
		foreach (EnemyIdentifier val in array)
		{
			if (val.enemyType == value.Item1 && !val.dead)
			{
				return;
			}
		}
		bossDiedAt = Time.time;
	}

	public static void DoorOpened(Component door)
	{
		if (BossDoors.TryGetValue(VoiceBank.CurrentLevel, out (EnemyType, string) value) && !(bossDiedAt < 0f))
		{
			float num = Time.time - bossDiedAt;
			if (!(num > 20f))
			{
				bossDiedAt = -1f;
				Say(value.Item2, $"door '{EarthmoverMoments.PathOf(door.transform)}' opened {num:0.0} s after the boss died");
			}
		}
	}

	public static void CurtainCall()
	{
		if (!SpecialMoments.FirstTime("Applause turned down"))
		{
			return;
		}
		AudioSource[] array = Object.FindObjectsOfType<AudioSource>(true);
		foreach (AudioSource val in array)
		{
			if (((Object)val).name.StartsWith("Applause") || ((Object)(object)val.clip != (Object)null && ((Object)val.clip).name.IndexOf("applause", StringComparison.OrdinalIgnoreCase) >= 0))
			{
				val.volume *= 0.5f;
				if (Plugin.LogVoiceEvents.Value)
				{
					ManualLogSource log = Plugin.Log;
					string[] obj = new string[5] { "Clue: turned down ", null, null, null, null };
					AudioClip clip = val.clip;
					obj[1] = ((clip != null) ? ((Object)clip).name : null);
					obj[2] = " on '";
					obj[3] = EarthmoverMoments.PathOf(((Component)val).transform);
					obj[4] = "'";
					log.LogInfo((object)string.Concat(obj));
				}
			}
		}
		Say("CurtainCall", "Geryon impaled", 2f);
	}
}
[HarmonyPatch(typeof(ObjectActivator), "Activate", new Type[] { typeof(bool) })]
internal static class HellCurtainCall
{
	private static void Postfix(ObjectActivator __instance)
	{
		ModLog.Guard("Hell Itself curtain call", delegate
		{
			if (VoiceBank.CurrentLevel == "8-4" && ((Object)__instance).name == "Impact")
			{
				HellItself.CurtainCall();
			}
		});
	}
}
[HarmonyPatch(typeof(OnLevelStart), "StartLevel")]
internal static class HellLevelStart
{
	private static void Prefix(bool ___activated, out bool __state)
	{
		__state = !___activated;
	}

	private static void Postfix(bool __state)
	{
		ModLog.Guard("Hell Itself level start", delegate
		{
			if (__state)
			{
				HellItself.LevelStarted("first door");
			}
		});
	}
}
[HarmonyPatch(typeof(StatsManager), "StartTimer")]
internal static class HellTimerStart
{
	private static void Postfix()
	{
		ModLog.Guard("Hell Itself timer start", delegate
		{
			HellItself.LevelStarted("timer");
		});
	}
}
[HarmonyPatch(typeof(Door), "Open")]
internal static class HellDoorOpens
{
	private static void Prefix(Door __instance, out bool __state)
	{
		__state = !__instance.open;
	}

	private static void Postfix(Door __instance, bool __state)
	{
		ModLog.Guard("Hell Itself door", delegate
		{
			if (__state)
			{
				HellItself.DoorOpened((Component)(object)__instance);
			}
		});
	}
}
[HarmonyPatch(typeof(FinalDoor), "Open")]
internal static class HellFinalDoorOpens
{
	private static void Prefix(FinalDoor __instance, out bool __state)
	{
		__state = !__instance.opened && !__instance.aboutToOpen;
	}

	private static void Postfix(FinalDoor __instance, bool __state)
	{
		ModLog.Guard("Hell Itself final door", delegate
		{
			if (__state)
			{
				HellItself.DoorOpened((Component)(object)__instance);
			}
		});
	}
}
[HarmonyPatch(typeof(EnemyIdentifier), "Death", new Type[] { typeof(bool) })]
internal static class HellBossDies
{
	private static void Prefix(EnemyIdentifier __instance, out bool __state)
	{
		__state = __instance.dead;
	}

	private static void Postfix(EnemyIdentifier __instance, bool __state)
	{
		ModLog.Guard("Hell Itself boss death", delegate
		{
			if (!__state && __instance.dead)
			{
				HellItself.EnemyDied(__instance);
			}
		});
	}
}
[HarmonyPatch(typeof(SlowMo), "OnEnable")]
internal static class HellCityLanding
{
	private static void Prefix(SlowMo __instance)
	{
		ModLog.Guard("Hell Itself city", delegate
		{
			if (VoiceBank.CurrentLevel == "6-1")
			{
				HellItself.Say("City", "slow motion '" + EarthmoverMoments.PathOf(((Component)__instance).transform) + "'");
			}
		});
	}
}
[HarmonyPatch(typeof(MusicChanger), "Change")]
internal static class HellFakeExit
{
	private static void Prefix(MusicChanger __instance)
	{
		ModLog.Guard("Hell Itself fake exit", delegate
		{
			if (VoiceBank.CurrentLevel == "8-1" && ((Object)__instance).name == "FakeExitOutsideMusicTrigger" && ((Component)__instance).gameObject.activeInHierarchy)
			{
				HellItself.Say("FakeExit", "music trigger '" + EarthmoverMoments.PathOf(((Component)__instance).transform) + "'");
			}
		});
	}
}
[HarmonyPatch(typeof(EnemySpawnRadius), "SpawnEnemy")]
internal static class HellBloodTree
{
	private static void Postfix(EnemySpawnRadius __instance)
	{
		ModLog.Guard("Hell Itself blood tree", delegate
		{
			if (VoiceBank.CurrentLevel == "7-3")
			{
				HellItself.Say("BloodTree", "puppet spawner '" + EarthmoverMoments.PathOf(((Component)__instance).transform) + "'", 0f, subtitle: false);
			}
		});
	}
}
internal class ModLog : ILogListener, IDisposable
{
	private static ModLog instance;

	private static readonly HashSet<string> reported = new HashSet<string>();

	private readonly ManualLogSource source;

	private readonly StreamWriter writer;

	private ModLog(ManualLogSource source, string path)
	{
		this.source = source;
		writer = new StreamWriter(path, append: false)
		{
			AutoFlush = true
		};
	}

	public static void Start(ManualLogSource source, string folder)
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected O, but got Unknown
		try
		{
			instance = new ModLog(source, Path.Combine(folder, "UltraVox.log"));
			Logger.Listeners.Add((ILogListener)(object)instance);
			Application.logMessageReceived += new LogCallback(instance.OnUnityLog);
		}
		catch (Exception ex)
		{
			source.LogWarning((object)("Could not create UltraVox.log: " + ex.Message));
		}
	}

	public static void Guard(string where, Action action)
	{
		try
		{
			action();
		}
		catch (Exception ex)
		{
			if (reported.Add(where + ": " + ex.GetType().Name + ": " + ex.Message))
			{
				Plugin.Log.LogError((object)$"{where} failed (further identical errors are not logged): {ex}");
			}
		}
	}

	public void LogEvent(object sender, LogEventArgs e)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		if ((object)e.Source == source)
		{
			Write($"{e.Level}: {e.Data}");
		}
	}

	private void OnUnityLog(string message, string stackTrace, LogType type)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Invalid comparison between Unknown and I4
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		if (((int)type == 4 || (int)type == 0) && stackTrace != null && stackTrace.Contains("UltraVox."))
		{
			Write($"Unity {type}: {message}\n{stackTrace}");
		}
	}

	private void Write(string text)
	{
		lock (writer)
		{
			writer.WriteLine($"[{DateTime.Now:HH:mm:ss}] {text}");
		}
	}

	public void Dispose()
	{
		writer.Dispose();
	}
}
[BepInPlugin("com.ultravox.ultravox", "UltraVox", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "com.ultravox.ultravox";

	public const string Name = "UltraVox";

	public const string Version = "1.0.0";

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<float> Volume;

	internal static ConfigEntry<bool> Subtitles;

	internal static ConfigEntry<bool> ColoredSubtitles;

	internal static ConfigEntry<float> ChatterSeconds;

	internal static ConfigEntry<bool> LogVoiceEvents;

	internal static ConfigEntry<bool> AlwaysMaleMindflayer;

	private void Awake()
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Expected O, but got Unknown
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Expected O, but got Unknown
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		ModLog.Start(((BaseUnityPlugin)this).Logger, Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location));
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Play enemy voice lines.");
		Volume = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Volume", 1f, new ConfigDescription("Voice volume, on top of the game's sound effects volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		Subtitles = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Subtitles", true, "Show subtitles for voice lines. The game's own subtitle setting must also be on.");
		ColoredSubtitles = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ColoredSubtitles", true, "Show each character's subtitles in their own color.");
		ChatterSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ChatterSeconds", 12f, new ConfigDescription("Average time between idle chatter lines for each enemy.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 120f), Array.Empty<object>()));
		LogVoiceEvents = ((BaseUnityPlugin)this).Config.Bind<bool>("Testing", "LogVoiceEvents", false, "Write every voice event to UltraVox.log: which line played, or why none did. For bug reports.");
		AlwaysMaleMindflayer = ((BaseUnityPlugin)this).Config.Bind<bool>("Testing", "AlwaysMaleMindflayer", false, "Give every Mindflayer the male voice. In the game only 1 in 50 Mindflayers is male.");
		VoiceBank.Initialize(((BaseUnityPlugin)this).Config);
		Harmony val = new Harmony("com.ultravox.ultravox");
		val.PatchAll(typeof(Plugin).Assembly);
		EventHooks.Apply(val);
		SceneManager.sceneLoaded += delegate
		{
			Log.LogInfo((object)("Scene: " + SceneHelper.CurrentScene));
			ModLog.Guard("PreloadScene", VoiceBank.PreloadScene);
			ModLog.Guard("Scripted moments", SpecialMoments.OnSceneLoaded);
			ModLog.Guard("Earthmover", EarthmoverMoments.OnSceneLoaded);
			ModLog.Guard("Terminals", TerminalVoices.OnSceneLoaded);
			ModLog.Guard("Dual bosses", DualBosses.OnSceneLoaded);
			ModLog.Guard("Hell Itself", HellItself.OnSceneLoaded);
		};
		Log.LogInfo((object)string.Format("{0} {1} loaded with voices for {2} enemies", "UltraVox", "1.0.0", VoiceBank.EnemyCount));
	}
}
internal static class SpecialMoments
{
	private const float TollDistance = 40f;

	private static readonly HashSet<string> said = new HashSet<string>();

	public static void OnSceneLoaded()
	{
		said.Clear();
		FerrymanFake[] array = Object.FindObjectsOfType<FerrymanFake>(true);
		for (int i = 0; i < array.Length; i++)
		{
			DockFerryman(array[i]);
		}
	}

	public static EnemyVoice DockFerryman(FerrymanFake dock)
	{
		return EnemyVoice.ForStandIn(((Component)dock).gameObject, "Ferryman", delegate(EnemyVoice voice)
		{
			voice.SayWhenNear("TollApproach", 40f);
		});
	}

	public static bool FirstTime(string moment)
	{
		return said.Add(moment);
	}

	public static bool Happened(string moment)
	{
		return said.Contains(moment);
	}

	public static EnemyVoice Wicked()
	{
		EnemyIdentifier val = ((IEnumerable<EnemyIdentifier>)Object.FindObjectsOfType<EnemyIdentifier>()).FirstOrDefault((Func<EnemyIdentifier, bool>)((EnemyIdentifier e) => (int)e.enemyType == 10 && !e.dead && (Object)(object)((Component)e).GetComponent<Wicked>() != (Object)null));
		if (!((Object)(object)val != (Object)null))
		{
			return null;
		}
		return EnemyVoice.For(val);
	}
}
[HarmonyPatch(typeof(FerrymanFake), "CoinCatch")]
internal static class FerrymanTollPaid
{
	private static void Postfix(FerrymanFake __instance)
	{
		ModLog.Guard("Ferryman toll paid", delegate
		{
			SpecialMoments.DockFerryman(__instance).Say("TollPaid", interrupt: true);
		});
	}
}
[HarmonyPatch(typeof(FerrymanFake), "StartFight")]
internal static class FerrymanFightStart
{
	private static void Postfix(FerrymanFake __instance)
	{
		ModLog.Guard("Ferryman fight start", delegate
		{
			bool value = Traverse.Create((object)__instance).Field<bool>("activated").Value;
			EnemyIdentifier val = (((Object)(object)__instance.realFerryman != (Object)null) ? __instance.realFerryman.GetComponentInChildren<EnemyIdentifier>(true) : null);
			if ((Object)(object)val != (Object)null)
			{
				EnemyVoice.For(val).SpawnAs(value ? "Deceit" : "BattleStart");
			}
		});
	}
}
[HarmonyPatch(typeof(V2))]
internal static class V2Moments
{
	private const float WindowBreakDelay = 0.25f;

	private const float SpeedrunTime = 20f;

	private const float SplatterDelay = 3f;

	private const float SplatterWatch = 20f;

	private const float ScreamLength = 1.35f;

	public const string FallActivator = "V2 Fall Activator";

	private static readonly FieldRef<V2, bool> dead = AccessTools.FieldRefAccess<V2, bool>("dead");

	private static readonly Dictionary<V2, float> appearedAt = new Dictionary<V2, float>();

	private static int restartsWhenFled;

	public static bool FallStarted;

	[HarmonyPostfix]
	[HarmonyPatch("Start")]
	private static void Start(V2 __instance)
	{
		ModLog.Guard("V2 appears", delegate
		{
			EnemyVoice enemyVoice = VoiceOf(__instance);
			if (!((Object)(object)enemyVoice == (Object)null))
			{
				appearedAt[__instance] = Time.time;
				string text = (__instance.secondEncounter ? "V2 4-4" : "V2 1-4");
				if (SpecialMoments.FirstTime(text))
				{
					Clue(__instance, $"appears (intro {__instance.intro}, long intro {__instance.longIntro})");
					if (SpecialMoments.Happened("V2 4-4 cutscene"))
					{
						enemyVoice.SkipSpawnLine("its opening cutscene already said the intro");
					}
					else if (!__instance.secondEncounter)
					{
						enemyVoice.DelaySpawnLine(0.25f);
					}
				}
				else
				{
					bool flag = MonoSingleton<StatsManager>.Instance.restarts == restartsWhenFled;
					string text2 = ((SpecialMoments.Happened(text + " fled") && flag && SpecialMoments.FirstTime(text + " phase 2")) ? "Phase2" : "Respawn");
					enemyVoice.SpawnAs(text2);
					Clue(__instance, $"appears again (intro {__instance.intro}, long intro {__instance.longIntro}): says {text2}");
				}
			}
		});
	}

	[HarmonyPostfix]
	[HarmonyPatch("KnockedOut")]
	private static void KnockedOut(V2 __instance, string triggerName)
	{
		ModLog.Guard("V2 knocked out", delegate
		{
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			bool flag = dead.Invoke(__instance);
			appearedAt.TryGetValue(__instance, out var value);
			float num = Time.time - value;
			Clue(__instance, $"knocked out ({triggerName}, beaten {flag}, {num:0.0} s after appearing)");
			EnemyVoice enemyVoice = VoiceOf(__instance);
			if (!((Object)(object)enemyVoice == (Object)null))
			{
				enemyVoice.ChatterOff = true;
				if (flag)
				{
					if (__instance.secondEncounter)
					{
						SpecialMoments.FirstTime("V2 4-4 beaten");
						enemyVoice.Say("Defeated", interrupt: true);
						((MonoBehaviour)Plugin.Instance).StartCoroutine(Splatter(enemyVoice, ((Component)__instance).transform.position));
					}
					else
					{
						enemyVoice.Say((num <= 20f) ? "Death" : "Defeated", interrupt: true);
					}
				}
			}
		});
	}

	private static IEnumerator Splatter(EnemyVoice voice, Vector3 at)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		NewMovement player = MonoSingleton<NewMovement>.Instance;
		Transform? obj = ((IEnumerable<Transform>)Object.FindObjectsOfType<Transform>(true)).FirstOrDefault((Func<Transform, bool>)((Transform t) => ((Object)t).name == "V2 Fall Activator"));
		GameObject fall = ((obj != null) ? ((Component)obj).gameObject : null);
		bool fallWasOn = (Object)(object)fall != (Object)null && fall.activeInHierarchy;
		FallStarted = false;
		float giveUp = Time.time + 20f;
		float movementOffAt = -1f;
		string why = null;
		while (why == null && Time.time < giveUp)
		{
			if (FallStarted)
			{
				why = "'V2 Fall Activator' activates";
			}
			else if ((Object)(object)fall != (Object)null && fall.activeInHierarchy && !fallWasOn)
			{
				why = "'V2 Fall Activator' switches on";
			}
			else if (movementOffAt < 0f && (Object)(object)player != (Object)null && !player.activated)
			{
				movementOffAt = Time.time;
				Note(voice, "Clue", "player movement off");
			}
			else if (movementOffAt >= 0f && Time.time - movementOffAt >= 3f)
			{
				why = string.Format("{0} s after player movement off ('{1}' not seen)", 3f, "V2 Fall Activator");
			}
			if (why == null)
			{
				yield return null;
			}
		}
		if (why == null)
		{
			Note(voice, "Death", $"skipped: V2's fall wasn't seen within {20f} s of it being beaten");
			yield break;
		}
		Note(voice, "Clue", "V2 falls: " + why);
		EnemyVoice scream = null;
		ModLog.Guard("V2 splattered", delegate
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("UltraVox V2 splatter");
			val.transform.position = (((Object)(object)player != (Object)null) ? ((Component)player).transform.position : at);
			scream = EnemyVoice.ForStandIn(val, "V2Second");
			scream.Say("Death", interrupt: true, routine: false, overlap: true);
		});
		if (!((Object)(object)scream == (Object)null))
		{
			yield return (object)new WaitForSeconds(1.35f);
			if ((Object)(object)scream != (Object)null)
			{
				scream.StopTalking("V2 hits the ground");
				Object.Destroy((Object)(object)((Component)scream).gameObject);
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch("BeginEscape")]
	private static void BeginEscape(V2 __instance)
	{
		ModLog.Guard("V2 escapes", delegate
		{
			Clue(__instance, "begins escape");
			EnemyVoice enemyVoice = VoiceOf(__instance);
			if (!((Object)(object)enemyVoice == (Object)null))
			{
				enemyVoice.ChatterOff = true;
				SpecialMoments.FirstTime(__instance.secondEncounter ? "V2 4-4 fled" : "V2 1-4 fled");
				restartsWhenFled = MonoSingleton<StatsManager>.Instance.restarts;
				enemyVoice.SayAfter("Fleeing", 0f);
			}
		});
	}

	[HarmonyPostfix]
	[HarmonyPatch("Undie")]
	private static void Undie(V2 __instance)
	{
		ModLog.Guard("V2 gets up", delegate
		{
			Clue(__instance, "gets back up");
			EnemyVoice enemyVoice = VoiceOf(__instance);
			if ((Object)(object)enemyVoice != (Object)null)
			{
				enemyVoice.ChatterOff = false;
			}
		});
	}

	private static EnemyVoice VoiceOf(V2 v2)
	{
		EnemyIdentifier component = ((Component)v2).GetComponent<EnemyIdentifier>();
		if (!((Object)(object)component != (Object)null))
		{
			return null;
		}
		return EnemyVoice.For(component);
	}

	private static void Clue(V2 v2, string what)
	{
		VoiceOf(v2)?.Report("Clue", what);
	}

	private static void Note(EnemyVoice voice, string evt, string what)
	{
		if ((Object)(object)voice != (Object)null)
		{
			voice.Report(evt, what);
		}
	}
}
[HarmonyPatch(typeof(ObjectActivator), "Activate", new Type[] { typeof(bool) })]
internal static class V2FallStarts
{
	private static void Postfix(ObjectActivator __instance)
	{
		ModLog.Guard("V2 fall", delegate
		{
			if (!(VoiceBank.CurrentLevel != "4-4") && ((Object)__instance).name == "V2 Fall Activator")
			{
				V2Moments.FallStarted = true;
			}
		});
	}
}
internal static class V2CutsceneStarts
{
	[HarmonyPatch(typeof(CutsceneSkip), "Start")]
	private static class SkipPrompt
	{
		private static void Postfix(CutsceneSkip __instance)
		{
			ModLog.Guard("V2 cutscene", delegate
			{
				if (Waiting && SpecialMoments.FirstTime("V2 4-4 cutscene"))
				{
					EnemyVoice enemyVoice = EnemyVoice.ForStandIn(((Component)__instance).gameObject, "V2Second");
					enemyVoice.Report("Clue", "cutscene '" + Path(((Component)__instance).transform) + "' starts");
					enemyVoice.Say("Spawn", interrupt: true);
				}
			});
		}
	}

	[HarmonyPatch(typeof(CutsceneSkip), "LateUpdate")]
	private static class Skipped
	{
		private static readonly FieldRef<CutsceneSkip, bool> waiting = AccessTools.FieldRefAccess<CutsceneSkip, bool>("waitingForInput");

		private static void Prefix(CutsceneSkip __instance, out bool __state)
		{
			__state = waiting.Invoke(__instance);
		}

		private static void Postfix(CutsceneSkip __instance, bool __state)
		{
			ModLog.Guard("V2 cutscene skipped", delegate
			{
				if (__state && !waiting.Invoke(__instance))
				{
					EnemyVoice component = ((Component)__instance).GetComponent<EnemyVoice>();
					if (!((Object)(object)component == (Object)null) && !(component.EnemyName != "V2Second"))
					{
						component.StopTalking("cutscene skipped");
						component.Say("Chatter", interrupt: true);
					}
				}
			});
		}
	}

	[HarmonyPatch(typeof(ObjectActivator), "Activate", new Type[] { typeof(bool) })]
	private static class Activated
	{
		private static void Postfix(ObjectActivator __instance)
		{
			ModLog.Guard("V2 cutscene clues", delegate
			{
				bool flag = VoiceBank.CurrentLevel == "4-4" && SpecialMoments.Happened("V2 4-4 beaten");
				if ((Waiting || flag) && Plugin.LogVoiceEvents.Value)
				{
					Plugin.Log.LogInfo((object)$"{Time.timeSinceLevelLoad,6:0.0}s  Clue: 4-4 activates '{Path(((Component)__instance).transform)}'");
				}
			});
		}
	}

	private static bool Waiting
	{
		get
		{
			if (VoiceBank.CurrentLevel == "4-4")
			{
				return !SpecialMoments.Happened("V2 4-4");
			}
			return false;
		}
	}

	private static string Path(Transform t)
	{
		if (!((Object)(object)t.parent != (Object)null))
		{
			return ((Object)t).name;
		}
		return ((Object)t.parent).name + "/" + ((Object)t).name;
	}
}
[HarmonyPatch(typeof(ObjectActivator), "Activate", new Type[] { typeof(bool) })]
internal static class GeryonImpaled
{
	private const float Watch = 60f;

	private static EnemyVoice geryon;

	private static float diedAt;

	public static void Died(EnemyVoice voice)
	{
		geryon = voice;
		diedAt = Time.time;
		voice.Report("Impaled", "waiting for the cutscene");
	}

	private static void Postfix(ObjectActivator __instance)
	{
		ModLog.Guard("Geryon impaled", delegate
		{
			if (!((Object)(object)geryon == (Object)null) && !(((Object)__instance).name != "Impact") && !(VoiceBank.CurrentLevel != "8-4"))
			{
				EnemyVoice enemyVoice = geryon;
				geryon = null;
				float num = Time.time - diedAt;
				if (!(num > 60f))
				{
					enemyVoice.Report("Impaled", $"cutscene impact, {num:0.0} s after death");
					enemyVoice.SayDetached("Impaled");
				}
			}
		});
	}
}
[HarmonyPatch(typeof(MassAnimationReceiver))]
internal static class MassBurstsOut
{
	[HarmonyPostfix]
	[HarmonyPatch("GroundBreak")]
	private static void GroundBreak(MassAnimationReceiver __instance)
	{
		ModLog.Guard("Mass bursts out", delegate
		{
			Burst(__instance, "ground breaks");
		});
	}

	[HarmonyPostfix]
	[HarmonyPatch("SmallGroundBreak")]
	private static void SmallGroundBreak(MassAnimationReceiver __instance)
	{
		ModLog.Guard("Mass bursts out", delegate
		{
			Burst(__instance, "ground cracks");
		});
	}

	private static void Burst(MassAnimationReceiver receiver, string how)
	{
		if (!receiver.fakeMass || VoiceBank.CurrentLevel != "1-3")
		{
			return;
		}
		EnemyVoice enemyVoice = EnemyVoice.ForStandIn(((Component)receiver).gameObject, "HideousMass");
		if (!enemyVoice.Spoke)
		{
			enemyVoice.Report("Spawn", "bursting out of the ground (" + how + ")");
			enemyVoice.Spoke = enemyVoice.Say("Spawn", interrupt: true);
			EnemyIdentifier val = (((Object)(object)receiver.realMass != (Object)null) ? receiver.realMass.GetComponentInChildren<EnemyIdentifier>(true) : null);
			if (enemyVoice.Spoke && (Object)(object)val != (Object)null)
			{
				EnemyVoice.For(val).SkipSpawnLine("the copy bursting out of the ground already spoke");
			}
		}
	}
}
[HarmonyPatch(typeof(StatueFake))]
internal static class CerberusStatueWake
{
	private const float SlowWakeOffset = 1.4f;

	[HarmonyPostfix]
	[HarmonyPatch("Activate")]
	private static void Activate(StatueFake __instance)
	{
		ModLog.Guard("Cerberus statue activated", delegate
		{
			if (__instance.quickSpawn)
			{
				Wake(__instance);
			}
		});
	}

	[HarmonyPostfix]
	[HarmonyPatch("SlowStart")]
	private static void SlowStart(StatueFake __instance)
	{
		ModLog.Guard("Cerberus statue slow start", delegate
		{
			((MonoBehaviour)EnemyVoice.ForStandIn(((Component)__instance).gameObject, "Cerberus")).StartCoroutine(WakeAfter(__instance, 1.4f));
		});
	}

	private static IEnumerator WakeAfter(StatueFake statue, float seconds)
	{
		yield return (object)new WaitForSeconds(seconds);
		if ((Object)(object)statue != (Object)null)
		{
			ModLog.Guard("Cerberus statue slow wake", delegate
			{
				Wake(statue);
			});
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch("Done")]
	private static void Done(StatueFake __instance)
	{
		ModLog.Guard("Cerberus statue done", delegate
		{
			Wake(__instance);
			EnemyVoice.StatueWokeAt = Time.time;
		});
	}

	private static void Wake(StatueFake statue)
	{
		EnemyVoice enemyVoice = EnemyVoice.ForStandIn(((Component)statue).gameObject, "Cerberus");
		if (!enemyVoice.Spoke)
		{
			enemyVoice.Spoke = enemyVoice.Say("Spawn", interrupt: true);
		}
	}
}
[HarmonyPatch(typeof(ItemIdentifier), "PickUp")]
internal static class SkullPickedUp
{
	private static void Postfix(ItemIdentifier __instance)
	{
		ModLog.Guard("Skull picked up", delegate
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Invalid comparison between Unknown and I4
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			if (!(VoiceBank.CurrentLevel != "0-S"))
			{
				string text = (((int)__instance.itemType == 1) ? "BlueSkull" : (((int)__instance.itemType == 2) ? "RedSkull" : null));
				if (text != null && SpecialMoments.FirstTime(text))
				{
					(SpecialMoments.Wicked() ?? EnemyVoice.ForStandIn(((Component)__instance).gameObject, "Wicked")).Say(text, interrupt: true);
				}
			}
		});
	}
}
[HarmonyPatch(typeof(ItemPlaceZone), "CheckItem")]
internal static class RedSkullPlaced
{
	private static void Prefix(bool prelim, out EnemyVoice __state)
	{
		EnemyVoice wicked = null;
		ModLog.Guard("Red skull placed (before)", delegate
		{
			if (!prelim && VoiceBank.CurrentLevel == "0-S")
			{
				wicked = SpecialMoments.Wicked();
			}
		});
		__state = wicked;
	}

	private static void Postfix(ItemPlaceZone __instance, EnemyVoice __state)
	{
		ModLog.Guard("Red skull placed", delegate
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			if (!((Object)(object)__state == (Object)null) && (int)__instance.acceptedItemType == 2 && !((Component)__state).gameObject.activeInHierarchy && SpecialMoments.FirstTime("RedSkullPlaced"))
			{
				__state.SayDetached("RedSkullPlaced");
			}
		});
	}
}
[HarmonyPatch(typeof(BossHealthBar), "OnEnable")]
internal static class BossBarShown
{
	private static void Postfix(BossHealthBar __instance)
	{
		ModLog.Guard("Boss bar shown", delegate
		{
			EnemyVoice enemyVoice = ((Component)__instance).GetComponent<EnemyVoice>();
			if ((Object)(object)enemyVoice == (Object)null)
			{
				enemyVoice = ((Component)__instance).GetComponentInParent<EnemyVoice>();
			}
			if ((Object)(object)enemyVoice != (Object)null)
			{
				enemyVoice.OnBossBarShown();
			}
		});
	}
}
[HarmonyPatch]
internal static class MinosArmAttack
{
	private static IEnumerable<MethodBase> TargetMethods()
	{
		return ((IEnumerable<string>)new string[3] { "SlamDown", "SlamLeft", "SlamRight" }).Select((Func<string, MethodBase>)((string name) => AccessTools.Method(typeof(MinosArm), name, (Type[])null, (Type[])null)));
	}

	private static void Postfix(MinosArm __instance)
	{
		ModLog.Guard("Minos arm attack", delegate
		{
			EnemyIdentifier component = ((Component)__instance).GetComponent<EnemyIdentifier>();
			if (!((Object)(object)component == (Object)null) && !component.dead)
			{
				EnemyVoice enemyVoice = EnemyVoice.For(component);
				if (!enemyVoice.Spoke)
				{
					enemyVoice.Spoke = enemyVoice.Say("Chatter_4", interrupt: true);
				}
			}
		});
	}
}
internal static class SubtitleColors
{
	private static readonly Dictionary<string, Color32> colors = new Dictionary<string, Color32>
	{
		["MaliciousFace"] = Rgb(155, 95, 57),
		["Swordsmachine"] = Rgb(227, 181, 60),
		["Cerberus"] = Rgb(100, 75, 75),
		["Streetcleaner"] = Rgb(215, 100, 0),
		["HideousMass"] = Rgb(124, 10, 11),
		["Mindflayer"] = Rgb(117, 247, 215),
		["MindflayerMale"] = Rgb(117, 247, 215),
		["Virtue"] = Rgb(93, 110, 250),
		["Stalker"] = Rgb(195, 110, 31),
		["Sisyphus"] = Rgb(208, 102, 29),
		["Turret"] = Rgb(159, 189, 57),
		["Idol"] = Rgb(210, 236, byte.MaxValue),
		["Ferryman"] = Rgb(150, 187, 213),
		["Mannequin"] = Rgb(216, 188, 176),
		["Gutterman"] = Rgb(133, 101, 51),
		["Guttertank"] = Rgb(220, 0, 0),
		["Providence"] = Rgb(byte.MaxValue, byte.MaxValue, 234),
		["Deathcatcher"] = Rgb(235, 82, 91),
		["V2"] = Rgb(183, 22, 9),
		["V2Second"] = Rgb(183, 22, 9),
		["Minos"] = Rgb(84, 25, 102),
		["Leviathan"] = Rgb(163, 13, 33),
		["MirrorReaper"] = Rgb(63, 44, 49),
		["Geryon"] = Rgb(213, 26, 30),
		["Wicked"] = Rgb(50, 50, 50),
		["Centaur"] = Rgb(75, 65, 65),
		["ShopTerminal"] = Rgb(245, 205, 0),
		["ConfigTerminal"] = Rgb(0, 145, 220),
		["DualRed"] = Rgb(200, 50, 50),
		["DualBlue"] = Rgb(50, 50, 200),
		["HellItself"] = Rgb(150, 0, 0)
	};

	private static readonly Dictionary<string, Color32> lineColors = new Dictionary<string, Color32> { ["ShopTerminal/Boot@P-2_1"] = Rgb(byte.MaxValue, 0, 0) };

	private static Color32 Rgb(byte r, byte g, byte b)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		return new Color32(r, g, b, byte.MaxValue);
	}

	public static string Paint(string enemyName, string lineName, string text)
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.ColoredSubtitles.Value || (!lineColors.TryGetValue(enemyName + "/" + lineName, out var value) && !colors.TryGetValue(enemyName, out value)))
		{
			return text;
		}
		return "<color=#" + ColorUtility.ToHtmlStringRGB(Color32.op_Implicit(value)) + ">" + text + "</color>";
	}
}
internal class TerminalVoices : MonoBehaviour
{
	private const string ShopVoice = "ShopTerminal";

	private const string ConfigVoice = "ConfigTerminal";

	private const string Cybergrind = "Endless";

	private const string Sandbox = "uk_construct";

	private const int PRankScore = 12;

	private const float GreetAgainAfter = 20f;

	private const float BootDelay = 0.5f;

	private const float BootLineWait = 5f;

	private const float IdleSeconds = 20f;

	private static readonly HashSet<string> ConfigZones = new HashSet<string> { "Sandbox Shop", "Cybergrind Shop" };

	private static readonly Dictionary<string, string> ShopTabs = new Dictionary<string, string>
	{
		["WeaponsButton"] = "Shop",
		["EnemiesButton"] = "Enemies"
	};

	private static readonly Dictionary<string, string> ConfigTabs = new Dictionary<string, string>
	{
		["Themes Button"] = "Patterns",
		["Music Button"] = "Music"
	};

	private static readonly FieldRef<ScreenZone, bool> AtScreen = AccessTools.FieldRefAccess<ScreenZone, bool>("touchMode");

	private static string levelResult;

	private static TerminalVoices instance;

	private readonly Dictionary<ShopZone, float> switchedOffAt = new Dictionary<ShopZone, float>();

	private EnemyVoice shop;

	private EnemyVoice config;

	private ShopZone current;

	private EnemyVoice voice;

	private Dictionary<string, string> tabs;

	private string pendingBoot;

	private float bootStartsAt;

	private float bootGivesUpAt;

	private float idleFrom;

	private GameObject lastClicked;

	private int lastClickFrame;

	private int wavesStarted;

	private bool saidDeath;

	private static TerminalVoices Instance
	{
		get
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance == (Object)null)
			{
				instance = new GameObject("UltraVox Terminals").AddComponent<TerminalVoices>();
			}
			return instance;
		}
	}

	private void Awake()
	{
		shop = EnemyVoice.ForStandIn(Child("Shop terminal"), "ShopTerminal");
		config = EnemyVoice.ForStandIn(Child("Config terminal"), "ConfigTerminal");
	}

	private GameObject Child(string name)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected O, but got Unknown
		GameObject val = new GameObject(name);
		val.transform.SetParent(((Component)this).transform, false);
		return val;
	}

	public static void OnSceneLoaded()
	{
		string currentLevel = VoiceBank.CurrentLevel;
		if (currentLevel == "Endless" || Object.FindObjectsOfType<ShopZone>(true).Length != 0)
		{
			VoiceBank.Request("ShopTerminal");
		}
		if (currentLevel == "Endless" || currentLevel == "uk_construct")
		{
			VoiceBank.Request("ConfigTerminal");
		}
	}

	public static void SwitchedOn(ShopZone zone)
	{
		if (ConfigZones.Contains(((Object)zone).name))
		{
			Instance.Boot(zone, Instance.config, ConfigTabs, ConfigBootEvent());
		}
		else if ((Object)(object)((Component)zone).GetComponentInChildren<ShopCategory>(true) != (Object)null)
		{
			Instance.Boot(zone, Instance.shop, ShopTabs, ShopBootEvent(zone));
		}
		else if (Plugin.LogVoiceEvents.Value)
		{
			Plugin.Log.LogInfo((object)("Clue: terminal '" + EarthmoverMoments.PathOf(((Component)zone).transform) + "' switches on, but isn't one that talks"));
		}
	}

	private void Boot(ShopZone zone, EnemyVoice speaker, Dictionary<string, string> zoneTabs, string evt)
	{
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0060: Unknown result type (might be due to invalid IL or missing references)
		current = zone;
		voice = speaker;
		tabs = zoneTabs;
		pendingBoot = null;
		idleFrom = Time.time;
		((Component)this).transform.position = ((Component)zone).transform.position;
		voice.Report("Clue", $"terminal '{EarthmoverMoments.PathOf(((Component)zone).transform)}' switches on: {evt} (up {((Component)zone).transform.up.y:0.00})");
		if (switchedOffAt.TryGetValue(zone, out var value) && Time.time - value < 20f)
		{
			voice.Report(evt, "skipped: this terminal only just switched off");
			return;
		}
		pendingBoot = evt;
		bootStartsAt = Time.time + 0.5f;
		bootGivesUpAt = bootStartsAt + 5f;
		if ((Object)(object)voice == (Object)(object)shop && VoiceBank.CurrentLevel != "Endless" && VoiceBank.CurrentLevel != "uk_construct")
		{
			levelResult = null;
		}
	}

	private static string ShopBootEvent(ShopZone zone)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		string currentLevel = VoiceBank.CurrentLevel;
		if (currentLevel == "5-3" && ((Component)zone).transform.up.y > -0.5f)
		{
			return "Flipped";
		}
		if (VoiceBank.HasUnplayedLevelLine("ShopTerminal", "Boot"))
		{
			return "Boot";
		}
		if (currentLevel == "Endless")
		{
			return "Cybergrind";
		}
		if (currentLevel != "uk_construct" && levelResult != null)
		{
			return levelResult;
		}
		return "Boot";
	}

	private static string ConfigBootEvent()
	{
		if (!(VoiceBank.CurrentLevel == "Endless"))
		{
			return "Sandbox";
		}
		return "Cybergrind";
	}

	public static void LevelFinished(StatsManager stats)
	{
		AssistController val = MonoSingleton<AssistController>.Instance;
		levelResult = (((Object)(object)val != (Object)null && val.cheatsEnabled) ? "Cheats" : ((stats.rankScore == 12) ? "Prank" : null));
		if (Plugin.LogVoiceEvents.Value)
		{
			Plugin.Log.LogInfo((object)string.Format("Clue: level finished, rank score {0}, next terminal says: {1}", stats.rankScore, levelResult ?? "nothing special"));
		}
	}

	public static void SwitchedOff(ShopZone zone)
	{
		if (!((Object)(object)instance == (Object)null))
		{
			instance.switchedOffAt[zone] = Time.time;
			if ((Object)(object)instance.current == (Object)(object)zone)
			{
				instance.current = null;
				instance.pendingBoot = null;
			}
		}
	}

	private static bool InUse(Component screenPart)
	{
		if ((Object)(object)instance != (Object)null && (Object)(object)instance.current != (Object)null)
		{
			return (Object)(object)screenPart.GetComponentInParent<ShopZone>() == (Object)(object)instance.current;
		}
		return false;
	}

	public static void ButtonClicked(Component button, bool failed)
	{
		if (InUse(button) && (!((Object)(object)button.gameObject == (Object)(object)instance.lastClicked) || Time.frameCount != instance.lastClickFrame))
		{
			instance.lastClicked = button.gameObject;
			instance.lastClickFrame = Time.frameCount;
			instance.idleFrom = Time.time;
			instance.voice.Report("Clue", "button '" + EarthmoverMoments.PathOf(button.transform) + "' clicked" + (failed ? " (failed)" : ""));
			if (!failed && instance.tabs.TryGetValue(((Object)button).name, out var value))
			{
				instance.voice.Say(value);
			}
		}
	}

	public static void WeaponBought(VariationInfo weapon)
	{
		if (InUse((Component)(object)weapon))
		{
			instance.shop.Say("Purchase", interrupt: true);
		}
	}

	public static void WaveStarted()
	{
		if (Instance.wavesStarted++ > 0)
		{
			instance.shop.Say("Wave");
		}
	}

	public static void CybergrindResultsShown()
	{
		if (!Instance.saidDeath)
		{
			instance.saidDeath = true;
			instance.shop.SayOutsideGame("CyberDeath");
		}
	}

	private void Update()
	{
		ModLog.Guard("Terminals", delegate
		{
			if (pendingBoot != null)
			{
				if (!(Time.time < bootStartsAt) && (VoiceBank.IsLoaded(voice.EnemyName) || !(Time.time < bootGivesUpAt)))
				{
					if (voice.Say(pendingBoot, interrupt: true, routine: true))
					{
						pendingBoot = null;
					}
					else if (Time.time >= bootGivesUpAt)
					{
						voice.Report(pendingBoot, "skipped: line still loading");
						pendingBoot = null;
					}
				}
			}
			else if (!((Object)(object)current == (Object)null))
			{
				if (!AtScreen.Invoke((ScreenZone)(object)current) || voice.IsTalking || Input.GetMouseButtonDown(0))
				{
					idleFrom = Time.time;
				}
				else if (Time.time - idleFrom >= 20f)
				{
					idleFrom = Time.time;
					voice.Say("Idle");
				}
			}
		});
	}
}
[HarmonyPatch(typeof(ShopZone), "TurnOn")]
internal static class TerminalSwitchedOn
{
	private static void Prefix(ShopZone __instance, bool ___inUse, out bool __state)
	{
		__state = !___inUse && !__instance.forcedOff;
	}

	private static void Postfix(ShopZone __instance, bool __state)
	{
		if (__state)
		{
			ModLog.Guard("Terminal on", delegate
			{
				TerminalVoices.SwitchedOn(__instance);
			});
		}
	}
}
[HarmonyPatch(typeof(ShopZone), "TurnOff")]
internal static class TerminalSwitchedOff
{
	private static void Prefix(bool ___inUse, out bool __state)
	{
		__state = ___inUse;
	}

	private static void Postfix(ShopZone __instance, bool __state)
	{
		if (__state)
		{
			ModLog.Guard("Terminal off", delegate
			{
				TerminalVoices.SwitchedOff(__instance);
			});
		}
	}
}
[HarmonyPatch(typeof(ShopButton), "OnPointerClick")]
internal static class ShopButtonClicked
{
	private static void Postfix(ShopButton __instance)
	{
		ModLog.Guard("Terminal button", delegate
		{
			TerminalVoices.ButtonClicked((Component)(object)__instance, __instance.failure || __instance.deactivated);
		});
	}
}
[HarmonyPatch(typeof(Button), "Press")]
internal static class UiButtonClicked
{
	private static void Postfix(Button __instance)
	{
		ModLog.Guard("Terminal button", delegate
		{
			TerminalVoices.ButtonClicked((Component)(object)__instance, !((UIBehaviour)__instance).IsActive() || !((Selectable)__instance).IsInteractable());
		});
	}
}
[HarmonyPatch(typeof(VariationInfo), "WeaponBought")]
internal static class ShopWeaponBought
{
	private static void Postfix(VariationInfo __instance)
	{
		ModLog.Guard("Shop purchase", delegate
		{
			TerminalVoices.WeaponBought(__instance);
		});
	}
}
[HarmonyPatch(typeof(EndlessGrid), "NextWave")]
internal static class CybergrindNextWave
{
	private static void Postfix()
	{
		ModLog.Guard("Cybergrind wave", TerminalVoices.WaveStarted);
	}
}
[HarmonyPatch(typeof(FinalCyberRank), "Appear")]
internal static class CybergrindResultsAppear
{
	private static void Postfix(bool ___gameOver)
	{
		if (___gameOver)
		{
			ModLog.Guard("Cybergrind results", TerminalVoices.CybergrindResultsShown);
		}
	}
}
[HarmonyPatch(typeof(StatsManager), "SendInfo")]
internal static class LevelFinished
{
	private static void Postfix(StatsManager __instance)
	{
		ModLog.Guard("Level finished", delegate
		{
			TerminalVoices.LevelFinished(__instance);
		});
	}
}
internal static class VoiceBank
{
	internal class Line
	{
		public string Resource;

		public string Subtitle;

		public AudioClip Clip;
	}

	private class Actor
	{
		public readonly Dictionary<string, List<Line>> Events = new Dictionary<string, List<Line>>(StringComparer.OrdinalIgnoreCase);

		public bool LoadStarted;
	}

	private class Enemy
	{
		public readonly Dictionary<string, Actor> Actors = new Dictionary<string, Actor>(StringComparer.OrdinalIgnoreCase);

		public ConfigEntry<bool> Enabled;

		public ConfigEntry<string> ActorChoice;
	}

	private const string ResourcePrefix = "UltraVox/Voices/";

	private static readonly Dictionary<string, Enemy> enemies = new Dictionary<string, Enemy>(StringComparer.OrdinalIgnoreCase);

	private static readonly Dictionary<List<Line>, Line> lastPicked = new Dictionary<List<Line>, Line>();

	private static readonly HashSet<Line> playedThisLevel = new HashSet<Line>();

	private static string cacheDir;

	public static int EnemyCount => enemies.Count;

	internal static string CurrentLevel
	{
		get
		{
			string text = SceneHelper.CurrentScene ?? "";
			if (!text.StartsWith("Level "))
			{
				return text;
			}
			return text.Substring("Level ".Length);
		}
	}

	public static void Initialize(ConfigFile config)
	{
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Expected O, but got Unknown
		Assembly assembly = typeof(VoiceBank).Assembly;
		Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
		string[] manifestResourceNames = assembly.GetManifestResourceNames();
		foreach (string text in manifestResourceNames)
		{
			string text2 = text.Replace('\\', '/');
			if (!text2.StartsWith("UltraVox/Voices/"))
			{
				continue;
			}
			string[] array = text2.Substring("UltraVox/Voices/".Length).Split('/');
			if (array.Length == 2 && array[1].Equals("subtitles.tsv", StringComparison.OrdinalIgnoreCase))
			{
				dictionary[array[0]] = ReadSubtitles(assembly, text);
				continue;
			}
			if (array.Length != 3)
			{
				Plugin.Log.LogWarning((object)("Ignoring voice file in unexpected place: " + text2));
				continue;
			}
			if (!enemies.TryGetValue(array[0], out var value))
			{
				value = (enemies[array[0]] = new Enemy());
			}
			if (!value.Actors.TryGetValue(array[1], out var value2))
			{
				value2 = (value.Actors[array[1]] = new Actor());
			}
			string key = EventName(Path.GetFileNameWithoutExtension(array[2]));
			if (!value2.Events.TryGetValue(key, out var value3))
			{
				value3 = (value2.Events[key] = new List<Line>());
			}
			value3.Add(new Line
			{
				Resource = text
			});
		}
		foreach (KeyValuePair<string, Enemy> item in enemies.OrderBy((KeyValuePair<string, Enemy> p) => p.Key))
		{
			string key2 = item.Key;
			Enemy value4 = item.Value;
			string[] array2 = value4.Actors.Keys.OrderBy((string a) => a).ToArray();
			value4.Enabled = config.Bind<bool>("Enemies", key2, true, "Play voice lines for " + key2 + ".");
			value4.ActorChoice = config.Bind<string>("Actors", key2, array2[0], new ConfigDescription("Which voice actor to use for " + key2 + ".", (AcceptableValueBase)(object)new AcceptableValueList<string>(array2), Array.Empty<object>()));
			dictionary.TryGetValue(key2, out var value5);
			foreach (Actor value7 in value4.Actors.Values)
			{
				foreach (List<Line> value8 in value7.Events.Values)
				{
					value8.Sort((Line a, Line b) => TakeNumber(a).CompareTo(TakeNumber(b)));
					foreach (Line item2 in value8)
					{
						string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ShortName(item2.Resource));
						if (value5 != null && value5.TryGetValue(fileNameWithoutExtension, out var value6))
						{
							item2.Subtitle = value6;
						}
					}
				}
			}
		}
		PrepareCache(assembly);
	}

	public static bool IsEnabled(string enemyName)
	{
		if (enemies.TryGetValue(enemyName, out var value))
		{
			return value.Enabled.Value;
		}
		return false;
	}

	public static bool HasEvent(string enemyName, string evt)
	{
		return ChosenActor(enemyName)?.Events.ContainsKey(evt) ?? false;
	}

	public static bool IsLoaded(string enemyName)
	{
		return ChosenActor(enemyName)?.Events.Values.All((List<Line> lines) => lines.All((Line l) => (Object)(object)l.Clip != (Object)null)) ?? true;
	}

	public static bool HasUnplayedLevelLine(string enemyName, string evt)
	{
		Actor actor = ChosenActor(enemyName);
		if (actor != null && actor.Events.TryGetValue(evt + "@" + CurrentLevel, out var value))
		{
			return value.Any((Line l) => !playedThisLevel.Contains(l));
		}
		return false;
	}

	public static bool HasLine(string enemyName, string evt)
	{
		int num = evt.LastIndexOf('_');
		Actor actor = ChosenActor(enemyName);
		if (num <= 0 || actor == null || !actor.Events.TryGetValue(evt.Substring(0, num), out var value))
		{
			return false;
		}
		return value.Any((Line l) => Path.GetFileNameWithoutExtension(l.Resource) == evt);
	}

	public static void Request(string enemyName)
	{
		Actor actor = ChosenActor(enemyName);
		if (actor != null && !actor.LoadStarted)
		{
			actor.LoadStarted = true;
			((MonoBehaviour)Plugin.Instance).StartCoroutine(LoadActor(enemyName, actor));
		}
	}

	public static void PreloadScene()
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Invalid comparison between Unknown and I4
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Invalid comparison between Unknown and I4
		playedThisLevel.Clear();
		EnemyIdentifier[] array = Object.FindObjectsOfType<EnemyIdentifier>(true);
		foreach (EnemyIdentifier obj in array)
		{
			Request(((object)Unsafe.As<EnemyType, EnemyType>(ref obj.enemyType)/*cast due to .constrained prefix*/).ToString());
			if ((int)obj.enemyType == 5)
			{
				Request("MindflayerMale");
			}
			if ((int)obj.enemyType == 8)
			{
				Request("V2Second");
			}
		}
	}

	public static Line Pick(string enemyName, string evt)
	{
		Actor actor = ChosenActor(enemyName);
		if (actor == null)
		{
			return null;
		}
		if (!actor.LoadStarted)
		{
			Request(enemyName);
		}
		if (actor.Events.TryGetValue(evt + "@" + CurrentLevel, out var value))
		{
			Line line = value.FirstOrDefault((Line l) => !playedThisLevel.Contains(l));
			if (line != null && (Object)(object)line.Clip != (Object)null)
			{
				playedThisLevel.Add(line);
				return line;
			}
		}
		List<Line> lines;
		if (value != null && !actor.Events.ContainsKey(evt))
		{
			lines = value;
		}
		else if (!actor.Events.TryGetValue(evt, out lines))
		{
			int num = evt.LastIndexOf('_');
			if (num > 0 && actor.Events.TryGetValue(evt.Substring(0, num), out var value2))
			{
				return value2.FirstOrDefault((Line l) => (Object)(object)l.Clip != (Object)null && Path.GetFileNameWithoutExtension(l.Resource) == evt);
			}
			return null;
		}
		lastPicked.TryGetValue(lines, out var last);
		List<Line> list = lines.Where((Line l) => (Object)(object)l.Clip != (Object)null && (l != last || lines.Count == 1)).ToList();
		if (list.Count == 0)
		{
			return null;
		}
		Line line2 = list[Random.Range(0, list.Count)];
		lastPicked[lines] = line2;
		return line2;
	}

	private static Actor ChosenActor(string enemyName)
	{
		if (!enemies.TryGetValue(enemyName, out var value))
		{
			return null;
		}
		if (value.Actors.TryGetValue(value.ActorChoice.Value, out var value2))
		{
			return value2;
		}
		return value.Actors.Values.First();
	}

	private static IEnumerator LoadActor(string enemyName, Actor actor)
	{
		int loaded = 0;
		foreach (Line line in actor.Events.Values.SelectMany((List<Line> l) => l))
		{
			string text = ExtractToCache(line.Resource);
			AudioType val = (AudioType)(text.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase) ? 14 : 20);
			UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(new Uri(text).AbsoluteUri, val);
			try
			{
				yield return request.SendWebRequest();
				if ((int)request.result != 1)
				{
					Plugin.Log.LogWarning((object)("Could not load " + ShortName(line.Resource) + ": " + request.error));
					continue;
				}
				line.Clip = DownloadHandlerAudioClip.GetContent(request);
				((Object)line.Clip).name = ShortName(line.Resource);
				loaded++;
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
		}
		Plugin.Log.LogInfo((object)$"Loaded {loaded} voice lines for {enemyName}");
	}

	private static void PrepareCache(Assembly assembly)
	{
		string text = Path.Combine(Paths.CachePath, "UltraVox");
		string text2 = assembly.ManifestModule.ModuleVersionId.ToString("N");
		cacheDir = Path.Combine(text, text2);
		if (!Directory.Exists(text))
		{
			return;
		}
		string[] directories = Directory.GetDirectories(text);
		foreach (string text3 in directories)
		{
			if (!(Path.GetFileName(text3) == text2))
			{
				try
				{
					Directory.Delete(text3, recursive: true);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Could not clear old voice cache " + text3 + ": " + ex.Message));
				}
			}
		}
	}

	private static string ExtractToCache(string resource)
	{
		string text = Path.Combine(cacheDir, ShortName(resource).Replace('/', Path.DirectorySeparatorChar));
		if (File.Exists(text))
		{
			return text;
		}
		Directory.CreateDirectory(Path.GetDirectoryName(text));
		using Stream stream = typeof(VoiceBank).Assembly.GetManifestResourceStream(resource);
		using FileStream destination = File.Create(text);
		stream.CopyTo(destination);
		return text;
	}

	private static Dictionary<string, string> ReadSubtitles(Assembly assembly, string resource)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
		using StreamReader streamReader = new StreamReader(assembly.GetManifestResourceStream(resource));
		string text;
		while ((text = streamReader.ReadLine()) != null)
		{
			int num = text.IndexOf('\t');
			if (num > 0 && !text.StartsWith("#"))
			{
				dictionary[text.Substring(0, num).Trim()] = text.Substring(num + 1).Trim();
			}
		}
		return dictionary;
	}

	private static string EventName(string fileName)
	{
		int num = fileName.LastIndexOf('_');
		if (num > 0 && fileName.Substring(num + 1).All(char.IsDigit))
		{
			return fileName.Substring(0, num);
		}
		return fileName;
	}

	private static int TakeNumber(Line line)
	{
		string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(ShortName(line.Resource));
		int num = fileNameWithoutExtension.LastIndexOf('_');
		if (num <= 0 || !int.TryParse(fileNameWithoutExtension.Substring(num + 1), out var result))
		{
			return 0;
		}
		return result;
	}

	private static string ShortName(string resource)
	{
		return resource.Replace('\\', '/').Substring("UltraVox/Voices/".Length);
	}
}