Decompiled source of No Blocking Ally v1.0.0

NoBlockingAlly.dll

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

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("NoBlockingAlly")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("NoBlockingAlly")]
[assembly: AssemblyTitle("NoBlockingAlly")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace NoBlockingAlly;

[HarmonyPatch]
internal class AllyPusher : MonoBehaviour
{
	private struct Approach
	{
		public float Time;

		public Vector3 Direction;
	}

	private struct Push
	{
		public Vector3 Aside;

		public float Since;

		public float Until;
	}

	private const float Reach = 4f;

	private const float MaxHeightDifference = 1.5f;

	private const float ApproachMemory = 0.5f;

	private const float ApproachSpeed = 0.5f;

	private const float ApproachCosine = 0.5f;

	private const float IntentThreshold = 0.3f;

	private const float TeleportSpeed = 20f;

	internal static bool Vanilla;

	internal static Action<Character, Character, Vector3> Pushed;

	private const float RepushDelay = 0.5f;

	private static readonly Dictionary<CharacterAI, Push> s_pushes = new Dictionary<CharacterAI, Push>();

	private readonly Dictionary<(int player, int ally), Approach> m_approaches = new Dictionary<(int, int), Approach>();

	private readonly Dictionary<Character, Vector3> m_lastPositions = new Dictionary<Character, Vector3>();

	private List<Character> m_near = new List<Character>();

	private float m_nextPrune;

	private const float PushedSpeed = 1f;

	internal static bool IsPushed(Character c)
	{
		if ((Object)(object)c != (Object)null)
		{
			CharacterControl characterControl = c.CharacterControl;
			CharacterAI val = (CharacterAI)(object)((characterControl is CharacterAI) ? characterControl : null);
			if (val != null && s_pushes.TryGetValue(val, out var value))
			{
				return Time.time < value.Until;
			}
		}
		return false;
	}

	private void Update()
	{
		if (Time.time >= m_nextPrune)
		{
			Prune();
		}
		NetworkLevelLoader instance = NetworkLevelLoader.Instance;
		CharacterManager instance2 = CharacterManager.Instance;
		LobbySystem lobby = Global.Lobby;
		if (Vanilla || PhotonNetwork.isNonMasterClientInRoom || (Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || (Object)(object)lobby == (Object)null || !instance.IsOverallLoadingDone || instance.IsGameplayLoading || instance.IsGameplayPaused)
		{
			m_lastPositions.Clear();
			return;
		}
		float deltaTime = Time.deltaTime;
		if (deltaTime <= 0f)
		{
			return;
		}
		List<PlayerSystem> playersInLobby = lobby.PlayersInLobby;
		int num = 0;
		while (playersInLobby != null && num < playersInLobby.Count)
		{
			PlayerSystem obj = playersInLobby[num];
			Character val = ((obj != null) ? obj.ControlledCharacter : null);
			if (!((Object)(object)val == (Object)null) && val.Alive && ((Component)val).gameObject.activeInHierarchy)
			{
				try
				{
					CheckPlayer(val, instance2, deltaTime);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"push check failed for {val.Name}: {arg}");
					m_lastPositions.Remove(val);
				}
			}
			num++;
		}
	}

	private void CheckPlayer(Character player, CharacterManager manager, float dt)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: 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_0039: 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)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: 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_005f: 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_0097: 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)
		Vector3 position = ((Component)player).transform.position;
		if (!m_lastPositions.TryGetValue(player, out var value))
		{
			m_lastPositions[player] = position;
			return;
		}
		m_lastPositions[player] = position;
		Vector3 velocity = (position - value) / dt;
		velocity.y = 0f;
		if (((Vector3)(ref velocity)).magnitude > 20f)
		{
			velocity = Vector3.zero;
		}
		manager.FindCharactersInRange(position, 4f, ref m_near);
		for (int i = 0; i < m_near.Count; i++)
		{
			Character val = m_near[i];
			if (IsAlly(val, player))
			{
				Check(player, val, position, velocity);
			}
		}
	}

	internal static bool IsAlly(Character c, Character player)
	{
		//IL_0030: 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)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)c != (Object)null && (Object)(object)c != (Object)(object)player && c.IsAI && c.Alive && ((Component)c).gameObject.activeInHierarchy && c.Faction == player.Faction && (int)c.Faction != 0)
		{
			CharacterControl characterControl = c.CharacterControl;
			CharacterAI val = (CharacterAI)(object)((characterControl is CharacterAI) ? characterControl : null);
			if (val != null && ((Behaviour)val).enabled)
			{
				return (Object)(object)((Component)c).GetComponent("CompanionKeeper") == (Object)null;
			}
		}
		return false;
	}

	private void Check(Character player, Character ally, Vector3 position, Vector3 velocity)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: 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_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: 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_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: 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_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0137: 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_0155: 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_018c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f1: Expected O, but got Unknown
		//IL_021c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0221: Unknown result type (might be due to invalid IL or missing references)
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		//IL_0229: Unknown result type (might be due to invalid IL or missing references)
		//IL_0238: Unknown result type (might be due to invalid IL or missing references)
		//IL_023d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: 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_0257: Unknown result type (might be due to invalid IL or missing references)
		//IL_0288: Unknown result type (might be due to invalid IL or missing references)
		//IL_030b: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = ((Component)ally).transform.position - position;
		if (Mathf.Abs(val.y) > 1.5f)
		{
			return;
		}
		val.y = 0f;
		if (((Vector3)(ref val)).sqrMagnitude < 0.0001f)
		{
			return;
		}
		float num = (((Object)(object)player.CharacterController != (Object)null) ? player.CharacterController.radius : 0.4f) + (((Object)(object)ally.CharacterController != (Object)null) ? ally.CharacterController.radius : 0.5f);
		float num2 = ((Vector3)(ref val)).magnitude - num;
		(int, int) key = (((Object)player).GetInstanceID(), ((Object)ally).GetInstanceID());
		if (((Vector3)(ref velocity)).magnitude > 0.5f && Vector3.Dot(((Vector3)(ref velocity)).normalized, ((Vector3)(ref val)).normalized) > 0.5f)
		{
			m_approaches[key] = new Approach
			{
				Time = Time.time,
				Direction = ((Vector3)(ref velocity)).normalized
			};
		}
		else if (num2 < Plugin.PushGap.Value)
		{
			Vector2 animMove = player.AnimMove;
			Vector3 val2 = ((Component)player).transform.TransformDirection(new Vector3(animMove.x, 0f, animMove.y));
			val2.y = 0f;
			if (((Vector3)(ref val2)).magnitude > 0.3f && Vector3.Dot(((Vector3)(ref val2)).normalized, ((Vector3)(ref val)).normalized) > 0.5f)
			{
				m_approaches[key] = new Approach
				{
					Time = Time.time,
					Direction = ((Vector3)(ref val2)).normalized
				};
			}
		}
		if (!(num2 < Plugin.PushGap.Value) || !m_approaches.TryGetValue(key, out var value) || !(Time.time - value.Time < 0.5f))
		{
			return;
		}
		m_approaches.Remove(key);
		CharacterAI val3 = (CharacterAI)ally.CharacterControl;
		if (!s_pushes.TryGetValue(val3, out var value2) || !(Time.time - value2.Since < 0.5f))
		{
			Vector3 val4 = ((Component)ally).transform.position + AsideDirection(val, value.Direction) * Plugin.StepAsideDistance.Value;
			s_pushes[val3] = new Push
			{
				Aside = val4,
				Since = Time.time,
				Until = Time.time + Plugin.StepAsideTime.Value
			};
			val3.SetDestination(val4, false);
			if (Plugin.LogPushes.Value)
			{
				Plugin.Log.LogMessage((object)$"{player.Name} pushes {ally.Name} ({((Object)ally).name}, {((object)val3.CurrentAiState)?.GetType().Name}) aside, gap {num2:F2} m, to {val4}");
			}
			Pushed?.Invoke(player, ally, val4);
		}
	}

	internal static Vector3 AsideDirection(Vector3 toAlly, Vector3 walk)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: 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_0054: 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_005f: 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_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: 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)
		walk.y = 0f;
		((Vector3)(ref walk)).Normalize();
		Vector3 val = toAlly - Vector3.Dot(toAlly, walk) * walk;
		val.y = 0f;
		if (((Vector3)(ref val)).magnitude < 0.2f)
		{
			val = Vector3.Cross(Vector3.up, walk);
		}
		Vector3 val2 = ((Vector3)(ref val)).normalized + walk * 0.5f;
		return ((Vector3)(ref val2)).normalized;
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(CharacterAI), "SetDestination")]
	private static void KeepAside(CharacterAI __instance, ref Vector3 _position)
	{
		//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)
		if (s_pushes.Count != 0 && s_pushes.TryGetValue(__instance, out var value))
		{
			if (Time.time < value.Until)
			{
				_position = value.Aside;
			}
			else
			{
				s_pushes.Remove(__instance);
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(AISWander), "Update")]
	private static void StepBriskly(CharacterAI ___m_characterAI)
	{
		if (s_pushes.Count > 0 && (Object)(object)___m_characterAI != (Object)null && s_pushes.TryGetValue(___m_characterAI, out var value) && Time.time < value.Until && ___m_characterAI.SpeedModif < 1f)
		{
			___m_characterAI.SpeedModif = 1f;
		}
	}

	private void Prune()
	{
		m_nextPrune = Time.time + 10f;
		foreach (CharacterAI item in (from p in s_pushes
			where (Object)(object)p.Key == (Object)null || Time.time >= p.Value.Until
			select p.Key).ToList())
		{
			s_pushes.Remove(item);
		}
		foreach (var item2 in (from a in m_approaches
			where Time.time - a.Value.Time >= 0.5f
			select a.Key).ToList())
		{
			m_approaches.Remove(item2);
		}
		foreach (Character item3 in m_lastPositions.Keys.Where((Character c) => (Object)(object)c == (Object)null).ToList())
		{
			m_lastPositions.Remove(item3);
		}
	}
}
public class MeasureHarness : MonoBehaviour
{
	internal struct Point
	{
		public string Scene;

		public Vector3 Centre;

		public Vector3 Direction;

		public float Width;

		public bool Measure;
	}

	private const float LegTimeout = 12f;

	private static bool s_driving;

	private static Vector2 s_move;

	private static readonly FieldRef<LocalCharacterControl, Transform> s_horiControl = AccessTools.FieldRefAccess<LocalCharacterControl, Transform>("m_horiControl");

	private int m_pushes;

	public static void StartIfRequested(GameObject host)
	{
		if (UnityEngineExtensions.Contains<string>(Environment.GetCommandLineArgs(), "--nba-measure"))
		{
			host.AddComponent<MeasureHarness>();
		}
	}

	private static void Log(string s)
	{
		Plugin.Log.LogMessage((object)("nba-measure: " + s));
	}

