Decompiled source of TickSpawner v0.1.3

BepInEx\plugins\TickSpawner\TickSpawner.dll

Decompiled 11 hours ago
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Photon.Pun;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TextCore;
using UnityEngine.UI;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace TickSpawner;

internal static class HuntKeyboardCompatibility
{
	private static Harmony harmony;

	private static MethodInfo cancel;

	private static FieldInfo picker;

	internal static void Install(ManualLogSource log)
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		try
		{
			Type type = AccessTools.TypeByName("HuntMod.Runtime.NativeCardInput");
			if (!(type == null))
			{
				MethodInfo methodInfo = AccessTools.Method(type, "Update", (Type[])null, (Type[])null);
				if (!(methodInfo == null))
				{
					cancel = AccessTools.Method(type, "CancelHold", (Type[])null, (Type[])null);
					picker = AccessTools.Field(type, "picker");
					harmony = new Harmony("local.peak.tickspawner.keyboard");
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(HuntKeyboardCompatibility), "Prefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					log.LogInfo((object)"[tick-spawner] Hunt optional keyboard compatibility active; no files modified.");
				}
			}
		}
		catch (Exception ex)
		{
			log.LogWarning((object)("[tick-spawner] optional Hunt keyboard compatibility unavailable: " + ex.Message));
		}
	}

	private static bool Prefix(object __instance)
	{
		if (!TickSpawnerPlugin.KeyboardReserved)
		{
			return true;
		}
		if (cancel != null)
		{
			cancel.Invoke(__instance, null);
		}
		object obj = ((picker == null) ? null : picker.GetValue(__instance));
		if (obj != null)
		{
			MethodInfo methodInfo = AccessTools.Method(obj.GetType(), "Close", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				methodInfo.Invoke(obj, null);
			}
		}
		return false;
	}

	internal static void Remove()
	{
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		harmony = null;
	}
}
internal sealed class TickPanel
{
	private const int PageSize = 8;

	private readonly Transform parent;

	private GameObject root;

	private GameObject board;

	private RectTransform frame;

	private RectTransform background;

	private TextMeshProUGUI title;

	private TextMeshProUGUI keys;

	private TextMeshProUGUI footer;

	private TextMeshProUGUI toast;

	private readonly List<TextMeshProUGUI> rows = new List<TextMeshProUGUI>();

	private Sprite round;

	private Texture2D texture;

	private TMP_FontAsset font;

	private float nextFont;

	internal TickPanel(Transform parent)
	{
		this.parent = parent;
	}

	private TMP_FontAsset Font()
	{
		if (Time.unscaledTime < nextFont && (Object)(object)font != (Object)null)
		{
			return font;
		}
		nextFont = Time.unscaledTime + 0.5f;
		TMP_FontAsset val = font;
		int num = Rank(val);
		TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
		foreach (TMP_FontAsset val2 in array)
		{
			if ((Object)(object)val2 != (Object)null && Rank(val2) > num)
			{
				val = val2;
				num = Rank(val2);
			}
		}
		if ((Object)(object)val == (Object)null && (Object)(object)GUIManager.instance != (Object)null && (Object)(object)GUIManager.instance.interactPromptText != (Object)null)
		{
			val = ((TMP_Text)GUIManager.instance.interactPromptText).font;
		}
		font = val;
		return font;
	}

