Decompiled source of GhostCam v0.1.3

GhostCam.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace GhostCam;

internal static class ConfigLabels
{
	private sealed class TrackedLabel
	{
		internal WeakReference Target;

		internal string English;
	}

	private static readonly Dictionary<string, string> EnToCn = new Dictionary<string, string>(StringComparer.Ordinal)
	{
		{ "General", "通用" },
		{ "Language", "语言" },
		{ "Enabled", "启用" },
		{ "ToggleKey", "切换键" },
		{ "HideWatchedModel", "隐藏队友模型" },
		{ "Hide Watched Model", "隐藏队友模型" },
		{ "EyeForwardOffset", "视线前移" },
		{ "Eye Forward Offset", "视线前移" },
		{ "FollowSmoothing", "跟随平滑" },
		{ "Follow Smoothing", "跟随平滑" },
		{ "SuppressSwitchOnToggle", "切换键不切人" },
		{ "Suppress Switch On Toggle", "切换键不切人" },
		{ "Auto", "自动" },
		{ "Chinese", "中文" },
		{ "English", "英文" }
	};

	private static readonly Dictionary<string, string> CnToEn = new Dictionary<string, string>(StringComparer.Ordinal);

	private static readonly List<TrackedLabel> Tracked = new List<TrackedLabel>();

	private const int MaxTracked = 512;

	private static readonly Dictionary<Type, PropertyInfo> TextSetters = new Dictionary<Type, PropertyInfo>();

	internal static void AddPair(string english, string chinese, bool bothWays)
	{
		if (!string.IsNullOrEmpty(english) && !string.IsNullOrEmpty(chinese) && !string.Equals(english, chinese, StringComparison.Ordinal))
		{
			EnToCn[english] = chinese;
			if (bothWays)
			{
				CnToEn[chinese] = english;
			}
		}
	}

	private static void Translate(ref string __0, object __instance)
	{
		if (string.IsNullOrEmpty(__0))
		{
			return;
		}
		string text = __0;
		string value2;
		if (EnToCn.TryGetValue(text, out var value))
		{
			value2 = text;
		}
		else
		{
			if (!CnToEn.TryGetValue(text, out value2))
			{
				return;
			}
			value = text;
		}
		Track(__instance, value2);
		__0 = (GhostCamPlugin.Chinese ? value : value2);
	}

	private static void TranslateOnly(ref string __0)
	{
		if (!string.IsNullOrEmpty(__0) && EnToCn.TryGetValue(__0, out var value) && GhostCamPlugin.Chinese)
		{
			__0 = value;
		}
	}

	internal static void Install(Harmony harmony)
	{
		int num = PatchEverything(harmony, "Translate");
		if (num == 0)
		{
			num = PatchEverything(harmony, "TranslateOnly");
		}
		if (GhostCamPlugin.Log != null)
		{
			if (num == 0)
			{
				GhostCamPlugin.Log.LogWarning((object)"[GhostCam] no text setter found - config labels stay English.");
			}
			else
			{
				GhostCamPlugin.Log.LogInfo((object)("[GhostCam] config labels: " + num + " text setter(s) patched."));
			}
		}
	}

	private static int PatchEverything(Harmony harmony, string prefixName)
	{
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Expected O, but got Unknown
		MethodInfo method = typeof(ConfigLabels).GetMethod(prefixName, BindingFlags.Static | BindingFlags.NonPublic);
		if (method == null)
		{
			return 0;
		}
		HarmonyMethod prefix = new HarmonyMethod(method);
		HashSet<MethodInfo> seen = new HashSet<MethodInfo>();
		return 0 + PatchSetter(harmony, prefix, seen, "TMPro.TMP_Text", "Unity.TextMeshPro") + PatchSetter(harmony, prefix, seen, "TMPro.TextMeshProUGUI", "Unity.TextMeshPro") + PatchSetter(harmony, prefix, seen, "TMPro.TextMeshPro", "Unity.TextMeshPro") + PatchSetter(harmony, prefix, seen, "UnityEngine.UI.Text", "UnityEngine.UI");
	}