	private static string Arg(string name)
	{
		string[] commandLineArgs = Environment.GetCommandLineArgs();
		int num = Array.IndexOf(commandLineArgs, name);
		if (num < 0 || num + 1 >= commandLineArgs.Length)
		{
			return null;
		}
		return commandLineArgs[num + 1];
	}

	internal static IEnumerator WaitRealtime(float seconds)
	{
		float end = Time.realtimeSinceStartup + seconds;
		while (Time.realtimeSinceStartup < end)
		{
			yield return null;
		}
	}

	private static Vector3 Flat(Vector3 v)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: 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)
		return new Vector3(v.x, 0f, v.z);
	}

	internal static void DriveMovement(ref Vector2 ___m_moveInput, ref Vector3 ___m_modifMoveInput)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		if (s_driving)
		{
			___m_moveInput = s_move;
			___m_modifMoveInput = Vector2.op_Implicit(s_move);
		}
	}

	internal static void Steer(Character character, Vector3 direction)
	{
		//IL_0017: 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)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: 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_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: 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_004e: 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_005d: Unknown result type (might be due to invalid IL or missing references)
		FieldRef<LocalCharacterControl, Transform> obj = s_horiControl;
		CharacterControl characterControl = character.CharacterControl;
		Transform val = obj.Invoke((LocalCharacterControl)(object)((characterControl is LocalCharacterControl) ? characterControl : null));
		Vector3 val2 = Flat(direction);
		Vector3 normalized = ((Vector3)(ref val2)).normalized;
		val2 = Flat(val.right);
		float num = Vector3.Dot(normalized, ((Vector3)(ref val2)).normalized);
		val2 = Flat(val.forward);
		s_move = new Vector2(num, Vector3.Dot(normalized, ((Vector3)(ref val2)).normalized));
	}

	internal static Character Player()
	{
		try
		{
			CharacterManager instance = CharacterManager.Instance;
			return (instance != null) ? instance.GetFirstLocalCharacter() : null;
		}
		catch (NullReferenceException)
		{
			return null;
		}
	}

	internal static bool Settled(string scene)
	{
		//IL_002f: 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)
		NetworkLevelLoader instance = NetworkLevelLoader.Instance;
		if ((Object)(object)Player() != (Object)null && (Object)(object)instance != (Object)null && instance.IsOverallLoadingDone && !instance.IsGameplayLoading)
		{
			if (scene != null)
			{
				Scene activeScene = SceneManager.GetActiveScene();
				return ((Scene)(ref activeScene)).name == scene;
			}
			return true;
		}
		return false;
	}

	internal static float PathLength(Vector3 from, Vector3 to, out NavMeshPath path)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: 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)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: 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)
		path = new NavMeshPath();
		NavMeshHit val = default(NavMeshHit);
		NavMeshHit val2 = default(NavMeshHit);
		if (!NavMesh.SamplePosition(from, ref val, 2f, -1) || !NavMesh.SamplePosition(to, ref val2, 2f, -1))
		{
			return -1f;
		}
		if (!NavMesh.CalculatePath(((NavMeshHit)(ref val)).position, ((NavMeshHit)(ref val2)).position, -1, path) || (int)path.status != 0)
		{
			return -1f;
		}
		float num = 0f;
		for (int i = 1; i < path.corners.Length; i++)
		{
			num += Vector3.Distance(path.corners[i - 1], path.corners[i]);
		}
		return num;
	}

	internal static Vector3? Side(Point p, float sign)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: 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_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: 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)
		//IL_006e: 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_0099: Unknown result type (might be due to invalid IL or missing references)
		float[] array = new float[4] { 3f, 2.5f, 2f, 1.5f };
		NavMeshHit val = default(NavMeshHit);
		foreach (float num in array)
		{
			if (NavMesh.SamplePosition(p.Centre + p.Direction * num * sign, ref val, 0.8f, -1) && Mathf.Abs(((NavMeshHit)(ref val)).position.y - p.Centre.y) < 1.5f)
			{
				NavMeshPath path;
				float num2 = PathLength(p.Centre, ((NavMeshHit)(ref val)).position, out path);
				if (num2 >= 0f && num2 < num * 1.5f)
				{
					return ((NavMeshHit)(ref val)).position;
				}
			}
		}
		return null;
	}

	private void Start()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Expected O, but got Unknown
		new Harmony("tchernobill.noblockingally.measure").Patch((MethodBase)AccessTools.Method(typeof(LocalCharacterControl), "DetectMovementInputs", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MeasureHarness), "DriveMovement", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		((MonoBehaviour)this).StartCoroutine(Run());
	}

	private IEnumerator Run()
	{
		AllyPusher.Pushed = (Action<Character, Character, Vector3>)Delegate.Combine(AllyPusher.Pushed, (Action<Character, Character, Vector3>)delegate
		{
			m_pushes++;
		});
		List<Point> points = new List<Point>();
		string[] array = File.ReadAllLines(Arg("--nba-measure"));
		foreach (string text in array)
		{
			string[] f = text.Split(new char[1] { ';' });
			if (f.Length >= 8)
			{
				Point item = new Point
				{
					Scene = f[0],
					Centre = new Vector3(F(1), F(2), F(3))
				};
				Vector3 val = new Vector3(F(4), 0f, F(5));
				item.Direction = ((Vector3)(ref val)).normalized;
				item.Width = F(6);
				item.Measure = f[7].Trim() == "1";
				points.Add(item);
			}
			float F(int i)
			{
				return float.Parse(f[i], CultureInfo.InvariantCulture);
			}
		}
		while (!Settled(null))
		{
			yield return WaitRealtime(1f);
		}
		yield return WaitRealtime(3f);
		MenuManager.Instance.MasterCanvas.alpha = 1f;
		foreach (IGrouping<string, Point> group in from point in points
			group point by point.Scene)
		{
			string scene = group.Key;
			NetworkLevelLoader.Instance.LoadLevel(scene, 0, 1.5f, false);
			float deadline = Time.realtimeSinceStartup + 180f;
			yield return WaitRealtime(5f);
			while (!Settled(scene) && Time.realtimeSinceStartup < deadline)
			{
				yield return WaitRealtime(1f);
			}
			if (!Settled(scene))
			{
				Log(scene + ": not loaded after 180 s, skipped");
				continue;
			}
			yield return WaitRealtime(3f);
			Character player = Player();
			player.Invincible = true;
			Vector3 arrival = ((Component)player).transform.position;
			Character ally = null;
			foreach (Point p in group)
			{
				Vector3? a = Side(p, -1f);
				Vector3? b = Side(p, 1f);
				NavMeshPath path;
				float num2 = ((!a.HasValue) ? (-1f) : PathLength(arrival, a.Value, out path));
				float num3 = ((!b.HasValue) ? (-1f) : PathLength(arrival, b.Value, out path));
				float num4 = ((!a.HasValue || !b.HasValue) ? (-1f) : PathLength(a.Value, b.Value, out path));
				bool flag = num2 >= 0f && num3 >= 0f && num4 >= 0f;
				Log(string.Format("reach {0} {1:F2} m at {2}: {3} (from the arrival: ", scene, p.Width, p.Centre, flag ? "REACHABLE" : "unreachable") + "side 1 " + ((num2 < 0f) ? "no path" : (num2.ToString("F0") + " m")) + ", side 2 " + ((num3 < 0f) ? "no path" : (num3.ToString("F0") + " m")) + "; through " + ((num4 < 0f) ? "no path" : (num4.ToString("F1") + " m")) + ")");
				if (flag && UnityEngineExtensions.Contains<string>(Environment.GetCommandLineArgs(), "--nba-measure-shots"))
				{
					yield return Shoot(player, a.Value, b.Value, $"{scene}_{p.Width:F2}_a");
					yield return Shoot(player, b.Value, a.Value, $"{scene}_{p.Width:F2}_b");
				}
				else
				{
					if (!p.Measure || !flag)
					{
						continue;
					}
					if ((Object)(object)ally == (Object)null || !ally.Alive)
					{
						player.Teleport(a.Value, ((Component)player).transform.rotation);
						yield return TestHarness.WaitGame(1f);
						yield return TestHarness.SummonAlly(player, delegate(Character c)
						{
							ally = c;
						});
						if ((Object)(object)ally == (Object)null)
						{
							Log(scene + ": no ally summoned");
							continue;
						}
					}
					List<string> results = new List<string>();
					for (int round = 0; round < 2; round++)
					{
						string[] array2 = new string[3] { "free", "vanilla", "mod" };
						foreach (string mode in array2)
						{
							float there = 0f;
							float back = 0f;
							int pushes = 0;
							yield return Take(player, ally, a.Value, b.Value, arrival, mode, delegate(float t1, float t2, int n)
							{
								there = t1;
								back = t2;
								pushes = n;
							});
							results.Add(string.Format("{0} {1:F1}/{2} s{3}", mode, there, (back < 0f) ? "stuck" : back.ToString("F1"), (pushes > 0) ? $" ({pushes} push)" : ""));
						}
					}
					Log($"measure {scene} {p.Width:F2} m at {p.Centre}: there/back: " + string.Join(", ", results));
				}
			}
		}
		AllyPusher.Vanilla = false;
		Log("done");
	}

	private static IEnumerator Shoot(Character player, Vector3 from, Vector3 to, string name)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = Flat(to - from);
		Vector3 dir = ((Vector3)(ref val)).normalized;
		player.Teleport(from - dir * 1f, Quaternion.LookRotation(dir));
		CharacterCamera camera = player.CharacterCamera;
		for (float t = 0f; t < 2.5f; t += Time.deltaTime)
		{
			((Component)camera).transform.rotation = Quaternion.LookRotation(dir);
			TestHarness.s_cameraPitch.Invoke(camera).localRotation = Quaternion.Euler(15f, 0f, 0f);
			yield return null;
		}
		yield return (object)new WaitForEndOfFrame();
		string text = Path.Combine(Paths.BepInExRootPath, "NoBlockingAllyScan", "spots");
		Directory.CreateDirectory(text);
		Texture2D val2 = ScreenCapture.CaptureScreenshotAsTexture();
		File.WriteAllBytes(Path.Combine(text, name + ".jpg"), ImageConversion.EncodeToJPG(val2, 85));
		Object.Destroy((Object)(object)val2);
		Log("picture " + name);
	}

	private IEnumerator Take(Character player, Character ally, Vector3 a, Vector3 b, Vector3 far, string mode, Action<float, float, int> done)
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: 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_002b: 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)
		AllyPusher.Vanilla = mode == "vanilla";
		Vector3 val = Flat(b - a);
		Vector3 normalized = ((Vector3)(ref val)).normalized;
		player.Teleport(a, Quaternion.LookRotation(normalized));
		AISWander[] wanders = ((Component)ally).GetComponentsInChildren<AISWander>(true);
		Transform[] followed = wanders.Select((AISWander w) => w.FollowTransform).ToArray();
		Transform hold = null;
		if (mode == "free")
		{
			hold = new GameObject("NBA_Hold").transform;
			hold.position = far;
			AISWander[] array = wanders;
			for (int num = 0; num < array.Length; num++)
			{
				array[num].FollowTransform = hold;
			}
			ally.Teleport(far, ((Component)ally).transform.rotation);
		}
		else
		{
			ally.Teleport(a - normalized * 1.2f, Quaternion.LookRotation(normalized));
		}
		yield return TestHarness.WaitGame(1.5f);
		float there = -1f;
		float back = -1f;
		yield return Walk(player, b, delegate(float t)
		{
			there = t;
		});
		yield return TestHarness.WaitGame(1f);
		m_pushes = 0;
		yield return Walk(player, a, delegate(float t)
		{
			back = t;
		});
		int pushes = m_pushes;
		if ((Object)(object)hold != (Object)null)
		{
			for (int num2 = 0; num2 < wanders.Length; num2++)
			{
				wanders[num2].FollowTransform = followed[num2];
			}
			Object.Destroy((Object)(object)((Component)hold).gameObject);
		}
		yield return TestHarness.WaitGame(0.5f);
		done(there, back, pushes);
	}

	internal static IEnumerator Walk(Character player, Vector3 target, Action<float> done)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		NavMeshHit val = default(NavMeshHit);
		NavMesh.SamplePosition(((Component)player).transform.position, ref val, 2f, -1);
		NavMeshPath val2 = new NavMeshPath();
		NavMesh.CalculatePath(((NavMeshHit)(ref val)).position, target, -1, val2);
		Vector3[] corners = (Vector3[])((val2.corners.Length != 0) ? ((Array)val2.corners) : ((Array)new Vector3[1] { target }));
		int next = 0;
		float t = 0f;
		s_driving = true;
		while (t < 12f)
		{
			Vector3 direction = Flat(corners[next] - ((Component)player).transform.position);
			if (((Vector3)(ref direction)).magnitude < ((next == corners.Length - 1) ? 0.6f : 0.4f))
			{
				if (next == corners.Length - 1)
				{
					break;
				}
				next++;
			}
			else
			{
				Steer(player, direction);
				yield return null;
				t += Time.deltaTime;
			}
		}
		s_driving = false;
		s_move = Vector2.zero;
		done((t < 12f) ? t : (-1f));
	}
}
internal static class Passage
{
	public struct Found
	{
		public Vector3 Centre;