	private static int Rank(TMP_FontAsset value)
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: 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)
		if ((Object)(object)value == (Object)null)
		{
			return 0;
		}
		string text = ((Object)value).name.Replace(" ", "").Replace("-", "").ToLowerInvariant();
		FaceInfo faceInfo = ((TMP_Asset)value).faceInfo;
		if ((((FaceInfo)(ref faceInfo)).familyName ?? "").Replace(" ", "").ToLowerInvariant() == "notosanssc")
		{
			FaceInfo faceInfo2 = ((TMP_Asset)value).faceInfo;
			if ((((FaceInfo)(ref faceInfo2)).styleName ?? "").ToLowerInvariant() == "bold")
			{
				return 3;
			}
		}
		if (!(text == "notosansscboldsdf"))
		{
			return 0;
		}
		return 2;
	}

	private bool Ensure()
	{
		//IL_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Expected O, but got Unknown
		//IL_00b9: 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_00f6: Expected O, but got Unknown
		//IL_0123: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: 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_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_020e: Unknown result type (might be due to invalid IL or missing references)
		//IL_021d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0320: Unknown result type (might be due to invalid IL or missing references)
		//IL_032f: 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_0375: Unknown result type (might be due to invalid IL or missing references)
		//IL_0376: Unknown result type (might be due to invalid IL or missing references)
		//IL_037d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0399: Unknown result type (might be due to invalid IL or missing references)
		TMP_FontAsset val = Font();
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		if ((Object)(object)root != (Object)null)
		{
			return true;
		}
		root = new GameObject("TickSpawner_UI", new Type[3]
		{
			typeof(RectTransform),
			typeof(Canvas),
			typeof(CanvasScaler)
		});
		root.transform.SetParent(parent, false);
		Canvas component = root.GetComponent<Canvas>();
		component.renderMode = (RenderMode)0;
		component.sortingOrder = 30100;
		CanvasScaler component2 = root.GetComponent<CanvasScaler>();
		component2.uiScaleMode = (ScaleMode)1;
		component2.referenceResolution = new Vector2(1920f, 1080f);
		component2.matchWidthOrHeight = 0.5f;
		board = new GameObject("Picker", new Type[1] { typeof(RectTransform) });
		board.transform.SetParent(root.transform, false);
		frame = Rect(board.transform, "Frame", Vector2.zero, new Vector2(620f, 300f), centered: true);
		Image val2 = ((Component)frame).gameObject.AddComponent<Image>();
		val2.sprite = Round();
		val2.type = (Type)1;
		((Graphic)val2).color = Color.white;
		((Graphic)val2).raycastTarget = false;
		background = Rect(board.transform, "Green", Vector2.zero, new Vector2(610f, 290f), centered: true);
		Image val3 = ((Component)background).gameObject.AddComponent<Image>();
		val3.sprite = round;
		val3.type = (Type)1;
		((Graphic)val3).color = new Color(0.1f, 0.45f, 0.2f, 0.95f);
		((Graphic)val3).raycastTarget = false;
		title = Text((Transform)(object)background, "Title", new Vector2(24f, -20f), new Vector2(562f, 34f), 26);
		((TMP_Text)title).text = "蜱虫 · 选择目标";
		keys = Text((Transform)(object)background, "Keys", new Vector2(24f, -60f), new Vector2(562f, 28f), 21);
		((TMP_Text)keys).text = "↑↓ 选择    Enter 生成    N 关闭";
		for (int i = 0; i < 8; i++)
		{
			rows.Add(Text((Transform)(object)background, "Player_" + i, new Vector2(30f, (float)(-104 - i * 36)), new Vector2(550f, 32f), 21));
		}
		footer = Text((Transform)(object)background, "Footer", Vector2.zero, new Vector2(562f, 28f), 18);
		toast = Text(root.transform, "Notice", Vector2.zero, new Vector2(1400f, 52f), 24);
		((TMP_Text)toast).alignment = (TextAlignmentOptions)514;
		RectTransform rectTransform = ((TMP_Text)toast).rectTransform;
		Vector2 anchorMin = (((TMP_Text)toast).rectTransform.anchorMax = new Vector2(0.5f, 0.18f));
		rectTransform.anchorMin = anchorMin;
		((TMP_Text)toast).rectTransform.pivot = new Vector2(0.5f, 0.5f);
		board.SetActive(false);
		((Component)toast).gameObject.SetActive(false);
		return true;
	}

	internal void Show(List<Character> targets, int selected)
	{
		//IL_0050: 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_01df: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		if (!Ensure())
		{
			return;
		}
		board.SetActive(true);
		int num = selected / 8 * 8;
		int num2 = Mathf.Min(8, targets.Count - num);
		int num3 = Mathf.Max(1, num2);
		float num4 = 152 + num3 * 36;
		frame.sizeDelta = new Vector2(620f, num4 + 10f);
		background.sizeDelta = new Vector2(610f, num4);
		for (int i = 0; i < rows.Count; i++)
		{
			bool flag = i < num3;
			((Component)rows[i]).gameObject.SetActive(flag);
			if (flag)
			{
				int num5 = num + i;
				bool flag2 = targets.Count > 0 && num5 == selected;
				if (targets.Count == 0)
				{
					((TMP_Text)rows[i]).text = "暂无已加载的存活角色";
				}
				else
				{
					Character val = targets[num5];
					((TMP_Text)rows[i]).text = (flag2 ? "▶  " : "     ") + TickSpawnService.Name(val) + (((Object)(object)val == (Object)(object)Character.localCharacter) ? "(自己)" : "") + "    蜱虫 " + TickSpawnService.Count(val) + "只";
				}
				((Graphic)rows[i]).color = (Color)(flag2 ? Color.white : new Color(1f, 1f, 1f, 0.6f));
				ApplyFont((TMP_Text)(object)rows[i]);
			}
		}
		((TMP_Text)footer).rectTransform.anchoredPosition = new Vector2(24f, (float)(-112 - num3 * 36));
		((TMP_Text)footer).text = ((targets.Count == 0) ? "存活角色加载后会自动列出" : ("每次确认生成1只 · " + (selected + 1) + " / " + targets.Count));
		ApplyFont((TMP_Text)(object)title);
		ApplyFont((TMP_Text)(object)keys);
		ApplyFont((TMP_Text)(object)footer);
	}

	internal void Hide()
	{
		if ((Object)(object)board != (Object)null)
		{
			board.SetActive(false);
		}
	}

	internal void ShowNotice(string text, bool visible)
	{
		if (!visible)
		{
			if ((Object)(object)toast != (Object)null)
			{
				((Component)toast).gameObject.SetActive(false);
			}
		}
		else if (Ensure())
		{
			((TMP_Text)toast).text = text;
			ApplyFont((TMP_Text)(object)toast);
			((Component)toast).gameObject.SetActive(true);
		}
	}

	private void ApplyFont(TMP_Text label)
	{
		if (!((Object)(object)font == (Object)null))
		{
			if ((Object)(object)label.font != (Object)(object)font || (Object)(object)label.fontSharedMaterial == (Object)null || (Object)(object)label.fontSharedMaterial.mainTexture != (Object)(object)((TMP_Asset)font).material.mainTexture)
			{
				label.font = font;
				label.fontSharedMaterial = ((TMP_Asset)font).material;
			}
			label.fontStyle = (FontStyles)0;
			label.fontWeight = (FontWeight)400;
		}
	}

	private TextMeshProUGUI Text(Transform ancestor, string name, Vector2 position, Vector2 size, int points)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		TextMeshProUGUI val = ((Component)Rect(ancestor, name, position, size, centered: false)).gameObject.AddComponent<TextMeshProUGUI>();
		ApplyFont((TMP_Text)(object)val);
		((TMP_Text)val).fontSize = points;
		((TMP_Text)val).richText = false;
		((Graphic)val).raycastTarget = false;
		((TMP_Text)val).textWrappingMode = (TextWrappingModes)0;
		((TMP_Text)val).overflowMode = (TextOverflowModes)1;
		((Graphic)val).color = Color.white;
		((TMP_Text)val).alignment = (TextAlignmentOptions)513;
		return val;
	}

	private static RectTransform Rect(Transform ancestor, string name, Vector2 position, Vector2 size, bool centered)
	{
		//IL_0016: 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_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: 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_0057: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: 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_0066: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		RectTransform component = new GameObject(name, new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
		((Transform)component).SetParent(ancestor, false);
		Vector2 val = (component.pivot = (centered ? new Vector2(0.5f, 0.5f) : new Vector2(0f, 1f)));
		Vector2 anchorMin = (component.anchorMax = val);
		component.anchorMin = anchorMin;
		component.anchoredPosition = position;
		component.sizeDelta = size;
		return component;
	}

	private Sprite Round()
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Expected O, but got Unknown
		//IL_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: 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_00e1: 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)
		if ((Object)(object)round != (Object)null)
		{
			return round;
		}
		texture = new Texture2D(64, 64, (TextureFormat)4, false);
		((Texture)texture).wrapMode = (TextureWrapMode)1;
		((Texture)texture).filterMode = (FilterMode)1;
		Color32[] array = (Color32[])(object)new Color32[4096];
		for (int i = 0; i < 64; i++)
		{
			for (int j = 0; j < 64; j++)
			{
				float num = Mathf.Max(Mathf.Abs((float)j + 0.5f - 32f) - 12f, 0f);
				float num2 = Mathf.Max(Mathf.Abs((float)i + 0.5f - 32f) - 12f, 0f);
				ref Color32 reference = ref array[i * 64 + j];
				reference = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, (byte)(Mathf.Clamp01(20f - Mathf.Sqrt(num * num + num2 * num2) + 0.5f) * 255f));
			}
		}
		texture.SetPixels32(array);
		texture.Apply(false, true);
		round = Sprite.Create(texture, new Rect(0f, 0f, 64f, 64f), new Vector2(0.5f, 0.5f), 100f, 0u, (SpriteMeshType)0, new Vector4(20f, 20f, 20f, 20f));
		return round;
	}

	internal void Dispose()
	{
		if ((Object)(object)root != (Object)null)
		{
			Object.Destroy((Object)(object)root);
		}
		if ((Object)(object)round != (Object)null)
		{
			Object.Destroy((Object)(object)round);
		}
		if ((Object)(object)texture != (Object)null)
		{
			Object.Destroy((Object)(object)texture);
		}
	}
}
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("local.peak.tickspawner", "Tick Spawner", "0.1.1")]
public sealed class TickSpawnerPlugin : BaseUnityPlugin
{
	internal static TickSpawnerPlugin Instance;

