Decompiled source of ForbiddenWords v1.0.0

Vosk.dll

Decompiled 8 hours ago
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Vosk;

public class Model : IDisposable
{
	private HandleRef handle;

	internal Model(IntPtr cPtr)
	{
		handle = new HandleRef(this, cPtr);
	}

	public Model(string model_path)
		: this(VoskPINVOKE.new_Model(model_path))
	{
	}

	internal static HandleRef getCPtr(Model obj)
	{
		return obj?.handle ?? new HandleRef(null, IntPtr.Zero);
	}

	~Model()
	{
		Dispose(disposing: false);
	}

	public void Dispose()
	{
		Dispose(disposing: true);
		GC.SuppressFinalize(this);
	}

	protected virtual void Dispose(bool disposing)
	{
		lock (this)
		{
			if (handle.Handle != IntPtr.Zero)
			{
				VoskPINVOKE.delete_Model(handle);
				handle = new HandleRef(null, IntPtr.Zero);
			}
		}
	}

	public int FindWord(string word)
	{
		return VoskPINVOKE.Model_vosk_model_find_word(handle, word);
	}
}
public class SpkModel : IDisposable
{
	private HandleRef handle;

	internal SpkModel(IntPtr cPtr)
	{
		handle = new HandleRef(this, cPtr);
	}

	public SpkModel(string model_path)
		: this(VoskPINVOKE.new_SpkModel(model_path))
	{
	}

	internal static HandleRef getCPtr(SpkModel obj)
	{
		return obj?.handle ?? new HandleRef(null, IntPtr.Zero);
	}

	~SpkModel()
	{
		Dispose(disposing: false);
	}

	public void Dispose()
	{
		Dispose(disposing: true);
		GC.SuppressFinalize(this);
	}

	protected virtual void Dispose(bool disposing)
	{
		lock (this)
		{
			if (handle.Handle != IntPtr.Zero)
			{
				VoskPINVOKE.delete_SpkModel(handle);
				handle = new HandleRef(null, IntPtr.Zero);
			}
		}
	}
}
public class Vosk
{
	public static void SetLogLevel(int level)
	{
		VoskPINVOKE.SetLogLevel(level);
	}

	public static void GpuInit()
	{
		VoskPINVOKE.GpuInit();
	}

	public static void GpuThreadInit()
	{
		VoskPINVOKE.GpuThreadInit();
	}
}
internal class VoskPINVOKE
{
	static VoskPINVOKE()
	{
	}