		public Vector3 Direction;

		public float Width;

		public float Distance;

		public string Sides;

		public override string ToString()
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			return $"centre {Centre}, direction {Direction}, width {Width:F2} m, {Distance:F0} m away, between {Sides}";
		}
	}

	public static float MinWidth = 1.4f;

	public static float MaxWidth = 3f;

	public static float NarrowBefore = 0f;

	public static float NarrowAfter = 0f;

	public static float Before = 2.5f;

	public static float After = 4.5f;

	public static readonly List<Found> All = new List<Found>();

	public static Func<string, bool> SideFilter;

	private static readonly int[] s_rejected = new int[5];

	private static readonly List<(float width, Vector3 centre, Vector3 dir)> s_closed = new List<(float, Vector3, Vector3)>();

	public static Vector3? Ground(Vector3 spot)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: 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_0015: 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_003e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: 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)
		RaycastHit val = default(RaycastHit);
		if (!Physics.Raycast(spot + Vector3.up * 1.5f, Vector3.down, ref val, 4f, Global.GeneralEnvironmentMask))
		{
			return null;
		}
		return ((RaycastHit)(ref val)).point + Vector3.up * 0.05f;
	}

	public static float Width(Vector3 at, Vector3 dir, out Vector3 middle)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: 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_006e: 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_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		Vector3 val = Vector3.Cross(Vector3.up, dir);
		Vector3 normalized = ((Vector3)(ref val)).normalized;
		Vector3 val2 = at + Vector3.up;
		RaycastHit val3 = default(RaycastHit);
		float num = (Physics.Raycast(val2, -normalized, ref val3, 4f, Global.GeneralEnvironmentMask) ? ((RaycastHit)(ref val3)).distance : 4f);
		RaycastHit val4 = default(RaycastHit);
		float num2 = (Physics.Raycast(val2, normalized, ref val4, 4f, Global.GeneralEnvironmentMask) ? ((RaycastHit)(ref val4)).distance : 4f);
		middle = at + normalized * (num2 - num) * 0.5f;
		return num + num2;
	}

	public static string Sides(Vector3 at, Vector3 dir)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: 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)
		Vector3 val = Vector3.Cross(Vector3.up, dir);
		Vector3 normalized = ((Vector3)(ref val)).normalized;
		Vector3 val2 = at + Vector3.up;
		RaycastHit val3 = default(RaycastHit);
		string text = (Physics.Raycast(val2, -normalized, ref val3, 4f, Global.GeneralEnvironmentMask) ? ((Object)((RaycastHit)(ref val3)).collider).name : "-");
		RaycastHit val4 = default(RaycastHit);
		string text2 = (Physics.Raycast(val2, normalized, ref val4, 4f, Global.GeneralEnvironmentMask) ? ((Object)((RaycastHit)(ref val4)).collider).name : "-");
		return text + " | " + text2;
	}

	public static bool OpenLine(Vector3 from, Vector3 dir, float length)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		return WhyNotOpen(from, dir, length) == null;
	}

	public static string WhyNotOpen(Vector3 from, Vector3 dir, float length)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: 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_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b8: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: 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_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: 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_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_012f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0134: Unknown result type (might be due to invalid IL or missing references)
		Vector3? val = Ground(from);
		if (!val.HasValue)
		{
			return "no ground at 0 m";
		}
		RaycastHit val3 = default(RaycastHit);
		RaycastHit val4 = default(RaycastHit);
		for (float num = 0.5f; num <= length; num += 0.5f)
		{
			Vector3? val2 = Ground(from + dir * num);
			if (!val2.HasValue)
			{
				return $"no ground at {num} m";
			}
			if (Mathf.Abs(val2.Value.y - val.Value.y) > 0.5f)
			{
				return $"step {val2.Value.y - val.Value.y:F2} m at {num} m";
			}
			if (Physics.Linecast(val.Value + Vector3.up * 0.5f, val2.Value + Vector3.up * 0.5f, ref val3, Global.GeneralEnvironmentMask))
			{
				return $"{((Object)((RaycastHit)(ref val3)).collider).name} at knee height at {num} m";
			}
			if (Physics.Linecast(val.Value + Vector3.up * 1.6f, val2.Value + Vector3.up * 1.6f, ref val4, Global.GeneralEnvironmentMask))
			{
				return $"{((Object)((RaycastHit)(ref val4)).collider).name} at head height at {num} m";
			}
			val = val2;
		}
		return null;
	}

	private static bool Check(Vector3 point, Vector3 dir, out Found found)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: 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_0137: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: 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_017f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Expected O, but got Unknown
		//IL_0188: 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_0193: 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_019f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01af: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0200: Unknown result type (might be due to invalid IL or missing references)
		//IL_0254: Unknown result type (might be due to invalid IL or missing references)
		//IL_0259: Unknown result type (might be due to invalid IL or missing references)
		//IL_0260: Unknown result type (might be due to invalid IL or missing references)
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		found = default(Found);
		Vector3 middle;
		float num = Width(point, dir, out middle);
		if (num < MinWidth || num > MaxWidth)
		{
			s_rejected[0]++;
			return false;
		}
		Vector3? val = Ground(middle);
		string text = ((!val.HasValue) ? null : Sides(val.Value, dir));
		if (!val.HasValue || (SideFilter != null && !SideFilter(text)))
		{
			s_rejected[1]++;
			return false;
		}
		float num2 = 0f;
		for (float num3 = 0f - NarrowBefore; num3 <= NarrowAfter + 0.01f; num3 += 0.25f)
		{
			Vector3? val2 = Ground(val.Value + dir * num3);
			Vector3 middle2;
			float num4 = ((!val2.HasValue) ? 0f : Width(val2.Value, dir, out middle2));
			if (num4 < MinWidth - 0.1f || num4 > MaxWidth + 0.2f)
			{
				s_rejected[2]++;
				return false;
			}
			num2 = Mathf.Max(num2, num4);
		}
		if (!OpenLine(val.Value - dir * Before, dir, Before + After))
		{
			s_rejected[3]++;
			s_closed.Add((num2, val.Value, dir));
			return false;
		}
		NavMeshPath val3 = new NavMeshPath();
		if (!NavMesh.CalculatePath(val.Value - dir * Before, val.Value + dir * After, -1, val3) || (int)val3.status != 0)
		{
			s_rejected[4]++;
			return false;
		}
		float num5 = 0f;
		for (int i = 1; i < val3.corners.Length; i++)
		{
			num5 += Vector3.Distance(val3.corners[i - 1], val3.corners[i]);
		}
		if (num5 > (Before + After) * 1.1f)
		{
			s_rejected[4]++;
			return false;
		}
		found = new Found
		{
			Centre = val.Value,
			Direction = dir,
			Width = num2,
			Sides = text
		};
		return true;
	}

	public static IEnumerator Find(Vector3 around, float radius, Action<Found?> done)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		Array.Clear(s_rejected, 0, s_rejected.Length);
		s_closed.Clear();
		NavMeshTriangulation val = NavMesh.CalculateTriangulation();
		List<Vector3> points = new List<Vector3>();
		HashSet<Vector3Int> seen = new HashSet<Vector3Int>();
		Vector3[] vertices = val.vertices;
		foreach (Vector3 val2 in vertices)
		{
			for (float num = -0.5f; num <= 0.5f; num += 0.5f)
			{
				for (float num2 = -0.5f; num2 <= 0.5f; num2 += 0.5f)
				{
					Add(val2 + new Vector3(num, 0f, num2));
				}
			}
		}
		for (int j = 0; j + 2 < val.indices.Length; j += 3)
		{
			Add((val.vertices[val.indices[j]] + val.vertices[val.indices[j + 1]] + val.vertices[val.indices[j + 2]]) / 3f);
		}
		Found? best = null;
		int tried = 0;
		All.Clear();
		foreach (Vector3 item in points)
		{
			for (int k = 0; k < 360; k += 15)
			{
				Vector3 dir = Quaternion.Euler(0f, (float)k, 0f) * Vector3.forward;
				tried++;
				if (Check(item, dir, out var found))
				{
					found.Distance = Vector3.Distance(found.Centre, around);
					All.Add(found);
					if (!best.HasValue || found.Width < best.Value.Width - 0.1f || (found.Width < best.Value.Width + 0.1f && found.Distance < best.Value.Distance))
					{
						best = found;
					}
				}
			}
			if (tried % 2400 == 0)
			{
				yield return null;
			}
		}
		Plugin.Log.LogMessage((object)($"passage: {points.Count} navmesh points, {tried} tries within {radius} m of {around}: " + string.Format("{0}; rejected by width {1}, middle or sides {2}, ", (!best.HasValue) ? "none" : best.ToString(), s_rejected[0], s_rejected[1]) + $"narrow part {s_rejected[2]}, open line {s_rejected[3]}, path {s_rejected[4]}"));
		List<Vector3> list = new List<Vector3>();
		foreach (var r in s_closed.OrderBy(((float width, Vector3 centre, Vector3 dir) tuple) => tuple.width))
		{
			if (list.Count < 8)
			{
				if (!list.Any((Vector3 p) => Vector3.Distance(p, r.centre) < 3f))
				{
					list.Add(r.centre);
					Plugin.Log.LogMessage((object)$"passage: closed {r.width:F2} m at {r.centre} toward {r.dir}: {WhyNotOpen(r.centre - r.dir * Before, r.dir, Before + After)}");
				}
				continue;
			}
			break;
		}
		done(best);
		void Add(Vector3 p)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: 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_0048: 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)
			if (!(Vector3.Distance(p, around) > radius) && seen.Add(new Vector3Int(Mathf.RoundToInt(p.x * 2f), Mathf.RoundToInt(p.y), Mathf.RoundToInt(p.z * 2f))))
			{
				points.Add(p);
			}
		}
	}
}
[BepInPlugin("tchernobill.noblockingally", "No Blocking Ally", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "tchernobill.noblockingally";

	public const string NAME = "No Blocking Ally";

	public const string VERSION = "1.0.0";

	internal static ManualLogSource Log;

	internal static ConfigEntry<float> PushGap;

	internal static ConfigEntry<float> StepAsideDistance;

	internal static ConfigEntry<float> StepAsideTime;

	internal static ConfigEntry<bool> LogPushes;

	private void Awake()
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Expected O, but got Unknown
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Expected O, but got Unknown
		//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Expected O, but got Unknown
		//IL_00e7: 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_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Expected O, but got Unknown
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: Expected O, but got Unknown
		//IL_0120: Unknown result type (might be due to invalid IL or missing references)
		//IL_0126: Expected O, but got Unknown
		//IL_0126: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Expected O, but got Unknown
		//IL_0131: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		PushGap = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Push Gap", 0.1f, new ConfigDescription("Walking into an ally pushes it aside when the gap between your bodies is below this (metres).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		StepAsideDistance = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Step Aside Distance", 2f, new ConfigDescription("How far (metres) a pushed ally steps aside, along your walk.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 5f), Array.Empty<object>()));
		StepAsideTime = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Step Aside Time", 1.5f, new ConfigDescription("How long (seconds) a pushed ally keeps out of your way before it follows you or fights again.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 5f), Array.Empty<object>()));
		LogPushes = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Log Pushes", false, "Writes each push in the BepInEx log.");
		new Harmony("tchernobill.noblockingally").PatchAll(typeof(AllyPusher));
		GameObject val = new GameObject("NoBlockingAlly");
		Object.DontDestroyOnLoad((Object)val);
		((Object)val).hideFlags = (HideFlags)61;
		val.AddComponent<AllyPusher>();
		TestHarness.StartIfRequested(val);
		ScanHarness.StartIfRequested(val);
		MeasureHarness.StartIfRequested(val);
		SaveHarness.StartIfRequested(val);
		Log.LogMessage((object)"No Blocking Ally 1.0.0 ready");
	}
}
public class SaveHarness : MonoBehaviour
{
	private int m_pushes;