	internal bool PanelOpen;

	private TickPanel panel;

	private TickSpawnService service;

	private readonly List<Character> targets = new List<Character>();

	private int selectedView;

	private int handledFrame = -1;

	private object room;

	private float noticeUntil;

	private string message = "";

	internal static bool KeyboardReserved
	{
		get
		{
			if ((Object)(object)Instance != (Object)null && ((Behaviour)Instance).isActiveAndEnabled)
			{
				if (!Instance.PanelOpen && Instance.handledFrame != Time.frameCount)
				{
					if (!BlockedInput())
					{
						return Input.GetKeyDown((KeyCode)98);
					}
					return false;
				}
				return true;
			}
			return false;
		}
	}

	private void Awake()
	{
		Instance = this;
		panel = new TickPanel(((Component)this).transform);
		service = new TickSpawnService(Notice, delegate(string value)
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)("[tick-spawner] " + value));
		});
		HuntKeyboardCompatibility.Install(((BaseUnityPlugin)this).Logger);
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Tick Spawner 0.1.1 ready. N / Up / Down / Enter. Uses native BugfixOnYou networking; no host requirement.");
	}

	private static bool BlockedInput()
	{
		if ((Object)(object)GUIManager.instance == (Object)null)
		{
			return true;
		}
		if (GUIManager.InPauseMenu)
		{
			return true;
		}
		if ((Object)(object)GUIManager.instance != (Object)null && (GUIManager.instance.windowBlockingInput || GUIManager.instance.windowShowingCursor))
		{
			return true;
		}
		GameObject val = (((Object)(object)EventSystem.current == (Object)null) ? null : EventSystem.current.currentSelectedGameObject);
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		InputField component = val.GetComponent<InputField>();
		TMP_InputField component2 = val.GetComponent<TMP_InputField>();
		if (!((Object)(object)component != (Object)null) || !component.isFocused)
		{
			if ((Object)(object)component2 != (Object)null)
			{
				return component2.isFocused;
			}
			return false;
		}
		return true;
	}

	private void Notice(string value)
	{
		message = value;
		noticeUntil = Time.unscaledTime + 5f;
		((BaseUnityPlugin)this).Logger.LogInfo((object)("[tick-spawner] " + value));
	}

	private void Update()
	{
		try
		{
			Tick();
		}
		catch (Exception ex)
		{
			Close();
			((BaseUnityPlugin)this).Logger.LogError((object)("[tick-spawner] update failed: " + ex));
		}
	}

	private void Tick()
	{
		service.Poll();
		if (!object.ReferenceEquals(room, PhotonNetwork.CurrentRoom))
		{
			room = PhotonNetwork.CurrentRoom;
			Close();
			selectedView = 0;
			message = "";
		}
		if (!PhotonNetwork.InRoom || (Object)(object)Character.localCharacter == (Object)null)
		{
			Close();
			panel.ShowNotice("", visible: false);
			return;
		}
		if (BlockedInput())
		{
			Close();
			panel.ShowNotice("", visible: false);
			return;
		}
		if (Input.GetKeyDown((KeyCode)110))
		{
			handledFrame = Time.frameCount;
			PanelOpen = !PanelOpen;
			if (!PanelOpen)
			{
				Close();
				return;
			}
		}
		if (PanelOpen)
		{
			handledFrame = Time.frameCount;
			if (Input.GetKeyDown((KeyCode)27))
			{
				Close();
				return;
			}
			Rebuild();
			int num = targets.FindIndex((Character ch) => ((MonoBehaviourPun)ch).photonView.ViewID == selectedView);
			bool flag = selectedView != 0 && num < 0;
			if (num < 0)
			{
				num = 0;
			}
			if (targets.Count > 0)
			{
				if (Input.GetKeyDown((KeyCode)273))
				{
					num = (num + targets.Count - 1) % targets.Count;
				}
				if (Input.GetKeyDown((KeyCode)274))
				{
					num = (num + 1) % targets.Count;
				}
				selectedView = ((MonoBehaviourPun)targets[num]).photonView.ViewID;
				if (Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271))
				{
					if (flag)
					{
						Notice("刚才的目标已失效,请重新选择后确认");
					}
					else
					{
						service.Request(targets[num]);
						Close();
					}
				}
			}
			else
			{
				selectedView = 0;
			}
			if (PanelOpen)
			{
				panel.Show(targets, num);
			}
		}
		else
		{
			panel.Hide();
		}
		panel.ShowNotice(message, Time.unscaledTime < noticeUntil);
	}

	private void Rebuild()
	{
		targets.Clear();
		foreach (Character allCharacter in Character.AllCharacters)
		{
			if (TickSpawnService.Eligible(allCharacter) && !targets.Contains(allCharacter))
			{
				targets.Add(allCharacter);
			}
		}
		targets.Sort(delegate(Character a, Character b)
		{
			bool flag = (Object)(object)a == (Object)(object)Character.localCharacter;
			bool flag2 = (Object)(object)b == (Object)(object)Character.localCharacter;
			if (flag != flag2)
			{
				if (!flag)
				{
					return 1;
				}
				return -1;
			}
			int num = ((MonoBehaviourPun)a).photonView.OwnerActorNr.CompareTo(((MonoBehaviourPun)b).photonView.OwnerActorNr);
			return (num == 0) ? ((MonoBehaviourPun)a).photonView.ViewID.CompareTo(((MonoBehaviourPun)b).photonView.ViewID) : num;
		});
	}

	private void Close()
	{
		PanelOpen = false;
		if (panel != null)
		{
			panel.Hide();
		}
	}

	private void OnDisable()
	{
		Close();
		if (panel != null)
		{
			panel.ShowNotice("", visible: false);
		}
	}

	private void OnDestroy()
	{
		Close();
		HuntKeyboardCompatibility.Remove();
		if (panel != null)
		{
			panel.Dispose();
		}
		if ((Object)(object)Instance == (Object)(object)this)
		{
			Instance = null;
		}
	}
}
internal sealed class TickSpawnService
{
	private sealed class Pending
	{
		internal object Room;