	[DllImport("libvosk", EntryPoint = "vosk_model_new")]
	public static extern IntPtr new_Model(string jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_model_free")]
	public static extern void delete_Model(HandleRef jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_model_find_word")]
	public static extern int Model_vosk_model_find_word(HandleRef jarg1, string jarg2);

	[DllImport("libvosk", EntryPoint = "vosk_spk_model_new")]
	public static extern IntPtr new_SpkModel(string jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_spk_model_free")]
	public static extern void delete_SpkModel(HandleRef jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_new")]
	public static extern IntPtr new_VoskRecognizer(HandleRef jarg1, float jarg2);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_new_spk")]
	public static extern IntPtr new_VoskRecognizerSpk(HandleRef jarg1, float jarg2, HandleRef jarg3);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_new_grm")]
	public static extern IntPtr new_VoskRecognizerGrm(HandleRef jarg1, float jarg2, string jarg3);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_free")]
	public static extern void delete_VoskRecognizer(HandleRef jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_set_max_alternatives")]
	public static extern void VoskRecognizer_SetMaxAlternatives(HandleRef jarg1, int jarg2);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_set_words")]
	public static extern void VoskRecognizer_SetWords(HandleRef jarg1, int jarg2);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_set_partial_words")]
	public static extern void VoskRecognizer_SetPartialWords(HandleRef jarg1, int jarg2);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_set_spk_model")]
	public static extern void VoskRecognizer_SetSpkModel(HandleRef jarg1, HandleRef jarg2);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_accept_waveform")]
	public static extern bool VoskRecognizer_AcceptWaveform(HandleRef jarg1, [In][MarshalAs(UnmanagedType.LPArray)] byte[] jarg2, int jarg3);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_accept_waveform_s")]
	public static extern bool VoskRecognizer_AcceptWaveformShort(HandleRef jarg1, [In][MarshalAs(UnmanagedType.LPArray)] short[] jarg2, int jarg3);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_accept_waveform_f")]
	public static extern bool VoskRecognizer_AcceptWaveformFloat(HandleRef jarg1, [In][MarshalAs(UnmanagedType.LPArray)] float[] jarg2, int jarg3);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_result")]
	public static extern IntPtr VoskRecognizer_Result(HandleRef jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_partial_result")]
	public static extern IntPtr VoskRecognizer_PartialResult(HandleRef jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_final_result")]
	public static extern IntPtr VoskRecognizer_FinalResult(HandleRef jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_recognizer_reset")]
	public static extern void VoskRecognizer_Reset(HandleRef jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_set_log_level")]
	public static extern void SetLogLevel(int jarg1);

	[DllImport("libvosk", EntryPoint = "vosk_gpu_init")]
	public static extern void GpuInit();

	[DllImport("libvosk", EntryPoint = "vosk_gpu_thread_init")]
	public static extern void GpuThreadInit();
}
public class VoskRecognizer : IDisposable
{
	private HandleRef handle;

	internal VoskRecognizer(IntPtr cPtr)
	{
		handle = new HandleRef(this, cPtr);
	}

	public VoskRecognizer(Model model, float sample_rate)
		: this(VoskPINVOKE.new_VoskRecognizer(Model.getCPtr(model), sample_rate))
	{
	}

	public VoskRecognizer(Model model, float sample_rate, SpkModel spk_model)
		: this(VoskPINVOKE.new_VoskRecognizerSpk(Model.getCPtr(model), sample_rate, SpkModel.getCPtr(spk_model)))
	{
	}

	public VoskRecognizer(Model model, float sample_rate, string grammar)
		: this(VoskPINVOKE.new_VoskRecognizerGrm(Model.getCPtr(model), sample_rate, grammar))
	{
	}

	internal static HandleRef getCPtr(VoskRecognizer obj)
	{
		return obj?.handle ?? new HandleRef(null, IntPtr.Zero);
	}

	~VoskRecognizer()
	{
		Dispose(disposing: false);
	}

	public void Dispose()
	{
		Dispose(disposing: true);
		GC.SuppressFinalize(this);
	}

	protected virtual void Dispose(bool disposing)
	{
		lock (this)
		{
			if (handle.Handle != IntPtr.Zero)
			{
				VoskPINVOKE.delete_VoskRecognizer(handle);
				handle = new HandleRef(null, IntPtr.Zero);
			}
		}
	}

	public void SetMaxAlternatives(int max_alternatives)
	{
		VoskPINVOKE.VoskRecognizer_SetMaxAlternatives(handle, max_alternatives);
	}

	public void SetWords(bool words)
	{
		VoskPINVOKE.VoskRecognizer_SetWords(handle, words ? 1 : 0);
	}

	public void SetPartialWords(bool partial_words)
	{
		VoskPINVOKE.VoskRecognizer_SetPartialWords(handle, partial_words ? 1 : 0);
	}

	public void SetSpkModel(SpkModel spk_model)
	{
		VoskPINVOKE.VoskRecognizer_SetSpkModel(handle, SpkModel.getCPtr(spk_model));
	}

	public bool AcceptWaveform(byte[] data, int len)
	{
		return VoskPINVOKE.VoskRecognizer_AcceptWaveform(handle, data, len);
	}

	public bool AcceptWaveform(short[] sdata, int len)
	{
		return VoskPINVOKE.VoskRecognizer_AcceptWaveformShort(handle, sdata, len);
	}

	public bool AcceptWaveform(float[] fdata, int len)
	{
		return VoskPINVOKE.VoskRecognizer_AcceptWaveformFloat(handle, fdata, len);
	}

	private static string PtrToStringUTF8(IntPtr ptr)
	{
		int i;
		for (i = 0; Marshal.ReadByte(ptr, i) != 0; i++)
		{
		}
		byte[] array = new byte[i];
		Marshal.Copy(ptr, array, 0, i);
		return Encoding.UTF8.GetString(array);
	}

	public string Result()
	{
		return PtrToStringUTF8(VoskPINVOKE.VoskRecognizer_Result(handle));
	}

	public string PartialResult()
	{
		return PtrToStringUTF8(VoskPINVOKE.VoskRecognizer_PartialResult(handle));
	}

	public string FinalResult()
	{
		return PtrToStringUTF8(VoskPINVOKE.VoskRecognizer_FinalResult(handle));
	}

	public void Reset()
	{
		VoskPINVOKE.VoskRecognizer_Reset(handle);
	}
}

ForbiddenWords.dll

Decompiled 8 hours ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Vosk;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PalabraProhibida
{
	internal static class Aparicion
	{
		private enum Fase
		{
			Esperando,
			Activo,
			Retirando,
			Retirado
		}

		private sealed class Invocado
		{
			public EnemyParent Padre;

			public LevelPoint Punto;

			public Vector3 Origen;

			public Fase Fase;

			public float Reloj;

			public float TiempoVisible;
		}

		private const float DistanciaMinima = 4f;

		private const float DistanciaMaxima = 12f;

		private const float Nunca = 1E+09f;

		private static readonly List<Invocado> invocados = new List<Invocado>();

		private static float proximaPermitida;

		internal static bool Pedir(PlayerAvatar? jugador)
		{
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_028d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Unknown result type (might be due to invalid IL or missing references)
			//IL_021f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Unknown result type (might be due to invalid IL or missing references)
			if (!SemiFunc.IsMasterClientOrSingleplayer())
			{
				Avisar("no soy el host: no hago aparecer nada");
				return false;
			}
			if (!SemiFunc.RunIsLevel() || !Object.op_Implicit((Object)(object)LevelGenerator.Instance) || !LevelGenerator.Instance.Generated || !Object.op_Implicit((Object)(object)EnemyDirector.instance))
			{
				Avisar("fuera de un nivel: no aparece nada");
				return false;
			}
			if (!Object.op_Implicit((Object)(object)jugador) || jugador.isDisabled)
			{
				Avisar("el jugador no está vivo: no aparece nada");
				return false;
			}
			if (Time.time < proximaPermitida)
			{
				Avisar($"en espera {proximaPermitida - Time.time:0} s más");
				return false;
			}
			int num = 0;
			foreach (Invocado invocado in invocados)
			{
				if (invocado.Fase != Fase.Retirado)
				{
					num++;
				}
			}
			if (Plugin.MaximoALaVez.Value > 0 && num >= Plugin.MaximoALaVez.Value)
			{
				Avisar("ya hay demasiados enemigos invocados a la vez");
				return false;
			}
			EnemySetup val = ElegirEnemigo();
			if (!Object.op_Implicit((Object)(object)val))
			{
				Avisar("no hay ningún enemigo que elegir en este nivel");
				return false;
			}
			LevelPoint val2 = ElegirPunto(((Component)jugador).transform.position);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				Avisar("no encuentro un punto del nivel cerca del jugador");
				return false;
			}
			Transform transform = LevelGenerator.Instance.EnemyParent.transform;
			HashSet<EnemyParent> hashSet = new HashSet<EnemyParent>(((Component)transform).GetComponentsInChildren<EnemyParent>(true));
			LevelGenerator.Instance.EnemySpawn(val, ((Component)val2).transform.position);
			int num2 = 0;
			EnemyParent[] componentsInChildren = ((Component)transform).GetComponentsInChildren<EnemyParent>(true);
			foreach (EnemyParent val3 in componentsInChildren)
			{
				if (hashSet.Contains(val3))
				{
					continue;
				}
				val3.firstSpawnPoint = val2;
				val3.firstSpawnPointUsed = false;
				if (Object.op_Implicit((Object)(object)val3.Enemy))
				{
					foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
					{
						val3.Enemy.PlayerAdded(player.photonView.ViewID);
					}
				}
				SinNucleo(val3);
				invocados.Add(new Invocado
				{
					Padre = val3,
					Punto = val2,
					Origen = ((Component)jugador).transform.position,
					Fase = Fase.Esperando,
					Reloj = 20f
				});
				num2++;
			}
			if (num2 == 0)
			{
				Avisar("el juego no creó ningún enemigo para " + ((Object)val).name);
				return false;
			}
			proximaPermitida = Time.time + Plugin.EsperaEntreApariciones.Value;
			float num3 = Vector3.Distance(((Component)val2).transform.position, ((Component)jugador).transform.position);
			Avisar($"aparece {((Object)val).name} a {num3:0} m de {jugador.playerName}");
			return true;
		}

		internal static void Tick()
		{
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			if (invocados.Count == 0)
			{
				return;
			}
			invocados.RemoveAll((Invocado i) => !Object.op_Implicit((Object)(object)i.Padre));
			if (!SemiFunc.IsMasterClientOrSingleplayer() || !Object.op_Implicit((Object)(object)EnemyDirector.instance))
			{
				return;
			}
			for (int num = invocados.Count - 1; num >= 0; num--)
			{
				Invocado invocado = invocados[num];
				EnemyParent padre = invocado.Padre;
				switch (invocado.Fase)
				{
				case Fase.Esperando:
					if (!EnemyDirector.instance.enemiesSpawned.Contains(padre))
					{
						break;
					}
					invocado.Reloj -= Time.deltaTime;
					SinNucleo(padre);
					if (!padre.Spawned)
					{
						padre.firstSpawnPoint = invocado.Punto;
						padre.firstSpawnPointUsed = false;
						padre.DespawnedTimer = Mathf.Min(padre.DespawnedTimer, 0.5f);
						invocado.TiempoVisible = 0f;
					}
					else
					{
						invocado.TiempoVisible += Time.deltaTime;
					}
					if (padre.Spawned && (padre.firstSpawnPointUsed || invocado.TiempoVisible > 3f))
					{
						float value = Plugin.DuracionEnemigo.Value;
						EnemyDirector.instance.SetInvestigate(invocado.Origen, 15f, false);
						if (value <= 0f)
						{
							invocados.RemoveAt(num);
							break;
						}
						invocado.Fase = Fase.Activo;
						invocado.Reloj = value;
					}
					else if (invocado.Reloj <= 0f)
					{
						Plugin.Log.LogWarning((object)(padre.enemyName + " no llegó a aparecer; se retira."));
						Retirar(invocado);
					}
					break;
				case Fase.Activo:
					if (!padre.Spawned)
					{
						invocado.Fase = Fase.Retirado;
						break;
					}
					invocado.Reloj -= Time.deltaTime;
					if (invocado.Reloj <= 0f)
					{
						Plugin.Log.LogInfo((object)("Se acabó el tiempo de " + padre.enemyName + "; se retira."));
						Retirar(invocado);
					}
					break;
				case Fase.Retirando:
					if (!padre.Spawned)
					{
						invocado.Fase = Fase.Retirado;
						break;
					}
					invocado.Reloj -= Time.deltaTime;
					if (invocado.Reloj <= 0f)
					{
						padre.Despawn();
						invocado.Reloj = 5f;
					}
					break;
				case Fase.Retirado:
					if (padre.Spawned)
					{
						Retirar(invocado);
					}
					else
					{
						padre.DespawnedTimer = 1E+09f;
					}
					break;
				}
			}
		}

		private static void SinNucleo(EnemyParent padre)
		{
			if (Object.op_Implicit((Object)(object)padre.Enemy) && padre.Enemy.HasHealth && Object.op_Implicit((Object)(object)padre.Enemy.Health))
			{
				padre.Enemy.Health.spawnValuable = false;
			}
		}

		private static void Retirar(Invocado i)
		{
			if (i.Padre.Spawned)
			{
				i.Padre.SpawnedTimerSet(0f);
				i.Fase = Fase.Retirando;
				i.Reloj = 10f;
			}
			else
			{
				i.Fase = Fase.Retirado;
			}
		}

		private static EnemySetup? ElegirEnemigo()
		{
			List<EnemySetup> list = Filtrar(EnemyDirector.instance.enemyList);
			if (list.Count == 0)
			{
				List<EnemySetup> list2 = new List<EnemySetup>();
				list2.AddRange(EnemyDirector.instance.enemiesDifficulty1);
				list2.AddRange(EnemyDirector.instance.enemiesDifficulty2);
				list2.AddRange(EnemyDirector.instance.enemiesDifficulty3);
				list = Filtrar(list2);
			}
			if (list.Count != 0)
			{
				return list[Random.Range(0, list.Count)];
			}
			return null;
		}

		private static List<EnemySetup> Filtrar(List<EnemySetup> lista)
		{
			List<EnemySetup> list = new List<EnemySetup>();
			foreach (EnemySetup listum in lista)
			{
				if (Object.op_Implicit((Object)(object)listum) && listum.spawnObjects != null && listum.spawnObjects.Count != 0 && !list.Contains(listum) && (listum.spawnObjects.Count <= 1 || Plugin.PermitirGrupos.Value))
				{
					list.Add(listum);
				}
			}
			return list;
		}

		private static LevelPoint? ElegirPunto(Vector3 posicion)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			List<LevelPoint> list = new List<LevelPoint>();
			LevelPoint result = null;
			float num = float.MaxValue;
			foreach (LevelPoint levelPathPoint in LevelGenerator.Instance.LevelPathPoints)
			{
				if (Object.op_Implicit((Object)(object)levelPathPoint) && (!Object.op_Implicit((Object)(object)levelPathPoint.Room) || !levelPathPoint.Room.Truck))
				{
					float num2 = Vector3.Distance(((Component)levelPathPoint).transform.position, posicion);
					if (num2 >= 4f && num2 <= 12f)
					{
						list.Add(levelPathPoint);
					}
					if (num2 < num)
					{
						num = num2;
						result = levelPathPoint;
					}
				}
			}
			if (list.Count <= 0)
			{
				return result;
			}
			return list[Random.Range(0, list.Count)];
		}

		private static void Avisar(string texto)
		{
			Plugin.Log.LogInfo((object)("Aparición: " + texto));
		}
	}
	internal static class CargaNativa
	{
		private const uint BuscarJuntoALaDll = 8u;

		[DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern IntPtr LoadLibraryExW(string ruta, IntPtr reservado, uint opciones);

		internal static bool Cargar(string carpetaPlugin)
		{
			string[] files = Directory.GetFiles(carpetaPlugin, "libvosk.dll", SearchOption.AllDirectories);
			if (files.Length == 0)
			{
				Plugin.Log.LogError((object)("No encuentro libvosk.dll dentro de " + carpetaPlugin));
				return false;
			}
			if (LoadLibraryExW(files[0], IntPtr.Zero, 8u) == IntPtr.Zero)
			{
				Plugin.Log.LogError((object)$"No se pudo cargar {files[0]} (error de Windows {Marshal.GetLastWin32Error()})");
				return false;
			}
			Plugin.Log.LogInfo((object)("Vosk nativo cargado desde " + files[0]));
			return true;
		}
	}
	internal static class Listas
	{
		private const string DeFabrica = "monster careful help running cart money dead door wait truck pistol enemy head extraction shop upgrade health heavy quickly slowly quiet hiding upstairs downstairs left right behind forward danger relax clown duck robot hunter ghost bomb grenade flashlight map exit entrance hallway room stairs kitchen vase diamond valuable fragile broken drop grab throw push lift revive heal energy battery crystal sword hammer sorry thanks buddy brother dude damn really never always maybe problem please okay inside outside";

		internal static List<string> Bolsa(string personalizadas)
		{
			List<string> list = Partir(personalizadas, ',', ';', '\n');
			if (list.Count == 0)
			{
				list = Partir("monster careful help running cart money dead door wait truck pistol enemy head extraction shop upgrade health heavy quickly slowly quiet hiding upstairs downstairs left right behind forward danger relax clown duck robot hunter ghost bomb grenade flashlight map exit entrance hallway room stairs kitchen vase diamond valuable fragile broken drop grab throw push lift revive heal energy battery crystal sword hammer sorry thanks buddy brother dude damn really never always maybe problem please okay inside outside", ' ');
			}
			return list;
		}

		internal static string[] Sortear(List<string> bolsa, int cuantas)
		{
			List<string> list = new List<string>(bolsa);
			List<string> list2 = new List<string>();
			while (list2.Count < cuantas && list.Count > 0)
			{
				int index = Random.Range(0, list.Count);
				list2.Add(list[index]);
				list.RemoveAt(index);
			}
			return list2.ToArray();
		}

		private static List<string> Partir(string texto, params char[] separadores)
		{
			List<string> list = new List<string>();
			string[] array = texto.Split(separadores, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim().ToLowerInvariant();
				if (text.Length > 0 && text.IndexOf(' ') < 0 && text.IndexOf('|') < 0 && !list.Contains(text))
				{
					list.Add(text);
				}
			}
			return list;
		}

		internal static string TituloLista(bool ingles)
		{
			if (!ingles)
			{
				return "PALABRAS PROHIBIDAS";
			}
			return "FORBIDDEN WORDS";
		}

		internal static string Dijo(bool ingles)
		{
			if (!ingles)
			{
				return "DIJO";
			}
			return "SAID";
		}

		internal static string Alguien(bool ingles)
		{
			if (!ingles)
			{
				return "ALGUIEN";
			}
			return "SOMEONE";
		}
	}
	internal sealed class Oido : IProcessor<float>, IDisposable, IProcessor<short>
	{
		private readonly int frecuencia;

		private readonly int canales;

		internal Oido(int frecuencia, int canales)
		{
			this.frecuencia = frecuencia;
			this.canales = Math.Max(1, canales);
		}

		public float[] Process(float[] buf)
		{
			short[] array = new short[buf.Length / canales];
			for (int i = 0; i < array.Length; i++)
			{
				float num = 0f;
				for (int j = 0; j < canales; j++)
				{
					num += buf[i * canales + j];
				}
				float num2 = Math.Max(-1f, Math.Min(1f, num / (float)canales));
				array[i] = (short)(num2 * 32767f);
			}
			Reconocedor.Alimentar(array, frecuencia);
			return buf;
		}

		public short[] Process(short[] buf)
		{
			short[] array = new short[buf.Length / canales];
			for (int i = 0; i < array.Length; i++)
			{
				int num = 0;
				for (int j = 0; j < canales; j++)
				{
					num += buf[i * canales + j];
				}
				array[i] = (short)(num / canales);
			}
			Reconocedor.Alimentar(array, frecuencia);
			return buf;
		}

		public void Dispose()
		{
		}
	}
	[HarmonyPatch(typeof(PlayerVoiceChat), "PhotonVoiceCreated")]
	internal static class PlayerVoiceChatPatch
	{
		private static void Postfix(PlayerVoiceChat __instance)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.photonView.IsMine)
			{
				return;
			}
			LocalVoice localVoice = __instance.localVoice;
			if (localVoice == null)
			{
				return;
			}
			VoiceInfo info = localVoice.Info;
			int samplingRate = ((VoiceInfo)(ref info)).SamplingRate;
			info = localVoice.Info;
			Oido oido = new Oido(samplingRate, ((VoiceInfo)(ref info)).Channels);
			LocalVoiceAudioFloat val = (LocalVoiceAudioFloat)(object)((localVoice is LocalVoiceAudioFloat) ? localVoice : null);
			if (val != null)
			{
				((LocalVoiceFramed<float>)(object)val).AddPostProcessor(new IProcessor<float>[1] { oido });
			}
			else
			{
				LocalVoiceAudioShort val2 = (LocalVoiceAudioShort)(object)((localVoice is LocalVoiceAudioShort) ? localVoice : null);
				if (val2 == null)
				{
					Plugin.Log.LogWarning((object)("Tipo de voz inesperado: " + ((object)localVoice).GetType().Name));
					return;
				}
				((LocalVoiceFramed<short>)(object)val2).AddPostProcessor(new IProcessor<short>[1] { oido });
			}
			ManualLogSource log = Plugin.Log;
			info = localVoice.Info;
			object arg = ((VoiceInfo)(ref info)).SamplingRate;
			info = localVoice.Info;
			log.LogInfo((object)$"Oído enganchado a la voz local: {arg} Hz, {((VoiceInfo)(ref info)).Channels} canal(es), {((object)localVoice).GetType().Name}");
		}
	}
	internal static class Pantalla
	{
		private enum Tipo
		{
			Nada,
			Dicha,
			Lista
		}

		private const int PalabrasPorLinea = 4;

		private const float SegundosDicha = 4.5f;

		private static GameObject? raiz;

		private static TextMeshProUGUI? texto;

		private static Image? banda;

		private static Image? destello;

		private static Tipo mostrando = Tipo.Nada;

		private static float inicio;

		private static string textoDicha = "";

		private static float dichaDesde;

		private static float dichaHasta;

		private static string textoLista = "";

		private static float listaDesde = float.MaxValue;

		private static float listaHasta = float.MaxValue;

		private static bool listaPendiente;

		internal static void MostrarDicha(string nombre, string palabra)
		{
			string text = Listas.Dijo(Plugin.Ingles);
			textoDicha = "<size=45%>" + nombre.ToUpperInvariant() + " " + text + "</size>\n\"" + palabra.ToUpperInvariant() + "\"";
			dichaDesde = Time.unscaledTime;
			dichaHasta = dichaDesde + 4.5f;
			mostrando = Tipo.Nada;
			if (Object.op_Implicit((Object)(object)CameraGlitch.Instance))
			{
				CameraGlitch.Instance.PlayLong();
			}
			if (Object.op_Implicit((Object)(object)GameDirector.instance))
			{
				SemiFunc.CameraShake(5f, 0.8f);
			}
		}

		internal static void MostrarLista(string[] palabras)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<size=45%><color=#FF8A00>").Append(Listas.TituloLista(Plugin.Ingles)).Append("</color></size>");
			for (int i = 0; i < palabras.Length; i++)
			{
				stringBuilder.Append((i % 4 == 0) ? "\n" : "  ·  ");
				stringBuilder.Append(palabras[i].ToUpperInvariant());
			}
			textoLista = stringBuilder.ToString();
			listaPendiente = true;
			listaDesde = float.MaxValue;
			listaHasta = float.MaxValue;
		}

		internal static void Tick()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Invalid comparison between Unknown and I4
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0277: Unknown result type (might be due to invalid IL or missing references)
			//IL_02de: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02da: Unknown result type (might be due to invalid IL or missing references)
			//IL_030e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			float unscaledTime = Time.unscaledTime;
			if (listaPendiente && Object.op_Implicit((Object)(object)GameDirector.instance) && (int)GameDirector.instance.currentState == 2 && (!Object.op_Implicit((Object)(object)LoadingUI.instance) || LoadingUI.instance.levelAnimationCompleted))
			{
				listaPendiente = false;
				listaDesde = unscaledTime + 1.5f;
				listaHasta = listaDesde + Plugin.SegundosLista.Value;
			}
			Tipo tipo = Tipo.Nada;
			float num = 0f;
			if (unscaledTime < dichaHasta)
			{
				tipo = Tipo.Dicha;
				num = dichaHasta;
			}
			else if (unscaledTime >= listaDesde && unscaledTime < listaHasta)
			{
				tipo = Tipo.Lista;
				num = listaHasta;
			}
			if (tipo == Tipo.Nada)
			{
				mostrando = Tipo.Nada;
				if (Object.op_Implicit((Object)(object)raiz) && raiz.activeSelf)
				{
					raiz.SetActive(false);
				}
				return;
			}
			Crear();
			if (!Object.op_Implicit((Object)(object)raiz) || !Object.op_Implicit((Object)(object)texto) || !Object.op_Implicit((Object)(object)banda) || !Object.op_Implicit((Object)(object)destello))
			{
				return;
			}
			if (tipo != mostrando)
			{
				mostrando = tipo;
				inicio = ((tipo == Tipo.Dicha) ? dichaDesde : unscaledTime);
				((TMP_Text)texto).text = ((tipo == Tipo.Dicha) ? textoDicha : textoLista);
				((TMP_Text)texto).fontSizeMax = ((tipo == Tipo.Dicha) ? 190f : 120f);
				raiz.SetActive(true);
				if (tipo == Tipo.Lista && Object.op_Implicit((Object)(object)CameraGlitch.Instance))
				{
					CameraGlitch.Instance.PlayShort();
				}
			}
			if (Object.op_Implicit((Object)(object)BigMessageUI.instance) && Object.op_Implicit((Object)(object)BigMessageUI.instance.Text) && (Object)(object)((TMP_Text)texto).font != (Object)(object)((TMP_Text)BigMessageUI.instance.Text).font)
			{
				((TMP_Text)texto).font = ((TMP_Text)BigMessageUI.instance.Text).font;
			}
			bool flag = tipo == Tipo.Dicha;
			float num2 = unscaledTime - inicio;
			float num3 = Mathf.Clamp01(1f - num2 / (flag ? 0.45f : 0.3f));
			num3 *= num3;
			float num4 = Mathf.Min(Mathf.Clamp01(num2 / 0.08f), Mathf.Clamp01((num - unscaledTime) / 0.5f));
			RectTransform rectTransform = ((TMP_Text)texto).rectTransform;
			((Transform)rectTransform).localScale = Vector3.one * (1f + (flag ? 1.6f : 0.4f) * num3);
			rectTransform.anchoredPosition = Random.insideUnitCircle * ((flag ? 30f : 8f) * num3 + (flag ? 2.5f : 0f));
			Color color;
			if (flag)
			{
				float num5 = 0.5f + 0.5f * Mathf.Sin(num2 * 14f);
				color = Color.Lerp(Color.Lerp(new Color(1f, 0.05f, 0.05f), new Color(1f, 0.4f, 0.25f), num5), Color.white, num3);
			}
			else
			{
				color = Color.Lerp(Color.white, new Color(1f, 0.54f, 0f), num3);
			}
			color.a = num4;
			((Graphic)texto).color = color;
			((Graphic)banda).color = new Color(0f, 0f, 0f, 0.6f * num4);
			((Graphic)destello).color = new Color(0.9f, 0f, 0f, flag ? (0.55f * Mathf.Clamp01(1f - num2 / 0.7f)) : 0f);
		}

		private static void Crear()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)raiz))
			{
				raiz = new GameObject("ForbiddenWords Pantalla");
				Object.DontDestroyOnLoad((Object)(object)raiz);
				((Object)raiz).hideFlags = (HideFlags)61;
				Canvas obj = raiz.AddComponent<Canvas>();
				obj.renderMode = (RenderMode)0;
				obj.sortingOrder = 30001;
				CanvasScaler obj2 = raiz.AddComponent<CanvasScaler>();
				obj2.uiScaleMode = (ScaleMode)1;
				obj2.referenceResolution = new Vector2(1920f, 1080f);
				obj2.matchWidthOrHeight = 0.5f;
				destello = NuevaImagen("Destello");
				((Graphic)destello).rectTransform.anchorMin = Vector2.zero;
				((Graphic)destello).rectTransform.anchorMax = Vector2.one;
				((Graphic)destello).rectTransform.sizeDelta = Vector2.zero;
				banda = NuevaImagen("Banda");
				((Graphic)banda).rectTransform.anchorMin = new Vector2(0f, 0.6f);
				((Graphic)banda).rectTransform.anchorMax = new Vector2(1f, 0.6f);
				((Graphic)banda).rectTransform.sizeDelta = new Vector2(0f, 330f);
				GameObject val = new GameObject("Texto");
				val.transform.SetParent(raiz.transform, false);
				texto = val.AddComponent<TextMeshProUGUI>();
				((TMP_Text)texto).alignment = (TextAlignmentOptions)514;
				((Graphic)texto).raycastTarget = false;
				((TMP_Text)texto).fontStyle = (FontStyles)1;
				((TMP_Text)texto).richText = true;
				((TMP_Text)texto).enableAutoSizing = true;
				((TMP_Text)texto).fontSizeMin = 30f;
				((TMP_Text)texto).fontSizeMax = 120f;
				((TMP_Text)texto).lineSpacing = -10f;
				((TMP_Text)texto).rectTransform.anchorMin = new Vector2(0.5f, 0.6f);
				((TMP_Text)texto).rectTransform.anchorMax = new Vector2(0.5f, 0.6f);
				((TMP_Text)texto).rectTransform.sizeDelta = new Vector2(1750f, 310f);
				raiz.SetActive(false);
			}
		}

		private static Image NuevaImagen(string nombre)
		{
			//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_0029: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(nombre);
			val.transform.SetParent(raiz.transform, false);
			Image obj = val.AddComponent<Image>();
			((Graphic)obj).raycastTarget = false;
			((Graphic)obj).color = Color.clear;
			return obj;
		}
	}
	[BepInPlugin("tommy777.forbiddenwords", "ForbiddenWords", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "tommy777.forbiddenwords";

		public const string Nombre = "ForbiddenWords";

		internal static readonly bool Ingles = true;

		public const string Version = "1.0.0";

		private const string MarcaActivo = "tommy777.forbiddenwords.activo";

		internal static ManualLogSource Log = null;

		internal static ConfigEntry<string> PalabrasPersonalizadas = null;

		internal static ConfigEntry<int> PalabrasIniciales = null;

		internal static ConfigEntry<int> PalabrasPorNivel = null;

		internal static ConfigEntry<int> MaximoPalabras = null;

		internal static ConfigEntry<float> SegundosLista = null;

		internal static ConfigEntry<Modo> ModoReconocimiento = null;

		internal static ConfigEntry<float> ConfianzaMinima = null;

		internal static ConfigEntry<float> DuracionEnemigo = null;

		internal static ConfigEntry<float> EsperaEntreApariciones = null;

		internal static ConfigEntry<int> MaximoALaVez = null;

		internal static ConfigEntry<bool> PermitirGrupos = null;

		internal static ConfigEntry<bool> RegistroDetallado = null;

		private void Awake()
		{
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Expected O, but got Unknown
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Expected O, but got Unknown
			//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Expected O, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Expected O, but got Unknown
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Expected O, but got Unknown
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Expected O, but got Unknown
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			if (AppDomain.CurrentDomain.GetData("tommy777.forbiddenwords.activo") is string text)
			{
				Log.LogWarning((object)T(text + " is also installed. ForbiddenWords and PalabrasProhibidas are the same mod in two languages: keep only one. ForbiddenWords stays off.", text + " también está instalado. ForbiddenWords y PalabrasProhibidas son el mismo mod en dos idiomas: deja solo uno. ForbiddenWords queda apagado."));
				((Behaviour)this).enabled = false;
				return;
			}
			AppDomain.CurrentDomain.SetData("tommy777.forbiddenwords.activo", "ForbiddenWords");
			PalabrasPersonalizadas = ((BaseUnityPlugin)this).Config.Bind<string>("Words", "CustomList", "", T("Your own word list, comma separated (e.g. cat, dog, house). Empty = use the built-in list. One word per entry, lower case, and it must exist in the voice model's vocabulary (unknown words are skipped). Host only.", "Tu propia lista de palabras, separadas por comas (p. ej. gato, perro, casa). Vacío = lista de fábrica. Una palabra por entrada, en minúsculas, y tiene que existir en el vocabulario del modelo de voz (las desconocidas se saltan). Solo anfitrión."));
			PalabrasIniciales = ((BaseUnityPlugin)this).Config.Bind<int>("Words", "StartingWords", 2, new ConfigDescription(T("Forbidden words on the first level. Host only.", "Palabras prohibidas en el primer nivel. Solo anfitrión."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>()));
			PalabrasPorNivel = ((BaseUnityPlugin)this).Config.Bind<int>("Words", "WordsPerLevel", 1, new ConfigDescription(T("Extra forbidden words for each level completed. Host only.", "Palabras prohibidas de más por cada nivel superado. Solo anfitrión."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
			MaximoPalabras = ((BaseUnityPlugin)this).Config.Bind<int>("Words", "MaxWords", 8, new ConfigDescription(T("Most forbidden words at once. Host only.", "Máximo de palabras prohibidas a la vez. Solo anfitrión."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>()));
			SegundosLista = ((BaseUnityPlugin)this).Config.Bind<float>("Words", "ListSeconds", 8f, new ConfigDescription(T("How long the forbidden words stay on screen when a level starts.", "Segundos que se muestran las palabras prohibidas al empezar un nivel."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 30f), Array.Empty<object>()));
			ModoReconocimiento = ((BaseUnityPlugin)this).Config.Bind<Modo>("Recognition", "Mode", Modo.Strict, T("Strict: free dictation, the word must be heard whole and clear (almost no false triggers, misses a few). Sensitive: the recogniser can only hear the forbidden words (misses almost none, but similar or half-said words trigger it).", "Strict: dictado libre, la palabra tiene que oírse entera y clara (casi nunca salta por error, se le escapa alguna). Sensitive: el reconocedor solo puede oír las palabras prohibidas (casi no se le escapa ninguna, pero saltan palabras parecidas o a medio decir)."));
			ConfianzaMinima = ((BaseUnityPlugin)this).Config.Bind<float>("Recognition", "MinConfidence", 0.5f, new ConfigDescription(T("How sure (0 to 1) the recogniser must be. Raise it if words trigger that you did not say; lower it if real words are missed. Never below 0.9 in Sensitive mode.", "Seguridad (de 0 a 1) que debe tener el reconocedor. Súbela si saltan palabras que no dijiste; bájala si se le escapan las de verdad. Nunca menos de 0.9 en modo Sensitive."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			DuracionEnemigo = ((BaseUnityPlugin)this).Config.Bind<float>("Enemy", "Seconds", 60f, new ConfigDescription(T("How long a summoned enemy stays before it vanishes. 0 = it stays for good. Host only.", "Segundos que se queda un enemigo invocado antes de desaparecer. 0 = se queda para siempre. Solo anfitrión."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>()));
			EsperaEntreApariciones = ((BaseUnityPlugin)this).Config.Bind<float>("Enemy", "Cooldown", 0f, new ConfigDescription(T("Minimum seconds between two summons. 0 = no cooldown. Host only.", "Segundos mínimos entre dos invocaciones. 0 = sin espera. Solo anfitrión."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>()));
			MaximoALaVez = ((BaseUnityPlugin)this).Config.Bind<int>("Enemy", "MaxAtOnce", 0, new ConfigDescription(T("Most summoned enemies alive at once. 0 = no limit. Host only.", "Máximo de enemigos invocados vivos a la vez. 0 = sin límite. Solo anfitrión."), (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>()));
			PermitirGrupos = ((BaseUnityPlugin)this).Config.Bind<bool>("Enemy", "AllowGroups", false, T("Also summon enemies that come in groups (several at once). They may misbehave when created mid-level. Host only.", "Invocar también enemigos que vienen en grupo (varios a la vez). Pueden fallar al crearse a mitad de nivel. Solo anfitrión."));
			RegistroDetallado = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLog", false, T("Writes every phrase the recogniser hears from YOUR microphone to the BepInEx log, with confidence values. Only for troubleshooting.", "Escribe en el log de BepInEx cada frase que el reconocedor oye de TU micrófono, con su confianza. Solo para buscar fallos."));
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			if (CargaNativa.Cargar(directoryName))
			{
				Reconocedor.Iniciar(directoryName, Ingles, ModoReconocimiento.Value, ConfianzaMinima.Value);
				new Harmony("tommy777.forbiddenwords").PatchAll();
				Log.LogInfo((object)("ForbiddenWords 1.0.0 cargado. Idioma: " + (Ingles ? "inglés" : "español")));
			}
		}

		private static string T(string ingles, string espanol)
		{
			if (!Ingles)
			{
				return espanol;
			}
			return ingles;
		}

		private void Update()
		{
			Deteccion result;
			while (Reconocedor.Detecciones.TryDequeue(out result))
			{
				Log.LogInfo((object)("Palabra prohibida detectada: \"" + result.Palabra + "\" (" + result.Origen + ")"));
				Red.DeteccionLocal(result.Palabra);
			}
			Red.Tick();
			Aparicion.Tick();
			Pantalla.Tick();
		}

		private void OnDestroy()
		{
			Reconocedor.Detener();
		}
	}
	internal enum Modo
	{
		Strict,
		Sensitive
	}
	internal struct Deteccion
	{
		public string Palabra;

		public string Origen;
	}
	internal static class Reconocedor
	{
		private struct Trozo
		{
			public short[] Muestras;

			public int Frecuencia;
		}

		private struct Oida
		{
			public string Palabra;

			public float Confianza;
		}

		private static readonly Regex PalabraJson = new Regex("\"conf\"\\s*:\\s*([0-9.eE+-]+)[^}]*?\"word\"\\s*:\\s*\"([^\"]*)\"", RegexOptions.Compiled);

		private const int MaximoEnCola = 200;

		private const double SegundosEntreDetecciones = 2.0;

		private const float ConfianzaMinimaSensible = 0.9f;

		private static readonly ConcurrentQueue<Trozo> cola = new ConcurrentQueue<Trozo>();

		private static readonly AutoResetEvent hayAudio = new AutoResetEvent(initialState: false);

		private static readonly List<Oida> oidas = new List<Oida>();

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

		private static Thread? hilo;

		private static volatile bool salir;

		private static string carpeta = "";

		private static bool ingles;

		private static volatile Model? modeloCargado;

		private static Modo modo;

		private static float confianzaMinima;

		private static long ultimaDeteccion;

		private static volatile string[] pedidas = Array.Empty<string>();

		internal static readonly ConcurrentQueue<Deteccion> Detecciones = new ConcurrentQueue<Deteccion>();

		internal static void Iniciar(string carpetaPlugin, bool enIngles, Modo modoElegido, float confianza)
		{
			carpeta = carpetaPlugin;
			ingles = enIngles;
			modo = modoElegido;
			confianzaMinima = ((modo == Modo.Sensitive) ? Math.Max(confianza, 0.9f) : confianza);
			hilo = new Thread(Bucle)
			{
				IsBackground = true,
				Name = "ForbiddenWords-Vosk"
			};
			hilo.Start();
		}

		internal static void CambiarPalabras(string[] palabras)
		{
			string[] array = pedidas;
			if (array.Length == palabras.Length)
			{
				bool flag = true;
				for (int i = 0; i < palabras.Length && flag; i++)
				{
					flag = array[i] == palabras[i];
				}
				if (flag)
				{
					return;
				}
			}
			pedidas = palabras;
			hayAudio.Set();
		}

		internal static bool Conoce(string palabra)
		{
			Model val = modeloCargado;
			if (val != null)
			{
				if (palabra.Length > 0 && palabra.IndexOf(' ') < 0)
				{
					return val.FindWord(palabra) >= 0;
				}
				return false;
			}
			return true;
		}

		internal static void Detener()
		{
			salir = true;
			hayAudio.Set();
		}

		internal static void Alimentar(short[] muestras, int frecuencia)
		{
			if (cola.Count < 200)
			{
				cola.Enqueue(new Trozo
				{
					Muestras = muestras,
					Frecuencia = frecuencia
				});
				hayAudio.Set();
			}
		}

		private static void Bucle()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Expected O, but got Unknown
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			Model val = null;
			VoskRecognizer val2 = null;
			int num = 0;
			try
			{
				string text = BuscarModelo();
				if (text == null)
				{
					Plugin.Log.LogError((object)("No encuentro el modelo de Vosk de " + NombreIdioma() + " dentro de " + carpeta));
					return;
				}
				Vosk.SetLogLevel(-1);
				Stopwatch stopwatch = Stopwatch.StartNew();
				val = (modeloCargado = new Model(text));
				Plugin.Log.LogInfo((object)$"Modelo de {NombreIdioma()} cargado en {stopwatch.ElapsedMilliseconds} ms");
				string text2 = "";
				string[] array = null;
				while (!salir)
				{
					hayAudio.WaitOne(500);
					string[] array2 = pedidas;
					if (array2 != array)
					{
						array = array2;
						Validar(val, array2);
						if (modo == Modo.Sensitive)
						{
							if (val2 != null)
							{
								val2.Dispose();
							}
							val2 = null;
						}
					}
					Trozo result;
					while (!salir && cola.TryDequeue(out result))
					{
						if (val2 == null || result.Frecuencia != num)
						{
							if (val2 != null)
							{
								val2.Dispose();
							}
							num = result.Frecuencia;
							val2 = ((modo == Modo.Sensitive && activas.Count > 0) ? new VoskRecognizer(val, (float)num, Gramatica()) : new VoskRecognizer(val, (float)num));
							val2.SetWords(true);
							val2.SetPartialWords(true);
							Plugin.Log.LogInfo((object)$"Escuchando el micrófono del juego a {num} Hz ({NombreIdioma()}, modo {modo}, confianza mínima {confianzaMinima:0.00})");
						}
						if (val2.AcceptWaveform(result.Muestras, result.Muestras.Length))
						{
							Leer(val2.Result());
							text2 = "";
							if (oidas.Count > 0)
							{
								if (Plugin.RegistroDetallado.Value)
								{
									Plugin.Log.LogInfo((object)("Frase: " + Describir()));
								}
								Comprobar(oidas.Count, "frase completa", null);
							}
						}
						else
						{
							if (modo != Modo.Strict)
							{
								continue;
							}
							string text3 = val2.PartialResult();
							if (text3 != text2)
							{
								text2 = text3;
								Leer(text3);
								if (oidas.Count > 0)
								{
									Comprobar(oidas.Count - 1, "a mitad de frase", val2);
								}
							}
						}
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Fallo en el hilo de reconocimiento: {arg}");
			}
			finally
			{
				modeloCargado = null;
				if (val2 != null)
				{
					val2.Dispose();
				}
				if (val != null)
				{
					val.Dispose();
				}
			}
		}

		private static string NombreIdioma()
		{
			if (!ingles)
			{
				return "español";
			}
			return "inglés";
		}

		private static void Validar(Model modelo, string[] palabras)
		{
			activas.Clear();
			List<string> list = new List<string>();
			foreach (string text in palabras)
			{
				if (text.Length > 0 && text.IndexOf(' ') < 0 && modelo.FindWord(text) >= 0)
				{
					activas.Add(text);
				}
				else
				{
					list.Add(text);
				}
			}
			if (list.Count > 0)
			{
				Plugin.Log.LogWarning((object)("Palabras de esta ronda que tu modelo de " + NombreIdioma() + " no conoce y no puede detectar: " + string.Join(", ", list)));
			}
		}

		private static string Gramatica()
		{
			StringBuilder stringBuilder = new StringBuilder("[");
			foreach (string activa in activas)
			{
				stringBuilder.Append('"').Append(activa).Append("\", ");
			}
			return stringBuilder.Append("\"[unk]\"]").ToString();
		}

		private static void Leer(string json)
		{
			oidas.Clear();
			foreach (Match item in PalabraJson.Matches(json))
			{
				float.TryParse(item.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result);
				oidas.Add(new Oida
				{
					Palabra = item.Groups[2].Value,
					Confianza = result
				});
			}
		}

		private static string Describir()
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Oida oida in oidas)
			{
				stringBuilder.Append(oida.Palabra).Append('(').Append(oida.Confianza.ToString("0.00", CultureInfo.InvariantCulture))
					.Append(") ");
			}
			return stringBuilder.ToString().TrimEnd();
		}

		private static void Comprobar(int cuantas, string origen, VoskRecognizer? reiniciar)
		{
			int num = -1;
			for (int i = 0; i < cuantas; i++)
			{
				if (oidas[i].Confianza >= confianzaMinima && activas.Contains(oidas[i].Palabra))
				{
					num = i;
					break;
				}
			}
			if (num >= 0)
			{
				if (reiniciar != null)
				{
					reiniciar.Reset();
				}
				long timestamp = Stopwatch.GetTimestamp();
				if (ultimaDeteccion == 0L || !((double)(timestamp - ultimaDeteccion) / (double)Stopwatch.Frequency < 2.0))
				{
					ultimaDeteccion = timestamp;
					Detecciones.Enqueue(new Deteccion
					{
						Palabra = oidas[num].Palabra,
						Origen = origen + ", confianza " + oidas[num].Confianza.ToString("0.00", CultureInfo.InvariantCulture)
					});
				}
			}
		}

		private static string? BuscarModelo()
		{
			string text = (ingles ? "-en-" : "-es-");
			string text2 = BuscarModeloEn(carpeta, text);
			if (text2 != null)
			{
				return text2;
			}
			string[] files = Directory.GetFiles(carpeta, "vosk-model*" + text + "*.zip", SearchOption.AllDirectories);
			if (files.Length == 0)
			{
				return null;
			}
			string text3 = Path.Combine(Paths.CachePath, "ForbiddenWords", Path.GetFileNameWithoutExtension(files[0]));
			string path = Path.Combine(text3, ".descomprimido");
			if (!File.Exists(path))
			{
				if (Directory.Exists(text3))
				{
					Directory.Delete(text3, recursive: true);
				}
				Directory.CreateDirectory(text3);
				ZipFile.ExtractToDirectory(files[0], text3);
				File.WriteAllText(path, "");
				Plugin.Log.LogInfo((object)("Modelo descomprimido en " + text3));
			}
			return BuscarModeloEn(text3, text);
		}

		private static string? BuscarModeloEn(string raiz, string marca)
		{
			string[] files = Directory.GetFiles(raiz, "final.mdl", SearchOption.AllDirectories);
			for (int i = 0; i < files.Length; i++)
			{
				string directoryName = Path.GetDirectoryName(files[i]);
				if (directoryName != null && !(Path.GetFileName(directoryName) != "am"))
				{
					string directoryName2 = Path.GetDirectoryName(directoryName);
					if (directoryName2 != null && Path.GetFileName(directoryName2).Contains(marca))
					{
						return directoryName2;
					}
				}
			}
			return null;
		}
	}
	internal static class Red
	{
		private const byte EventoDeteccion = 147;

		private const byte EventoAnuncio = 148;

		private const string Marca = "tommy777.forbiddenwords";

		private const string PropiedadPalabras = "ForbiddenWords.words";

		private const string PropiedadRonda = "ForbiddenWords.round";

		private static float proximaRevision;

		private static bool suscrito;

		private static bool eraHost;

		private static int nivelSorteado;

		private static int ronda;

		private static int rondaMostrada = -1;

		internal static string[] Activas = Array.Empty<string>();

		internal static void DeteccionLocal(string palabra)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			if (!PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient)
			{
				Resolver(PlayerAvatar.instance, PhotonNetwork.InRoom ? PhotonNetwork.LocalPlayer.ActorNumber : (-1), palabra);
				return;
			}
			PhotonNetwork.RaiseEvent((byte)147, (object)new object[2] { "tommy777.forbiddenwords", palabra }, new RaiseEventOptions
			{
				Receivers = (ReceiverGroup)2
			}, SendOptions.SendReliable);
		}

		internal static void Tick()
		{
			//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
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Expected O, but got Unknown
			//IL_0191: Expected O, but got Unknown
			if (!suscrito)
			{
				PhotonNetwork.NetworkingClient.EventReceived += AlRecibir;
				suscrito = true;
			}
			if (Time.unscaledTime < proximaRevision)
			{
				return;
			}
			proximaRevision = Time.unscaledTime + 0.5f;
			bool flag = SemiFunc.RunIsLevel() && Object.op_Implicit((Object)(object)LevelGenerator.Instance) && LevelGenerator.Instance.Generated;
			bool flag2 = !PhotonNetwork.InRoom || PhotonNetwork.IsMasterClient;
			Hashtable val = (PhotonNetwork.InRoom ? ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties : null);
			if (flag2)
			{
				string text = default(string);
				int num;
				if (!eraHost && val != null)
				{
					text = val[(object)"ForbiddenWords.words"] as string;
					num = ((text != null) ? 1 : 0);
				}
				else
				{
					num = 0;
				}
				if (((uint)num & (flag ? 1u : 0u)) != 0)
				{
					Usar(text.Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries));
					nivelSorteado = ((Object)LevelGenerator.Instance).GetInstanceID();
					ronda = ((val[(object)"ForbiddenWords.round"] is int num2) ? num2 : 0);
					rondaMostrada = ronda;
				}
				if (flag && ((Object)LevelGenerator.Instance).GetInstanceID() != nivelSorteado)
				{
					nivelSorteado = ((Object)LevelGenerator.Instance).GetInstanceID();
					Sortear();
					if (PhotonNetwork.InRoom)
					{
						Room currentRoom = PhotonNetwork.CurrentRoom;
						Hashtable val2 = new Hashtable();
						((Dictionary<object, object>)val2).Add((object)"ForbiddenWords.words", (object)string.Join("|", Activas));
						((Dictionary<object, object>)val2).Add((object)"ForbiddenWords.round", (object)ronda);
						currentRoom.SetCustomProperties(val2, (Hashtable)null, (WebFlags)null);
					}
					rondaMostrada = ronda;
					Pantalla.MostrarLista(Activas);
				}
			}
			else if (val != null && val[(object)"ForbiddenWords.words"] is string text2)
			{
				Usar(text2.Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries));
				if (flag && Activas.Length != 0 && val[(object)"ForbiddenWords.round"] is int num3 && num3 != rondaMostrada)
				{
					rondaMostrada = num3;
					Pantalla.MostrarLista(Activas);
				}
			}
			eraHost = flag2;
			Reconocedor.CambiarPalabras(Activas);
		}

		private static void Sortear()
		{
			int num = (Object.op_Implicit((Object)(object)RunManager.instance) ? RunManager.instance.levelsCompleted : 0);
			int num2 = Plugin.PalabrasIniciales.Value + Plugin.PalabrasPorNivel.Value * num;
			num2 = Mathf.Clamp(num2, 1, Mathf.Max(1, Plugin.MaximoPalabras.Value));
			List<string> list = Listas.Bolsa(Plugin.PalabrasPersonalizadas.Value);
			int count = list.Count;
			list.RemoveAll((string p) => !Reconocedor.Conoce(p));
			if (list.Count < count)
			{
				Plugin.Log.LogWarning((object)$"{count - list.Count} palabra(s) de la lista no existen en el vocabulario del modelo de voz y se ignoran.");
			}
			Activas = Listas.Sortear(list, num2);
			ronda++;
			Plugin.Log.LogInfo((object)string.Format("Ronda {0} (niveles superados: {1}): {2}", ronda, num, string.Join(", ", Activas)));
		}

		private static void Usar(string[] palabras)
		{
			if (palabras.Length == Activas.Length)
			{
				bool flag = true;
				for (int i = 0; i < palabras.Length && flag; i++)
				{
					flag = palabras[i] == Activas[i];
				}
				if (flag)
				{
					return;
				}
			}
			Activas = palabras;
		}

		private static void AlRecibir(EventData evento)
		{
			if ((evento.Code != 147 && evento.Code != 148) || !(evento.CustomData is object[] array) || array.Length < 2 || !(array[0] is string text) || text != "tommy777.forbiddenwords")
			{
				return;
			}
			if (evento.Code == 147)
			{
				if (PhotonNetwork.IsMasterClient && array[1] is string text2 && Array.IndexOf(Activas, text2) >= 0)
				{
					Resolver(BuscarJugador(evento.Sender), evento.Sender, text2);
				}
			}
			else if (array.Length >= 3 && array[1] is int actor && array[2] is string palabra && PhotonNetwork.MasterClient != null && evento.Sender == PhotonNetwork.MasterClient.ActorNumber)
			{
				Anunciar(BuscarJugador(actor), palabra);
			}
		}

		private static void Resolver(PlayerAvatar? jugador, int actor, string palabra)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: 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)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			if (Aparicion.Pedir(jugador))
			{
				if (PhotonNetwork.InRoom)
				{
					PhotonNetwork.RaiseEvent((byte)148, (object)new object[3] { "tommy777.forbiddenwords", actor, palabra }, new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)1
					}, SendOptions.SendReliable);
				}
				else
				{
					Anunciar(jugador, palabra);
				}
			}
		}

		private static void Anunciar(PlayerAvatar? jugador, string palabra)
		{
			Pantalla.MostrarDicha(Object.op_Implicit((Object)(object)jugador) ? jugador.playerName : Listas.Alguien(Plugin.Ingles), palabra);
		}

		private static PlayerAvatar? BuscarJugador(int actor)
		{
			if (!Object.op_Implicit((Object)(object)GameDirector.instance))
			{
				return null;
			}
			foreach (PlayerAvatar player in GameDirector.instance.PlayerList)
			{
				if (Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)player.photonView) && player.photonView.OwnerActorNr == actor)
				{
					return player;
				}
			}
			return null;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}