	private static int Conjure
	{
		get
		{
			if (!int.TryParse(Arg("--nba-skill"), out var result))
			{
				return 8200021;
			}
			return result;
		}
	}

	public static void StartIfRequested(GameObject host)
	{
		string[] commandLineArgs = Environment.GetCommandLineArgs();
		if (UnityEngineExtensions.Contains<string>(commandLineArgs, "--nba-makesave") || UnityEngineExtensions.Contains<string>(commandLineArgs, "--nba-replay"))
		{
			host.AddComponent<SaveHarness>();
		}
	}

	private static void Log(string s)
	{
		Plugin.Log.LogMessage((object)("nba-save: " + s));
	}

	private static string Arg(string name)
	{
		string[] commandLineArgs = Environment.GetCommandLineArgs();
		int num = Array.IndexOf(commandLineArgs, name);
		if (num < 0 || num + 1 >= commandLineArgs.Length)
		{
			return null;
		}
		return commandLineArgs[num + 1];
	}

	private static MeasureHarness.Point ParsePoint(string text)
	{
		//IL_0049: 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_006a: 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_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		string[] f = text.Split(new char[1] { ';' });
		MeasureHarness.Point result = new MeasureHarness.Point
		{
			Scene = f[0],
			Centre = new Vector3(F(1), F(2), F(3))
		};
		Vector3 val = new Vector3(F(4), 0f, F(5));
		result.Direction = ((Vector3)(ref val)).normalized;
		return result;
		float F(int i)
		{
			return float.Parse(f[i], CultureInfo.InvariantCulture);
		}
	}

	private void Start()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Expected O, but got Unknown
		new Harmony("tchernobill.noblockingally.save").Patch((MethodBase)AccessTools.Method(typeof(LocalCharacterControl), "DetectMovementInputs", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MeasureHarness), "DriveMovement", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		AllyPusher.Pushed = (Action<Character, Character, Vector3>)Delegate.Combine(AllyPusher.Pushed, (Action<Character, Character, Vector3>)delegate
		{
			m_pushes++;
		});
		((MonoBehaviour)this).StartCoroutine((Arg("--nba-makesave") != null) ? Make(ParsePoint(Arg("--nba-makesave"))) : Replay(ParsePoint(Arg("--nba-replay"))));
	}