		internal Character Target;

		internal int ViewId;

		internal Bugfix Bug;

		internal GameObject Object;

		internal float Expires;

		internal string Name;
	}

	private readonly List<Pending> pending = new List<Pending>();

	private static readonly MethodInfo NativeLeg = typeof(Character).GetMethod("GetBodypartRig", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

	private readonly Action<string> notice;

	private readonly Action<string> log;

	internal TickSpawnService(Action<string> notice, Action<string> log)
	{
		this.notice = notice;
		this.log = log;
	}

	internal static bool Eligible(Character target)
	{
		if (!PhotonNetwork.InRoom || PhotonNetwork.CurrentRoom == null || (Object)(object)target == (Object)null || (Object)(object)target.data == (Object)null || target.data.dead || target.warping)
		{
			return false;
		}
		PhotonView photonView = ((MonoBehaviourPun)target).photonView;
		if ((Object)(object)photonView == (Object)null || photonView.ViewID <= 0 || photonView.Owner == null || !PhotonNetwork.CurrentRoom.Players.ContainsKey(photonView.OwnerActorNr) || (Object)(object)PhotonView.Find(photonView.ViewID) != (Object)(object)photonView || NativeLeg == null)
		{
			return false;
		}
		try
		{
			object? obj = NativeLeg.Invoke(target, new object[1] { (object)(BodypartType)15 });
			return (Object)((obj is Rigidbody) ? obj : null) != (Object)null;
		}
		catch
		{
			return false;
		}
	}

	internal static string Name(Character target)
	{
		if ((Object)(object)target == (Object)null || (Object)(object)((MonoBehaviourPun)target).photonView == (Object)null)
		{
			return "未知玩家";
		}
		string text = ((((MonoBehaviourPun)target).photonView.Owner == null) ? null : ((MonoBehaviourPun)target).photonView.Owner.NickName);
		if (!string.IsNullOrEmpty(text))
		{
			return text;
		}
		return "玩家 " + ((MonoBehaviourPun)target).photonView.OwnerActorNr;
	}

	internal static int Count(Character target)
	{
		int num = 0;
		foreach (KeyValuePair<Bugfix, Character> allAttachedBug in Bugfix.AllAttachedBugs)
		{
			if ((Object)(object)allAttachedBug.Key != (Object)null && (Object)(object)allAttachedBug.Value == (Object)(object)target)
			{
				num++;
			}
		}
		return num;
	}

	internal bool Request(Character target)
	{
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		if (Bugfix.AllAttachedBugs.Count != 0)
		{
			notice("已经有一只蜱虫了,无法继续添加新的");
			return false;
		}
		if (!Eligible(target))
		{
			notice("目标已离开、死亡或尚未加载,未生成蜱虫");
			return false;
		}
		GameObject val = null;
		object currentRoom = PhotonNetwork.CurrentRoom;
		try
		{
			int viewID = ((MonoBehaviourPun)target).photonView.ViewID;
			val = PhotonNetwork.Instantiate("BugfixOnYou", Vector3.zero, Quaternion.identity, (byte)0, (object[])null);
			Bugfix val2 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<Bugfix>());
			PhotonView val3 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<PhotonView>());
			if ((Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null || !val3.IsMine || (int)val3.Synchronization == 0 || val3.ObservedComponents == null || !val3.ObservedComponents.Contains((Component)(object)val2))
			{
				throw new InvalidOperationException("原生蜱虫或Photon同步组件未就绪");
			}
			if (!object.ReferenceEquals(currentRoom, PhotonNetwork.CurrentRoom) || !Eligible(target) || ((MonoBehaviourPun)target).photonView.ViewID != viewID)
			{
				throw new InvalidOperationException("生成期间目标已失效");
			}
			val2.AttachBug(viewID);
			pending.Add(new Pending
			{
				Room = PhotonNetwork.CurrentRoom,
				Target = target,
				ViewId = viewID,
				Bug = val2,
				Object = val,
				Expires = Time.unscaledTime + 4f,
				Name = Name(target)
			});
			log("spawn_requested target_actor=" + ((MonoBehaviourPun)target).photonView.OwnerActorNr + " target_view=" + viewID + " tick_view=" + val3.ViewID + " is_host=" + PhotonNetwork.IsMasterClient + " observed_bugfix=true");
			notice("正在给 " + Name(target) + " 生成蜱虫…");
			return true;
		}
		catch (Exception ex)
		{
			DestroyOwned(val, currentRoom);
			log("spawn_failed: " + ex);
			notice("蜱虫生成失败:" + ex.Message);
			return false;
		}
	}