	private static int PatchSetter(Harmony harmony, HarmonyMethod prefix, HashSet<MethodInfo> seen, string typeName, string assemblyName)
	{
		int num = 0;
		try
		{
			Type type = FindType(typeName, assemblyName);
			if (type == null)
			{
				return 0;
			}
			PropertyInfo property = type.GetProperty("text", BindingFlags.Instance | BindingFlags.Public);
			MethodInfo methodInfo = Declared((property == null) ? null : property.GetSetMethod());
			if (methodInfo != null && methodInfo.GetParameters().Length == 1 && seen.Add(methodInfo))
			{
				harmony.Patch((MethodBase)methodInfo, prefix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				num++;
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
			foreach (MethodInfo methodInfo2 in methods)
			{
				if (methodInfo2.Name != "SetText")
				{
					continue;
				}
				ParameterInfo[] parameters = methodInfo2.GetParameters();
				if (parameters.Length == 1 && !(parameters[0].ParameterType != typeof(string)))
				{
					MethodInfo methodInfo3 = Declared(methodInfo2);
					if (!(methodInfo3 == null) && seen.Add(methodInfo3))
					{
						harmony.Patch((MethodBase)methodInfo3, prefix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
						num++;
					}
				}
			}
		}
		catch (Exception ex)
		{
			ManualLogSource log = GhostCamPlugin.Log;
			if (log != null)
			{
				log.LogDebug((object)("label patch skipped for " + typeName + ": " + ex.Message));
			}
		}
		return num;
	}

	private static MethodInfo Declared(MethodInfo m)
	{
		if (m == null || m.DeclaringType == null || m.DeclaringType == m.ReflectedType)
		{
			return m;
		}
		ParameterInfo[] parameters = m.GetParameters();
		Type[] array = new Type[parameters.Length];
		for (int i = 0; i < parameters.Length; i++)
		{
			array[i] = parameters[i].ParameterType;
		}
		return m.DeclaringType.GetMethod(m.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, array, null) ?? m;
	}

	private static Type FindType(string typeName, string assemblyName)
	{
		Type type = Type.GetType(typeName + ", " + assemblyName, throwOnError: false);
		if (type != null)
		{
			return type;
		}
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			if (!(assembly.GetName().Name != assemblyName))
			{
				type = assembly.GetType(typeName, throwOnError: false);
				if (type != null)
				{
					return type;
				}
			}
		}
		return null;
	}

	private static void Track(object instance, string english)
	{
		if (instance == null)
		{
			return;
		}
		for (int i = 0; i < Tracked.Count; i++)
		{
			object target = Tracked[i].Target.Target;
			if (target != null && target == instance)
			{
				Tracked[i].English = english;
				return;
			}
		}
		if (Tracked.Count >= 512)
		{
			for (int num = Tracked.Count - 1; num >= 0; num--)
			{
				if (!Tracked[num].Target.IsAlive)
				{
					Tracked.RemoveAt(num);
				}
			}
			if (Tracked.Count >= 512)
			{
				Tracked.RemoveAt(0);
			}
		}
		Tracked.Add(new TrackedLabel
		{
			Target = new WeakReference(instance),
			English = english
		});
	}

	internal static void RefreshAll()
	{
		int num = 0;
		for (int num2 = Tracked.Count - 1; num2 >= 0; num2--)
		{
			TrackedLabel trackedLabel = Tracked[num2];
			object target = trackedLabel.Target.Target;
			if (target == null)
			{
				Tracked.RemoveAt(num2);
			}
			else
			{
				try
				{
					if (SetText(target, trackedLabel.English))
					{
						num++;
					}
				}
				catch (Exception ex)
				{
					Tracked.RemoveAt(num2);
					ManualLogSource log = GhostCamPlugin.Log;
					if (log != null)
					{
						log.LogDebug((object)("label refresh dropped: " + ex.GetType().Name));
					}
				}
			}
		}
		ManualLogSource log2 = GhostCamPlugin.Log;
		if (log2 != null)
		{
			log2.LogInfo((object)("[GhostCam] config labels re-applied on " + num + " component(s)."));
		}
	}

	private static bool SetText(object target, string english)
	{
		Type type = target.GetType();
		if (!TextSetters.TryGetValue(type, out var value))
		{
			value = type.GetProperty("text", BindingFlags.Instance | BindingFlags.Public);
			TextSetters[type] = value;
		}
		if (value == null || !value.CanWrite)
		{
			return false;
		}
		value.SetValue(target, english, null);
		return true;
	}

	internal static bool GameIsChinese()
	{
		//IL_0118: 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_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0122: Invalid comparison between Unknown and I4
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_0128: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Invalid comparison between Unknown and I4
		try
		{
			Type type = typeof(SpectateCamera).Assembly.GetType("LocalizationManager");
			if (type != null)
			{
				object obj = type.GetField("instance", BindingFlags.Static | BindingFlags.Public)?.GetValue(null) ?? type.GetProperty("instance", BindingFlags.Static | BindingFlags.Public)?.GetValue(null, null);
				if (obj != null)
				{
					object obj2 = type.GetProperty("ActiveLocale")?.GetValue(obj, null);
					object obj3 = obj2?.GetType().GetProperty("LocaleReference")?.GetValue(obj2, null);
					object obj4 = obj3?.GetType().GetProperty("Identifier")?.GetValue(obj3, null);
					string text = obj4?.GetType().GetProperty("Code")?.GetValue(obj4, null) as string;
					if (!string.IsNullOrEmpty(text))
					{
						return text.StartsWith("zh", StringComparison.OrdinalIgnoreCase);
					}
				}
			}
		}
		catch
		{
		}
		SystemLanguage systemLanguage = Application.systemLanguage;
		if ((int)systemLanguage == 6 || systemLanguage - 40 <= 1)
		{
			return true;
		}
		return false;
	}
}
[BepInPlugin("com.peachh.GhostCam", "GhostCam", "0.1.3")]
public class GhostCamPlugin : BaseUnityPlugin
{
	public enum UiLanguage
	{
		Auto,
		Chinese,
		English
	}

	public const string PluginGuid = "com.peachh.GhostCam";

	internal static ManualLogSource Log;

	internal static ConfigEntry<UiLanguage> Language;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<KeyboardShortcut> ToggleKey;

	internal static ConfigEntry<bool> HideWatchedModel;

	internal static ConfigEntry<bool> SuppressSwitchOnToggle;

	internal static ConfigEntry<float> EyeForwardOffset;

	internal static ConfigEntry<float> FollowSmoothing;

	internal static bool FirstPerson;

	internal static SpectateCamera LastInstance;

	private const string EnabledCn = "启用本插件的观战第一人称开关。关闭后完全回到原版第三人称观战。";

	private const string EnabledEn = "Enable the first-person spectate toggle. Off falls back to the vanilla third-person camera.";

	private const string ToggleKeyCn = "在第三人称 / 第一人称之间切换的按键(默认空格)。";

	private const string ToggleKeyEn = "Key that switches between third-person and first-person (Space by default).";

	private const string HideModelCn = "第一人称时把被观战队友的模型改成只投影,避免相机卡在他脑袋里看到模型内壁。";

	private const string HideModelEn = "Shadows-only the watched teammate in first-person so the camera does not sit inside their head.";

	private const string EyeOffsetCn = "第一人称时把相机沿视线方向再向前挪出的距离(米)。默认 0 = 正好落在队友眼球位置,与他自己看到的画面一致。队友模型默认会被整体隐藏,所以通常不需要加;只有在模型没藏干净、出现穿模闪烁时才调到 0.03~0.1。";

	private const string EyeOffsetEn = "Extra distance (metres) to push the camera forward along the view ray in first-person. 0 = exactly at the teammate's eyes, matching what they see. The model is hidden by default, so you normally do not need this; raise it to 0.03-0.1 only if the model still clips.";

	private const string SmoothingCn = "相机跟随平滑系数。原版对远程队友的位置不做插值(网络包到了就直接搬过去),所以贴到他眼睛上看会一顿一顿的;这里把相机做成指数平滑来抹平那些台阶。越大越跟手、越小越顺滑,0 = 关闭平滑回到硬跟随。";

	private const string SmoothingEn = "Camera follow smoothing. Remote teammates are not interpolated, so sitting at their eyes jitters; this smooths it exponentially. Higher = tighter, lower = smoother, 0 = hard follow.";

	private const string SuppressCn = "原版在观战时把空格(Jump)绑成了「切下一个队友」,和默认的切换键撞车。开启时,按下切换键的那一下不再触发切人;关掉则一次空格同时切视角和切队友。";

	private const string SuppressEn = "Vanilla binds Space (Jump) to \"switch to next teammate\" while spectating, which collides with the default toggle key. On: that keypress no longer switches player. Off: one Space does both.";

	private const string LanguageCn = "Auto 跟随游戏语言;Chinese / English 强制指定。";

	private const string LanguageEn = "Auto follows the game language; Chinese / English force it.";

	internal static bool Chinese { get; private set; }

	private static string T(string cn, string en)
	{
		if (!Chinese)
		{
			return en;
		}
		return cn;
	}

	private void Awake()
	{
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Expected O, but got Unknown
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Expected O, but got Unknown
		//IL_0213: Unknown result type (might be due to invalid IL or missing references)
		//IL_0219: Expected O, but got Unknown
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		Language = ((BaseUnityPlugin)this).Config.Bind<UiLanguage>("General", "Language", UiLanguage.Auto, "Auto 跟随游戏语言;Chinese / English 强制指定。\nAuto follows the game language; Chinese / English force it.");
		Chinese = ResolveChinese(Language.Value);
		Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, T("启用本插件的观战第一人称开关。关闭后完全回到原版第三人称观战。", "Enable the first-person spectate toggle. Off falls back to the vanilla third-person camera."));
		ToggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "ToggleKey", new KeyboardShortcut((KeyCode)32, Array.Empty<KeyCode>()), T("在第三人称 / 第一人称之间切换的按键(默认空格)。", "Key that switches between third-person and first-person (Space by default)."));
		HideWatchedModel = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "HideWatchedModel", true, T("第一人称时把被观战队友的模型改成只投影,避免相机卡在他脑袋里看到模型内壁。", "Shadows-only the watched teammate in first-person so the camera does not sit inside their head."));
		EyeForwardOffset = ((BaseUnityPlugin)this).Config.Bind<float>("General", "EyeForwardOffset", 0f, new ConfigDescription(T("第一人称时把相机沿视线方向再向前挪出的距离(米)。默认 0 = 正好落在队友眼球位置,与他自己看到的画面一致。队友模型默认会被整体隐藏,所以通常不需要加;只有在模型没藏干净、出现穿模闪烁时才调到 0.03~0.1。", "Extra distance (metres) to push the camera forward along the view ray in first-person. 0 = exactly at the teammate's eyes, matching what they see. The model is hidden by default, so you normally do not need this; raise it to 0.03-0.1 only if the model still clips."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.5f), Array.Empty<object>()));
		FollowSmoothing = ((BaseUnityPlugin)this).Config.Bind<float>("General", "FollowSmoothing", 20f, new ConfigDescription(T("相机跟随平滑系数。原版对远程队友的位置不做插值(网络包到了就直接搬过去),所以贴到他眼睛上看会一顿一顿的;这里把相机做成指数平滑来抹平那些台阶。越大越跟手、越小越顺滑,0 = 关闭平滑回到硬跟随。", "Camera follow smoothing. Remote teammates are not interpolated, so sitting at their eyes jitters; this smooths it exponentially. Higher = tighter, lower = smoother, 0 = hard follow."), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>()));
		SuppressSwitchOnToggle = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "SuppressSwitchOnToggle", true, T("原版在观战时把空格(Jump)绑成了「切下一个队友」,和默认的切换键撞车。开启时,按下切换键的那一下不再触发切人;关掉则一次空格同时切视角和切队友。", "Vanilla binds Space (Jump) to \"switch to next teammate\" while spectating, which collides with the default toggle key. On: that keypress no longer switches player. Off: one Space does both."));
		ApplyDescriptions();
		ConfigLabels.AddPair("Enable the first-person spectate toggle. Off falls back to the vanilla third-person camera.", "启用本插件的观战第一人称开关。关闭后完全回到原版第三人称观战。", bothWays: true);
		ConfigLabels.AddPair("Key that switches between third-person and first-person (Space by default).", "在第三人称 / 第一人称之间切换的按键(默认空格)。", bothWays: true);
		ConfigLabels.AddPair("Shadows-only the watched teammate in first-person so the camera does not sit inside their head.", "第一人称时把被观战队友的模型改成只投影,避免相机卡在他脑袋里看到模型内壁。", bothWays: true);
		ConfigLabels.AddPair("Extra distance (metres) to push the camera forward along the view ray in first-person. 0 = exactly at the teammate's eyes, matching what they see. The model is hidden by default, so you normally do not need this; raise it to 0.03-0.1 only if the model still clips.", "第一人称时把相机沿视线方向再向前挪出的距离(米)。默认 0 = 正好落在队友眼球位置,与他自己看到的画面一致。队友模型默认会被整体隐藏,所以通常不需要加;只有在模型没藏干净、出现穿模闪烁时才调到 0.03~0.1。", bothWays: true);
		ConfigLabels.AddPair("Camera follow smoothing. Remote teammates are not interpolated, so sitting at their eyes jitters; this smooths it exponentially. Higher = tighter, lower = smoother, 0 = hard follow.", "相机跟随平滑系数。原版对远程队友的位置不做插值(网络包到了就直接搬过去),所以贴到他眼睛上看会一顿一顿的;这里把相机做成指数平滑来抹平那些台阶。越大越跟手、越小越顺滑,0 = 关闭平滑回到硬跟随。", bothWays: true);
		ConfigLabels.AddPair("Vanilla binds Space (Jump) to \"switch to next teammate\" while spectating, which collides with the default toggle key. On: that keypress no longer switches player. Off: one Space does both.", "原版在观战时把空格(Jump)绑成了「切下一个队友」,和默认的切换键撞车。开启时,按下切换键的那一下不再触发切人;关掉则一次空格同时切视角和切队友。", bothWays: true);
		Language.SettingChanged += delegate
		{
			Chinese = ResolveChinese(Language.Value);
			ApplyDescriptions();
			ConfigLabels.RefreshAll();
			Log.LogInfo((object)("[GhostCam] config language -> " + (Chinese ? "Chinese" : "English")));
		};
		Harmony val = new Harmony("com.peachh.GhostCam");
		ConfigLabels.Install(val);
		try
		{
			val.PatchAll(typeof(SpectateLateUpdatePatch));
			val.PatchAll(typeof(StopSpectatePatch));
			val.PatchAll(typeof(PlayerSwitchPatch));
			Log.LogInfo((object)$"[GhostCam] 补丁成功:切换键={ToggleKey.Value},启用={Enabled.Value}");
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"[GhostCam] 补丁失败:{arg}");
		}
	}

	private static void ApplyDescriptions()
	{
		ForceDescription((ConfigEntryBase)(object)Enabled, T("启用本插件的观战第一人称开关。关闭后完全回到原版第三人称观战。", "Enable the first-person spectate toggle. Off falls back to the vanilla third-person camera."));
		ForceDescription((ConfigEntryBase)(object)ToggleKey, T("在第三人称 / 第一人称之间切换的按键(默认空格)。", "Key that switches between third-person and first-person (Space by default)."));
		ForceDescription((ConfigEntryBase)(object)HideWatchedModel, T("第一人称时把被观战队友的模型改成只投影,避免相机卡在他脑袋里看到模型内壁。", "Shadows-only the watched teammate in first-person so the camera does not sit inside their head."));
		ForceDescription((ConfigEntryBase)(object)EyeForwardOffset, T("第一人称时把相机沿视线方向再向前挪出的距离(米)。默认 0 = 正好落在队友眼球位置,与他自己看到的画面一致。队友模型默认会被整体隐藏,所以通常不需要加;只有在模型没藏干净、出现穿模闪烁时才调到 0.03~0.1。", "Extra distance (metres) to push the camera forward along the view ray in first-person. 0 = exactly at the teammate's eyes, matching what they see. The model is hidden by default, so you normally do not need this; raise it to 0.03-0.1 only if the model still clips."));
		ForceDescription((ConfigEntryBase)(object)FollowSmoothing, T("相机跟随平滑系数。原版对远程队友的位置不做插值(网络包到了就直接搬过去),所以贴到他眼睛上看会一顿一顿的;这里把相机做成指数平滑来抹平那些台阶。越大越跟手、越小越顺滑,0 = 关闭平滑回到硬跟随。", "Camera follow smoothing. Remote teammates are not interpolated, so sitting at their eyes jitters; this smooths it exponentially. Higher = tighter, lower = smoother, 0 = hard follow."));
		ForceDescription((ConfigEntryBase)(object)SuppressSwitchOnToggle, T("原版在观战时把空格(Jump)绑成了「切下一个队友」,和默认的切换键撞车。开启时,按下切换键的那一下不再触发切人;关掉则一次空格同时切视角和切队友。", "Vanilla binds Space (Jump) to \"switch to next teammate\" while spectating, which collides with the default toggle key. On: that keypress no longer switches player. Off: one Space does both."));
	}

	private static void ForceDescription(ConfigEntryBase entry, string text)
	{
		if (entry == null)
		{
			return;
		}
		try
		{
			FieldInfo field = typeof(ConfigEntryBase).GetField("<Description>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
			if (field == null)
			{
				return;
			}
			object value = field.GetValue(entry);
			if (value != null)
			{
				FieldInfo field2 = value.GetType().GetField("<Description>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
				if (!(field2 == null))
				{
					field2.SetValue(value, text);
					field.SetValue(entry, value);
				}
			}
		}
		catch
		{
		}
	}

	private static bool ResolveChinese(UiLanguage mode)
	{
		return mode switch
		{
			UiLanguage.Chinese => true, 
			UiLanguage.English => false, 
			_ => ConfigLabels.GameIsChinese(), 
		};
	}
}
[HarmonyPatch(typeof(SpectateCamera), "LateUpdate")]
internal static class SpectateLateUpdatePatch
{
	private static FieldInfo _fiPlayer;

	private static FieldInfo _fiChatActive;

	private static FieldInfo _fiCurrentMenuPage;

	private static readonly Dictionary<Renderer, bool> SavedEnabled = new Dictionary<Renderer, bool>();

	private static PlayerAvatar _hiddenTarget;

	private static GameObject _savedMeshParent;

	private static bool _savedMeshParentActive;

	private static Renderer[] _cachedRenderers;

	private static bool _eyeLogged;

	private static Vector3 _smoothPosition;

	private static Quaternion _smoothRotation = Quaternion.identity;

	private static bool _smoothReady;

	private static Transform _smoothTarget;

	private static void ResolveFields()
	{
		if (!(_fiPlayer != null))
		{
			_fiPlayer = AccessTools.Field(typeof(SpectateCamera), "player");
			_fiChatActive = AccessTools.Field(typeof(ChatManager), "chatActive");
			_fiCurrentMenuPage = AccessTools.Field(typeof(MenuManager), "currentMenuPage");
			if (_fiPlayer == null)
			{
				GhostCamPlugin.Log.LogError((object)"[GhostCam] 找不到 SpectateCamera.player 字段,第一人称不可用。");
			}
		}
	}

	internal static PlayerAvatar GetWatchedPlayer(SpectateCamera sc)
	{
		ResolveFields();
		if (_fiPlayer == null || (Object)(object)sc == (Object)null)
		{
			return null;
		}
		object? value = _fiPlayer.GetValue(sc);
		return (PlayerAvatar)((value is PlayerAvatar) ? value : null);
	}

	private static bool InputIsFree()
	{
		try
		{
			if (_fiChatActive != null && (Object)(object)ChatManager.instance != (Object)null && (bool)_fiChatActive.GetValue(ChatManager.instance))
			{
				return false;
			}
			if (_fiCurrentMenuPage != null && (Object)(object)MenuManager.instance != (Object)null && _fiCurrentMenuPage.GetValue(MenuManager.instance) != null)
			{
				return false;
			}
		}
		catch
		{
		}
		return true;
	}

	private static void Postfix(SpectateCamera __instance)
	{
		//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_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance == (Object)null)
		{
			return;
		}
		ResolveFields();
		if ((Object)(object)GhostCamPlugin.LastInstance != (Object)(object)__instance)
		{
			GhostCamPlugin.LastInstance = __instance;
			GhostCamPlugin.FirstPerson = false;
			RestoreHidden();
		}
		if (!__instance.CheckState((State)1))
		{
			if (GhostCamPlugin.FirstPerson)
			{
				GhostCamPlugin.FirstPerson = false;
			}
			RestoreHidden();
			return;
		}
		if (GhostCamPlugin.Enabled.Value && InputIsFree())
		{
			KeyboardShortcut value = GhostCamPlugin.ToggleKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				GhostCamPlugin.FirstPerson = !GhostCamPlugin.FirstPerson;
				GhostCamPlugin.Log.LogInfo((object)("[GhostCam] 已切换到" + (GhostCamPlugin.FirstPerson ? "第一人称" : "第三人称")));
				if (!GhostCamPlugin.FirstPerson)
				{
					RestoreHidden();
				}
				else
				{
					_eyeLogged = false;
				}
			}
		}
		if (!GhostCamPlugin.FirstPerson)
		{
			RestoreHidden();
			return;
		}
		PlayerAvatar watchedPlayer = GetWatchedPlayer(__instance);
		if ((Object)(object)watchedPlayer == (Object)null)
		{
			RestoreHidden();
			return;
		}
		Transform val = ResolveEye(watchedPlayer);
		if ((Object)(object)val == (Object)null)
		{
			RestoreHidden();
			return;
		}
		ApplyCamera(__instance, val);
		ApplyHide(watchedPlayer);
		if (!_eyeLogged)
		{
			_eyeLogged = true;
			GhostCamPlugin.Log.LogInfo((object)($"[GhostCam] 第一人称视点 = {((Object)val).name},离人物根节点高度差 {val.position.y - ((Component)watchedPlayer).transform.position.y:F2}m," + $"隐藏 Renderer {((_cachedRenderers != null) ? _cachedRenderers.Length : 0)} 个"));
		}
	}

	private static Transform ResolveEye(PlayerAvatar target)
	{
		//IL_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)target.PlayerVisionTarget != (Object)null && (Object)(object)target.PlayerVisionTarget.VisionTransform != (Object)null)
		{
			Transform visionTransform = target.PlayerVisionTarget.VisionTransform;
			if (IsUsable(visionTransform.position))
			{
				return visionTransform;
			}
		}
		if ((Object)(object)target.localCamera != (Object)null)
		{
			Transform transform = ((Component)target.localCamera).transform;
			if (IsUsable(transform.position))
			{
				return transform;
			}
		}
		if ((Object)(object)target.spectatePoint != (Object)null && IsUsable(target.spectatePoint.position))
		{
			return target.spectatePoint;
		}
		return null;
	}

	private static bool IsUsable(Vector3 position)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		if (!float.IsFinite(position.x) || !float.IsFinite(position.y) || !float.IsFinite(position.z))
		{
			return false;
		}
		return ((Vector3)(ref position)).sqrMagnitude > 0.0001f;
	}

	private static void ApplyCamera(SpectateCamera sc, Transform eye)
	{
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: 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_0047: 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_004e: 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_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: 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_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: 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)
		//IL_0099: 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_0131: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f1: 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_0085: Unknown result type (might be due to invalid IL or missing references)
		//IL_0176: 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_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: 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_00ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d4: 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)
		//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_0199: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		Camera val = (((Object)(object)GameDirector.instance != (Object)null) ? GameDirector.instance.MainCamera : null);
		float value = GhostCamPlugin.EyeForwardOffset.Value;
		Vector3 val2 = eye.position + eye.rotation * new Vector3(0f, 0f, value);
		Quaternion val3 = eye.rotation;
		float value2 = GhostCamPlugin.FollowSmoothing.Value;
		if (value2 > 0f)
		{
			if (!_smoothReady || (Object)(object)_smoothTarget != (Object)(object)eye || Vector3.Distance(_smoothPosition, val2) > 5f)
			{
				_smoothPosition = val2;
				_smoothRotation = val3;
				_smoothReady = true;
				_smoothTarget = eye;
			}
			else
			{
				float num = 1f - Mathf.Exp((0f - value2) * Time.deltaTime);
				_smoothPosition = Vector3.Lerp(_smoothPosition, val2, num);
				_smoothRotation = Quaternion.Slerp(_smoothRotation, val3, num);
			}
			val2 = _smoothPosition;
			val3 = _smoothRotation;
		}
		else
		{
			_smoothReady = false;
			_smoothTarget = null;
		}
		Vector3 position = val2;
		Quaternion rotation = val3;
		if ((Object)(object)CameraAim.Instance != (Object)null)
		{
			((Component)CameraAim.Instance).transform.localPosition = Vector3.zero;
			((Component)CameraAim.Instance).transform.localRotation = Quaternion.identity;
		}
		if ((Object)(object)CameraPosition.instance != (Object)null)
		{
			((Component)CameraPosition.instance).transform.localPosition = Vector3.zero;
			((Component)CameraPosition.instance).transform.localRotation = Quaternion.identity;
		}
		((Component)sc).transform.position = position;
		((Component)sc).transform.rotation = rotation;
		if ((Object)(object)val != (Object)null)
		{
			((Component)val).transform.position = position;
			((Component)val).transform.rotation = rotation;
			val.nearClipPlane = 0.01f;
			RenderSettings.fogStartDistance = 0.01f;
		}
		SemiFunc.PlayerCameraVisibilityRefresh();
	}

	private static void ApplyHide(PlayerAvatar target)
	{
		if (!GhostCamPlugin.HideWatchedModel.Value)
		{
			RestoreHidden();
			return;
		}
		if ((Object)(object)_hiddenTarget != (Object)(object)target)
		{
			RestoreHidden();
			_hiddenTarget = target;
		}
		PlayerAvatarVisuals playerAvatarVisuals = target.playerAvatarVisuals;
		if ((Object)(object)playerAvatarVisuals != (Object)null && (Object)(object)playerAvatarVisuals.meshParent != (Object)null && playerAvatarVisuals.meshParent.activeSelf)
		{
			if ((Object)(object)_savedMeshParent == (Object)null)
			{
				_savedMeshParent = playerAvatarVisuals.meshParent;
				_savedMeshParentActive = true;
			}
			playerAvatarVisuals.meshParent.SetActive(false);
		}
		if (_cachedRenderers == null)
		{
			_cachedRenderers = CollectHideableRenderers(target);
		}
		Renderer[] cachedRenderers = _cachedRenderers;
		foreach (Renderer val in cachedRenderers)
		{
			if ((Object)(object)val != (Object)null && val.enabled)
			{
				val.enabled = false;
			}
		}
	}

	private static Renderer[] CollectHideableRenderers(PlayerAvatar target)
	{
		List<Renderer> list = new List<Renderer>(64);
		AppendRenderers(((Component)target).gameObject, target, list);
		PlayerAvatarVisuals playerAvatarVisuals = target.playerAvatarVisuals;
		if ((Object)(object)playerAvatarVisuals != (Object)null && (Object)(object)playerAvatarVisuals.animBotRoot != (Object)null && !playerAvatarVisuals.animBotRoot.transform.IsChildOf(((Component)target).transform))
		{
			AppendRenderers(playerAvatarVisuals.animBotRoot, target, list);
		}
		return list.ToArray();
	}

	private static void AppendRenderers(GameObject root, PlayerAvatar target, List<Renderer> keep)
	{
		Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>(true);
		FlashlightController flashlightController = target.flashlightController;
		foreach (Renderer val in componentsInChildren)
		{
			if (!((Object)(object)val == (Object)null) && !keep.Contains(val) && !(val is LineRenderer) && (!((Object)(object)flashlightController != (Object)null) || (!((Object)(object)val == (Object)(object)flashlightController.mesh) && !((Object)(object)val == (Object)(object)flashlightController.meshShadows))))
			{
				if (!SavedEnabled.ContainsKey(val))
				{
					SavedEnabled[val] = val.enabled;
				}
				keep.Add(val);
			}
		}
	}

	internal static void RestoreHidden()
	{
		if ((Object)(object)_savedMeshParent != (Object)null)
		{
			_savedMeshParent.SetActive(_savedMeshParentActive);
			_savedMeshParent = null;
			_savedMeshParentActive = false;
		}
		if (SavedEnabled.Count > 0)
		{
			foreach (KeyValuePair<Renderer, bool> item in SavedEnabled)
			{
				if ((Object)(object)item.Key != (Object)null)
				{
					item.Key.enabled = item.Value;
				}
			}
			SavedEnabled.Clear();
		}
		_hiddenTarget = null;
		_cachedRenderers = null;
	}
}
[HarmonyPatch(typeof(SpectateCamera), "StopSpectate")]
internal static class StopSpectatePatch
{
	private static void Postfix()
	{
		SpectateLateUpdatePatch.RestoreHidden();
		GhostCamPlugin.FirstPerson = false;
		GhostCamPlugin.LastInstance = null;
	}
}
[HarmonyPatch(typeof(SpectateCamera), "PlayerSwitch")]
internal static class PlayerSwitchPatch
{
	private static bool Prefix(SpectateCamera __instance)
	{
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		if (!GhostCamPlugin.SuppressSwitchOnToggle.Value)
		{
			return true;
		}
		if (!GhostCamPlugin.Enabled.Value)
		{
			return true;
		}
		if ((Object)(object)SpectateLateUpdatePatch.GetWatchedPlayer(__instance) == (Object)null)
		{
			return true;
		}
		KeyboardShortcut value = GhostCamPlugin.ToggleKey.Value;
		return !((KeyboardShortcut)(ref value)).IsDown();
	}
}