Decompiled source of AlwaysDisplayPlayerName v0.1.16

plugins/com.github.yueby.AlwaysDisplayPlayerName.dll

Decompiled 4 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AlwaysDisplayPlayerName.Common;
using AlwaysDisplayPlayerName.Compatibility;
using AlwaysDisplayPlayerName.Components;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.github.yueby.AlwaysDisplayPlayerName")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.16.0")]
[assembly: AssemblyInformationalVersion("0.1.16+02d7186bae93f2676be4d295ce0b843c7825c092")]
[assembly: AssemblyProduct("com.github.yueby.AlwaysDisplayPlayerName")]
[assembly: AssemblyTitle("AlwaysDisplayPlayerName")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.16.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace AlwaysDisplayPlayerName
{
	[BepInPlugin("com.github.yueby.AlwaysDisplayPlayerName", "AlwaysDisplayPlayerName", "0.1.16")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ConfigEntry<bool> configEnable;

		internal static ConfigEntry<float> configVisibleAngle;

		internal static ConfigEntry<bool> configDisplayWhenBlind;

		internal static ConfigEntry<bool> configShowDistance;

		public const string Id = "com.github.yueby.AlwaysDisplayPlayerName";

		internal static ManualLogSource Log { get; private set; }

		internal static Plugin Instance { get; private set; }

		public static string Name => "AlwaysDisplayPlayerName";

		public static string Version => "0.1.16";

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			configEnable = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enable", true, (ConfigDescription)null);
			configVisibleAngle = ((BaseUnityPlugin)this).Config.Bind<float>("General", "VisibleAngle", 52f, (ConfigDescription)null);
			configDisplayWhenBlind = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DisplayWhenBlind", false, (ConfigDescription)null);
			configShowDistance = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowDistance", true, (ConfigDescription)null);
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), (string)null);
			Log.LogInfo((object)("Plugin " + Name + " is loaded!"));
		}
	}
}
namespace AlwaysDisplayPlayerName.Patches
{
	[HarmonyPatch(typeof(IsLookedAt))]
	[HarmonyWrapSafe]
	public static class IsLookedAtPatches
	{
		[CompilerGenerated]
		private sealed class <DelayedCreateDistanceDisplay>d__3 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public PlayerName originalPlayerName;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <DelayedCreateDistanceDisplay>d__3(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Expected O, but got Unknown
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					CreateDistanceDisplay(originalPlayerName);
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		[HarmonyPatch("Update")]
		[HarmonyPrefix]
		public static bool IsLookAtUpdatePath(IsLookedAt __instance)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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_00a8: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.configEnable.Value)
			{
				return true;
			}
			bool flag = false;
			float num = Vector3.Angle(((Component)MainCamera.instance).transform.forward, ((Component)__instance).transform.position - ((Component)MainCamera.instance).transform.position);
			if (num < Plugin.configVisibleAngle.Value)
			{
				flag = true;
			}
			if (__instance.mouth.character.data.isBlind)
			{
				flag = Plugin.configDisplayWhenBlind.Value;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(IsLookedAt), "index");
			int num2 = (int)fieldInfo.GetValue(__instance);
			GUIManager.instance.playerNames.UpdateName(num2, __instance.playerNamePos.position, flag, __instance.mouth.amplitudeIndex);
			return false;
		}

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		public static void IsLookedAtStartPatch(IsLookedAt __instance)
		{
			if ((Object)(object)__instance == (Object)null || (Object)(object)GUIManager.instance?.playerNames == (Object)null || (Object)(object)__instance.characterInteractible.character == (Object)(object)Character.localCharacter)
			{
				return;
			}
			FieldInfo fieldInfo = AccessTools.Field(typeof(IsLookedAt), "index");
			if (fieldInfo != null)
			{
				int num = (int)fieldInfo.GetValue(__instance);
				Plugin.Log.LogInfo((object)$"IsLookedAt Start - Index: {num}");
				PlayerName playerNameByIndex = GetPlayerNameByIndex(num);
				ShowPlayerDistance component = ((Component)playerNameByIndex).GetComponent<ShowPlayerDistance>();
				if ((Object)(object)playerNameByIndex != (Object)null && (Object)(object)component == (Object)null)
				{
					Plugin.Log.LogInfo((object)$"Creating distance display for PlayerName at index {num}: {((Object)playerNameByIndex).name}");
					((MonoBehaviour)Plugin.Instance).StartCoroutine(DelayedCreateDistanceDisplay(playerNameByIndex));
				}
			}
		}

		private static PlayerName GetPlayerNameByIndex(int index)
		{
			if (GUIManager.instance?.playerNames?.playerNameText != null && index >= 0 && index < GUIManager.instance.playerNames.playerNameText.Length)
			{
				return GUIManager.instance.playerNames.playerNameText[index];
			}
			return null;
		}