	internal void Poll()
	{
		for (int num = this.pending.Count - 1; num >= 0; num--)
		{
			Pending pending = this.pending[num];
			Character value;
			if (!PhotonNetwork.InRoom || !object.ReferenceEquals(pending.Room, PhotonNetwork.CurrentRoom))
			{
				this.pending.RemoveAt(num);
			}
			else if ((Object)(object)pending.Bug == (Object)null || !Eligible(pending.Target) || ((MonoBehaviourPun)pending.Target).photonView.ViewID != pending.ViewId)
			{
				DestroyOwned(pending.Object, pending.Room);
				this.pending.RemoveAt(num);
				notice("目标失效,已取消这次蜱虫生成");
			}
			else if (Bugfix.AllAttachedBugs.TryGetValue(pending.Bug, out value) && (Object)(object)value == (Object)(object)pending.Target)
			{
				this.pending.RemoveAt(num);
				log("local_attachment_verified target_view=" + pending.ViewId + "; remote receipt is not measured");
				notice("已给 " + pending.Name + " 生成蜱虫(当前 " + Count(pending.Target) + " 只)");
			}
			else if (Time.unscaledTime >= pending.Expires)
			{
				DestroyOwned(pending.Object, pending.Room);
				this.pending.RemoveAt(num);
				log("attachment_timeout target_view=" + pending.ViewId);
				notice("附着超时,已移除本次未成功的蜱虫");
			}
		}
	}

	private static void DestroyOwned(GameObject spawned, object expectedRoom)
	{
		if (!((Object)(object)spawned == (Object)null) && PhotonNetwork.InRoom && object.ReferenceEquals(expectedRoom, PhotonNetwork.CurrentRoom))
		{
			PhotonView component = spawned.GetComponent<PhotonView>();
			if ((Object)(object)component != (Object)null && component.IsMine)
			{
				PhotonNetwork.Destroy(spawned);
			}
		}
	}
}