	private static IEnumerator WaitIn(string scene, bool travel)
	{
		while (!MeasureHarness.Settled(null))
		{
			yield return MeasureHarness.WaitRealtime(1f);
		}
		yield return MeasureHarness.WaitRealtime(3f);
		MenuManager.Instance.MasterCanvas.alpha = 1f;
		if (travel)
		{
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name != scene)
			{
				NetworkLevelLoader.Instance.LoadLevel(scene, 0, 1.5f, false);
				yield return MeasureHarness.WaitRealtime(5f);
			}
		}
		float deadline = Time.realtimeSinceStartup + 180f;
		while (!MeasureHarness.Settled(scene) && Time.realtimeSinceStartup < deadline)
		{
			yield return MeasureHarness.WaitRealtime(1f);
		}
		yield return MeasureHarness.WaitRealtime(3f);
	}

	private static IEnumerator PrepareConjure(Character player, Action<Skill> done)
	{
		if ((Object)(object)((CharacterKnowledge)player.Inventory.SkillKnowledge).GetItemFromItemID(Conjure) == (Object)null)
		{
			player.Inventory.ReceiveSkillReward(Conjure);
			yield return TestHarness.WaitGame(1f);
		}
		Item itemFromItemID = ((CharacterKnowledge)player.Inventory.SkillKnowledge).GetItemFromItemID(Conjure);
		Skill skill = (Skill)(object)((itemFromItemID is Skill) ? itemFromItemID : null);
		if ((Object)(object)skill == (Object)null)
		{
			done(null);
			yield break;
		}
		while (player.Stats.MaxMana < skill.ManaCost + 1f && player.Stats.ManaPoint < 10)
		{
			player.Stats.GiveManaPoint(1);
			yield return null;
		}
		player.Stats.RestoreAllVitals();
		player.QuickSlotMngr.SetQuickSlot(0, (Item)(object)skill, true);
		string text = $"{((Item)skill).Name} ({((Item)skill).ItemID}): mana cost {skill.ManaCost}, health cost {skill.HealthCost}, cooldown {skill.Cooldown} s; player mana points ";
		object arg = player.Stats.ManaPoint;
		object arg2 = player.Stats.MaxMana;
		QuickSlot quickSlot = player.QuickSlotMngr.GetQuickSlot(0);
		object arg3;
		if (quickSlot == null)
		{
			arg3 = null;
		}
		else
		{
			Item registeredItem = quickSlot.RegisteredItem;
			arg3 = ((registeredItem != null) ? registeredItem.Name : null);
		}
		Log(text + $"{arg}, max mana {arg2:F0}; quick slot 1 = {arg3}");
		done(skill);
	}

	private static IEnumerator Cast(Character player, Action<Character> done)
	{
		HashSet<Character> before = new HashSet<Character>(TestHarness.Allies(player));
		QuickSlot quickSlot = player.QuickSlotMngr.GetQuickSlot(0);
		Item obj = ((quickSlot != null) ? quickSlot.RegisteredItem : null);
		Skill skill = (Skill)(object)((obj is Skill) ? obj : null);
		if ((Object)(object)skill == (Object)null)
		{
			Log("no skill in quick slot 1");
			done(null);
			yield break;
		}
		for (float t = 0f; t < 30f; t += 0.5f)
		{
			if (!skill.InCooldown())
			{
				break;
			}
			yield return TestHarness.WaitGame(0.5f);
		}
		Log(string.Format("cast {0}: requirements {1}, mana {2:F0}/{3:F0}", ((Item)skill).Name, skill.HasBaseRequirements(false) ? "met" : "NOT met", player.Stats.CurrentMana, player.Stats.MaxMana));
		player.QuickSlotMngr.QuickSlotInput(0);
		Character val = null;
		for (float t = 0f; t < 6f; t += 0.25f)
		{
			if (!((Object)(object)val == (Object)null))
			{
				break;
			}
			yield return TestHarness.WaitGame(0.25f);
			val = ((IEnumerable<Character>)TestHarness.Allies(player)).FirstOrDefault((Func<Character, bool>)((Character c) => !before.Contains(c)));
		}
		Log(((Object)(object)val != (Object)null) ? $"cast: {val.Name} summoned at {Vector3.Distance(((Component)val).transform.position, ((Component)player).transform.position):F1} m" : $"cast: no ally after 6 s, mana {player.Stats.CurrentMana:F0}, in cooldown {skill.InCooldown()}");
		if ((Object)(object)val == (Object)null)
		{
			Transform[] componentsInChildren = ((Component)skill).GetComponentsInChildren<Transform>(true);
			foreach (Transform val2 in componentsInChildren)
			{
				Log("  " + ((Object)val2).name + ": " + string.Join(", ", (from c in ((Component)val2).GetComponents<Component>()
					where !(c is Transform)
					select c).Select(delegate(Component c)
				{
					Component obj2 = c;
					ProximityCondition val3 = (ProximityCondition)(object)((obj2 is ProximityCondition) ? obj2 : null);
					if (val3 == null)
					{
						Component obj3 = c;
						EffectCondition val4 = (EffectCondition)(object)((obj3 is EffectCondition) ? obj3 : null);
						if (val4 == null)
						{
							return ((object)c).GetType().Name;
						}
						return string.Format("{0}(invert {1}: {2})", ((object)c).GetType().Name, val4.Invert, string.Join(" ", from f in ((object)c).GetType().GetFields()
							select f.Name + "=" + f.GetValue(c)));
					}
					return $"Proximity {val3.ProximityDist} m of " + string.Join(" + ", val3.ProximityItemReq.Select(delegate(ItemRequired r)
					{
						object[] obj4 = new object[4]
						{
							((ItemQuantity)r).Quantity,
							null,
							null,
							null
						};
						Item item = ((ItemQuantity)r).Item;
						obj4[1] = ((item != null) ? item.Name : null);
						obj4[2] = ((ItemQuantity)r).Item?.ItemID;
						obj4[3] = ((object)((ItemQuantity)r).Item)?.GetType().Name;
						return string.Format("{0}x {1} ({2}, {3})", obj4);
					}));
				})));
			}
		}
		done(val);
	}

	private IEnumerator Round(Character player, Vector3 a, Vector3 b, string label)
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		float there = -1f;
		float back = -1f;
		yield return MeasureHarness.Walk(player, b, delegate(float t)
		{
			there = t;
		});
		yield return TestHarness.WaitGame(1f);
		m_pushes = 0;
		yield return MeasureHarness.Walk(player, a, delegate(float t)
		{
			back = t;
		});
		Log(string.Format("{0}: there {1:F1} s, back {2}, {3} push(es)", label, there, (back < 0f) ? "STUCK (12 s)" : (back.ToString("F1") + " s"), m_pushes));
	}

	private IEnumerator Make(MeasureHarness.Point p)
	{
		yield return WaitIn(p.Scene, travel: true);
		Character player = MeasureHarness.Player();
		if (!MeasureHarness.Settled(p.Scene))
		{
			Plugin.Log.LogError((object)("nba-save: FAILED " + p.Scene + " not loaded"));
			yield break;
		}
		Vector3? a = MeasureHarness.Side(p, -1f);
		Vector3? b = MeasureHarness.Side(p, 1f);
		if (!a.HasValue || !b.HasValue)
		{
			Plugin.Log.LogError((object)"nba-save: FAILED no navmesh on both sides of the gap");
			yield break;
		}
		Skill skill = null;
		yield return PrepareConjure(player, delegate(Skill s)
		{
			skill = s;
		});
		if ((Object)(object)skill == (Object)null)
		{
			Plugin.Log.LogError((object)"nba-save: FAILED Conjure not learned");
			yield break;
		}
		Vector3 val = new Vector3(b.Value.x - a.Value.x, 0f, b.Value.z - a.Value.z);
		Vector3 dir = ((Vector3)(ref val)).normalized;
		player.Teleport(a.Value, Quaternion.LookRotation(dir));
		yield return TestHarness.WaitGame(1.5f);
		Character ally = null;
		yield return Cast(player, delegate(Character c)
		{
			ally = c;
		});
		if ((Object)(object)ally == (Object)null)
		{
			Plugin.Log.LogError((object)"nba-save: FAILED Conjure summoned nothing");
			yield break;
		}
		yield return TestHarness.WaitGame(2f);
		yield return Round(player, a.Value, b.Value, "check");
		player.Teleport(a.Value, Quaternion.LookRotation(dir));
		yield return TestHarness.WaitGame(1f);
		for (float t = 0f; t < 60f; t += 0.5f)
		{
			if (!skill.InCooldown())
			{
				break;
			}
			yield return TestHarness.WaitGame(0.5f);
		}
		player.Stats.RestoreAllVitals();
		yield return TestHarness.WaitGame(0.5f);
		SaveManager.Instance.Save(false, true);
		yield return MeasureHarness.WaitRealtime(2f);
		Log($"saved {player.Name} ({player.UID}) in {SaveManager.GetSavePath()} at {((Component)player).transform.position}, facing {dir}, " + $"side 2 at {b.Value}");
		Plugin.Log.LogMessage((object)"nba-save: done");
	}

	private IEnumerator Replay(MeasureHarness.Point p)
	{
		yield return WaitIn(p.Scene, travel: false);
		Character player = MeasureHarness.Player();
		if (!MeasureHarness.Settled(p.Scene))
		{
			ManualLogSource log = Plugin.Log;
			Scene activeScene = SceneManager.GetActiveScene();
			log.LogError((object)("nba-save: FAILED loaded in " + ((Scene)(ref activeScene)).name + ", not " + p.Scene));
			yield break;
		}
		int result;
		int rounds = (int.TryParse(Arg("--nba-replay-rounds"), out result) ? result : 3);
		Vector3? a = MeasureHarness.Side(p, -1f);
		Vector3? b = MeasureHarness.Side(p, 1f);
		Log($"loaded {player.Name} in {p.Scene} at {((Component)player).transform.position}, {Vector3.Distance(((Component)player).transform.position, a.Value):F2} m from side 1; " + $"allies {TestHarness.Allies(player).Count}");
		player.Invincible = true;
		Vector3 val = new Vector3(b.Value.x - a.Value.x, 0f, b.Value.z - a.Value.z);
		Vector3 dir = ((Vector3)(ref val)).normalized;
		Character ally = null;
		bool[] array = new bool[2] { false, true };
		foreach (bool vanilla in array)
		{
			for (int r = 0; r < rounds; r++)
			{
				AllyPusher.Vanilla = vanilla;
				bool fromSave = !vanilla && r == 0;
				if (!fromSave)
				{
					player.Teleport(a.Value, Quaternion.LookRotation(dir));
					if ((Object)(object)ally != (Object)null && ally.Alive)
					{
						ally.Teleport(a.Value - dir * 1.2f, Quaternion.LookRotation(dir));
					}
					yield return TestHarness.WaitGame(1.5f);
				}
				if ((Object)(object)ally == (Object)null || !ally.Alive)
				{
					yield return Cast(player, delegate(Character c)
					{
						ally = c;
					});
					if ((Object)(object)ally == (Object)null)
					{
						Plugin.Log.LogError((object)"nba-save: FAILED Conjure summoned nothing");
						yield break;
					}
					yield return TestHarness.WaitGame(2f);
				}
				yield return Round(player, a.Value, b.Value, string.Format("{0} round {1}{2}", vanilla ? "vanilla" : "mod", r + 1, fromSave ? " (from the save)" : ""));
			}
		}
		AllyPusher.Vanilla = false;
		Plugin.Log.LogMessage((object)"nba-save: done");
	}
}
public class ScanHarness : MonoBehaviour
{
	private static readonly string[] Dungeons = new string[61]
	{
		"Chersonese_Dungeon1", "Chersonese_Dungeon2", "Chersonese_Dungeon3", "Chersonese_Dungeon4_BlueChamber", "Chersonese_Dungeon4_CommonPath", "Chersonese_Dungeon4_HolyMission", "Chersonese_Dungeon4_Levant", "Chersonese_Dungeon5", "Chersonese_Dungeon6", "Chersonese_Dungeon8",
		"Chersonese_Dungeon9", "ChersoneseDungeonsSmall", "ChersoneseDungeonsBosses", "Abrassar_Dungeon1", "Abrassar_Dungeon2", "Abrassar_Dungeon3", "Abrassar_Dungeon4", "Abrassar_Dungeon5", "Abrassar_Dungeon6", "AbrassarDungeonsBosses",
		"AbrassarDungeonsSmall", "AntiqueField_Dungeon1", "AntiqueField_Dungeon2", "AntiqueField_Dungeon3", "AntiqueField_Dungeon4", "AntiqueField_Dungeon5", "AntiqueField_Dungeon6", "AntiqueField_Dungeon7", "AntiqueField_Dungeon8", "AntiqueField_Dungeon9",
		"AntiqueFieldDungeonsBosses", "AntiqueFieldDungeonsSmall", "Emercar_Dungeon1", "Emercar_Dungeon2", "Emercar_Dungeon3", "Emercar_Dungeon4", "Emercar_Dungeon5", "Emercar_Dungeon6", "EmercarDungeonsBosses", "EmercarDungeonsSmall",
		"Hallowed_Dungeon1", "Hallowed_Dungeon2", "Hallowed_Dungeon3", "Hallowed_Dungeon4_Interior", "Hallowed_Dungeon5", "Hallowed_Dungeon6", "Hallowed_Dungeon7", "HallowedDungeonsBosses", "HallowedDungeonsSmall", "Caldera_Dungeon1",
		"Caldera_Dungeon2", "Caldera_Dungeon3", "Caldera_Dungeon4", "Caldera_Dungeon5", "Caldera_Dungeon6", "Caldera_Dungeon7", "Caldera_Dungeon8", "Caldera_Dungeon9", "Caldera_Dungeon10", "CalderaDungeonsBosses",
		"CalderaDungeonsSmall"
	};

	private static readonly FieldRef<CharacterCamera, Transform> s_cameraPitch = AccessTools.FieldRefAccess<CharacterCamera, Transform>("m_cameraVertHolder");

	private const float Cell = 0.4f;

	private const float Region = 8f;

	private const float Blocked = 1.04f;

	public static void StartIfRequested(GameObject host)
	{
		if (UnityEngineExtensions.Contains<string>(Environment.GetCommandLineArgs(), "--nba-scan"))
		{
			host.AddComponent<ScanHarness>();
		}
	}

	private static void Log(string s)
	{
		Plugin.Log.LogMessage((object)("nba-scan: " + s));
	}

	private static string Arg(string name)
	{
		string[] commandLineArgs = Environment.GetCommandLineArgs();
		int num = Array.IndexOf(commandLineArgs, name);
		if (num < 0 || num + 1 >= commandLineArgs.Length)
		{
			return null;
		}
		return commandLineArgs[num + 1];
	}

	private static IEnumerator WaitRealtime(float seconds)
	{
		float end = Time.realtimeSinceStartup + seconds;
		while (Time.realtimeSinceStartup < end)
		{
			yield return null;
		}
	}

	private static Character Player()
	{
		try
		{
			CharacterManager instance = CharacterManager.Instance;
			return (instance != null) ? instance.GetFirstLocalCharacter() : null;
		}
		catch (NullReferenceException)
		{
			return null;
		}
	}

	private static bool Settled(string scene)
	{
		//IL_002f: 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)
		NetworkLevelLoader instance = NetworkLevelLoader.Instance;
		if ((Object)(object)Player() != (Object)null && (Object)(object)instance != (Object)null && instance.IsOverallLoadingDone && !instance.IsGameplayLoading)
		{
			if (scene != null)
			{
				Scene activeScene = SceneManager.GetActiveScene();
				return ((Scene)(ref activeScene)).name == scene;
			}
			return true;
		}
		return false;
	}