		[IteratorStateMachine(typeof(<DelayedCreateDistanceDisplay>d__3))]
		public static IEnumerator DelayedCreateDistanceDisplay(PlayerName originalPlayerName)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DelayedCreateDistanceDisplay>d__3(0)
			{
				originalPlayerName = originalPlayerName
			};
		}

		public static void CreateDistanceDisplay(PlayerName originalPlayerName)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			RectTransform rectTransform = ((TMP_Text)originalPlayerName.text).rectTransform;
			GameObject val = new GameObject("DistanceDisplay");
			RectTransform val2 = val.AddComponent<RectTransform>();
			LayoutElement val3 = val.AddComponent<LayoutElement>();
			val3.ignoreLayout = true;
			((Transform)val2).SetParent((Transform)(object)rectTransform);
			TextMeshProUGUI val4 = val.AddComponent<TextMeshProUGUI>();
			float fontSize = ((TMP_Text)originalPlayerName.text).fontSize;
			float fontSize2 = fontSize * 1.4f;
			((TMP_Text)val4).text = "0.0m";
			((TMP_Text)val4).alignment = (TextAlignmentOptions)514;
			((TMP_Text)val4).font = ((TMP_Text)originalPlayerName.text).font;
			((TMP_Text)val4).fontSize = fontSize2;
			((Graphic)val4).color = Color.white;
			if ((Object)(object)((TMP_Text)originalPlayerName.text).fontSharedMaterial != (Object)null)
			{
				((TMP_Text)val4).fontSharedMaterial = ((TMP_Text)originalPlayerName.text).fontSharedMaterial;
			}
			ShowPlayerDistance showPlayerDistance = val.AddComponent<ShowPlayerDistance>();
			showPlayerDistance.Initialize(val4, originalPlayerName);
			Plugin.Log.LogInfo((object)("Created distance display for player name: " + ((Object)originalPlayerName).name));
		}
	}
}
namespace AlwaysDisplayPlayerName.Components
{
	public class ShowPlayerDistance : MonoBehaviour
	{
		private const float UPDATE_INTERVAL = 0.1f;

		private const float FIXED_DISTANCE_WIDTH = 200f;

		private const float FIXED_DISTANCE_HEIGHT = 50f;

		public TextMeshProUGUI distanceText;

		private PlayerName _playerName;

		private CanvasGroup _canvasGroup;

		private bool _shouldShowDistance;

		private bool _hasSetPosition;

		private Character _lastCharacter;

		private RectTransform _playerNameRect;

		private RectTransform _distanceRect;

		private IntervalTimer _mainUpdateTimer;

		private IntervalTimer _uiUpdateTimer;

		private void Awake()
		{
			if (Plugin.configShowDistance != null)
			{
				Plugin.configShowDistance.SettingChanged += OnConfigChanged;
			}
			_mainUpdateTimer = new IntervalTimer(0.1f, OnMainUpdate);
			_uiUpdateTimer = new IntervalTimer(0.05f, OnUIUpdate);
		}

		private void OnDestroy()
		{
			if (Plugin.configShowDistance != null)
			{
				Plugin.configShowDistance.SettingChanged -= OnConfigChanged;
			}
		}

		private void OnConfigChanged(object sender, EventArgs e)
		{
			_shouldShowDistance = ShouldShowDistance();
			if (_shouldShowDistance)
			{
				UpdateDistance();
			}
			else
			{
				SetVisibility(visible: false);
			}
		}

