Decompiled source of StreamHud VR v0.1.0

plugins/StreamHud_VR.dll

Decompiled a day ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using UnityEngine.XR;

[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("StreamHud_VR")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("StreamHud_VR")]
[assembly: AssemblyTitle("StreamHud_VR")]
[assembly: AssemblyVersion("0.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ValheimStreamHUD
{
	public class HudConfig
	{
		public ConfigEntry<string> TwitchChannel;

		public ConfigEntry<string> StreamlabsSocketToken;

		public ConfigEntry<string> Mode;

		public ConfigEntry<bool> ShowInMenus;

		public ConfigEntry<int> Layer;

		public ConfigEntry<bool> ShowStatusBox;

		public ConfigEntry<KeyboardShortcut> KeyToggleStatus;

		public ConfigEntry<bool> VRStatusCombo;

		public ConfigEntry<string> StatusOffset;

		public ConfigEntry<string> StatusRotation;

		public ConfigEntry<KeyboardShortcut> KeyToggleChat;

		public ConfigEntry<KeyboardShortcut> KeyTest;

		public ConfigEntry<KeyboardShortcut> KeyReload;

		public ConfigEntry<string> VRTestButton;

		public ConfigEntry<float> VRTestHold;

		public ConfigEntry<bool> WelcomeTest;

		public ConfigEntry<string> FontHint;

		public ConfigEntry<string> PanelColor;

		public ConfigEntry<string> AccentColor;

		public ConfigEntry<string> TextColor;

		public ConfigEntry<string> DefaultNameColor;

		public ConfigEntry<string> AlertNameColor;

		public ConfigEntry<bool> ChatEnabled;

		public ConfigEntry<string> ChatAnchor;

		public ConfigEntry<string> ChatOffset;

		public ConfigEntry<string> ChatRotation;

		public ConfigEntry<bool> ChatFaceHead;

		public ConfigEntry<string> ChatVisibility;

		public ConfigEntry<float> ChatLookAngle;

		public ConfigEntry<float> PalmFullAngle;

		public ConfigEntry<float> PalmZeroAngle;

		public ConfigEntry<bool> ChatPlaceholder;

		public ConfigEntry<float> ChatScale;

		public ConfigEntry<int> ChatWidth;

		public ConfigEntry<int> ChatHeight;

		public ConfigEntry<float> ChatFontSize;

		public ConfigEntry<int> ChatMaxMessages;

		public ConfigEntry<float> ChatMessageLifetime;

		public ConfigEntry<float> ChatOpacity;

		public ConfigEntry<bool> AlertsEnabled;

		public ConfigEntry<string> AlertOffset;

		public ConfigEntry<string> AlertRotation;

		public ConfigEntry<float> AlertScale;

		public ConfigEntry<int> AlertWidth;

		public ConfigEntry<int> AlertHeight;

		public ConfigEntry<float> AlertFontSize;

		public ConfigEntry<float> AlertDuration;

		public ConfigEntry<string> TextFollow;

		public ConfigEntry<string> TextSubscription;

		public ConfigEntry<string> TextResub;

		public ConfigEntry<string> TextBits;

		public ConfigEntry<string> TextDonation;

		public ConfigEntry<string> TextRaid;

		public ConfigEntry<string> TextHost;

		public ConfigEntry<string> TextGiftSub;

		public ConfigEntry<string> TextMysteryGift;

		public ConfigEntry<bool> AlertShowLabel;

		public HudConfig(ConfigFile c)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: 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_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0243: Expected O, but got Unknown
			//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Expected O, but got Unknown
			//IL_045f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0469: Expected O, but got Unknown
			TwitchChannel = c.Bind<string>("Twitch", "Channel", "", "Nome do seu canal na Twitch (só o nome, sem link). O chat é lido de forma anônima, sem login.");
			StreamlabsSocketToken = c.Bind<string>("Streamlabs", "SocketToken", "", "Socket API Token do Streamlabs: Dashboard > Settings > API Settings > API Tokens > Your Socket API Token. NÃO compartilhe esse token nem suba este arquivo no GitHub.");
			Mode = c.Bind<string>("Geral", "Mode", "Auto", new ConfigDescription("Auto detecta o VR. VR força painéis no mundo; Flat força painéis na tela (para testar sem headset).", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Auto", "VR", "Flat" }), Array.Empty<object>()));
			ShowInMenus = c.Bind<bool>("Geral", "ShowInMenus", false, "Mostrar os painéis também no menu principal.");
			Layer = c.Bind<int>("Geral", "LayerOverride", -1, "Layer da Unity dos painéis em VR. -1 = automático (30, a mesma layer de UI do VHVR).");
			ShowStatusBox = c.Bind<bool>("Geral", "ShowStatusBox", true, "Caixa presa na visão mostrando se Twitch, Streamlabs e o pulso estão funcionando.");
			KeyToggleStatus = c.Bind<KeyboardShortcut>("Geral", "KeyToggleStatus", new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>()), "Mostra/oculta a caixa de status.");
			VRStatusCombo = c.Bind<bool>("Geral", "VRStatusCombo", true, "Clicar os dois analógicos juntos mostra/oculta a caixa de status (a escolha fica salva).");
			StatusOffset = c.Bind<string>("Geral", "StatusOffset", "0.17, -0.15, 0.60", "Posição da caixa de status em relação à cabeça (x, y, z).");
			StatusRotation = c.Bind<string>("Geral", "StatusRotation", "12, 15, 0", "Rotação da caixa de status (graus).");
			KeyToggleChat = c.Bind<KeyboardShortcut>("Geral", "KeyToggleChat", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Mostra/oculta o chat.");
			KeyTest = c.Bind<KeyboardShortcut>("Geral", "KeyTest", new KeyboardShortcut((KeyCode)290, Array.Empty<KeyCode>()), "Envia uma mensagem e um alerta de teste.");
			KeyReload = c.Bind<KeyboardShortcut>("Geral", "KeyReload", new KeyboardShortcut((KeyCode)291, Array.Empty<KeyCode>()), "Recarrega este arquivo sem reiniciar o jogo.");
			VRTestButton = c.Bind<string>("Geral", "VRTestButton", "LeftStickClick", new ConfigDescription("Botão do controle que, segurado, dispara o teste no VR.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[5] { "None", "LeftStickClick", "RightStickClick", "LeftPrimary", "LeftSecondary" }), Array.Empty<object>()));
			VRTestHold = c.Bind<float>("Geral", "VRTestHold", 1.5f, "Segundos segurando o botão para disparar o teste.");
			WelcomeTest = c.Bind<bool>("Geral", "WelcomeTest", true, "Ao entrar no mundo, manda uma mensagem e um alerta de teste.");
			FontHint = c.Bind<string>("Estilo", "FontHint", "AveriaSerif", "Parte do nome da fonte do jogo a usar (ex.: AveriaSerif, Norse). Veja os nomes disponíveis no LogOutput.log.");
			PanelColor = c.Bind<string>("Estilo", "PanelColor", "#140B06D9", "Cor do painel (RRGGBBAA).");
			AccentColor = c.Bind<string>("Estilo", "AccentColor", "#E6C36A", "Cor dourada da barra e do separador.");
			TextColor = c.Bind<string>("Estilo", "TextColor", "#F0E4C4", "Cor do texto das mensagens.");
			DefaultNameColor = c.Bind<string>("Estilo", "DefaultNameColor", "#E6C36A", "Cor do nome quando o usuário não definiu uma cor na Twitch.");
			AlertNameColor = c.Bind<string>("Estilo", "AlertNameColor", "#FF4A3D", "Cor do nome nos alertas.");
			ChatEnabled = c.Bind<bool>("Chat", "Enabled", true, "Ativa o chat.");
			ChatAnchor = c.Bind<string>("Chat", "AttachTo", "LeftWristHud", new ConfigDescription("Onde prender o chat em VR. LeftWristHud = junto da barra de vida do VHVR no pulso esquerdo.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[6] { "LeftWristHud", "RightWristHud", "LeftHand", "LeftHandBone", "RightHand", "Head" }), Array.Empty<object>()));
			ChatOffset = c.Bind<string>("Chat", "PalmOffset", "0.00, 0.085, -0.005", "Posição em metros, no plano do painel do pulso: x = lado, y = acima/abaixo da barra de vida, z = para perto (-) ou longe (+) do braço.");
			ChatRotation = c.Bind<string>("Chat", "PalmRotation", "0, 0, 0", "Rotação extra (graus) em relação ao painel do pulso.");
			ChatFaceHead = c.Bind<bool>("Chat", "AlwaysFaceHead", false, "Força o painel a virar de frente para os olhos (ignora a rotação do pulso).");
			ChatVisibility = c.Bind<string>("Chat", "ShowWhen", "Palm", new ConfigDescription("Palm: aparece quando você vira o pulso para os olhos, igual à barra de vida do VHVR. LookAt: quando olha para o braço. Always: sempre.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Palm", "LookAt", "Always" }), Array.Empty<object>()));
			PalmFullAngle = c.Bind<float>("Chat", "PalmFullAngle", 10f, "Até este ângulo (graus) entre o pulso e a visão, o chat fica totalmente visível.");
			PalmZeroAngle = c.Bind<float>("Chat", "PalmZeroAngle", 90f, "A partir deste ângulo o chat some.");
			ChatLookAngle = c.Bind<float>("Chat", "LookAngle", 28f, "Quão perto do centro da visão o braço precisa estar para mostrar o chat (graus).");
			ChatPlaceholder = c.Bind<bool>("Chat", "Placeholder", true, "Mostra 'aguardando mensagens' quando o chat está vazio.");
			ChatScale = c.Bind<float>("Chat", "PanelScale", 0.0003f, "Metros por pixel. 0.0003 com largura 460 = painel de ~14 cm.");
			ChatWidth = c.Bind<int>("Chat", "PanelWidth", 460, "Largura do painel em pixels.");
			ChatHeight = c.Bind<int>("Chat", "PanelHeight", 300, "Altura do painel em pixels.");
			ChatFontSize = c.Bind<float>("Chat", "PanelFontSize", 24f, "Tamanho da fonte.");
			ChatMaxMessages = c.Bind<int>("Chat", "MaxMessages", 8, "Quantas mensagens ficam visíveis.");
			ChatMessageLifetime = c.Bind<float>("Chat", "MessageLifetime", 45f, "Segundos até a mensagem sumir (0 = nunca).");
			ChatOpacity = c.Bind<float>("Chat", "Opacity", 1f, "Opacidade geral do chat (0 a 1).");
			AlertsEnabled = c.Bind<bool>("Alertas", "Enabled", true, "Ativa os alertas.");
			AlertOffset = c.Bind<string>("Alertas", "BoxOffset", "-0.09, 0.11, 0.65", "Posição em relação à cabeça, em metros: x (- esquerda / + direita), y (+ cima), z (distância).");
			AlertRotation = c.Bind<string>("Alertas", "BoxRotation", "-10, -8, 0", "Rotação em relação à cabeça (inclina a caixa para você).");
			AlertScale = c.Bind<float>("Alertas", "Scale", 0.0004f, "Metros por pixel.");
			AlertWidth = c.Bind<int>("Alertas", "BoxWidth", 620, "Largura da caixa de alerta em pixels.");
			AlertHeight = c.Bind<int>("Alertas", "BoxHeight", 175, "Altura da caixa de alerta em pixels.");
			AlertFontSize = c.Bind<float>("Alertas", "BoxFontSize", 32f, "Tamanho da fonte.");
			AlertDuration = c.Bind<float>("Alertas", "Duration", 6f, "Segundos na tela.");
			TextFollow = c.Bind<string>("Textos", "Follow", "{name} se juntou ao clã!", "Variáveis: {name}, {amount}, {count}.");
			TextSubscription = c.Bind<string>("Textos", "Subscription", "{name} jurou lealdade (sub)!", "Variáveis: {name}, {amount}, {count}.");
			TextResub = c.Bind<string>("Textos", "Resub", "{name} renovou o juramento por {count} meses!", "Variáveis: {name}, {amount}, {count}.");
			TextBits = c.Bind<string>("Textos", "Bits", "{name} ofertou {amount} bits!", "Variáveis: {name}, {amount}, {count}.");
			TextDonation = c.Bind<string>("Textos", "Donation", "{name} ofertou {amount} ao saque!", "Variáveis: {name}, {amount}, {count}.");
			TextRaid = c.Bind<string>("Textos", "Raid", "{name} invadiu com {count} vikings!", "Variáveis: {name}, {amount}, {count}.");
			TextHost = c.Bind<string>("Textos", "Host", "{name} hospedou a live com {count} vikings!", "Variáveis: {name}, {amount}, {count}.");
			TextGiftSub = c.Bind<string>("Textos", "GiftSub", "{gifter} presenteou {name} com um juramento!", "Variáveis: {name}, {amount}, {count}. {gifter} = quem deu o sub.");
			TextMysteryGift = c.Bind<string>("Textos", "MysteryGift", "{name} distribuiu {count} juramentos ao clã!", "Variáveis: {name}, {amount}, {count}.");
			AlertShowLabel = c.Bind<bool>("Alertas", "ShowLabel", true, "Mostra o título do tipo de alerta (NOVO MEMBRO, OFERENDA...).");
		}

		public string TemplateFor(string type)
		{
			return type switch
			{
				"follow" => TextFollow.Value, 
				"subscription" => TextSubscription.Value, 
				"resub" => TextResub.Value, 
				"bits" => TextBits.Value, 
				"donation" => TextDonation.Value, 
				"raid" => TextRaid.Value, 
				"host" => TextHost.Value, 
				"giftsub" => TextGiftSub.Value, 
				"subMysteryGift" => TextMysteryGift.Value, 
				_ => "{name}", 
			};
		}

		public static Vector3 ParseVector(string s, Vector3 fallback)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: 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_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string[] array = s.Split(',');
				if (array.Length != 3)
				{
					return fallback;
				}
				return new Vector3(float.Parse(array[0].Trim(), CultureInfo.InvariantCulture), float.Parse(array[1].Trim(), CultureInfo.InvariantCulture), float.Parse(array[2].Trim(), CultureInfo.InvariantCulture));
			}
			catch (Exception)
			{
				return fallback;
			}
		}

		public static Color ParseColor(string s, Color fallback)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			Color result = default(Color);
			if (!ColorUtility.TryParseHtmlString((s ?? "").Trim(), ref result))
			{
				return fallback;
			}
			return result;
		}
	}
	public class HudManager : MonoBehaviour
	{
		private HudConfig cfg;

		private ManualLogSource log;

		private HudPanel chatPanel;

		private HudPanel alertPanel;

		private HudPanel statusPanel;

		private readonly List<ChatMessage> lines = new List<ChatMessage>();

		private readonly Queue<StreamAlert> alertQueue = new Queue<StreamAlert>();

		private StreamAlert currentAlert;

		private float alertStart;

		private bool chatVisible = true;

		private bool chatDirty;

		private bool worldMode;

		private TMP_FontAsset font;

		private bool fontIsPreferred;

		private bool fontsLogged;

		private float nextCheck;

		private float chatViewAlpha = 1f;

		private bool wasInWorld;

		private float enteredAt;

		private bool welcomed;

		private float anchorMissingSince = -1f;

		private bool warnedAnchor;

		private string twitchState = "";

		private string slState = "";

		private bool twitchOk;

		private bool slOk;

		private int twitchCount;

		private int slCount;

		private float nextStatusRefresh;

		private int testIndex;

		private static readonly StreamAlert[] TestAlerts = new StreamAlert[8]
		{
			new StreamAlert
			{
				Type = "follow",
				Name = "Ragnar"
			},
			new StreamAlert
			{
				Type = "subscription",
				Name = "Lagertha"
			},
			new StreamAlert
			{
				Type = "resub",
				Name = "Bjorn",
				Count = "6",
				Message = "Pelo trono de Odin!"
			},
			new StreamAlert
			{
				Type = "giftsub",
				Name = "Ivar",
				Gifter = "Floki"
			},
			new StreamAlert
			{
				Type = "subMysteryGift",
				Name = "Rollo",
				Count = "5"
			},
			new StreamAlert
			{
				Type = "bits",
				Name = "Ubbe",
				Amount = "500"
			},
			new StreamAlert
			{
				Type = "donation",
				Name = "Torvi",
				Amount = "R$ 10,00",
				Message = "Hidromel pra todos!"
			},
			new StreamAlert
			{
				Type = "raid",
				Name = "Harald",
				Count = "42"
			}
		};

		public void Init(HudConfig config, ManualLogSource logger)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			cfg = config;
			log = logger;
			Application.onBeforeRender += new UnityAction(UpdatePoses);
			Rebuild();
		}

		private void OnDestroy()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			Application.onBeforeRender -= new UnityAction(UpdatePoses);
		}

		public void AddChat(ChatMessage m)
		{
			m.Time = Time.unscaledTime;
			lines.Add(m);
			while (lines.Count > Mathf.Max(1, cfg.ChatMaxMessages.Value))
			{
				lines.RemoveAt(0);
			}
			chatDirty = true;
		}

		public void AddAlert(StreamAlert a)
		{
			if (alertQueue.Count < 20)
			{
				alertQueue.Enqueue(a);
			}
		}

		public void RunTest()
		{
			StreamAlert streamAlert = TestAlerts[testIndex % TestAlerts.Length];
			testIndex++;
			AddChat(new ChatMessage("Odin", "#E6C36A", "Teste: alerta de " + streamAlert.Type));
			AddAlert(streamAlert);
			log.LogInfo((object)("Teste disparado: " + streamAlert.Type));
		}

		private static (string label, Color color) StyleFor(string type)
		{
			//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			switch (type)
			{
			case "follow":
				return (label: "NOVO MEMBRO DO CLÃ", color: new Color(0.9f, 0.76f, 0.42f));
			case "subscription":
			case "resub":
			case "giftsub":
			case "subMysteryGift":
				return (label: "JURAMENTO DE LEALDADE", color: new Color(0.62f, 0.42f, 0.95f));
			case "bits":
				return (label: "OFERENDA DE BITS", color: new Color(0.35f, 0.85f, 0.95f));
			case "donation":
				return (label: "OFERENDA AO SAQUE", color: new Color(1f, 0.84f, 0.25f));
			case "host":
			case "raid":
				return (label: "INVASÃO!", color: new Color(0.92f, 0.25f, 0.2f));
			default:
				return (label: "ALERTA", color: new Color(0.9f, 0.76f, 0.42f));
			}
		}

		public void ToggleChat()
		{
			chatVisible = !chatVisible;
		}

		public void SetStatus(string tState, bool tOk, int tCount, string sState, bool sOk, int sCount)
		{
			twitchState = tState;
			twitchOk = tOk;
			twitchCount = tCount;
			slState = sState;
			slOk = sOk;
			slCount = sCount;
		}

		public void Rebuild()
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: 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_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: 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_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_0294: Unknown result type (might be due to invalid IL or missing references)
			//IL_0299: Unknown result type (might be due to invalid IL or missing references)
			//IL_029a: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			worldMode = WantWorldMode();
			FindFont();
			if (chatPanel != null)
			{
				Object.Destroy((Object)(object)chatPanel.Root);
			}
			if (alertPanel != null)
			{
				Object.Destroy((Object)(object)alertPanel.Root);
			}
			if (statusPanel != null)
			{
				Object.Destroy((Object)(object)statusPanel.Root);
			}
			int num = ((cfg.Layer.Value >= 0) ? cfg.Layer.Value : (VRBridge.VRModInstalled ? 30 : 0));
			Color bg = HudConfig.ParseColor(cfg.PanelColor.Value, new Color(0.08f, 0.04f, 0.02f, 0.85f));
			Color accent = HudConfig.ParseColor(cfg.AccentColor.Value, new Color(0.9f, 0.76f, 0.42f));
			Color textColor = HudConfig.ParseColor(cfg.TextColor.Value, new Color(0.94f, 0.89f, 0.77f));
			chatPanel = HudPanel.Create("Chat", ((Component)this).transform, worldMode, num, cfg.ChatWidth.Value, cfg.ChatHeight.Value, font, cfg.ChatFontSize.Value, bg, accent, textColor, (TextAlignmentOptions)1025, withSlash: false, solid: true);
			chatPanel.SetScreenPlacement(new Vector2(0f, 0f), new Vector2(30f, 30f));
			alertPanel = HudPanel.Create("Alert", ((Component)this).transform, worldMode, num, cfg.AlertWidth.Value, cfg.AlertHeight.Value, font, cfg.AlertFontSize.Value, bg, accent, textColor, (TextAlignmentOptions)513, withSlash: true, solid: true);
			alertPanel.SetScreenPlacement(new Vector2(0f, 1f), new Vector2(40f, -40f));
			alertPanel.Group.alpha = 0f;
			if (currentAlert != null)
			{
				((TMP_Text)alertPanel.Text).text = BuildAlertText(currentAlert);
			}
			statusPanel = HudPanel.Create("Status", ((Component)this).transform, worldMode, num, 440f, 150f, font, 21f, new Color(0.05f, 0.03f, 0.02f, 0.92f), accent, textColor, (TextAlignmentOptions)257, withSlash: false, solid: true);
			statusPanel.SetScreenPlacement(new Vector2(1f, 0f), new Vector2(-30f, 30f));
			chatDirty = true;
			log.LogInfo((object)string.Format("HUD montado em modo {0}, layer {1}, fonte: {2}.", worldMode ? "VR (mundo)" : "tela", num, ((Object)(object)font != (Object)null) ? ((Object)font).name : "nenhuma ainda"));
		}

		private void Update()
		{
			if (Time.unscaledTime >= nextCheck)
			{
				nextCheck = Time.unscaledTime + 2f;
				if (WantWorldMode() != worldMode || (!fontIsPreferred && HasPreferredFont()))
				{
					Rebuild();
				}
			}
			bool flag = (Object)(object)Player.m_localPlayer != (Object)null;
			if (flag && !wasInWorld)
			{
				enteredAt = Time.unscaledTime;
				welcomed = false;
			}
			wasInWorld = flag;
			if (flag && !welcomed && cfg.WelcomeTest.Value && Time.unscaledTime - enteredAt > 4f)
			{
				welcomed = true;
				AddChat(new ChatMessage("StreamHUD", null, "Chat no pulso funcionando. Vire a palma para ver."));
				AddAlert(new StreamAlert
				{
					Type = "follow",
					Name = "Ragnar (teste)"
				});
			}
			bool inGame = cfg.ShowInMenus.Value || flag;
			UpdateChat(inGame);
			UpdateAlert(inGame);
			UpdateStatus();
		}

		private void LateUpdate()
		{
			UpdatePoses();
		}

		private void UpdateChat(bool inGame)
		{
			if (chatPanel != null)
			{
				float life = cfg.ChatMessageLifetime.Value;
				if (life > 0f && lines.RemoveAll((ChatMessage l) => Time.unscaledTime - l.Time > life) > 0)
				{
					chatDirty = true;
				}
				if (chatDirty)
				{
					chatDirty = false;
					((TMP_Text)chatPanel.Text).text = BuildChatText();
				}
				bool flag = lines.Count > 0 || cfg.ChatPlaceholder.Value;
				float num = ((!worldMode || cfg.ChatVisibility.Value == "Always") ? 1f : chatViewAlpha);
				float num2 = ((chatVisible && inGame && flag && cfg.ChatEnabled.Value) ? (Mathf.Clamp01(cfg.ChatOpacity.Value) * num) : 0f);
				chatPanel.Group.alpha = Mathf.MoveTowards(chatPanel.Group.alpha, num2, Time.unscaledDeltaTime * 5f);
			}
		}

		private void UpdateAlert(bool inGame)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			if (alertPanel == null)
			{
				return;
			}
			if (currentAlert == null && alertQueue.Count > 0 && inGame)
			{
				currentAlert = alertQueue.Dequeue();
				alertStart = Time.unscaledTime;
				((TMP_Text)alertPanel.Text).text = BuildAlertText(currentAlert);
				((Graphic)alertPanel.AccentBar).color = StyleFor(currentAlert.Type).color;
			}
			if (currentAlert == null)
			{
				alertPanel.Group.alpha = 0f;
				return;
			}
			float num = Time.unscaledTime - alertStart;
			float num2 = Mathf.Max(1f, cfg.AlertDuration.Value);
			float num3 = Mathf.Clamp01(num / 0.35f);
			float num4 = Mathf.Clamp01((num2 - num) / 0.6f);
			float num5 = 1f - Mathf.Pow(1f - num3, 3f);
			alertPanel.Group.alpha = Mathf.Min(num3, num4);
			alertPanel.Content.anchoredPosition = new Vector2(Mathf.Lerp(-60f, 0f, num5), (1f - num4) * 18f);
			float num6 = (num - 0.25f) / 0.35f;
			Color color = ((Graphic)alertPanel.Slash).color;
			if (num6 > 0f && num6 < 1.6f)
			{
				((Graphic)alertPanel.Slash).rectTransform.sizeDelta = new Vector2(alertPanel.Width * Mathf.Clamp01(num6), 4f);
				color.a = 1f - Mathf.Clamp01((num6 - 1f) / 0.6f);
			}
			else
			{
				color.a = 0f;
			}
			((Graphic)alertPanel.Slash).color = color;
			if (num >= num2)
			{
				currentAlert = null;
			}
		}

		private void UpdateStatus()
		{
			if (statusPanel == null)
			{
				return;
			}
			statusPanel.Group.alpha = (cfg.ShowStatusBox.Value ? 1f : 0f);
			if (cfg.ShowStatusBox.Value && !(Time.unscaledTime < nextStatusRefresh))
			{
				nextStatusRefresh = Time.unscaledTime + 0.5f;
				string text;
				string text2;
				if (!worldMode)
				{
					text = "modo tela (sem VR)";
					text2 = "#FFD25A";
				}
				else if (VRBridge.IsFound(cfg.ChatAnchor.Value))
				{
					text = "preso no pulso";
					text2 = "#7CFC7C";
				}
				else
				{
					text = "procurando o pulso...";
					text2 = "#FF6A5A";
				}
				((TMP_Text)statusPanel.Text).text = "<b><color=#E6C36A>STREAMHUD VR</color></b>\n" + string.Format("Twitch: <color={0}>{1}</color>  <alpha=#99>({2} msgs)<alpha=#FF>\n", twitchOk ? "#7CFC7C" : "#FF6A5A", Esc(twitchState), twitchCount) + string.Format("Streamlabs: <color={0}>{1}</color>  <alpha=#99>({2} alertas)<alpha=#FF>\n", slOk ? "#7CFC7C" : "#FF6A5A", Esc(slState), slCount) + "Chat: <color=" + text2 + ">" + text + "</color>";
			}
		}

		private void UpdatePoses()
		{
			if (!worldMode)
			{
				return;
			}
			Transform head = VRBridge.GetHead();
			if (chatPanel != null)
			{
				Transform anchor = VRBridge.GetAnchor(cfg.ChatAnchor.Value);
				PlaceChat(anchor, head);
				if ((Object)(object)anchor != (Object)null)
				{
					anchorMissingSince = -1f;
				}
				else if (anchorMissingSince < 0f)
				{
					anchorMissingSince = Time.unscaledTime;
				}
				else if (!warnedAnchor && (Object)(object)Player.m_localPlayer != (Object)null && Time.unscaledTime - anchorMissingSince > 10f)
				{
					warnedAnchor = true;
					log.LogWarning((object)("VR: não encontrei a âncora '" + cfg.ChatAnchor.Value + "' para o chat. Teste [Chat] AttachTo = LeftHand."));
				}
			}
			if (alertPanel != null)
			{
				PlaceOnHead(alertPanel, head, cfg.AlertOffset.Value, cfg.AlertRotation.Value, cfg.AlertScale.Value);
			}
			if (statusPanel != null)
			{
				PlaceOnHead(statusPanel, head, cfg.StatusOffset.Value, cfg.StatusRotation.Value, 0.00032f);
			}
		}

		private void PlaceChat(Transform anchor, Transform head)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: 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)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//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)
			GameObject root = chatPanel.Root;
			if ((Object)(object)anchor == (Object)null)
			{
				root.SetActive(false);
				chatViewAlpha = 0f;
				return;
			}
			if (!root.activeSelf)
			{
				root.SetActive(true);
			}
			Vector3 val = HudConfig.ParseVector(cfg.ChatOffset.Value, new Vector3(0f, 0.085f, -0.005f));
			Vector3 val2 = HudConfig.ParseVector(cfg.ChatRotation.Value, Vector3.zero);
			Quaternion val3 = anchor.rotation * Quaternion.Euler(val2);
			Transform transform = root.transform;
			transform.position = anchor.position + anchor.rotation * val;
			transform.rotation = ((cfg.ChatFaceHead.Value && (Object)(object)head != (Object)null) ? Quaternion.LookRotation(transform.position - head.position, head.up) : val3);
			transform.localScale = Vector3.one * cfg.ChatScale.Value;
			if ((Object)(object)head == (Object)null)
			{
				chatViewAlpha = 1f;
				return;
			}
			if (cfg.ChatVisibility.Value == "LookAt")
			{
				float num = Vector3.Angle(head.forward, transform.position - head.position);
				chatViewAlpha = ((num < cfg.ChatLookAngle.Value) ? 1f : 0f);
				return;
			}
			float num2 = Quaternion.Angle(head.rotation, val3);
			float value = cfg.PalmFullAngle.Value;
			float num3 = Mathf.Max(value + 1f, cfg.PalmZeroAngle.Value);
			chatViewAlpha = 1f - Mathf.Clamp01((num2 - value) / (num3 - value));
		}

		private static void PlaceOnHead(HudPanel p, Transform head, string offsetText, string rotText, float scale)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)head == (Object)null)
			{
				p.Root.SetActive(false);
				return;
			}
			if (!p.Root.activeSelf)
			{
				p.Root.SetActive(true);
			}
			Transform transform = p.Root.transform;
			transform.position = head.position + head.rotation * HudConfig.ParseVector(offsetText, new Vector3(0f, 0f, 0.6f));
			transform.rotation = head.rotation * Quaternion.Euler(HudConfig.ParseVector(rotText, Vector3.zero));
			transform.localScale = Vector3.one * scale;
		}

		private string BuildChatText()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (lines.Count == 0 && cfg.ChatPlaceholder.Value)
			{
				return "<alpha=#99><i>Aguardando mensagens do chat...</i>";
			}
			string value = "#" + ColorUtility.ToHtmlStringRGB(HudConfig.ParseColor(cfg.AccentColor.Value, Color.yellow));
			string value2 = cfg.DefaultNameColor.Value;
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < lines.Count; i++)
			{
				ChatMessage chatMessage = lines[i];
				if (i > 0)
				{
					stringBuilder.Append('\n');
				}
				string value3 = (string.IsNullOrEmpty(chatMessage.Color) ? value2 : chatMessage.Color);
				stringBuilder.Append("<color=").Append(value3).Append("><b>")
					.Append(NoParse(chatMessage.User))
					.Append("</b></color>");
				stringBuilder.Append("<color=").Append(value).Append("> » </color>");
				stringBuilder.Append(NoParse(chatMessage.Text));
			}
			return stringBuilder.ToString();
		}

		private string BuildAlertText(StreamAlert a)
		{
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			string newValue = "<color=" + cfg.AlertNameColor.Value + "><b>" + NoParse(a.Name) + "</b></color>";
			string newValue2 = "<color=" + cfg.AlertNameColor.Value + "><b>" + NoParse(a.Gifter) + "</b></color>";
			string text = cfg.TemplateFor(a.Type).Replace("{name}", newValue).Replace("{gifter}", newValue2)
				.Replace("{amount}", NoParse(a.Amount))
				.Replace("{count}", NoParse(a.Count));
			if (cfg.AlertShowLabel.Value)
			{
				(string, Color) tuple = StyleFor(a.Type);
				text = "<size=58%><color=#" + ColorUtility.ToHtmlStringRGB(tuple.Item2) + "><b>" + tuple.Item1 + "</b></color></size>\n" + text;
			}
			if (!string.IsNullOrWhiteSpace(a.Message))
			{
				text = text + "\n<size=65%><i>" + NoParse(Trim(a.Message, 120)) + "</i></size>";
			}
			return text;
		}

		private static string NoParse(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			return "<noparse>" + s.Replace("</noparse>", "") + "</noparse>";
		}

		private static string Esc(string s)
		{
			return NoParse(s ?? "");
		}

		private static string Trim(string s, int max)
		{
			if (s.Length > max)
			{
				return s.Substring(0, max) + "...";
			}
			return s;
		}

		private bool WantWorldMode()
		{
			string value = cfg.Mode.Value;
			if (!(value == "VR"))
			{
				if (value == "Flat")
				{
					return false;
				}
				return VRBridge.IsVRActive();
			}
			return true;
		}

		private bool HasPreferredFont()
		{
			string hint = (cfg.FontHint.Value ?? "").ToLowerInvariant();
			return Resources.FindObjectsOfTypeAll<TMP_FontAsset>().Any((TMP_FontAsset f) => (Object)(object)f != (Object)null && ((Object)f).name.ToLowerInvariant().Contains(hint));
		}

		private void FindFont()
		{
			TMP_FontAsset[] array = (from f in Resources.FindObjectsOfTypeAll<TMP_FontAsset>()
				where (Object)(object)f != (Object)null
				select f).ToArray();
			if (!fontsLogged && array.Length != 0)
			{
				fontsLogged = true;
				log.LogInfo((object)("Fontes do jogo disponíveis: " + string.Join(", ", array.Select((TMP_FontAsset f) => ((Object)f).name).Distinct())));
			}
			string hint = (cfg.FontHint.Value ?? "").ToLowerInvariant();
			TMP_FontAsset val = ((IEnumerable<TMP_FontAsset>)array).FirstOrDefault((Func<TMP_FontAsset, bool>)((TMP_FontAsset f) => hint.Length > 0 && ((Object)f).name.ToLowerInvariant().Contains(hint)));
			fontIsPreferred = (Object)(object)val != (Object)null;
			TMP_FontAsset val2 = null;
			try
			{
				val2 = TMP_Settings.defaultFontAsset;
			}
			catch (Exception)
			{
			}
			font = val ?? val2 ?? array.FirstOrDefault();
		}
	}
	public class HudPanel
	{
		public GameObject Root;

		public CanvasGroup Group;

		public RectTransform Content;

		public TextMeshProUGUI Text;

		public Image Slash;

		public Image AccentBar;

		public float Width;

		public static HudPanel Create(string name, Transform parent, bool world, int layer, float w, float h, TMP_FontAsset font, float fontSize, Color bg, Color accent, Color textColor, TextAlignmentOptions align, bool withSlash, bool solid)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: 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_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: 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_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0313: Unknown result type (might be due to invalid IL or missing references)
			//IL_0329: Unknown result type (might be due to invalid IL or missing references)
			//IL_033f: Unknown result type (might be due to invalid IL or missing references)
			//IL_035a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0370: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Unknown result type (might be due to invalid IL or missing references)
			HudPanel hudPanel = new HudPanel
			{
				Width = w
			};
			hudPanel.Root = new GameObject("StreamHUD_" + name, new Type[1] { typeof(RectTransform) });
			hudPanel.Root.transform.SetParent(parent, false);
			Canvas val = hudPanel.Root.AddComponent<Canvas>();
			if (world)
			{
				val.renderMode = (RenderMode)2;
				val.sortingOrder = 50;
				hudPanel.Root.GetComponent<RectTransform>().sizeDelta = new Vector2(w, h);
			}
			else
			{
				val.renderMode = (RenderMode)0;
				val.sortingOrder = 500;
				CanvasScaler obj = hudPanel.Root.AddComponent<CanvasScaler>();
				obj.uiScaleMode = (ScaleMode)1;
				obj.referenceResolution = new Vector2(1920f, 1080f);
				obj.matchWidthOrHeight = 1f;
			}
			hudPanel.Group = hudPanel.Root.AddComponent<CanvasGroup>();
			hudPanel.Group.interactable = false;
			hudPanel.Group.blocksRaycasts = false;
			hudPanel.Group.alpha = 0f;
			RectTransform val2 = (hudPanel.Content = NewChild("Content", hudPanel.Root.transform));
			val2.sizeDelta = new Vector2(w, h);
			RawImage obj2 = ((Component)val2).gameObject.AddComponent<RawImage>();
			obj2.texture = (Texture)(object)MakeGradient(bg, solid);
			((Graphic)obj2).raycastTarget = false;
			((Component)val2).gameObject.AddComponent<RectMask2D>();
			RectTransform obj3 = NewChild("Accent", (Transform)(object)val2);
			obj3.anchorMin = new Vector2(0f, 0f);
			obj3.anchorMax = new Vector2(0f, 1f);
			obj3.pivot = new Vector2(0f, 0.5f);
			obj3.sizeDelta = new Vector2(5f, 0f);
			Image val3 = ((Component)obj3).gameObject.AddComponent<Image>();
			((Graphic)val3).color = accent;
			((Graphic)val3).raycastTarget = false;
			hudPanel.AccentBar = val3;
			AddLine(val2, top: true, accent, solid ? 1f : 0.8f);
			if (solid)
			{
				AddLine(val2, top: false, accent, 1f);
			}
			RectTransform val4 = NewChild("Text", (Transform)(object)val2);
			val4.anchorMin = Vector2.zero;
			val4.anchorMax = Vector2.one;
			val4.offsetMin = new Vector2(18f, 10f);
			val4.offsetMax = new Vector2(-14f, -10f);
			hudPanel.Text = ((Component)val4).gameObject.AddComponent<TextMeshProUGUI>();
			if ((Object)(object)font != (Object)null)
			{
				((TMP_Text)hudPanel.Text).font = font;
			}
			((TMP_Text)hudPanel.Text).fontSize = fontSize;
			((Graphic)hudPanel.Text).color = textColor;
			((TMP_Text)hudPanel.Text).alignment = align;
			((TMP_Text)hudPanel.Text).richText = true;
			((Graphic)hudPanel.Text).raycastTarget = false;
			((TMP_Text)hudPanel.Text).overflowMode = (TextOverflowModes)0;
			if ((Object)(object)font != (Object)null)
			{
				((TMP_Text)hudPanel.Text).outlineWidth = 0.18f;
				((TMP_Text)hudPanel.Text).outlineColor = new Color32((byte)18, (byte)10, (byte)4, byte.MaxValue);
			}
			RectTransform val5 = NewChild("Slash", (Transform)(object)val2);
			val5.anchorMin = new Vector2(0f, 0.5f);
			val5.anchorMax = new Vector2(0f, 0.5f);
			val5.pivot = new Vector2(0f, 0.5f);
			((Transform)val5).localRotation = Quaternion.Euler(0f, 0f, -6f);
			val5.sizeDelta = new Vector2(0f, 4f);
			hudPanel.Slash = ((Component)val5).gameObject.AddComponent<Image>();
			((Graphic)hudPanel.Slash).color = new Color(1f, 0.95f, 0.75f, 0f);
			((Graphic)hudPanel.Slash).raycastTarget = false;
			((Component)val5).gameObject.SetActive(withSlash);
			SetLayerRecursive(hudPanel.Root, world ? layer : 5);
			return hudPanel;
		}

		public void SetScreenPlacement(Vector2 corner, Vector2 margin)
		{
			//IL_000b: 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_004b: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			if ((int)Root.GetComponent<Canvas>().renderMode == 0)
			{
				RectTransform component = new GameObject("Holder", new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
				((Transform)component).SetParent(((Transform)Content).parent, false);
				Vector2 val = (component.pivot = corner);
				Vector2 anchorMin = (component.anchorMax = val);
				component.anchorMin = anchorMin;
				component.anchoredPosition = margin;
				component.sizeDelta = Content.sizeDelta;
				((Component)component).gameObject.layer = Root.layer;
				((Transform)Content).SetParent((Transform)(object)component, false);
				RectTransform content = Content;
				RectTransform content2 = Content;
				RectTransform content3 = Content;
				((Vector2)(ref val))..ctor(0.5f, 0.5f);
				content3.pivot = val;
				anchorMin = (content2.anchorMax = val);
				content.anchorMin = anchorMin;
				Content.anchoredPosition = Vector2.zero;
			}
		}

		private static void AddLine(RectTransform parent, bool top, Color accent, float widthFrac)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj = NewChild(top ? "TopLine" : "BottomLine", (Transform)(object)parent);
			float num = (top ? 1f : 0f);
			obj.anchorMin = new Vector2(0f, num);
			obj.anchorMax = new Vector2(widthFrac, num);
			obj.pivot = new Vector2(0f, num);
			obj.sizeDelta = new Vector2(0f, 2f);
			Image obj2 = ((Component)obj).gameObject.AddComponent<Image>();
			((Graphic)obj2).color = new Color(accent.r, accent.g, accent.b, 0.45f);
			((Graphic)obj2).raycastTarget = false;
		}

		private static RectTransform NewChild(string name, Transform parent)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(parent, false);
			return val.GetComponent<RectTransform>();
		}

		private static Texture2D MakeGradient(Color c, bool solid)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = new Texture2D(64, 1, (TextureFormat)4, false)
			{
				wrapMode = (TextureWrapMode)1
			};
			for (int i = 0; i < 64; i++)
			{
				float num = (float)i / 63f;
				float num2 = (solid ? 1f : ((num < 0.6f) ? 1f : Mathf.Lerp(1f, 0f, (num - 0.6f) / 0.4f)));
				val.SetPixel(i, 0, new Color(c.r, c.g, c.b, c.a * num2));
			}
			val.Apply();
			return val;
		}

		private static void SetLayerRecursive(GameObject go, int layer)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			go.layer = layer;
			foreach (Transform item in go.transform)
			{
				SetLayerRecursive(((Component)item).gameObject, layer);
			}
		}
	}
	public class ChatMessage
	{
		public string User;

		public string Color;

		public string Text;

		public float Time;

		public ChatMessage(string user, string color, string text)
		{
			User = user;
			Color = color;
			Text = text;
		}
	}
	public class StreamAlert
	{
		public string Type;

		public string Name = "";

		public string Amount = "";

		public string Count = "";

		public string Message = "";

		public string Gifter = "";
	}
	[BepInPlugin("StreamHud_VR", "StreamHud_VR", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "StreamHud_VR";

		public const string ModName = "StreamHud_VR";

		public const string Version = "0.1.0";

		private HudConfig cfg;

		private HudManager hud;

		private TwitchChatClient chat;

		private StreamlabsClient alerts;

		private float vrHold;

		private bool vrFired;

		private bool comboHeld;

		private void Awake()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			cfg = new HudConfig(((BaseUnityPlugin)this).Config);
			VRBridge.Log = ((BaseUnityPlugin)this).Logger;
			ApplyInstallerSettings();
			GameObject val = new GameObject("StreamHud_VR");
			Object.DontDestroyOnLoad((Object)(object)val);
			hud = val.AddComponent<HudManager>();
			hud.Init(cfg, ((BaseUnityPlugin)this).Logger);
			StartClients();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"StreamHud_VR 0.1.0 carregado.");
		}

		private void StartClients()
		{
			StopClients();
			string text = TwitchChatClient.CleanChannel(cfg.TwitchChannel.Value);
			if (cfg.ChatEnabled.Value && text.Length > 0)
			{
				chat = new TwitchChatClient(text, ((BaseUnityPlugin)this).Logger);
				chat.Start();
			}
			else if (cfg.ChatEnabled.Value)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Chat: preencha [Twitch] Channel no arquivo de config.");
			}
			string text2 = (cfg.StreamlabsSocketToken.Value ?? "").Trim();
			if (cfg.AlertsEnabled.Value && text2.Length > 0)
			{
				alerts = new StreamlabsClient(text2, ((BaseUnityPlugin)this).Logger);
				alerts.Start();
			}
			else if (cfg.AlertsEnabled.Value)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Alertas: preencha [Streamlabs] SocketToken no arquivo de config.");
			}
		}

		private void StopClients()
		{
			chat?.Stop();
			chat = null;
			alerts?.Stop();
			alerts = null;
		}

		private void Update()
		{
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			if (chat != null)
			{
				ChatMessage result;
				while (chat.Messages.TryDequeue(out result))
				{
					hud.AddChat(result);
				}
			}
			if (alerts != null)
			{
				StreamAlert result2;
				while (alerts.Events.TryDequeue(out result2))
				{
					hud.AddAlert(result2);
				}
			}
			hud.SetStatus((chat == null) ? "não configurado" : chat.State, chat != null && chat.Ok, chat?.Received ?? 0, (alerts == null) ? "não configurado" : alerts.State, alerts != null && alerts.Ok, alerts?.Received ?? 0);
			KeyboardShortcut value = cfg.KeyToggleChat.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				hud.ToggleChat();
			}
			value = cfg.KeyTest.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				hud.RunTest();
			}
			value = cfg.KeyToggleStatus.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				ToggleStatus();
			}
			bool flag = VRBridge.ReadButton("LeftStickClick");
			bool flag2 = VRBridge.ReadButton("RightStickClick");
			bool flag3 = cfg.VRStatusCombo.Value && flag && flag2;
			if (flag3 && !comboHeld)
			{
				ToggleStatus();
			}
			comboHeld = (flag || flag2) && (comboHeld || flag3);
			if (!comboHeld && VRBridge.ReadButton(cfg.VRTestButton.Value))
			{
				vrHold += Time.unscaledDeltaTime;
				if (!vrFired && vrHold >= cfg.VRTestHold.Value)
				{
					vrFired = true;
					hud.RunTest();
				}
			}
			else
			{
				vrHold = 0f;
				vrFired = false;
			}
			value = cfg.KeyReload.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				((BaseUnityPlugin)this).Config.Reload();
				hud.Rebuild();
				StartClients();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Config recarregada.");
			}
		}

		private void ApplyInstallerSettings()
		{
			string path = Path.Combine(Paths.ConfigPath, "StreamHud_VR.install.txt");
			if (!File.Exists(path))
			{
				return;
			}
			try
			{
				string[] array = File.ReadAllLines(path);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (text.StartsWith("#"))
					{
						continue;
					}
					int num = text.IndexOf('=');
					if (num <= 0)
					{
						continue;
					}
					string text2 = text.Substring(0, num).Trim();
					string text3 = text.Substring(num + 1).Trim();
					if (text3.Length != 0)
					{
						if (text2 == "Channel")
						{
							cfg.TwitchChannel.Value = text3;
						}
						else if (text2 == "SocketToken")
						{
							cfg.StreamlabsSocketToken.Value = text3;
						}
					}
				}
				((BaseUnityPlugin)this).Config.Save();
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Configuração do instalador aplicada (canal/token).");
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Não consegui aplicar a configuração do instalador: " + ex.Message));
			}
			finally
			{
				try
				{
					File.Delete(path);
				}
				catch (Exception)
				{
				}
			}
		}

		private void ToggleStatus()
		{
			cfg.ShowStatusBox.Value = !cfg.ShowStatusBox.Value;
			vrHold = 0f;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Caixa de status " + (cfg.ShowStatusBox.Value ? "visível." : "oculta.")));
		}

		private void OnDestroy()
		{
			StopClients();
		}
	}
	public class StreamlabsClient
	{
		public readonly ConcurrentQueue<StreamAlert> Events = new ConcurrentQueue<StreamAlert>();

		public volatile string State = "conectando...";

		public volatile bool Ok;

		public int Received;

		private static readonly HashSet<string> Supported = new HashSet<string> { "follow", "subscription", "resub", "bits", "donation", "raid", "host", "subMysteryGift" };

		private readonly string token;

		private readonly ManualLogSource log;

		private readonly HashSet<string> seen = new HashSet<string>();

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

		private CancellationTokenSource cts;

		public StreamlabsClient(string token, ManualLogSource log)
		{
			this.token = token;
			this.log = log;
		}

		public void Start()
		{
			try
			{
				ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
			}
			catch (Exception)
			{
			}
			cts = new CancellationTokenSource();
			CancellationToken ct = cts.Token;
			Task.Run(() => Loop(ct));
		}

		public void Stop()
		{
			try
			{
				cts?.Cancel();
			}
			catch (Exception)
			{
			}
		}

		private async Task Loop(CancellationToken ct)
		{
			int delay = 2000;
			while (!ct.IsCancellationRequested)
			{
				try
				{
					await RunOnce(ct);
					delay = 2000;
				}
				catch (OperationCanceledException)
				{
					break;
				}
				catch (Exception ex2)
				{
					log.LogWarning((object)("Streamlabs: " + ex2.Message));
					State = "erro: " + ex2.Message;
				}
				if (Ok)
				{
					State = "reconectando...";
				}
				Ok = false;
				try
				{
					await Task.Delay(delay, ct);
				}
				catch (OperationCanceledException)
				{
					break;
				}
				delay = Math.Min(delay * 2, 60000);
			}
		}

		private async Task RunOnce(CancellationToken ct)
		{
			using ClientWebSocket ws = new ClientWebSocket();
			using CancellationTokenSource pingCts = CancellationTokenSource.CreateLinkedTokenSource(new CancellationToken[1] { ct });
			Uri uri = new Uri("wss://sockets.streamlabs.com/socket.io/?token=" + Uri.EscapeDataString(token) + "&EIO=3&transport=websocket");
			await ws.ConnectAsync(uri, ct);
			byte[] buffer = new byte[8192];
			MemoryStream ms = new MemoryStream();
			try
			{
				while (ws.State == WebSocketState.Open)
				{
					ms.SetLength(0L);
					WebSocketReceiveResult webSocketReceiveResult;
					do
					{
						webSocketReceiveResult = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
						if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
						{
							log.LogWarning((object)"Streamlabs: conexão fechada pelo servidor (token inválido?).");
							return;
						}
						ms.Write(buffer, 0, webSocketReceiveResult.Count);
					}
					while (!webSocketReceiveResult.EndOfMessage);
					string text = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
					if (text.Length == 0)
					{
						continue;
					}
					if (text[0] == '0')
					{
						int interval = 25000;
						try
						{
							interval = ((JToken)JObject.Parse(text.Substring(1))).Value<int?>((object)"pingInterval") ?? 25000;
						}
						catch (Exception)
						{
						}
						PingLoop(ws, interval, pingCts.Token);
					}
					else if (text.StartsWith("40"))
					{
						log.LogInfo((object)"Streamlabs: conectado, aguardando alertas.");
						Ok = true;
						State = "conectado";
					}
					else if (text.StartsWith("44"))
					{
						log.LogWarning((object)("Streamlabs recusou a conexão: " + text));
						State = "token recusado";
					}
					else if (text.StartsWith("42"))
					{
						try
						{
							HandleEvent(text.Substring(2));
						}
						catch (Exception ex2)
						{
							log.LogWarning((object)("Streamlabs: evento ignorado (" + ex2.Message + ")"));
						}
					}
				}
			}
			finally
			{
				pingCts.Cancel();
			}
		}

		private static async Task PingLoop(ClientWebSocket ws, int interval, CancellationToken ct)
		{
			ArraySegment<byte> ping = new ArraySegment<byte>(Encoding.ASCII.GetBytes("2"));
			try
			{
				while (!ct.IsCancellationRequested && ws.State == WebSocketState.Open)
				{
					await Task.Delay(interval, ct);
					await ws.SendAsync(ping, WebSocketMessageType.Text, endOfMessage: true, ct);
				}
			}
			catch (Exception)
			{
			}
		}

		private void HandleEvent(string json)
		{
			JArray val = JArray.Parse(json);
			if (((JContainer)val).Count < 2 || (string)val[0] != "event")
			{
				return;
			}
			JToken obj = val[1];
			JObject val2 = (JObject)(object)((obj is JObject) ? obj : null);
			if (val2 == null)
			{
				return;
			}
			string text = (string)val2["type"];
			if (text == null || !Supported.Contains(text))
			{
				return;
			}
			JToken val3 = val2["message"];
			JArray val4 = (JArray)(object)((val3 is JArray) ? val3 : null);
			IEnumerable<JToken> enumerable;
			if (val4 != null)
			{
				enumerable = (IEnumerable<JToken>)val4;
			}
			else
			{
				if (!(val3 is JObject))
				{
					return;
				}
				enumerable = (IEnumerable<JToken>)(object)new JToken[1] { val3 };
			}
			foreach (JToken item in enumerable)
			{
				string text2 = Str(item[(object)"_id"]) ?? Str(item[(object)"event_id"]) ?? Str(item[(object)"id"]);
				if (text2 == null || Remember(text2))
				{
					StreamAlert streamAlert = new StreamAlert
					{
						Type = text,
						Name = (Str(item[(object)"display_name"]) ?? Str(item[(object)"name"]) ?? "Alguém"),
						Amount = (Str(item[(object)"formatted_amount"]) ?? Str(item[(object)"amount"]) ?? ""),
						Count = (Str(item[(object)"months"]) ?? Str(item[(object)"raiders"]) ?? Str(item[(object)"viewers"]) ?? ""),
						Message = (Str(item[(object)"message"]) ?? ""),
						Gifter = (Str(item[(object)"gifter_display_name"]) ?? Str(item[(object)"gifter"]) ?? "")
					};
					if (text == "subscription" && streamAlert.Gifter.Length > 0)
					{
						streamAlert.Type = "giftsub";
					}
					if (text == "subMysteryGift")
					{
						streamAlert.Count = Str(item[(object)"amount"]) ?? Str(item[(object)"sub_plan_count"]) ?? "";
					}
					Received++;
					log.LogInfo((object)("Streamlabs: alerta '" + streamAlert.Type + "' de " + streamAlert.Name + ((Str(item[(object)"isTest"]) == "True") ? " (teste do painel)" : "")));
					Events.Enqueue(streamAlert);
				}
			}
		}

		private static string Str(JToken t)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Invalid comparison between Unknown and I4
			if (t == null || (int)t.Type == 10)
			{
				return null;
			}
			JValue val = (JValue)(object)((t is JValue) ? t : null);
			if (val != null)
			{
				return Convert.ToString(val.Value, CultureInfo.InvariantCulture);
			}
			return null;
		}

		private bool Remember(string id)
		{
			if (!seen.Add(id))
			{
				return false;
			}
			seenOrder.Enqueue(id);
			while (seenOrder.Count > 200)
			{
				seen.Remove(seenOrder.Dequeue());
			}
			return true;
		}
	}
	public class TwitchChatClient
	{
		public readonly ConcurrentQueue<ChatMessage> Messages = new ConcurrentQueue<ChatMessage>();

		public volatile string State = "conectando...";

		public volatile bool Ok;

		public int Received;

		private readonly string channel;

		private readonly ManualLogSource log;

		private volatile bool running;

		private TcpClient client;

		private Thread thread;

		public TwitchChatClient(string channel, ManualLogSource log)
		{
			this.channel = channel;
			this.log = log;
		}

		public static string CleanChannel(string raw)
		{
			string text = (raw ?? "").Trim().TrimEnd('/');
			int num = text.LastIndexOf('/');
			if (num >= 0)
			{
				text = text.Substring(num + 1);
			}
			return text.TrimStart('#').ToLowerInvariant();
		}

		public void Start()
		{
			running = true;
			thread = new Thread(Run)
			{
				IsBackground = true,
				Name = "StreamHUD-Twitch"
			};
			thread.Start();
		}

		public void Stop()
		{
			running = false;
			try
			{
				client?.Close();
			}
			catch (Exception)
			{
			}
		}

		private void Run()
		{
			int num = 2000;
			Random random = new Random();
			while (running)
			{
				try
				{
					using (client = new TcpClient())
					{
						client.Connect("irc.chat.twitch.tv", 6667);
						using NetworkStream stream = client.GetStream();
						UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
						StreamReader streamReader = new StreamReader(stream, encoding);
						StreamWriter streamWriter = new StreamWriter(stream, encoding)
						{
							NewLine = "\r\n",
							AutoFlush = true
						};
						streamWriter.WriteLine("CAP REQ :twitch.tv/tags twitch.tv/commands");
						streamWriter.WriteLine("PASS SCHMOOPIIE");
						streamWriter.WriteLine("NICK justinfan" + random.Next(10000, 99999));
						streamWriter.WriteLine("JOIN #" + channel);
						log.LogInfo((object)("Twitch: conectado ao chat de #" + channel));
						State = "entrando em #" + channel + "...";
						num = 2000;
						string text;
						while (running && (text = streamReader.ReadLine()) != null)
						{
							if (text.StartsWith("PING"))
							{
								streamWriter.WriteLine("PONG" + text.Substring(4));
								continue;
							}
							if (!text.Contains(" RECONNECT"))
							{
								if (!Ok && (text.Contains(" 366 ") || text.Contains("ROOMSTATE")))
								{
									Ok = true;
									State = "conectado em #" + channel;
								}
								ChatMessage chatMessage = Parse(text);
								if (chatMessage != null)
								{
									Messages.Enqueue(chatMessage);
									Received++;
								}
								continue;
							}
							break;
						}
					}
				}
				catch (Exception ex)
				{
					if (running)
					{
						log.LogWarning((object)("Twitch: " + ex.Message));
					}
				}
				Ok = false;
				State = "reconectando...";
				if (running)
				{
					Thread.Sleep(num);
					num = Math.Min(num * 2, 60000);
					continue;
				}
				break;
			}
		}

		private static ChatMessage Parse(string line)
		{
			string text = null;
			string text2 = line;
			if (text2.StartsWith("@"))
			{
				int num = text2.IndexOf(' ');
				if (num < 0)
				{
					return null;
				}
				text = text2.Substring(1, num - 1);
				text2 = text2.Substring(num + 1);
			}
			if (!text2.StartsWith(":"))
			{
				return null;
			}
			int num2 = text2.IndexOf(' ');
			if (num2 < 0)
			{
				return null;
			}
			string text3 = text2.Substring(1, num2 - 1);
			string text4 = text2.Substring(num2 + 1);
			if (!text4.StartsWith("PRIVMSG "))
			{
				return null;
			}
			int num3 = text4.IndexOf(" :", StringComparison.Ordinal);
			if (num3 < 0)
			{
				return null;
			}
			string text5 = text4.Substring(num3 + 2);
			string user = text3.Split('!')[0];
			string color = null;
			if (text != null)
			{
				string[] array = text.Split(';');
				foreach (string text6 in array)
				{
					int num4 = text6.IndexOf('=');
					if (num4 >= 0)
					{
						string text7 = text6.Substring(0, num4);
						string text8 = text6.Substring(num4 + 1);
						if (text7 == "display-name" && text8.Length > 0)
						{
							user = text8.Replace("\\s", " ");
						}
						else if (text7 == "color" && text8.Length > 0)
						{
							color = text8;
						}
					}
				}
			}
			if (text5.StartsWith("\u0001ACTION "))
			{
				text5 = text5.Substring(8).TrimEnd('\u0001');
			}
			return new ChatMessage(user, color, text5);
		}
	}
	public static class VRBridge
	{
		public const int VhvrUiLayer = 30;

		private const BindingFlags Static = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private const BindingFlags Inst = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		public static ManualLogSource Log;

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

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

		private static readonly Dictionary<string, Transform> cache = new Dictionary<string, Transform>();

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

		public static bool VRModInstalled => FindType("VRPlayer") != null;

		public static bool IsVRActive()
		{
			try
			{
				return XRSettings.enabled && XRSettings.isDeviceActive;
			}
			catch (Exception)
			{
				return false;
			}
		}

		public static bool IsFound(string anchor)
		{
			if (cache.TryGetValue(anchor, out var value))
			{
				return (Object)(object)value != (Object)null;
			}
			return false;
		}

		public static Transform GetHead()
		{
			Transform val = Get("Head", () => ReadStatic("VRPlayer", "vrCam"));
			if ((Object)(object)val != (Object)null)
			{
				return val;
			}
			if (!((Object)(object)Camera.main != (Object)null))
			{
				return null;
			}
			return ((Component)Camera.main).transform;
		}

		public static Transform GetAnchor(string anchor)
		{
			return (Transform)(anchor switch
			{
				"LeftWristHud" => Get(anchor, () => ReadWristHud(left: true)), 
				"RightWristHud" => Get(anchor, () => ReadWristHud(left: false)), 
				"LeftHandBone" => Get(anchor, () => ReadStatic("VRPlayer", "leftHandBone")), 
				"RightHand" => Get(anchor, () => ReadStatic("VRPlayer", "rightHand") ?? WristParent(left: false)), 
				"Head" => GetHead(), 
				_ => Get("LeftHand", () => ReadStatic("VRPlayer", "leftHand") ?? WristParent(left: true)), 
			});
		}

		private static object ReadWristHud(bool left)
		{
			string text = (left ? "LeftHudCanvasParent" : "RightHudCanvasParent");
			try
			{
				Type type = FindType("VRHud");
				object obj = type?.GetField("_instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null);
				if (obj != null)
				{
					object? obj2 = type.GetField(left ? "leftHudCanvasParent" : "rightHudCanvasParent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(obj);
					GameObject val = (GameObject)((obj2 is GameObject) ? obj2 : null);
					if (val != null && (Object)(object)val != (Object)null)
					{
						return val;
					}
				}
			}
			catch (Exception ex)
			{
				if (logged.Add("hudErr"))
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogWarning((object)("VR: erro lendo o VRHud do VHVR: " + ex.Message));
					}
				}
			}
			return GameObject.Find(text);
		}

		private static object WristParent(bool left)
		{
			Transform val = ToTransform(ReadWristHud(left));
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val.parent;
		}

		private static Transform Get(string key, Func<object> finder)
		{
			if (cache.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (nextSearch.TryGetValue(key, out var value2) && Time.unscaledTime < value2)
			{
				return null;
			}
			nextSearch[key] = Time.unscaledTime + 1f;
			value = ToTransform(finder());
			cache[key] = value;
			if ((Object)(object)value != (Object)null && logged.Add("found:" + key))
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogInfo((object)$"VR: âncora {key} encontrada em '{PathOf(value)}' (layer {((Component)value).gameObject.layer}).");
				}
			}
			return value;
		}

		private static Type FindType(string name)
		{
			if (types.TryGetValue(name, out var value))
			{
				return value;
			}
			Type type = null;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (!(assembly.GetName().Name != "ValheimVRMod"))
				{
					Type[] source;
					try
					{
						source = assembly.GetTypes();
					}
					catch (ReflectionTypeLoadException ex)
					{
						source = ex.Types;
					}
					type = source.FirstOrDefault((Type x) => x != null && x.Name == name);
					break;
				}
			}
			types[name] = type;
			if (type == null && logged.Add("notype:" + name))
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)("VR: classe " + name + " do ValheimVR Mod não encontrada."));
				}
			}
			return type;
		}

		private static object ReadStatic(string typeName, string member)
		{
			Type type = FindType(typeName);
			if (type == null)
			{
				return null;
			}
			try
			{
				PropertyInfo property = type.GetProperty(member, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (property != null)
				{
					return property.GetValue(null);
				}
				FieldInfo field = type.GetField(member, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field.GetValue(null);
				}
			}
			catch (Exception ex)
			{
				Exception ex2 = (ex as TargetInvocationException)?.InnerException ?? ex;
				if (logged.Add("err:" + member))
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogWarning((object)("VR: erro lendo " + typeName + "." + member + ": " + ex2.GetType().Name + ": " + ex2.Message));
					}
				}
			}
			return null;
		}

		public static string PathOf(Transform t)
		{
			List<string> list = new List<string>();
			Transform val = t;
			while ((Object)(object)val != (Object)null && list.Count < 8)
			{
				list.Insert(0, ((Object)val).name);
				val = val.parent;
			}
			return string.Join("/", list);
		}

		private static Transform ToTransform(object o)
		{
			Transform val = (Transform)((o is Transform) ? o : null);
			if (val == null)
			{
				Component val2 = (Component)((o is Component) ? o : null);
				if (val2 == null)
				{
					GameObject val3 = (GameObject)((o is GameObject) ? o : null);
					if (val3 != null)
					{
						if (!((Object)(object)val3 != (Object)null))
						{
							return null;
						}
						return val3.transform;
					}
					return null;
				}
				if (!((Object)(object)val2 != (Object)null))
				{
					return null;
				}
				return val2.transform;
			}
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val;
		}

		public unsafe static bool ReadButton(string which)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: 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_0030: 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_0075: 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)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: 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)
			if (string.IsNullOrEmpty(which) || which == "None")
			{
				return false;
			}
			try
			{
				XRNode val = (XRNode)(which.StartsWith("Left") ? 4 : 5);
				InputDevice deviceAtXRNode = InputDevices.GetDeviceAtXRNode(val);
				if (!((InputDevice)(ref deviceAtXRNode)).isValid)
				{
					return false;
				}
				if (logged.Add("dev:" + ((object)(*(XRNode*)(&val))/*cast due to .constrained prefix*/).ToString()))
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogInfo((object)$"VR: controle {val} detectado: {((InputDevice)(ref deviceAtXRNode)).name}");
					}
				}
				InputFeatureUsage<bool> val2 = (which.EndsWith("StickClick") ? CommonUsages.primary2DAxisClick : (which.EndsWith("Secondary") ? CommonUsages.secondaryButton : CommonUsages.primaryButton));
				bool flag = default(bool);
				return ((InputDevice)(ref deviceAtXRNode)).TryGetFeatureValue(val2, ref flag) && flag;
			}
			catch (Exception)
			{
				return false;
			}
		}
	}
}