	private void Start()
	{
		((MonoBehaviour)this).StartCoroutine(Run());
	}

	private static IEnumerator Detour(Passage.Found f, Action<float> done)
	{
		int n = 41;
		Vector3?[,] cells = new Vector3?[n, n];
		Vector3 origin = f.Centre - new Vector3(8f, 0f, 8f);
		NavMeshHit val = default(NavMeshHit);
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				if (NavMesh.SamplePosition(origin + new Vector3((float)i * 0.4f, 0f, (float)j * 0.4f), ref val, 0.28f, -1) && Mathf.Abs(((NavMeshHit)(ref val)).position.y - f.Centre.y) < 1.5f)
				{
					cells[i, j] = ((NavMeshHit)(ref val)).position;
				}
			}
			if (i % 10 == 0)
			{
				yield return null;
			}
		}
		if (Bfs(block: false) < 0f)
		{
			done(0f);
			yield break;
		}
		yield return null;
		done(Bfs(block: true));
		float Bfs(bool block)
		{
			//IL_0006: 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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: 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_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_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Unknown result type (might be due to invalid IL or missing references)
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_024a: Unknown result type (might be due to invalid IL or missing references)
			(int, int)? tuple = Nearest(f.Centre - f.Direction * 1.6f);
			(int, int)? tuple2 = Nearest(f.Centre + f.Direction * 1.6f);
			if (!tuple.HasValue || !tuple2.HasValue)
			{
				return -1f;
			}
			float[,] array = new float[n, n];
			for (int k = 0; k < n; k++)
			{
				for (int l = 0; l < n; l++)
				{
					array[k, l] = -1f;
				}
			}
			Queue<(int, int)> queue = new Queue<(int, int)>();
			array[tuple.Value.Item1, tuple.Value.Item2] = 0f;
			queue.Enqueue(tuple.Value);
			NavMeshHit val2 = default(NavMeshHit);
			while (queue.Count > 0)
			{
				(int, int) tuple3 = queue.Dequeue();
				int item = tuple3.Item1;
				int item2 = tuple3.Item2;
				int num = item2;
				(int, int) value = tuple2.Value;
				if (item == value.Item1 && num == value.Item2)
				{
					return array[item, item2];
				}
				(int, int)[] array2 = new(int, int)[4]
				{
					(1, 0),
					(-1, 0),
					(0, 1),
					(0, -1)
				};
				for (num = 0; num < array2.Length; num++)
				{
					(int, int) tuple4 = array2[num];
					int item3 = tuple4.Item1;
					int item4 = tuple4.Item2;
					int num2 = item + item3;
					int num3 = item2 + item4;
					if (num2 >= 0 && num3 >= 0 && num2 < n && num3 < n && !(array[num2, num3] >= 0f) && cells[num2, num3].HasValue)
					{
						Vector3 value2 = cells[num2, num3].Value;
						if ((!block || !(Vector2.Distance(new Vector2(value2.x, value2.z), new Vector2(f.Centre.x, f.Centre.z)) < 1.04f)) && !NavMesh.Raycast(cells[item, item2].Value, value2, ref val2, -1))
						{
							array[num2, num3] = array[item, item2] + 0.4f;
							queue.Enqueue((num2, num3));
						}
					}
				}
			}
			return -1f;
		}
		(int, int) Index(Vector3 p)
		{
			//IL_0000: 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)
			return (Mathf.Clamp(Mathf.RoundToInt((p.x - origin.x) / 0.4f), 0, n - 1), Mathf.Clamp(Mathf.RoundToInt((p.z - origin.z) / 0.4f), 0, n - 1));
		}
		(int, int)? Nearest(Vector3 p)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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_008d: 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_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: 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_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: 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_0105: Unknown result type (might be due to invalid IL or missing references)
			(int, int) tuple = Index(p);
			int item = tuple.Item1;
			int item2 = tuple.Item2;
			float num = Vector3.Dot(p - f.Centre, f.Direction);
			(int, int)? result = null;
			float num2 = float.MaxValue;
			for (int k = Math.Max(0, item - 4); k <= Math.Min(n - 1, item + 4); k++)
			{
				for (int l = Math.Max(0, item2 - 4); l <= Math.Min(n - 1, item2 + 4); l++)
				{
					if (cells[k, l].HasValue)
					{
						Vector3 value = cells[k, l].Value;
						if (!(Vector2.Distance(new Vector2(value.x, value.z), new Vector2(f.Centre.x, f.Centre.z)) < 1.14f) && !(Vector3.Dot(value - f.Centre, f.Direction) * num <= 0f))
						{
							float num3 = Vector3.Distance(value, p);
							if (num3 < num2)
							{
								num2 = num3;
								result = (k, l);
							}
						}
					}
				}
			}
			return result;
		}
	}

	private IEnumerator Run()
	{
		while (!Settled(null))
		{
			yield return WaitRealtime(1f);
		}
		yield return WaitRealtime(3f);
		MenuManager.Instance.MasterCanvas.alpha = 1f;
		string dir = Path.Combine(Paths.BepInExRootPath, "NoBlockingAllyScan");
		Directory.CreateDirectory(dir);
		string[] array = Arg("--nba-scan-scenes")?.Split(new char[1] { ',' }) ?? Dungeons;
		Passage.MinWidth = 1f;
		Passage.MaxWidth = 2.05f;
		Passage.NarrowBefore = (Passage.NarrowAfter = 0f);
		Passage.Before = (Passage.After = 1.2f);
		string[] array2 = array;
		foreach (string scene in array2)
		{
			Log("travel to " + scene);
			NetworkLevelLoader.Instance.LoadLevel(scene, 0, 1.5f, false);
			float deadline = Time.realtimeSinceStartup + 180f;
			yield return WaitRealtime(5f);
			while (!Settled(scene) && Time.realtimeSinceStartup < deadline)
			{
				yield return WaitRealtime(1f);
			}
			if (!Settled(scene))
			{
				Log(scene + ": not loaded after 180 s (DLC missing?), skipped");
				continue;
			}
			yield return WaitRealtime(3f);
			Character player = Player();
			player.Invincible = true;
			yield return Passage.Find(((Component)player).transform.position, 3000f, delegate
			{
			});
			List<(Passage.Found spot, float detour)> spots = new List<(Passage.Found, float)>();
			List<Vector3> seen = new List<Vector3>();
			int checkedSpots = 0;
			foreach (Passage.Found f in Passage.All.OrderBy((Passage.Found found) => found.Width))
			{
				if (spots.Count >= 5 || checkedSpots >= 60)
				{
					break;
				}
				if (!seen.Any((Vector3 c) => Vector3.Distance(c, f.Centre) < 3f))
				{
					seen.Add(f.Centre);
					checkedSpots++;
					float detour = 0f;
					yield return Detour(f, delegate(float d)
					{
						detour = d;
					});
					Log(string.Format("  {0:F2} m at {1}: {2}", f.Width, f.Centre, (detour == 0f) ? "not a passage" : ((detour < 0f) ? "no way round" : $"detour {detour:F1} m")));
					if (detour < 0f || detour > 8f)
					{
						spots.Add((f, detour));
					}
				}
			}
			Log($"{scene}: {Passage.All.Count} spot(s) under {Passage.MaxWidth} m, {checkedSpots} checked, {spots.Count} chokepoint(s)" + ((spots.Count == 0) ? "" : (": " + string.Join(" ; ", spots.Select(((Passage.Found spot, float detour) s) => $"{s.spot.Width:F2} m at {s.spot.Centre} toward {s.spot.Direction} between {s.spot.Sides}, " + ((s.detour < 0f) ? "no way round within 8 m" : $"detour {s.detour:F0} m"))))));
			if (spots.Count != 0)
			{
				Passage.Found best = spots[0].spot;
				player.Teleport((Vector3)(((??)Passage.Ground(best.Centre - best.Direction * 1.6f)) ?? (best.Centre - best.Direction * 1.6f)), Quaternion.LookRotation(best.Direction));
				CharacterCamera camera = player.CharacterCamera;
				Quaternion yaw = Quaternion.LookRotation(best.Direction);
				for (float t = 0f; t < 1.5f; t += Time.unscaledDeltaTime)
				{
					((Component)camera).transform.rotation = yaw;
					s_cameraPitch.Invoke(camera).localRotation = Quaternion.Euler(15f, 0f, 0f);
					yield return null;
				}
				yield return (object)new WaitForEndOfFrame();
				Texture2D val = ScreenCapture.CaptureScreenshotAsTexture();
				File.WriteAllBytes(Path.Combine(dir, $"{scene}_{best.Width:F2}.jpg"), ImageConversion.EncodeToJPG(val, 88));
				Object.Destroy((Object)(object)val);
			}
		}
		Log("done");
	}
}
public class TestHarness : MonoBehaviour
{
	private const float WalkSeconds = 3f;

	private int m_failures;

	private int m_pushes;

	private static bool s_driving;

	private static Vector2 s_move;

	private static readonly FieldRef<LocalCharacterControl, Transform> s_horiControl = AccessTools.FieldRefAccess<LocalCharacterControl, Transform>("m_horiControl");

	internal static readonly FieldRef<CharacterCamera, Transform> s_cameraPitch = AccessTools.FieldRefAccess<CharacterCamera, Transform>("m_cameraVertHolder");

	private bool m_recording;

	public static void StartIfRequested(GameObject host)
	{
		if (UnityEngineExtensions.Contains<string>(Environment.GetCommandLineArgs(), "--nba-test"))
		{
			host.AddComponent<TestHarness>();
		}
	}

	private void Start()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Expected O, but got Unknown
		new Harmony("tchernobill.noblockingally.test").Patch((MethodBase)AccessTools.Method(typeof(LocalCharacterControl), "DetectMovementInputs", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(TestHarness), "DriveMovement", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		AllyPusher.Pushed = (Action<Character, Character, Vector3>)Delegate.Combine(AllyPusher.Pushed, (Action<Character, Character, Vector3>)delegate(Character player, Character ally, Vector3 aside)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			m_pushes++;
			Log($"push: {player.Name} -> {ally.Name} at gap, aside to {aside}");
		});
		((MonoBehaviour)this).StartCoroutine(Run());
	}

	private static void Log(string s)
	{
		Plugin.Log.LogMessage((object)("nba-test: " + s));
	}

	private void Check(bool ok, string what)
	{
		if (!ok)
		{
			m_failures++;
		}
		Plugin.Log.LogMessage((object)("nba-test: " + (ok ? "PASS" : "FAIL") + " " + what));
	}

	private static void DriveMovement(ref Vector2 ___m_moveInput, ref Vector3 ___m_modifMoveInput)
	{
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		if (s_driving)
		{
			___m_moveInput = s_move;
			___m_modifMoveInput = Vector2.op_Implicit(s_move);
		}
	}