		public void Initialize(TextMeshProUGUI text, PlayerName targetPlayerName)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: 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)
			distanceText = text;
			_playerName = targetPlayerName;
			_canvasGroup = ((Component)distanceText).gameObject.AddComponent<CanvasGroup>();
			_playerNameRect = ((TMP_Text)targetPlayerName.text).rectTransform;
			_distanceRect = ((TMP_Text)distanceText).rectTransform;
			_distanceRect.anchorMin = _playerNameRect.anchorMin;
			_distanceRect.anchorMax = _playerNameRect.anchorMax;
			_distanceRect.pivot = _playerNameRect.pivot;
			_distanceRect.sizeDelta = new Vector2(400f, 50f);
			ManualLogSource log = Plugin.Log;
			object obj;
			if (targetPlayerName == null)
			{
				obj = null;
			}
			else
			{
				CharacterInteractible characterInteractable = targetPlayerName.characterInteractable;
				if (characterInteractable == null)
				{
					obj = null;
				}
				else
				{
					Character character = characterInteractable.character;
					obj = ((character != null) ? ((Object)character).name : null);
				}
			}
			if (obj == null)
			{
				obj = "Unknown";
			}
			log.LogInfo((object)("ShowPlayerDistance initialized for character: " + (string?)obj + " with child: " + (((targetPlayerName != null) ? ((Object)targetPlayerName).name : null) ?? "Unknown")));
			_lastCharacter = _playerName.characterInteractable.character;
			_shouldShowDistance = ShouldShowDistance();
			if (!_shouldShowDistance)
			{
				SetVisibility(visible: false);
			}
		}

		private void Update()
		{
			_mainUpdateTimer.Update();
			_uiUpdateTimer.Update();
		}

		private void OnMainUpdate()
		{
			try
			{
				Character character = _playerName.characterInteractable.character;
				if ((Object)(object)character == (Object)null || (Object)(object)character != (Object)(object)_lastCharacter)
				{
					Plugin.Log.LogInfo((object)"Character changed, updating state");
					_lastCharacter = character;
				}
				_shouldShowDistance = ShouldShowDistance();
				if (!_shouldShowDistance)
				{
					SetVisibility(visible: false);
				}
				else
				{
					UpdateDistance();
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Error in OnUpdate: " + ex.Message));
				SetVisibility(visible: false);
				_shouldShowDistance = false;
			}
		}

		private void OnUIUpdate()
		{
			//IL_0032: 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_0038: 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_005d: 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_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: 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)
			try
			{
				if (_shouldShowDistance && (Object)(object)_playerName.text != (Object)null && !_hasSetPosition)
				{
					Vector2 anchoredPosition = _playerNameRect.anchoredPosition;
					float num = anchoredPosition.y + 50f + 25f + 5f;
					float num2 = anchoredPosition.x + _playerNameRect.sizeDelta.x * (0.5f - _playerNameRect.pivot.x);
					float num3 = num2 - 200f * (0.5f - _distanceRect.pivot.x);
					_distanceRect.anchoredPosition = new Vector2(num3, num);
					_hasSetPosition = true;
					Plugin.Log.LogInfo((object)$"Sync UI for character: {((Object)_playerName.characterInteractable.character).name}, playerNameSize: {_playerNameRect.sizeDelta}, playerNamePos: {anchoredPosition}");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Error in OnUISync: " + ex.Message));
			}
		}

		private void SetVisibility(bool visible, bool setParentVisible = false)
		{
			if ((Object)(object)_canvasGroup != (Object)null)
			{
				_canvasGroup.alpha = (visible ? 1f : 0f);
				if (setParentVisible && (Object)(object)_playerName.text != (Object)null)
				{
					((Behaviour)_playerName.text).enabled = visible;
				}
			}
		}

		private bool ShouldShowDistance()
		{
			if (!Plugin.configShowDistance.Value)
			{
				Plugin.Log.LogDebug((object)"ShowDistance is disabled");
				return false;
			}
			if ((Object)(object)_playerName.characterInteractable == (Object)null)
			{
				Plugin.Log.LogDebug((object)"Character interactable is null");
				return false;
			}
			if ((Object)(object)_playerName.characterInteractable.character == (Object)(object)Character.observedCharacter)
			{
				Plugin.Log.LogDebug((object)"Player character is observed character");
				return false;
			}
			return true;
		}

		private void UpdateDistance()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (PeakCinema_Compat.Loaded)
			{
				if ((Object)(object)PeakCinema_Compat.Cinema != (Object)null && PeakCinema_Compat.Cinema.on)
				{
					SetVisibility(visible: false, setParentVisible: true);
				}
				else
				{
					SetVisibility(visible: true, setParentVisible: true);
				}
			}
			else
			{
				SetVisibility(visible: true);
			}
			float num = Vector3.Distance(Character.observedCharacter.Center, _playerName.characterInteractable.character.Center);
			((TMP_Text)distanceText).text = $"{num:F1}m";
		}
	}
}
namespace AlwaysDisplayPlayerName.Compatibility
{
	internal class PeakCinema_Compat
	{
		private static float lastFindTime;

		private static CinemaCamera _cinemaCamera;

		internal static bool Loaded => Chainloader.PluginInfos.ContainsKey("com.github.megalon.peakcinema");

		internal static CinemaCamera? Cinema
		{
			get
			{
				if ((Object)(object)_cinemaCamera == (Object)null && Time.time - lastFindTime > 1f)
				{
					lastFindTime = Time.time;
					_cinemaCamera = Object.FindAnyObjectByType<CinemaCamera>();
				}
				return _cinemaCamera;
			}
		}
	}
}
namespace AlwaysDisplayPlayerName.Common
{
	public class IntervalTimer
	{
		private float _lastTime;

		private float _interval;

		private Action _onReady;

		public IntervalTimer(float interval, Action onReady = null)
		{
			_interval = interval;
			_onReady = onReady;
		}

		public void Update()
		{
			if (Time.time - _lastTime >= _interval)
			{
				_lastTime = Time.time;
				_onReady?.Invoke();
			}
		}

		public void Reset()
		{
			_lastTime = 0f;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}