	private static void Steer(Character character, Vector3 direction)
	{
		//IL_0017: 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)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: 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_0026: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Unknown result type (might be due to invalid IL or missing references)
		//IL_0046: 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_004e: 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_005d: Unknown result type (might be due to invalid IL or missing references)
		FieldRef<LocalCharacterControl, Transform> obj = s_horiControl;
		CharacterControl characterControl = character.CharacterControl;
		Transform val = obj.Invoke((LocalCharacterControl)(object)((characterControl is LocalCharacterControl) ? characterControl : null));
		Vector3 val2 = Flat(direction);
		Vector3 normalized = ((Vector3)(ref val2)).normalized;
		val2 = Flat(val.right);
		float num = Vector3.Dot(normalized, ((Vector3)(ref val2)).normalized);
		val2 = Flat(val.forward);
		s_move = new Vector2(num, Vector3.Dot(normalized, ((Vector3)(ref val2)).normalized));
	}

	private static Vector3 Flat(Vector3 v)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: 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)
		return new Vector3(v.x, 0f, v.z);
	}

	private static IEnumerator WaitRealtime(float seconds)
	{
		float end = Time.realtimeSinceStartup + seconds;
		while (Time.realtimeSinceStartup < end)
		{
			yield return null;
		}
	}

	internal static IEnumerator WaitGame(float seconds)
	{
		float end = Time.time + seconds;
		while (Time.time < end)
		{
			yield return null;
		}
	}

	private static string Arg(string name)
	{
		string[] commandLineArgs = Environment.GetCommandLineArgs();
		int num = Array.IndexOf(commandLineArgs, name);
		if (num < 0 || num + 1 >= commandLineArgs.Length)
		{
			return null;
		}
		return commandLineArgs[num + 1];
	}

	private static Vector3? Ground(Vector3 spot)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		return Passage.Ground(spot);
	}

	private static string OutputDir()
	{
		string text = Path.Combine(Paths.BepInExRootPath, "NoBlockingAllyTest");
		Directory.CreateDirectory(text);
		return text;
	}

	private static void Capture(string file)
	{
		Texture2D val = ScreenCapture.CaptureScreenshotAsTexture();
		string text = Path.Combine(OutputDir(), file);
		File.WriteAllBytes(text, ImageConversion.EncodeToPNG(val));
		Object.Destroy((Object)(object)val);
		Log("capture " + text);
	}

	private static List<(Skill skill, SummonAI summon)> SummonSkills()
	{
		Dictionary<string, Item> obj = (Dictionary<string, Item>)AccessTools.Field(typeof(ResourcesPrefabManager), "ITEM_PREFABS").GetValue(null);
		List<(Skill, SummonAI)> list = new List<(Skill, SummonAI)>();
		foreach (Item value in obj.Values)
		{
			Skill val = (Skill)(object)((value is Skill) ? value : null);
			if (val == null)
			{
				continue;
			}
			SummonAI[] componentsInChildren = ((Component)val).GetComponentsInChildren<SummonAI>(true);
			foreach (SummonAI val2 in componentsInChildren)
			{
				if ((Object)(object)((Summon)val2).SummonedPrefab != (Object)null && (Object)(object)((Component)((Summon)val2).SummonedPrefab).GetComponent<Character>() != (Object)null)
				{
					list.Add((val, val2));
				}
			}
		}
		return list.OrderBy(((Skill, SummonAI) f) => (((Object)((Summon)f.Item2).SummonedPrefab).name.IndexOf("Skeleton", StringComparison.OrdinalIgnoreCase) < 0) ? 1 : 0).ToList();
	}

	internal static List<Character> Allies(Character player)
	{
		return CharacterManager.Instance.Characters.Values.Where((Character c) => AllyPusher.IsAlly(c, player)).ToList();
	}

	private IEnumerator Video(Character player, Character ally, Passage.Found door, bool vanilla)
	{
		AllyPusher.Vanilla = vanilla;
		Vector3 dir = door.Direction;
		float ghostOffset = 0f;
		float num = 0f;
		string text = Arg("--nba-video-offsets");
		if (text != null)
		{
			float[] array = (from v in text.Split(new char[1] { ';' })
				select float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
			ghostOffset = array[0];
			num = array[1];
		}
		Vector3 val = Vector3.Cross(Vector3.up, dir);
		Vector3 right = ((Vector3)(ref val)).normalized;
		player.Teleport(Ground(door.Centre - dir * 2.2f + right * num).Value, Quaternion.LookRotation(dir));
		yield return WaitGame(0.5f);
		Vector3 val2 = (Vector3)(((??)Ground(door.Centre + right * ghostOffset)) ?? (door.Centre + right * ghostOffset));
		ally.Teleport(val2, Quaternion.LookRotation(-dir));
		Transform hold = new GameObject("NBA_Hold").transform;
		hold.position = val2;
		AISWander[] wanders = ((Component)ally).GetComponentsInChildren<AISWander>(true);
		Transform[] followed = wanders.Select((AISWander w) => w.FollowTransform).ToArray();
		Vector3[] offsets = wanders.Select((AISWander w) => w.FollowOffset).ToArray();
		AISWander[] array2 = wanders;
		foreach (AISWander obj in array2)
		{
			obj.FollowTransform = hold;
			obj.FollowOffset = Vector3.zero;
		}
		CharacterCamera camera = player.CharacterCamera;
		Quaternion yaw = Quaternion.LookRotation(dir);
		((Component)camera).transform.rotation = yaw;
		s_cameraPitch.Invoke(camera).localRotation = Quaternion.Euler(15f, 0f, 0f);
		yield return WaitRealtime(2f);
		string text2 = Path.Combine(OutputDir(), "video_" + (vanilla ? "vanilla" : "mod"));
		if (Directory.Exists(text2))
		{
			Directory.Delete(text2, recursive: true);
		}
		Directory.CreateDirectory(text2);
		Time.captureFramerate = 30;
		m_recording = true;
		((MonoBehaviour)this).StartCoroutine(Record(text2));
		float start = Time.time;
		float touched = -1f;
		float through = -1f;
		m_pushes = 0;
		for (float t = 0f; t < 0.7f; t += Time.deltaTime)
		{
			((Component)camera).transform.rotation = yaw;
			yield return null;
		}
		s_driving = true;
		while (Time.time - start < 8f)
		{
			Steer(player, dir);
			((Component)camera).transform.rotation = yaw;
			val = Flat(((Component)ally).transform.position - ((Component)player).transform.position);
			float num3 = ((Vector3)(ref val)).magnitude - player.CharacterController.radius - ally.CharacterController.radius;
			if (touched < 0f && num3 < 0.15f)
			{
				touched = Time.time - start;
			}
			if (through < 0f && Vector3.Dot(Flat(((Component)player).transform.position - door.Centre), dir) > 1.5f)
			{
				through = Time.time - start;
				for (int num4 = 0; num4 < wanders.Length; num4++)
				{
					wanders[num4].FollowTransform = followed[num4];
					wanders[num4].FollowOffset = offsets[num4];
				}
			}
			if (through > 0f && Time.time - start > through + 1.5f)
			{
				break;
			}
			yield return null;
		}
		s_driving = false;
		s_move = Vector2.zero;
		for (float t = 0f; t < 0.5f; t += Time.deltaTime)
		{
			((Component)camera).transform.rotation = yaw;
			yield return null;
		}
		m_recording = false;
		yield return null;
		Time.captureFramerate = 0;
		if (through < 0f)
		{
			for (int num5 = 0; num5 < wanders.Length; num5++)
			{
				wanders[num5].FollowTransform = followed[num5];
				wanders[num5].FollowOffset = offsets[num5];
			}
		}
		Object.Destroy((Object)(object)((Component)hold).gameObject);
		AllyPusher.Vanilla = false;
		Log(string.Format("video {0}: door {1:F2} m between {2}, touched at {3:F2} s, through at {4:F2} s, ", vanilla ? "vanilla" : "mod", door.Width, door.Sides, touched, through) + $"{m_pushes} push(es), take {Time.time - start:F2} s");
	}

	private IEnumerator Record(string dir)
	{
		int frame = 0;
		WaitForEndOfFrame endOfFrame = new WaitForEndOfFrame();
		while (m_recording)
		{
			yield return endOfFrame;
			Texture2D val = ScreenCapture.CaptureScreenshotAsTexture();
			File.WriteAllBytes(Path.Combine(dir, $"frame_{frame++:D4}.jpg"), ImageConversion.EncodeToJPG(val, 92));
			Object.Destroy((Object)(object)val);
		}
		Log($"video: {frame} frames in {dir}");
	}

	internal static IEnumerator SummonAlly(Character player, Action<Character> done)
	{
		List<(Skill, SummonAI)> list = SummonSkills();
		Log("summoning skills: " + string.Join(", ", list.Select<(Skill, SummonAI), string>(((Skill skill, SummonAI summon) s) => $"{((Item)s.skill).Name} ({((Item)s.skill).ItemID}) -> {((Object)((Summon)s.summon).SummonedPrefab).name}")));
		HashSet<Character> before = new HashSet<Character>(Allies(player));
		Character ally = null;
		foreach (var (prefabSkill, _) in list)
		{
			if ((Object)(object)((CharacterKnowledge)player.Inventory.SkillKnowledge).GetItemFromItemID(((Item)prefabSkill).ItemID) == (Object)null)
			{
				player.Inventory.ReceiveSkillReward(((Item)prefabSkill).ItemID);
				yield return WaitGame(1f);
			}
			Item itemFromItemID = ((CharacterKnowledge)player.Inventory.SkillKnowledge).GetItemFromItemID(((Item)prefabSkill).ItemID);
			SummonAI summon = (((Object)(object)itemFromItemID != (Object)null) ? ((Component)itemFromItemID).GetComponentInChildren<SummonAI>(true) : null);
			if ((Object)(object)summon == (Object)null)
			{
				Log(((Item)prefabSkill).Name + ": not learned, or no summon effect on the learned skill");
				continue;
			}
			yield return WaitGame(0.5f);
			try
			{
				((Effect)summon).Affect(player);
			}
			catch (Exception ex)
			{
				Log(((Item)prefabSkill).Name + ": summon threw " + ex.Message);
				continue;
			}
			for (float t = 0f; t < 5f; t += 0.25f)
			{
				if (!((Object)(object)ally == (Object)null))
				{
					break;
				}
				yield return WaitGame(0.25f);
				ally = ((IEnumerable<Character>)Allies(player)).FirstOrDefault((Func<Character, bool>)((Character c) => !before.Contains(c)));
			}
			if ((Object)(object)ally != (Object)null)
			{
				string text = $"summoned {ally.Name} ({((Object)ally).name}) with {((Item)prefabSkill).Name}, faction {ally.Faction}, ";
				CharacterController characterController = ally.CharacterController;
				object arg = ((characterController != null) ? new float?(characterController.radius) : ((float?)null));
				CharacterControl characterControl = ally.CharacterControl;
				CharacterControl obj = ((characterControl is CharacterAI) ? characterControl : null);
				Log(text + $"radius {arg}, AI state {((obj == null) ? null : ((object)((CharacterAI)obj).CurrentAiState)?.GetType().Name)}");
				break;
			}
			Log(((Item)prefabSkill).Name + ": no new ally after 5 s");
		}
		done(ally);
	}

	private IEnumerator Run()
	{
		string scene = Arg("--nba-scene");
		bool shots = UnityEngineExtensions.Contains<string>(Environment.GetCommandLineArgs(), "--nba-shots");
		Character player = null;
		float deadline = Time.realtimeSinceStartup + 900f;
		Scene activeScene;
		while (true)
		{
			if (Time.realtimeSinceStartup > deadline)
			{
				Plugin.Log.LogError((object)"nba-test: FAILED not in the scene after 900 s");
				yield break;
			}
			try
			{
				CharacterManager instance = CharacterManager.Instance;
				player = ((instance != null) ? instance.GetFirstLocalCharacter() : null);
			}
			catch (NullReferenceException)
			{
				player = null;
			}
			NetworkLevelLoader instance2 = NetworkLevelLoader.Instance;
			if ((Object)(object)player != (Object)null && (Object)(object)instance2 != (Object)null && instance2.IsOverallLoadingDone && !instance2.IsGameplayLoading)
			{
				if (scene == null)
				{
					break;
				}
				activeScene = SceneManager.GetActiveScene();
				if (((Scene)(ref activeScene)).name == scene)
				{
					break;
				}
			}
			yield return WaitRealtime(1f);
		}
		yield return WaitRealtime(3f);
		MenuManager.Instance.MasterCanvas.alpha = 1f;
		MenuManager.Instance.MasterCanvas.interactable = true;
		Plugin.LogPushes.Value = true;
		object[] array = new object[4];
		activeScene = SceneManager.GetActiveScene();
		array[0] = ((Scene)(ref activeScene)).name;
		AreaManager instance3 = AreaManager.Instance;
		activeScene = SceneManager.GetActiveScene();
		Area areaFromSceneName = instance3.GetAreaFromSceneName(((Scene)(ref activeScene)).name);
		array[1] = ((areaFromSceneName != null) ? areaFromSceneName.GetName() : null);
		array[2] = ((Component)player).transform.position;
		array[3] = player.Faction;
		Log(string.Format("in {0} ({1}) at {2}, player faction {3}, ", array) + $"push gap {Plugin.PushGap.Value}, step aside {Plugin.StepAsideDistance.Value} m / {Plugin.StepAsideTime.Value} s");
		if (Arg("--nba-video-point") != null)
		{
			player.Invincible = true;
			List<Character> list = CharacterManager.Instance.Characters.Values.Where((Character c) => (Object)(object)c != (Object)(object)player && c.IsAI && c.Faction != player.Faction).ToList();
			foreach (Character item in list)
			{
				((Component)item).gameObject.SetActive(false);
			}
			Log($"video: {list.Count} other character(s) removed");
		}
		Character ally = null;
		yield return SummonAlly(player, delegate(Character a)
		{
			ally = a;
		});
		if ((Object)(object)ally == (Object)null)
		{
			Plugin.Log.LogError((object)"nba-test: FAILED no ally summoned");
			yield break;
		}
		yield return WaitGame(2f);
		Passage.Found? passage = null;
		if (Arg("--nba-video") != null)
		{
			Passage.SideFilter = (string sides) => sides.IndexOf("door", StringComparison.OrdinalIgnoreCase) >= 0;
		}
		string text = Arg("--nba-video-point");
		if (text != null)
		{
			float[] array2 = (from v in text.Split(new char[1] { ';' })
				select float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(array2[0], array2[1], array2[2]);
			Vector3 val2 = new Vector3(array2[3], 0f, array2[4]);
			Vector3 normalized = ((Vector3)(ref val2)).normalized;
			Vector3 middle;
			float width = Passage.Width(val + Vector3.up * 0.1f, normalized, out middle);
			passage = new Passage.Found
			{
				Centre = (Ground(middle) ?? val),
				Direction = normalized,
				Width = width,
				Sides = Passage.Sides(middle, normalized)
			};
			Passage.Found? found = passage;
			Log("video point: " + found.ToString());
		}
		else
		{
			yield return Passage.Find(((Component)player).transform.position, 500f, delegate(Passage.Found? f)
			{
				passage = f;
			});
		}
		if (!passage.HasValue)
		{
			Plugin.Log.LogError((object)$"nba-test: FAILED no narrow passage around {((Component)player).transform.position}");
			yield break;
		}
		string text2 = Arg("--nba-video");
		if (text2 != null)
		{
			yield return Video(player, ally, passage.Value, text2 == "vanilla");
			Plugin.Log.LogMessage((object)"nba-test: done");
			yield break;
		}
		Vector3 dir = passage.Value.Direction;
		Vector3 past = Ground(passage.Value.Centre + dir * 2f).Value;
		Vector3 back = -dir;
		Vector3 home = ((Component)ally).transform.position;
		Log($"wait at {past}, then walk back toward {back} through a spot {passage.Value.Width:F2} m wide");
		float free = 0f;
		float vanilla = 0f;
		float mod = 0f;
		int vanillaPushes = 0;
		int modPushes = 0;
		float modAside = 0f;
		string[] array3 = new string[3] { "free", "vanilla", "mod" };
		foreach (string mode in array3)
		{
			AllyPusher.Vanilla = mode == "vanilla";
			player.Teleport(past, Quaternion.LookRotation(dir));
			yield return WaitGame(0.3f);
			AISWander[] wanders = ((Component)ally).GetComponentsInChildren<AISWander>(true);
			Transform[] followed = wanders.Select((AISWander w) => w.FollowTransform).ToArray();
			Transform hold = null;
			if (mode == "free")
			{
				hold = new GameObject("NBA_Hold").transform;
				hold.position = home;
				AISWander[] array4 = wanders;
				for (int num2 = 0; num2 < array4.Length; num2++)
				{
					array4[num2].FollowTransform = hold;
				}
				ally.Teleport(home, ((Component)ally).transform.rotation);
			}
			else
			{
				ally.Teleport((Vector3)(((??)Ground(passage.Value.Centre - dir * 1.5f)) ?? passage.Value.Centre), Quaternion.LookRotation(dir));
			}
			yield return WaitGame(4f);
			Vector3 val3 = Flat(((Component)ally).transform.position - passage.Value.Centre);
			Log($"  {mode}: ally settled {Vector3.Dot(val3, dir):F2} m along, {Vector3.Dot(val3, Vector3.Cross(Vector3.up, dir)):F2} m aside of the spot's centre");
			if (shots && mode != "free")
			{
				yield return (object)new WaitForEndOfFrame();
				Capture(mode + "_start.png");
			}
			m_pushes = 0;
			Vector3 from = ((Component)player).transform.position;
			float minGap = float.MaxValue;
			float maxAside = 0f;
			s_driving = true;
			int shot = 0;
			float nextTrace = 0f;
			CharacterControl characterControl = ally.CharacterControl;
			CharacterAI allyAi = (CharacterAI)(object)((characterControl is CharacterAI) ? characterControl : null);
			for (float t = 0f; t < 3f; t += Time.deltaTime)
			{
				Steer(player, back);
				if (mode != "free" && t >= nextTrace)
				{
					nextTrace += 0.25f;
					Log($"  t {t:F2} player {Vector3.Dot(Flat(((Component)player).transform.position - from), back):F2} along, ally " + $"{Vector3.Dot(Flat(((Component)ally).transform.position - from), back):F2} along " + $"{Vector3.Dot(Flat(((Component)ally).transform.position - from), Vector3.Cross(Vector3.up, back)):F2} aside, " + $"dest {allyAi.CurrentDestination}, speed {allyAi.SpeedModif:F2}, pushed {AllyPusher.IsPushed(ally)}");
				}
				Vector3 val4 = Flat(((Component)ally).transform.position - ((Component)player).transform.position);
				maxAside = Mathf.Max(maxAside, Mathf.Abs(Vector3.Dot(Flat(((Component)ally).transform.position - from), Vector3.Cross(Vector3.up, back))));
				minGap = Mathf.Min(minGap, ((Vector3)(ref val4)).magnitude - player.CharacterController.radius - ally.CharacterController.radius);
				if (shots && mode != "free" && t >= (float)shot * 0.5f && shot < 5)
				{
					yield return (object)new WaitForEndOfFrame();
					Capture($"{mode}_{shot++}.png");
				}
				yield return null;
			}
			s_driving = false;
			s_move = Vector2.zero;
			if ((Object)(object)hold != (Object)null)
			{
				for (int num3 = 0; num3 < wanders.Length; num3++)
				{
					wanders[num3].FollowTransform = followed[num3];
				}
				Object.Destroy((Object)(object)((Component)hold).gameObject);
			}
			float num4 = Vector3.Dot(Flat(((Component)player).transform.position - from), back);
			Log($"{mode}: walked {num4:F2} m in {3f} s, {m_pushes} push(es), closest gap {minGap:F2} m");
			if (mode == "free")
			{
				free = num4;
			}
			else if (mode == "vanilla")
			{
				vanilla = num4;
				vanillaPushes = m_pushes;
			}
			else
			{
				mod = num4;
			}
			if (mode == "mod")
			{
				modPushes = m_pushes;
				modAside = maxAside;
			}
			yield return WaitGame(0.5f);
		}
		AllyPusher.Vanilla = false;
		Check(free > 2f, $"free walk covers ground ({free:F2} m)");
		Check(vanilla < 0.8f * free, $"in vanilla the ally blocks: {vanilla:F2} m vs free {free:F2} m");
		Check(vanillaPushes == 0, $"no push with the mod off ({vanillaPushes})");
		Check(modPushes >= 1, $"walking into the ally pushes it ({modPushes} push(es), up to {modAside:F2} m aside)");
		Check(mod >= 0.8f * free, $"the pushed ally does not block: {mod:F2} m vs free {free:F2} m (vanilla {vanilla:F2} m)");
		yield return WaitGame(Plugin.StepAsideTime.Value + 4f);
		float num5 = Vector3.Distance(((Component)ally).transform.position, ((Component)player).transform.position);
		Check(!AllyPusher.IsPushed(ally) && num5 < 6f, $"the ally follows again ({num5:F2} m from the player)");
		Plugin.Log.LogMessage((object)((m_failures == 0) ? "nba-test: done" : $"nba-test: FAILED {m_failures} check(s)"));
	}
}