Decompiled source of Dopple But with fusion v1.4.6

DoppelNames.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BoneLib;
using BoneLib.BoneMenu;
using BoneLib.Notifications;
using DoppelNames;
using Il2CppSLZ.Marrow;
using Il2CppSLZ.Marrow.Warehouse;
using LabFusion.Data;
using LabFusion.Entities;
using LabFusion.Network;
using LabFusion.Network.Serialization;
using LabFusion.Player;
using LabFusion.Representation;
using LabFusion.SDK.Modules;
using LabFusion.UI;
using LabFusion.UI.Popups;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Mod), "DoppelNames", "1.7.0", "you", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: AssemblyCompany("DoppelNames")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.7.0.0")]
[assembly: AssemblyInformationalVersion("1.7.0")]
[assembly: AssemblyProduct("DoppelNames")]
[assembly: AssemblyTitle("DoppelNames")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.7.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DoppelNames
{
	internal static class AttackBridge
	{
		[MethodImpl(MethodImplOptions.NoInlining)]
		public static bool Step(object botRig, byte targetId, int index)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: 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_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: 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_00e3: Unknown result type (might be due to invalid IL or missing references)
			NetworkPlayer val = default(NetworkPlayer);
			if (!NetworkPlayerManager.TryGetPlayer(targetId, ref val) || val == null)
			{
				return false;
			}
			RigRefs rigRefs = val.RigRefs;
			if (rigRefs == null || !rigRefs.IsValid || (Object)(object)rigRefs.Head == (Object)null)
			{
				return false;
			}
			RigManager val2 = (RigManager)((botRig is RigManager) ? botRig : null);
			if ((Object)(object)val2 == (Object)null || (Object)(object)val2.physicsRig == (Object)null)
			{
				return true;
			}
			Hand leftHand = val2.physicsRig.leftHand;
			Hand rightHand = val2.physicsRig.rightHand;
			if ((Object)(object)leftHand == (Object)null || (Object)(object)rightHand == (Object)null)
			{
				return true;
			}
			Vector3 position = rigRefs.Head.position;
			if (Vector3.Distance(((Component)leftHand).transform.position, position) > 3f)
			{
				float num = (float)index * 90f * ((float)Math.PI / 180f);
				Vector3 val3 = position + new Vector3(Mathf.Cos(num) * 0.8f, -1.5f, Mathf.Sin(num) * 0.8f);
				val2.Teleport(val3, true);
				return true;
			}
			List<GameObject> list = new List<GameObject>();
			Grip[] rigGrips = rigRefs.RigGrips;
			foreach (Grip val4 in rigGrips)
			{
				if ((Object)(object)val4 != (Object)null)
				{
					list.Add(((Component)val4).gameObject);
				}
			}
			if (list.Count == 0)
			{
				return true;
			}
			AttachNearest(leftHand, list);
			AttachNearest(rightHand, list);
			return true;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Release(object botRig)
		{
			RigManager val = (RigManager)((botRig is RigManager) ? botRig : null);
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val.physicsRig == (Object)null))
			{
				if ((Object)(object)val.physicsRig.leftHand != (Object)null)
				{
					val.physicsRig.leftHand.DetachObject();
				}
				if ((Object)(object)val.physicsRig.rightHand != (Object)null)
				{
					val.physicsRig.rightHand.DetachObject();
				}
			}
		}

		private static void AttachNearest(Hand hand, List<GameObject> grips)
		{
			//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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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)
			if (hand.HasAttachedObject())
			{
				return;
			}
			Vector3 position = ((Component)hand).transform.position;
			GameObject val = null;
			float num = float.MaxValue;
			foreach (GameObject grip in grips)
			{
				Vector3 val2 = grip.transform.position - position;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				if (sqrMagnitude < num)
				{
					num = sqrMagnitude;
					val = grip;
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				hand.AttachObject(val);
			}
		}
	}
	internal static class AvatarClone
	{
		private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		private static bool _logged;

		public static string CurrentId(object rig)
		{
			RigManager val = (RigManager)((rig is RigManager) ? rig : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val.avatar == (Object)null || val.AvatarCrate == null)
			{
				return null;
			}
			string iD = ((ScannableReference)val.AvatarCrate).Barcode.ID;
			if (!string.IsNullOrEmpty(iD))
			{
				return iD;
			}
			return null;
		}

		public static bool Request(object rig, string barcodeId)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			MethodInfo methodInfo = rig.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo m) => m.Name == "SwapAvatarCrate");
			if (methodInfo == null)
			{
				MelonLogger.Warning("DoppelNames: this game version has no SwapAvatarCrate on the rig.");
				return false;
			}
			ParameterInfo[] parameters = methodInfo.GetParameters();
			object[] array = new object[parameters.Length];
			for (int num = 0; num < parameters.Length; num++)
			{
				if (num == 0)
				{
					array[num] = (object)new Barcode(barcodeId);
				}
				else if (parameters[num].ParameterType == typeof(bool))
				{
					array[num] = true;
				}
				else
				{
					array[num] = null;
				}
			}
			if (!_logged)
			{
				_logged = true;
				MelonLogger.Msg("DoppelNames: avatar cloning uses SwapAvatarCrate(" + string.Join(", ", parameters.Select((ParameterInfo p) => p.ParameterType.Name + " " + p.Name)) + ")");
			}
			try
			{
				methodInfo.Invoke(rig, array);
				return true;
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("DoppelNames: avatar swap failed: " + (ex.InnerException?.Message ?? ex.Message));
				return false;
			}
		}
	}
	internal static class BotNames
	{
		public static readonly string[] PackNames = new string[5] { "Classic", "Fantasy", "Sci-Fi", "Gamer", "Spooky" };

		private static readonly string[][] Adjectives = new string[5][]
		{
			new string[10] { "Mossy", "Quiet", "Rusty", "Sleepy", "Neon", "Dusty", "Lucky", "Fuzzy", "Gloomy", "Zesty" },
			new string[10] { "Brave", "Ancient", "Shadow", "Golden", "Wandering", "Silver", "Wild", "Noble", "Cursed", "Mighty" },
			new string[10] { "Cyber", "Quantum", "Plasma", "Hyper", "Orbital", "Stellar", "Rogue", "Binary", "Photon", "Turbo" },
			new string[10] { "xX", "Sweaty", "Pro", "Epic", "Toxic", "Sneaky", "Salty", "Clutch", "Tryhard", "Casual" },
			new string[10] { "Creepy", "Haunted", "Pale", "Midnight", "Hollow", "Grim", "Spooky", "Eerie", "Moaning", "Restless" }
		};

		private static readonly string[][] Nouns = new string[5][]
		{
			new string[10] { "Fox", "Pebble", "Moth", "Cactus", "Badger", "Comet", "Walnut", "Otter", "Beacon", "Gecko" },
			new string[10] { "Knight", "Wizard", "Dragon", "Ranger", "Bard", "Goblin", "Paladin", "Rogue", "Druid", "Troll" },
			new string[10] { "Pilot", "Droid", "Nebula", "Cadet", "Rover", "Android", "Comet", "Probe", "Rocket", "Alien" },
			new string[10] { "Sniper", "Noob", "Legend", "Gamer", "Hero", "Camper", "Wizard", "Boss", "Ninja", "Champ" },
			new string[10] { "Ghost", "Skeleton", "Phantom", "Witch", "Raven", "Zombie", "Ghoul", "Spirit", "Bat", "Pumpkin" }
		};

		private static readonly Random Rng = new Random();

		public static int Pack;

		public static string NextPack()
		{
			Pack = (Pack + 1) % PackNames.Length;
			return PackNames[Pack];
		}

		public static string Next(Func<string, bool> isTaken)
		{
			string[] array = Adjectives[Pack];
			string[] array2 = Nouns[Pack];
			for (int i = 0; i < 50; i++)
			{
				string text = "[Bot] " + array[Rng.Next(array.Length)] + " " + array2[Rng.Next(array2.Length)];
				if (!isTaken(text))
				{
					return text;
				}
			}
			return "[Bot] #" + Rng.Next(1000, 9999);
		}

		public static string ForDoppelOf(string playerName)
		{
			return "[Bot] " + playerName + "'s Doppel";
		}
	}
	internal static class DoppelBridge
	{
		private static Assembly _asm;

		private static readonly Dictionary<string, MethodInfo> Cache = new Dictionary<string, MethodInfo>();

		public static bool Available => FindAssembly() != null;

		private static Assembly FindAssembly()
		{
			if (_asm != null)
			{
				return _asm;
			}
			_asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "Doppel");
			return _asm;
		}

		private static MethodInfo Find(string method)
		{
			if (Cache.TryGetValue(method, out var value))
			{
				return value;
			}
			Assembly assembly = FindAssembly();
			if (assembly == null)
			{
				return null;
			}
			Type[] source;
			try
			{
				source = assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				source = ex.Types.Where((Type t) => t != null).ToArray();
			}
			MethodInfo methodInfo = (from m in source.SelectMany((Type t) => t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
				where m.Name == method
				orderby m.GetParameters().Length
				select m).FirstOrDefault();
			Cache[method] = methodInfo;
			if (methodInfo != null)
			{
				MelonLogger.Msg("[DoppelNames] " + method + " -> " + methodInfo.DeclaringType?.FullName + "." + methodInfo.Name + "(" + string.Join(", ", from p in methodInfo.GetParameters()
					select p.ParameterType.Name + " " + p.Name) + ") static=" + methodInfo.IsStatic);
			}
			else
			{
				MelonLogger.Warning("[DoppelNames] Doppel has no method named " + method + ".");
			}
			return methodInfo;
		}

		public static bool Call(string method, string botName, Vector3? at = null)
		{
			MethodInfo methodInfo = Find(method);
			if (methodInfo == null)
			{
				return false;
			}
			object obj = null;
			if (!methodInfo.IsStatic)
			{
				Type? declaringType = methodInfo.DeclaringType;
				FieldInfo field = declaringType.GetField("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				PropertyInfo property = declaringType.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				obj = field?.GetValue(null) ?? property?.GetValue(null);
				if (obj == null)
				{
					MelonLogger.Warning("[DoppelNames] " + method + " is an instance method and no Instance was found.");
					return false;
				}
			}
			try
			{
				object[] parameters = methodInfo.GetParameters().Select(delegate(ParameterInfo p)
				{
					//IL_004e: 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)
					if (p.ParameterType == typeof(string))
					{
						return botName;
					}
					if (p.ParameterType == typeof(Vector3))
					{
						return (object)(Vector3)(((??)at) ?? Vector3.zero);
					}
					if (p.HasDefaultValue)
					{
						return p.DefaultValue;
					}
					return (!p.ParameterType.IsValueType) ? null : Activator.CreateInstance(p.ParameterType);
				}).ToArray();
				methodInfo.Invoke(obj, parameters);
				return true;
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[DoppelNames] " + method + " failed: " + (ex.InnerException?.Message ?? ex.Message));
				return false;
			}
		}
	}
	internal static class FusionBridge
	{
		private const long Tag = 7391645520138472951L;

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static bool Start()
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Expected O, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			if (ModuleMessageManager.TagToHandlerLookup.TryGetValue(7391645520138472951L, out var value))
			{
				ModuleMessageManager.TagToHandlerLookup.Remove(7391645520138472951L);
				ModuleMessageManager.Handlers.Remove(value);
				ModuleMessageManager.TypeToHandlerLookup.Remove(((object)value).GetType());
			}
			NamesMessage namesMessage = new NamesMessage();
			FieldInfo field = typeof(ModuleMessageHandler).GetField("_tag", BindingFlags.Instance | BindingFlags.NonPublic);
			if (field == null)
			{
				throw new Exception("this Fusion keeps its handlers' numbers some other way");
			}
			Type conversionType = Nullable.GetUnderlyingType(field.FieldType) ?? field.FieldType;
			field.SetValue(namesMessage, Convert.ChangeType(7391645520138472951L, conversionType));
			PropertyInfo property = typeof(MessageHandler).GetProperty("NetAttributes", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property != null)
			{
				property.SetValue(namesMessage, Array.CreateInstance(property.PropertyType.GetElementType(), 0));
			}
			ModuleMessageManager.Handlers.Add((ModuleMessageHandler)namesMessage);
			ModuleMessageManager.TypeToHandlerLookup[typeof(NamesMessage)] = (ModuleMessageHandler)namesMessage;
			ModuleMessageManager.TagToHandlerLookup[7391645520138472951L] = (ModuleMessageHandler)namesMessage;
			return true;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Stop()
		{
			if (ModuleMessageManager.TagToHandlerLookup.TryGetValue(7391645520138472951L, out var value))
			{
				ModuleMessageManager.TagToHandlerLookup.Remove(7391645520138472951L);
				ModuleMessageManager.Handlers.Remove(value);
				ModuleMessageManager.TypeToHandlerLookup.Remove(((object)value).GetType());
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static bool IsOnline()
		{
			try
			{
				return NetworkInfo.HasServer && PlayerIDManager.HasOtherPlayers;
			}
			catch
			{
				return false;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Send(byte[] payload)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			MessageRelay.RelayModule<NamesMessage, NamesData>(new NamesData
			{
				bytes = payload
			}, CommonMessageRoutes.ReliableToOtherClients);
		}
	}
	internal static class FusionFakes
	{
		private sealed class Fake
		{
			public ulong PlatformID;

			public byte SmallID;

			public PlayerID Id;

			public string Name;

			public string Barcode;

			public SerializedAvatarStats Stats;

			public RigSkeleton Skeleton;

			public readonly RigPose Pose = new RigPose();

			public float Created;

			public int Failures;

			public float RetryAt;

			public bool WarnedStop;

			public float SkeletonBuilt;

			public int PosesSent;

			public float NextReport;

			public readonly Dictionary<ulong, float> Introduced = new Dictionary<ulong, float>();
		}

		private const ulong FakePlatformBase = 940053923165634560uL;

		private static ulong counter;

		private const float IntroDelay = 1.5f;

		private const float PoseDelay = 0.6f;

		private static readonly List<Fake> all = new List<Fake>();

		private static readonly Dictionary<ulong, float> firstSeen = new Dictionary<ulong, float>();

		private static bool warnedNoIds;

		public static string LastReason = "";

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static bool IsHosting()
		{
			try
			{
				return NetworkInfo.HasServer && NetworkInfo.IsHost;
			}
			catch
			{
				return false;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static object Add(string name, object rig)
		{
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Expected O, but got Unknown
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Expected O, but got Unknown
			RigManager val = (RigManager)((rig is RigManager) ? rig : null);
			if ((Object)(object)val == (Object)null)
			{
				LastReason = "the bot has no rig yet";
				return null;
			}
			if ((Object)(object)val.avatar == (Object)null)
			{
				LastReason = "the bot has no avatar yet";
				return null;
			}
			if ((Object)(object)val.physicsRig == (Object)null)
			{
				LastReason = "the bot has no physics rig yet";
				return null;
			}
			if (val.AvatarCrate == null)
			{
				LastReason = "the bot's avatar has no crate";
				return null;
			}
			string iD = ((ScannableReference)val.AvatarCrate).Barcode.ID;
			if (string.IsNullOrEmpty(iD))
			{
				LastReason = "the bot's avatar has no barcode";
				return null;
			}
			PlayerID localID = PlayerIDManager.LocalID;
			if (localID == null)
			{
				LastReason = "your own player id is missing";
				return null;
			}
			byte? uniquePlayerID = PlayerIDManager.GetUniquePlayerID();
			if (!uniquePlayerID.HasValue)
			{
				LastReason = "no free player slot";
				if (!warnedNoIds)
				{
					warnedNoIds = true;
					MelonLogger.Warning("DoppelNames: no free player slot for a server-side bot.");
				}
				return null;
			}
			Dictionary<string, string> dictionary = new Dictionary<string, string>(localID.Metadata.Metadata.LocalDictionary);
			dictionary["Username"] = name;
			dictionary["Nickname"] = "";
			dictionary["Description"] = "";
			dictionary["Loading"] = "false";
			dictionary["PermissionLevel"] = ((object)(PermissionLevel)0/*cast due to .constrained prefix*/).ToString();
			Fake fake = new Fake
			{
				PlatformID = 940053923165634560L + ++counter,
				SmallID = uniquePlayerID.Value,
				Name = name,
				Barcode = iD,
				Stats = new SerializedAvatarStats(val.avatar),
				Created = Time.unscaledTime
			};
			fake.Id = new PlayerID(fake.PlatformID, fake.SmallID, dictionary, new List<string>());
			PlayerIDManager.ReserveSmallID(fake.SmallID);
			all.Add(fake);
			MelonLogger.Msg($"DoppelNames: server-side bot '{name}' created (player slot {fake.SmallID}).");
			return fake;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Tick(object handle, object rig)
		{
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Expected O, but got Unknown
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Expected O, but got Unknown
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			Fake fake = (Fake)handle;
			if (fake.Failures > 40)
			{
				if (Time.unscaledTime < fake.RetryAt)
				{
					return;
				}
				fake.Failures = 0;
				fake.Skeleton = null;
			}
			try
			{
				float unscaledTime = Time.unscaledTime;
				List<ulong> list = Recipients(unscaledTime);
				if (list.Count == 0)
				{
					if (unscaledTime >= fake.NextReport)
					{
						fake.NextReport = unscaledTime + 10f;
						MelonLogger.Msg("DoppelNames: '" + fake.Name + "': waiting, no other players in the lobby.");
					}
					return;
				}
				foreach (ulong item in list)
				{
					if (!fake.Introduced.ContainsKey(item) && !(unscaledTime - firstSeen[item] < 1.5f))
					{
						bool flag = unscaledTime - fake.Created < 4.5f;
						SendJoin(fake, item, flag);
						fake.Introduced[item] = unscaledTime;
						MelonLogger.Msg($"DoppelNames: introduced '{fake.Name}' (slot {fake.SmallID}) to player {item}" + (flag ? " with a join notice." : "."));
					}
				}
				RigManager val = (RigManager)((rig is RigManager) ? rig : null);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				List<ulong> list2 = new List<ulong>();
				foreach (KeyValuePair<ulong, float> item2 in fake.Introduced)
				{
					if (unscaledTime - item2.Value >= 0.6f && list.Contains(item2.Key))
					{
						list2.Add(item2.Key);
					}
				}
				if (list2.Count == 0)
				{
					if (unscaledTime >= fake.NextReport)
					{
						fake.NextReport = unscaledTime + 10f;
						MelonLogger.Msg($"DoppelNames: '{fake.Name}': {list.Count} player(s) here, none ready for poses yet.");
					}
					return;
				}
				if (fake.Skeleton == null || unscaledTime - fake.SkeletonBuilt > 10f)
				{
					fake.Skeleton = new RigSkeleton(val);
					fake.SkeletonBuilt = unscaledTime;
				}
				fake.Pose.ReadSkeleton(fake.Skeleton);
				PlayerPoseUpdateData val2 = PlayerPoseUpdateData.Create(fake.Pose);
				NetWriter val3 = NetWriter.Create(val2.GetSize());
				try
				{
					val2.Serialize((INetSerializer)val3);
					NetMessage val4 = NetMessage.Create(NativeMessageTag.PlayerPoseUpdate, val3, CommonMessageRoutes.UnreliableToOtherClients, (byte?)fake.SmallID);
					try
					{
						foreach (ulong item3 in list2)
						{
							MessageSender.SendFromServer(item3, (NetworkChannel)1, val4);
						}
					}
					finally
					{
						((IDisposable)val4)?.Dispose();
					}
				}
				finally
				{
					((IDisposable)val3)?.Dispose();
				}
				fake.PosesSent++;
				fake.Failures = 0;
				if (unscaledTime >= fake.NextReport)
				{
					fake.NextReport = unscaledTime + 10f;
					MelonLogger.Msg($"DoppelNames: '{fake.Name}': {fake.PosesSent} pose updates sent so far to {list2.Count} player(s).");
				}
			}
			catch (Exception ex)
			{
				fake.Skeleton = null;
				if (++fake.Failures == 41)
				{
					fake.RetryAt = Time.unscaledTime + 5f;
					if (!fake.WarnedStop)
					{
						fake.WarnedStop = true;
						MelonLogger.Warning("DoppelNames: server-side bot '" + fake.Name + "' paused updating (will retry): " + ex.Message);
					}
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Remove(object handle)
		{
			Fake fake = (Fake)handle;
			all.Remove(fake);
			try
			{
				foreach (ulong item in Recipients(Time.unscaledTime))
				{
					if (fake.Introduced.ContainsKey(item))
					{
						SendLeave(fake, item);
					}
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("DoppelNames: could not announce a bot leaving: " + ex.Message);
			}
			PlayerIDManager.UnreserveSmallID(fake.SmallID);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Forget(object handle)
		{
			Fake fake = (Fake)handle;
			all.Remove(fake);
			PlayerIDManager.UnreserveSmallID(fake.SmallID);
		}

		private static void SendJoin(Fake f, ulong recipient, bool notify)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			ConnectionResponseData val = ConnectionResponseData.Create(f.Id, f.Barcode, f.Stats, notify);
			NetWriter val2 = NetWriter.Create();
			try
			{
				NetSerializerExtensions.SerializeValue<ConnectionResponseData>((INetSerializer)val2, ref val);
				NetMessage val3 = NetMessage.Create(NativeMessageTag.ConnectionResponse, val2, CommonMessageRoutes.None, (byte?)null);
				try
				{
					MessageSender.SendFromServer(recipient, (NetworkChannel)0, val3);
				}
				finally
				{
					((IDisposable)val3)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}

		private static void SendLeave(Fake f, ulong recipient)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			DisconnectMessageData val = DisconnectMessageData.Create(f.PlatformID, "");
			NetWriter val2 = NetWriter.Create();
			try
			{
				NetSerializerExtensions.SerializeValue<DisconnectMessageData>((INetSerializer)val2, ref val);
				NetMessage val3 = NetMessage.Create(NativeMessageTag.Disconnect, val2, CommonMessageRoutes.None, (byte?)null);
				try
				{
					MessageSender.SendFromServer(recipient, (NetworkChannel)0, val3);
				}
				finally
				{
					((IDisposable)val3)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val2)?.Dispose();
			}
		}

		private static List<ulong> Recipients(float now)
		{
			List<ulong> list = new List<ulong>();
			HashSet<ulong> hashSet = new HashSet<ulong>();
			foreach (PlayerID playerID in PlayerIDManager.PlayerIDs)
			{
				if (!playerID.IsMe)
				{
					ulong platformID = playerID.PlatformID;
					hashSet.Add(platformID);
					list.Add(platformID);
					if (!firstSeen.ContainsKey(platformID))
					{
						firstSeen[platformID] = now;
					}
				}
			}
			List<ulong> list2 = null;
			foreach (ulong key in firstSeen.Keys)
			{
				if (!hashSet.Contains(key))
				{
					(list2 ?? (list2 = new List<ulong>())).Add(key);
				}
			}
			if (list2 != null)
			{
				foreach (ulong item in list2)
				{
					firstSeen.Remove(item);
					foreach (Fake item2 in all)
					{
						item2.Introduced.Remove(item);
					}
				}
			}
			return list;
		}
	}
	internal static class FusionTags
	{
		private sealed class Handle
		{
			public RigHeadUI HeadUI;

			public RigNameTag Tag;

			public int Failures;

			public float RetryAt;

			public bool Warned;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static object Create(string name)
		{
			//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_000d: Expected O, but got Unknown
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Expected O, but got Unknown
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			RigNameTag val = new RigNameTag
			{
				Username = name
			};
			RigHeadUI val2 = new RigHeadUI();
			val2.RegisterElement((IPopupLayoutElement)val);
			val2.Spawn();
			return new Handle
			{
				HeadUI = val2,
				Tag = val
			};
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void SetName(object handle, string name)
		{
			Handle handle2 = (Handle)handle;
			if (handle2.Tag.Username != name)
			{
				handle2.Tag.Username = name;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Follow(object handle, object rig)
		{
			Handle handle2 = (Handle)handle;
			if (handle2.Failures > 30)
			{
				if (Time.unscaledTime < handle2.RetryAt)
				{
					return;
				}
				handle2.Failures = 0;
			}
			RigManager val = (RigManager)((rig is RigManager) ? rig : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				handle2.HeadUI.UpdateScale(val);
				handle2.HeadUI.UpdateTransform(val);
				handle2.Failures = 0;
			}
			catch (Exception ex)
			{
				if (++handle2.Failures == 31)
				{
					handle2.RetryAt = Time.unscaledTime + 5f;
					if (!handle2.Warned)
					{
						handle2.Warned = true;
						MelonLogger.Warning("DoppelNames: a name tag paused following its bot (will retry): " + ex.Message);
					}
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Destroy(object handle)
		{
			((Handle)handle).HeadUI.Despawn();
		}
	}
	internal static class HostMenu
	{
		private static Page _root;

		private static Page _playerPage;

		private static Page _confirmPage;

		private static Page _fun;

		private static Page _botPage;

		private static Page _clonePage;

		private static Page _attackPage;

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static void Init()
		{
			//IL_000a: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: 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_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0175: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_0395: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_0455: Unknown result type (might be due to invalid IL or missing references)
			_root = Page.Root.CreatePage("Doppel with Fusion", Color.cyan, 0, true);
			_root.CreateFunction("Spawn Bot (random name)", Color.green, (Action)SpawnRandom);
			_root.CreateFunction("Spawn 3 bots", Color.green, (Action)SpawnThree);
			_root.CreateFunction("Attack player", Color.red, (Action)OpenAttackList);
			_root.CreateFunction("Stop attack", Color.white, (Action)StopAttack);
			_root.CreateFunction("Doppel a player...", Color.yellow, (Action)OpenPlayerList);
			_root.CreateFunction("Show bots", Color.white, (Action)ShowBots);
			_root.CreateFunction("Bring back lost bots now", Color.yellow, (Action)RespawnNow);
			_root.CreateBool("Keep bots alive", Color.cyan, Mod.Instance != null && Mod.Instance.KeepAlive, (Action<bool>)SetKeepAlive);
			_root.CreateBool("Name tags", Color.cyan, Mod.Instance != null && Mod.Instance.ShowNameTags, (Action<bool>)SetNameTags);
			_root.CreateBool("Join/leave pop-ups", Color.cyan, Mod.Instance != null && Mod.Instance.ShowPopups, (Action<bool>)SetPopups);
			_fun = _root.CreatePage("Fun stuff", Color.magenta, 0, true);
			_fun.CreateFunction("Bot party (5 trickle in)", Color.green, (Action)BotParty);
			_fun.CreateFunction("Doppel everyone", Color.yellow, (Action)DoppelEveryone);
			_fun.CreateInt("Keep N bots around (0 = off)", Color.cyan, 0, 1, 0, 10, (Action<int>)SetPopulation);
			_fun.CreateFunction("Next name pack", Color.white, (Action)NextPack);
			_fun.CreateBool("Silly join/leave messages", Color.cyan, Mod.Instance != null && Mod.Instance.SillyMessages, (Action<bool>)SetSilly);
			_fun.CreateFunction("Prank: fake player joins", Color.white, (Action)PrankJoin);
			_fun.CreateFunction("Prank: fake player leaves", Color.white, (Action)PrankLeave);
			_fun.CreateFunction("Possess a random bot (swap places)", Color.red, (Action)PossessRandom);
			_fun.CreateFunction("Possess a bot...", Color.red, (Action)OpenBotList);
			_fun.CreateFunction("Clone a player (same name)...", Color.yellow, (Action)OpenCloneList);
			_root.CreateFunction("Remove all bots", Color.red, (Action)RemoveAll);
		}

		private static void BotParty()
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			if (!RequireOwner() || Mod.Instance == null)
			{
				return;
			}
			for (int i = 0; i < 5; i++)
			{
				Mod.Instance.Schedule(BotNames.Next((string n) => Mod.Instance.IsNameTaken(n)), (float)i * 2f);
			}
			Toast("Bot party", "5 bots will trickle in over the next few seconds.", Kind("Information"));
		}

		private static void DoppelEveryone()
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			if (!RequireOwner() || Mod.Instance == null)
			{
				return;
			}
			int num = 0;
			foreach (PlayerID item in PlayerIDManager.PlayerIDs.ToList())
			{
				if (!item.IsMe)
				{
					string playerName = item.Metadata.Username.GetValue() ?? $"Player {item.SmallID}";
					Mod.Instance.Schedule(BotNames.ForDoppelOf(playerName), (float)num * 1.5f);
					num++;
				}
			}
			Toast("Doppel everyone", (num == 0) ? "No other players here." : ("Doppelling " + num + " player(s)."), Kind("Information"));
		}

		private static void SetPopulation(int value)
		{
			if (Mod.Instance != null && (value <= 0 || RequireOwner()))
			{
				Mod.Instance.SetPopulation(value);
			}
		}

		private static void NextPack()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Toast("Name pack", BotNames.NextPack(), Kind("Information"));
		}

		private static void SetSilly(bool value)
		{
			if (Mod.Instance != null)
			{
				Mod.Instance.SillyMessages = value;
			}
		}

		private static string AvatarOf(PlayerID player)
		{
			try
			{
				NetworkPlayer val = default(NetworkPlayer);
				if (!NetworkPlayerManager.TryGetPlayer(player.SmallID, ref val) || val == null)
				{
					return null;
				}
				string text = ((val.AvatarSetter != null) ? val.AvatarSetter.AvatarBarcode : null);
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
				RigManager val2 = ((val.RigRefs != null) ? val.RigRefs.RigManager : null);
				if ((Object)(object)val2 != (Object)null && val2.AvatarCrate != null)
				{
					return ((ScannableReference)val2.AvatarCrate).Barcode.ID;
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("DoppelNames: could not read a player's avatar: " + ex.Message);
			}
			return null;
		}

		private static void CloneNow(PlayerID player, string shown)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (RequireOwner() && Mod.Instance != null)
			{
				string text = AvatarOf(player);
				if (string.IsNullOrEmpty(text))
				{
					Toast("Clone", "Couldn't read their avatar, so only the name is copied.", Kind("Warning"));
				}
				else
				{
					Mod.Instance.ExpectClone(shown, text);
				}
				SpawnNamed(shown);
			}
		}

		private static void OpenAttackList()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			if (!RequireOwner())
			{
				return;
			}
			Page attackPage = _attackPage;
			if (attackPage != null)
			{
				attackPage.RemoveAll();
			}
			if (_attackPage == null)
			{
				_attackPage = _root.CreatePage("Attack who?", Color.red, 0, true);
			}
			int num = 0;
			foreach (PlayerID player in PlayerIDManager.PlayerIDs.ToList())
			{
				if (!player.IsMe)
				{
					string shown = player.Metadata.Username.GetValue() ?? $"Player {player.SmallID}";
					_attackPage.CreateFunction(shown, Color.white, (Action)delegate
					{
						AttackNow(player, shown);
					});
					num++;
				}
			}
			if (num == 0)
			{
				Toast("Attack", "No other players here.", Kind("Warning"));
			}
			else
			{
				Menu.OpenPage(_attackPage);
			}
		}

		private static void AttackNow(PlayerID player, string shown)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			if (RequireOwner() && Mod.Instance != null)
			{
				for (int i = 0; i < 4; i++)
				{
					string text = "Husser " + (i + 1);
					Mod.Instance.ExpectAttack(text, player.SmallID, i);
					Mod.Instance.Schedule(text, (float)i * 0.5f);
				}
				Toast("Attack", "Husser 1-4 are going after " + shown + ".", Kind("Information"));
			}
		}

		private static void StopAttack()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			Mod.Instance?.StopAttacks();
			Toast("Attack", "The Hussers let go.", Kind("Information"));
		}

		private static void OpenCloneList()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			if (!RequireOwner())
			{
				return;
			}
			Page clonePage = _clonePage;
			if (clonePage != null)
			{
				clonePage.RemoveAll();
			}
			if (_clonePage == null)
			{
				_clonePage = _fun.CreatePage("Clone which player?", Color.yellow, 0, true);
			}
			foreach (PlayerID player in PlayerIDManager.PlayerIDs.ToList())
			{
				if (!player.IsMe)
				{
					string shown = player.Metadata.Username.GetValue() ?? $"Player {player.SmallID}";
					_clonePage.CreateFunction(shown, Color.white, (Action)delegate
					{
						CloneNow(player, shown);
					});
				}
			}
			Menu.OpenPage(_clonePage);
		}

		private static void PossessRandom()
		{
			DoPossess(null);
		}

		private static void OpenBotList()
		{
			//IL_002a: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			if (Mod.Instance == null)
			{
				return;
			}
			List<string> list = Mod.Instance.BotList();
			if (list.Count == 0)
			{
				Toast("Possession", "No bots to possess. Spawn one first.", Kind("Warning"));
				return;
			}
			Page botPage = _botPage;
			if (botPage != null)
			{
				botPage.RemoveAll();
			}
			if (_botPage == null)
			{
				_botPage = _fun.CreatePage("Pick a bot", Color.red, 0, true);
			}
			foreach (string item in list)
			{
				string picked = item;
				_botPage.CreateFunction(picked, Color.white, (Action)delegate
				{
					DoPossess(picked);
				});
			}
			Menu.OpenPage(_botPage);
		}

		private static void DoPossess(string botName)
		{
			//IL_0030: 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)
			if (Mod.Instance != null)
			{
				string message;
				bool flag = Mod.Instance.Possess(botName, out message);
				Toast("Possession", message, flag ? Kind("Success") : Kind("Warning"));
			}
		}

		private static void PrankJoin()
		{
			Mod.Instance?.FakeJoin();
		}

		private static void PrankLeave()
		{
			Mod.Instance?.FakeLeave();
		}

		private static NotificationType Kind(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			if (!Enum.TryParse<NotificationType>(name, out NotificationType result))
			{
				return (NotificationType)0;
			}
			return result;
		}

		private static void SetKeepAlive(bool value)
		{
			if (Mod.Instance != null)
			{
				Mod.Instance.KeepAlive = value;
			}
		}

		private static void SetNameTags(bool value)
		{
			if (Mod.Instance != null)
			{
				Mod.Instance.ShowNameTags = value;
			}
		}

		private static void SetPopups(bool value)
		{
			if (Mod.Instance != null)
			{
				Mod.Instance.ShowPopups = value;
			}
		}

		private static void SpawnThree()
		{
			if (!RequireOwner())
			{
				return;
			}
			for (int i = 0; i < 3; i++)
			{
				SpawnNamed(BotNames.Next((string name) => Mod.Instance != null && Mod.Instance.IsNameTaken(name)));
			}
		}

		private static void ShowBots()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			string message = ((Mod.Instance != null) ? Mod.Instance.DescribeBots() : "Mod not ready.");
			Toast("Bots", message, Kind("Information"));
		}

		private static void RespawnNow()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			if (RequireOwner())
			{
				int num = ((Mod.Instance != null) ? Mod.Instance.RespawnNow() : 0);
				Toast("Bots", (num == 0) ? "No lost bots waiting." : ("Bringing back " + num + " bot(s)."), Kind("Information"));
			}
		}

		private static bool RequireOwner()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (NetworkInfo.IsHost)
			{
				return true;
			}
			Toast("Owner only", "You must be hosting the server (owner) to use this.", Kind("Error"));
			return false;
		}

		private static void Toast(string title, string message, NotificationType type)
		{
			//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_0007: 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_0013: 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_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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			Notifier.Send(new Notification
			{
				Title = NotificationText.op_Implicit(title),
				Message = NotificationText.op_Implicit(message),
				Type = type,
				SaveToMenu = false,
				ShowPopup = true
			});
		}

		private static void SpawnRandom()
		{
			if (RequireOwner())
			{
				SpawnNamed(BotNames.Next((string name) => Mod.Instance != null && Mod.Instance.IsNameTaken(name)));
			}
		}

		private static void SpawnNamed(string name)
		{
			//IL_0016: 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_0053: Unknown result type (might be due to invalid IL or missing references)
			if (!DoppelBridge.Available)
			{
				Toast("Doppel missing", "Doppel.dll isn't loaded.", Kind("Error"));
			}
			else if (DoppelBridge.Call("SpawnBot", name))
			{
				Mod.Instance?.ExpectSpawn(name);
				Toast("Bot spawned", name, Kind("Success"));
			}
			else
			{
				Toast("Spawn failed", "See the MelonLoader log for Doppel's method list.", Kind("Error"));
			}
		}

		private static void OpenPlayerList()
		{
			//IL_0029: 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)
			if (!RequireOwner())
			{
				return;
			}
			Page playerPage = _playerPage;
			if (playerPage != null)
			{
				playerPage.RemoveAll();
			}
			if (_playerPage == null)
			{
				_playerPage = _root.CreatePage("Pick a player", Color.yellow, 0, true);
			}
			foreach (PlayerID item in PlayerIDManager.PlayerIDs.ToList())
			{
				if (!item.IsMe)
				{
					string shown = item.Metadata.Username.GetValue() ?? $"Player {item.SmallID}";
					_playerPage.CreateFunction(shown, Color.white, (Action)delegate
					{
						AskDoppel(shown);
					});
				}
			}
			Menu.OpenPage(_playerPage);
		}

		private static void AskDoppel(string playerName)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			Page confirmPage = _confirmPage;
			if (confirmPage != null)
			{
				confirmPage.RemoveAll();
			}
			if (_confirmPage == null)
			{
				_confirmPage = _root.CreatePage("Confirm", Color.yellow, 0, true);
			}
			_confirmPage.CreateFunction("Doppel " + playerName + "?", Color.white, (Action)delegate
			{
			});
			_confirmPage.CreateFunction("Yes", Color.green, (Action)delegate
			{
				if (RequireOwner())
				{
					SpawnNamed(BotNames.ForDoppelOf(playerName));
				}
				Menu.OpenPage(_root);
			});
			_confirmPage.CreateFunction("No", Color.red, (Action)delegate
			{
				Menu.OpenPage(_root);
			});
			Menu.OpenPage(_confirmPage);
		}

		private static void RemoveAll()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (RequireOwner())
			{
				Mod.Instance?.ForgetAllBots();
				DoppelBridge.Call("RemoveAllBots", null);
				Toast("Bots removed", "All Doppel bots removed.", Kind("Success"));
			}
		}
	}
	public class Mod : MelonMod
	{
		private sealed class Entry
		{
			public object Bot;

			public string Name;

			public bool Puppet;

			public bool NetAnnounced;

			public int Id;

			public float Born;

			public object TagHandle;

			public object Fake;

			public float FakeNextTry;

			public bool FakeWarned;

			public float MissingSince = -1f;

			public bool Quiet;

			public string CloneBarcode;

			public bool CloneDone;

			public int CloneTries;

			public float CloneNextTry;

			public int AttackTarget = -1;

			public int AttackIndex;

			public float AttackNext;

			public float AttackUntil;

			public int AttackMisses;
		}

		private sealed class Scheduled
		{
			public string Name;

			public float Due;
		}

		private sealed class Respawn
		{
			public string Name;

			public float Due;

			public int Tries;

			public bool Called;

			public string Clone;
		}

		internal struct Inbound
		{
			public int Owner;

			public byte[] Bytes;
		}

		internal static Mod Instance;

		private readonly List<KeyValuePair<string, float>> pendingNames = new List<KeyValuePair<string, float>>();

		private const float PendingLifetime = 15f;

		private MelonPreferences_Entry<bool> prefEnabled;

		private MelonPreferences_Entry<bool> prefTags;

		private MelonPreferences_Entry<bool> prefPopups;

		private MelonPreferences_Entry<bool> prefServer;

		private MelonPreferences_Entry<bool> prefKeepAlive;

		private MelonPreferences_Entry<bool> prefSilly;

		private readonly List<Scheduled> scheduled = new List<Scheduled>();

		private readonly Dictionary<string, string> cloneTargets = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private readonly Dictionary<string, KeyValuePair<int, int>> attackTargets = new Dictionary<string, KeyValuePair<int, int>>(StringComparer.OrdinalIgnoreCase);

		private float cloneStamp;

		private float attackStamp;

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

		private int popTarget;

		private float nextPopCheck;

		private static readonly string[] JoinLines = new string[6] { "{0} just spawned in", "{0} has entered the arena", "{0} dropped in from nowhere", "A wild {0} appeared", "{0} is here to cause trouble", "{0} has joined the party" };

		private static readonly string[] LeaveLines = new string[6] { "{0} rage quit", "{0} went to get snacks", "{0} lost connection to reality", "{0} fell out of the world", "{0} left to touch grass", "{0} has left the server" };

		private const float GraceSeconds = 3f;

		private const float GraceAfterSceneSeconds = 10f;

		private float hostLostSince = -1f;

		private float respawnSuppressUntil;

		private readonly List<Respawn> respawns = new List<Respawn>();

		private readonly List<KeyValuePair<string, float>> respawnLog = new List<KeyValuePair<string, float>>();

		private readonly HashSet<string> quietNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private FieldInfo botsF;

		private FieldInfo nameIsF;

		private FieldInfo netOwnerF;

		private FieldInfo netIdF;

		private FieldInfo rigF;

		private bool doppelReady;

		private float nextResolve;

		private readonly Dictionary<IntPtr, Entry> tracked = new Dictionary<IntPtr, Entry>();

		private readonly Dictionary<int, string> remoteNames = new Dictionary<int, string>();

		private readonly Random rng = new Random();

		private float nextPoll;

		private float nextSnapshot;

		private float nextFakeTick;

		private float quietUntil;

		private bool fusionPresent;

		private bool fusionReady;

		private bool loggedError;

		internal static readonly ConcurrentQueue<Inbound> Inbox = new ConcurrentQueue<Inbound>();

		private const byte KindJoin = 1;

		private const byte KindLeave = 2;

		private const byte KindSnapshot = 3;

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

		private static readonly string[] Names = new string[111]
		{
			"Timmy", "Jake", "Mason", "Liam", "Noah", "Ethan", "Logan", "Lucas", "Owen", "Caleb",
			"Dylan", "Tyler", "Ryan", "Aiden", "Jayden", "Carter", "Wyatt", "Hunter", "Eli", "Landon",
			"Connor", "Colton", "Brody", "Gavin", "Austin", "Chase", "Cole", "Nolan", "Jace", "Parker",
			"Blake", "Declan", "Finn", "Grant", "Henry", "Isaac", "Jasper", "Kai", "Leo", "Miles",
			"Nate", "Oscar", "Pete", "Quinn", "Rex", "Sam", "Theo", "Vince", "Zane", "Max",
			"Emma", "Olivia", "Ava", "Mia", "Chloe", "Ella", "Lily", "Zoe", "Nora", "Hazel",
			"Piper", "Ruby", "Stella", "Violet", "Willow", "Ivy", "Maya", "Layla", "Aria", "Brooke",
			"Cara", "Dana", "Erin", "Faith", "Grace", "Hannah", "Iris", "Jade", "Kylie", "Lena",
			"Molly", "Nina", "Paige", "Riley", "Sadie", "Tessa", "Uma", "Vera", "Wendy", "Alex",
			"Casey", "Drew", "Jamie", "Jordan", "Morgan", "Sky", "Taylor", "Avery", "Bobby", "Danny",
			"Eddie", "Freddie", "Georgie", "Jimmy", "Kenny", "Larry", "Mikey", "Ricky", "Tommy", "Willy",
			"Zach"
		};

		private static readonly string[] PossessLines = new string[3] { "{0} possessed you!", "You feel a chill... {0} swapped bodies with you", "{0} has taken your place" };

		internal bool SillyMessages
		{
			get
			{
				if (prefSilly != null)
				{
					return prefSilly.Value;
				}
				return false;
			}
			set
			{
				if (prefSilly != null)
				{
					prefSilly.Value = value;
				}
			}
		}

		internal bool KeepAlive
		{
			get
			{
				if (prefKeepAlive != null)
				{
					return prefKeepAlive.Value;
				}
				return false;
			}
			set
			{
				if (prefKeepAlive != null)
				{
					prefKeepAlive.Value = value;
				}
				if (!value)
				{
					respawns.Clear();
				}
			}
		}

		internal bool ShowNameTags
		{
			get
			{
				if (prefTags != null)
				{
					return prefTags.Value;
				}
				return false;
			}
			set
			{
				if (prefTags != null)
				{
					prefTags.Value = value;
				}
			}
		}

		internal bool ShowPopups
		{
			get
			{
				if (prefPopups != null)
				{
					return prefPopups.Value;
				}
				return false;
			}
			set
			{
				if (prefPopups != null)
				{
					prefPopups.Value = value;
				}
			}
		}

		public override void OnInitializeMelon()
		{
			Instance = this;
			MelonPreferences_Category val = MelonPreferences.CreateCategory("DoppelNames");
			prefEnabled = val.CreateEntry<bool>("Enabled", true, "Turn the whole add-on on or off", (string)null, false, false, (ValueValidator)null, (string)null);
			prefTags = val.CreateEntry<bool>("NameTags", true, "Show name tags above bots (needs LabFusion)", (string)null, false, false, (ValueValidator)null, (string)null);
			prefPopups = val.CreateEntry<bool>("JoinLeavePopups", true, "Show 'has joined/left the server' pop-ups", (string)null, false, false, (ValueValidator)null, (string)null);
			prefServer = val.CreateEntry<bool>("ServerSideBots", true, "When you are the host: make bots show up for players who do NOT have this mod (experimental)", (string)null, false, false, (ValueValidator)null, (string)null);
			prefKeepAlive = val.CreateEntry<bool>("KeepBotsAlive", true, "Bring a bot back (same name) if it vanishes unexpectedly", (string)null, false, false, (ValueValidator)null, (string)null);
			prefSilly = val.CreateEntry<bool>("SillyMessages", false, "Use funny join/leave pop-up messages", (string)null, false, false, (ValueValidator)null, (string)null);
			((MelonBase)this).LoggerInstance.Msg("DoppelNames loaded. Waiting for Doppel.");
		}

		public override void OnLateInitializeMelon()
		{
			fusionPresent = AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => a.GetName().Name == "LabFusion");
			if (!fusionPresent)
			{
				((MelonBase)this).LoggerInstance.Warning("LabFusion is not installed: pop-ups will work, but name tags need LabFusion.");
				return;
			}
			try
			{
				fusionReady = FusionBridge.Start();
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Could not register the network message; names stay on your screen only. " + ex.Message);
			}
			try
			{
				HostMenu.Init();
			}
			catch (Exception ex2)
			{
				((MelonBase)this).LoggerInstance.Warning("Could not create the host menu: " + ex2.Message);
			}
		}

		public override void OnDeinitializeMelon()
		{
			foreach (Entry value in tracked.Values)
			{
				DestroyTag(value);
				DropFake(value, quiet: false);
			}
			tracked.Clear();
			if (fusionReady)
			{
				try
				{
					FusionBridge.Stop();
				}
				catch
				{
				}
			}
		}

		public override void OnSceneWasUnloaded(int buildIndex, string sceneName)
		{
			quietUntil = Time.unscaledTime + 4f;
		}

		public override void OnUpdate()
		{
			if (!prefEnabled.Value)
			{
				if (tracked.Count <= 0)
				{
					return;
				}
				foreach (Entry value in tracked.Values)
				{
					DestroyTag(value);
					DropFake(value, quiet: false);
				}
				tracked.Clear();
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (!doppelReady)
			{
				if (!(unscaledTime < nextResolve))
				{
					nextResolve = unscaledTime + 2f;
					doppelReady = ResolveDoppel();
				}
				return;
			}
			if (fusionReady)
			{
				Stage("inbox", DrainInbox);
			}
			if (unscaledTime >= nextPoll)
			{
				nextPoll = unscaledTime + 0.2f;
				Stage("poll", delegate
				{
					Poll(unscaledTime);
				});
				Stage("respawn", delegate
				{
					ProcessRespawns(unscaledTime);
				});
				Stage("queued spawns", delegate
				{
					ProcessScheduled(unscaledTime);
				});
			}
			if (fusionReady && unscaledTime >= nextSnapshot)
			{
				nextSnapshot = unscaledTime + 4f;
				Stage("snapshot", delegate
				{
					if (!ServerSideActive())
					{
						SendSnapshot();
					}
				});
			}
			if (unscaledTime >= nextFakeTick)
			{
				nextFakeTick = unscaledTime + 0.05f;
				Stage("bot updates", TickFakes);
			}
		}

		private void Stage(string name, Action action)
		{
			try
			{
				action();
			}
			catch (Exception ex)
			{
				if (loggedKeys.Add(name))
				{
					((MelonBase)this).LoggerInstance.Error("DoppelNames hit an error in '" + name + "' (logged once): " + ex);
				}
			}
		}

		public override void OnLateUpdate()
		{
			if (!doppelReady || !fusionPresent || rigF == null || !prefEnabled.Value || !prefTags.Value)
			{
				return;
			}
			foreach (Entry value in tracked.Values)
			{
				if (value.TagHandle != null && value.MissingSince < 0f)
				{
					try
					{
						FusionTags.Follow(value.TagHandle, rigF.GetValue(value.Bot));
					}
					catch
					{
					}
				}
			}
		}

		private static Type FindType(string full)
		{
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				try
				{
					Type type = assembly.GetType(full, throwOnError: false);
					if (type != null)
					{
						return type;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private bool ResolveDoppel()
		{
			Type type = FindType("ThirdEyeBonelabMod.Bots.BotManager");
			Type type2 = FindType("ThirdEyeBonelabMod.Bots.Bot");
			if (type == null || type2 == null)
			{
				return false;
			}
			botsF = type.GetField("bots", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			nameIsF = type2.GetField("nameIs", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			netOwnerF = type2.GetField("netOwner", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			netIdF = type2.GetField("netId", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			rigF = type2.GetField("rig", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (botsF == null || netOwnerF == null || netIdF == null)
			{
				((MelonBase)this).LoggerInstance.Error("Found Doppel, but it looks like a different version than 1.4.0 (a field this add-on needs is missing). Names are disabled.");
				nextResolve = float.MaxValue;
				return false;
			}
			((MelonBase)this).LoggerInstance.Msg("Hooked into Doppel.");
			return true;
		}

		private void Poll(float now)
		{
			if (!(botsF.GetValue(null) is IDictionary dictionary))
			{
				return;
			}
			List<KeyValuePair<IntPtr, object>> list = new List<KeyValuePair<IntPtr, object>>(dictionary.Count);
			foreach (DictionaryEntry item in dictionary)
			{
				list.Add(new KeyValuePair<IntPtr, object>((IntPtr)item.Key, item.Value));
			}
			HashSet<IntPtr> hashSet = new HashSet<IntPtr>(list.Select((KeyValuePair<IntPtr, object> k) => k.Key));
			pendingNames.RemoveAll((KeyValuePair<string, float> p) => now - p.Value > 15f);
			if (now - cloneStamp > 30f)
			{
				cloneTargets.Clear();
			}
			if (now - attackStamp > 30f)
			{
				attackTargets.Clear();
			}
			bool flag = now < quietUntil;
			float num = ((now < quietUntil + 6f) ? 10f : 3f);
			foreach (IntPtr item2 in tracked.Keys.ToList())
			{
				Entry entry = tracked[item2];
				if (hashSet.Contains(item2))
				{
					entry.MissingSince = -1f;
					continue;
				}
				if (entry.MissingSince < 0f)
				{
					entry.MissingSince = now;
				}
				if (now - entry.MissingSince < num)
				{
					continue;
				}
				tracked.Remove(item2);
				DestroyTag(entry);
				DropFake(entry, quiet: false);
				bool flag2 = QueueRespawn(entry, now);
				if (!(entry.Puppet || flag || flag2) && !string.IsNullOrEmpty(entry.Name))
				{
					Popup(LeaveText(entry.Name));
					if (fusionReady && entry.NetAnnounced && entry.Id > 0 && !ServerSideActive())
					{
						FusionSend(Pack(2, entry.Id, entry.Name));
					}
				}
			}
			foreach (KeyValuePair<IntPtr, object> item3 in list)
			{
				try
				{
					if (!tracked.TryGetValue(item3.Key, out var value))
					{
						value = new Entry
						{
							Bot = item3.Value,
							Born = now,
							Puppet = IsPuppet(item3.Value)
						};
						tracked[item3.Key] = value;
						if (!value.Puppet)
						{
							value.Name = TakePendingName(now, value.Bot) ?? PickName();
							nameIsF?.SetValue(value.Bot, value.Name);
							if (cloneTargets.TryGetValue(value.Name, out var value2))
							{
								cloneTargets.Remove(value.Name);
								value.CloneBarcode = value2;
							}
							if (attackTargets.TryGetValue(value.Name, out var value3))
							{
								attackTargets.Remove(value.Name);
								value.AttackTarget = value3.Key;
								value.AttackIndex = value3.Value;
								value.AttackUntil = now + 120f;
							}
							value.Quiet = quietNames.Remove(value.Name);
							if (!flag && !value.Quiet)
							{
								Popup(JoinText(value.Name));
							}
						}
					}
					if (value.Puppet)
					{
						ResolvePuppetName(value);
					}
					else
					{
						EnsureCloneAvatar(value, now);
						EnsureAttack(value, now);
						EnsureFake(value, now);
						if (!value.NetAnnounced && !ServerSideActive())
						{
							TryAnnounceOverNetwork(value, now, flag || value.Quiet);
						}
					}
					EnsureTag(value);
				}
				catch (Exception ex)
				{
					if (loggedKeys.Add("bot-step"))
					{
						((MelonBase)this).LoggerInstance.Warning("A bot could not be processed (logged once): " + ex.Message);
					}
				}
			}
		}

		private bool ServerSideActive()
		{
			if (!fusionPresent || !prefServer.Value)
			{
				return false;
			}
			try
			{
				return FusionFakes.IsHosting();
			}
			catch
			{
				return false;
			}
		}

		private void EnsureFake(Entry e, float now)
		{
			if (e.Fake != null || e.Puppet || string.IsNullOrEmpty(e.Name) || now < e.FakeNextTry || (e.CloneBarcode != null && !e.CloneDone) || !ServerSideActive())
			{
				return;
			}
			e.FakeNextTry = now + 0.5f;
			try
			{
				e.Fake = FusionFakes.Add(e.Name, rigF?.GetValue(e.Bot));
				if (e.Fake == null && !e.FakeWarned && now - e.Born > 5f)
				{
					e.FakeWarned = true;
					((MelonBase)this).LoggerInstance.Warning("Server-side bot '" + e.Name + "' still not created: " + FusionFakes.LastReason);
				}
			}
			catch (Exception ex)
			{
				e.FakeNextTry = now + 5f;
				((MelonBase)this).LoggerInstance.Warning("Could not make a server-side bot: " + ex.Message);
			}
		}

		private void DropFake(Entry e, bool quiet)
		{
			if (e.Fake == null)
			{
				return;
			}
			object fake = e.Fake;
			e.Fake = null;
			try
			{
				if (quiet || !FusionFakes.IsHosting())
				{
					FusionFakes.Forget(fake);
				}
				else
				{
					FusionFakes.Remove(fake);
				}
			}
			catch (Exception ex)
			{
				((MelonBase)this).LoggerInstance.Warning("Could not remove a server-side bot: " + ex.Message);
			}
		}

		private void TickFakes()
		{
			if (!fusionPresent)
			{
				return;
			}
			bool flag = ServerSideActive();
			float unscaledTime = Time.unscaledTime;
			if (flag)
			{
				hostLostSince = -1f;
			}
			else if (hostLostSince < 0f)
			{
				hostLostSince = unscaledTime;
			}
			bool flag2 = !flag && unscaledTime - hostLostSince >= 3f;
			foreach (Entry value in tracked.Values)
			{
				if (value.Fake == null || value.MissingSince >= 0f)
				{
					continue;
				}
				if (!flag)
				{
					if (flag2)
					{
						DropFake(value, quiet: false);
					}
				}
				else
				{
					try
					{
						FusionFakes.Tick(value.Fake, rigF?.GetValue(value.Bot));
					}
					catch
					{
					}
				}
			}
		}

		private bool IsPuppet(object bot)
		{
			return Convert.ToInt32(netOwnerF.GetValue(bot)) >= 0;
		}

		private void ResolvePuppetName(Entry e)
		{
			if (string.IsNullOrEmpty(e.Name))
			{
				int num = Convert.ToInt32(netOwnerF.GetValue(e.Bot));
				int num2 = Convert.ToInt32(netIdF.GetValue(e.Bot));
				if (remoteNames.TryGetValue((num << 8) | (num2 & 0xFF), out var value))
				{
					e.Name = value;
					nameIsF?.SetValue(e.Bot, value);
				}
			}
		}

		private void TryAnnounceOverNetwork(Entry e, float now, bool quiet)
		{
			if (!fusionReady)
			{
				e.NetAnnounced = true;
			}
			else
			{
				if (!FusionBridge.IsOnline())
				{
					return;
				}
				int num = Convert.ToInt32(netIdF.GetValue(e.Bot));
				if (num <= 0 || num > 255)
				{
					if (now - e.Born > 8f)
					{
						e.NetAnnounced = true;
					}
					return;
				}
				e.Id = num;
				e.NetAnnounced = true;
				if (!quiet)
				{
					FusionSend(Pack(1, num, e.Name));
				}
			}
		}

		private void SendSnapshot()
		{
			if (!FusionBridge.IsOnline())
			{
				return;
			}
			List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
			foreach (Entry value in tracked.Values)
			{
				if (!value.Puppet && !string.IsNullOrEmpty(value.Name))
				{
					int num = Convert.ToInt32(netIdF.GetValue(value.Bot));
					if (num > 0 && num <= 255)
					{
						value.Id = num;
						list.Add(new KeyValuePair<int, string>(num, value.Name));
					}
				}
			}
			if (list.Count != 0)
			{
				FusionSend(PackSnapshot(list));
			}
		}

		private static void FusionSend(byte[] payload)
		{
			try
			{
				FusionBridge.Send(payload);
			}
			catch
			{
			}
		}

		private void DrainInbox()
		{
			Inbound result;
			while (Inbox.TryDequeue(out result))
			{
				try
				{
					Handle(result.Owner, result.Bytes);
				}
				catch (Exception ex)
				{
					((MelonBase)this).LoggerInstance.Warning("Bad message: " + ex.Message);
				}
			}
		}

		private void Handle(int owner, byte[] bytes)
		{
			using BinaryReader binaryReader = new BinaryReader(new MemoryStream(bytes));
			byte b = binaryReader.ReadByte();
			int num = binaryReader.ReadByte();
			if (b == 3)
			{
				HashSet<int> keep = new HashSet<int>();
				for (int i = 0; i < num; i++)
				{
					int num2 = binaryReader.ReadByte();
					string text = Clean(binaryReader.ReadString());
					if (text.Length != 0)
					{
						int num3 = (owner << 8) | num2;
						keep.Add(num3);
						remoteNames[num3] = text;
					}
				}
				{
					foreach (int item in remoteNames.Keys.Where((int k) => k >> 8 == owner && !keep.Contains(k)).ToList())
					{
						remoteNames.Remove(item);
					}
					return;
				}
			}
			if (num < 1)
			{
				return;
			}
			int num4 = binaryReader.ReadByte();
			string text2 = Clean(binaryReader.ReadString());
			if (text2.Length == 0)
			{
				return;
			}
			switch (b)
			{
			case 1:
				remoteNames[(owner << 8) | num4] = text2;
				if (Time.unscaledTime >= quietUntil)
				{
					Popup(JoinText(text2));
				}
				break;
			case 2:
				remoteNames.Remove((owner << 8) | num4);
				if (Time.unscaledTime >= quietUntil)
				{
					Popup(LeaveText(text2));
				}
				break;
			}
		}

		private static byte[] Pack(byte kind, int id, string name)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write(kind);
			binaryWriter.Write((byte)1);
			binaryWriter.Write((byte)id);
			binaryWriter.Write(name);
			binaryWriter.Flush();
			return memoryStream.ToArray();
		}

		private static byte[] PackSnapshot(List<KeyValuePair<int, string>> items)
		{
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write((byte)3);
			binaryWriter.Write((byte)Math.Min(items.Count, 255));
			foreach (KeyValuePair<int, string> item in items.Take(255))
			{
				binaryWriter.Write((byte)item.Key);
				binaryWriter.Write(item.Value);
			}
			binaryWriter.Flush();
			return memoryStream.ToArray();
		}

		private static string Clean(string s)
		{
			if (string.IsNullOrEmpty(s))
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (char c in s)
			{
				if (char.IsLetterOrDigit(c) || c == ' ' || c == '_' || c == '-' || c == '.' || c == '[' || c == ']' || c == '\'')
				{
					stringBuilder.Append(c);
				}
				if (stringBuilder.Length >= 32)
				{
					break;
				}
			}
			return stringBuilder.ToString().Trim();
		}

		private void Popup(string message)
		{
			//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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: 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_0043: 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_005a: Expected O, but got Unknown
			((MelonBase)this).LoggerInstance.Msg(message);
			if (!prefPopups.Value)
			{
				return;
			}
			try
			{
				Notifier.Send(new Notification
				{
					Title = NotificationText.op_Implicit("Server"),
					Message = NotificationText.op_Implicit(message),
					Type = (NotificationType)0,
					PopupLength = 2.5f,
					ShowTitleOnPopup = true
				});
			}
			catch
			{
			}
		}

		private void EnsureTag(Entry e)
		{
			if (!fusionPresent)
			{
				return;
			}
			if (!prefTags.Value || string.IsNullOrEmpty(e.Name))
			{
				if (e.TagHandle != null)
				{
					DestroyTag(e);
				}
				return;
			}
			try
			{
				if (e.TagHandle == null)
				{
					e.TagHandle = FusionTags.Create(e.Name);
				}
				else
				{
					FusionTags.SetName(e.TagHandle, e.Name);
				}
			}
			catch (Exception ex)
			{
				if (!loggedError)
				{
					loggedError = true;
					((MelonBase)this).LoggerInstance.Error("Could not make a name tag (logged once): " + ex);
				}
			}
		}

		private void DestroyTag(Entry e)
		{
			if (e.TagHandle != null)
			{
				try
				{
					FusionTags.Destroy(e.TagHandle);
				}
				catch
				{
				}
				e.TagHandle = null;
			}
		}

		internal void ExpectSpawn(string name)
		{
			if (!string.IsNullOrEmpty(name) && !pendingNames.Any((KeyValuePair<string, float> p) => p.Key == name))
			{
				pendingNames.Add(new KeyValuePair<string, float>(name, Time.unscaledTime));
			}
		}

		private bool QueueRespawn(Entry e, float now)
		{
			if (e.Puppet || string.IsNullOrEmpty(e.Name) || !prefKeepAlive.Value || now < respawnSuppressUntil || !DoppelBridge.Available)
			{
				return false;
			}
			foreach (Respawn respawn in respawns)
			{
				if (string.Equals(respawn.Name, e.Name, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			respawns.Add(new Respawn
			{
				Name = e.Name,
				Clone = e.CloneBarcode,
				Due = Math.Max(now, quietUntil) + 2.5f
			});
			((MelonBase)this).LoggerInstance.Msg("Bot '" + e.Name + "' vanished; it will be brought back.");
			return true;
		}

		private bool IsBotAlive(string name)
		{
			foreach (Entry value in tracked.Values)
			{
				if (!value.Puppet && value.MissingSince < 0f && string.Equals(value.Name, name, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		private void ProcessRespawns(float now)
		{
			if (respawns.Count == 0 || now < quietUntil)
			{
				return;
			}
			respawnLog.RemoveAll((KeyValuePair<string, float> p) => now - p.Value > 120f);
			for (int num = respawns.Count - 1; num >= 0; num--)
			{
				Respawn respawn = respawns[num];
				if (!(now < respawn.Due))
				{
					if (!prefKeepAlive.Value || now < respawnSuppressUntil)
					{
						respawns.RemoveAt(num);
					}
					else if (respawn.Called && IsBotAlive(respawn.Name))
					{
						respawns.RemoveAt(num);
					}
					else if (respawn.Tries >= 3)
					{
						((MelonBase)this).LoggerInstance.Warning("Could not bring back bot '" + respawn.Name + "'. Giving up.");
						respawns.RemoveAt(num);
					}
					else
					{
						string name = respawn.Name;
						if (respawnLog.Count((KeyValuePair<string, float> p) => p.Key == name) >= 5)
						{
							((MelonBase)this).LoggerInstance.Warning("Bot '" + name + "' keeps vanishing; not bringing it back again for a while.");
							respawns.RemoveAt(num);
						}
						else
						{
							respawn.Tries++;
							respawn.Called = true;
							respawn.Due = now + 10f;
							respawnLog.Add(new KeyValuePair<string, float>(name, now));
							if (DoppelBridge.Call("SpawnBot", name))
							{
								ExpectSpawn(name);
								quietNames.Add(name);
								if (respawn.Clone != null)
								{
									cloneTargets[name] = respawn.Clone;
									cloneStamp = now;
								}
								((MelonBase)this).LoggerInstance.Msg("Brought back bot '" + name + "'.");
							}
							else
							{
								respawn.Due = now + 3f;
							}
						}
					}
				}
			}
		}

		internal void ExpectAttack(string botName, int targetId, int index)
		{
			if (!string.IsNullOrEmpty(botName))
			{
				attackTargets[botName] = new KeyValuePair<int, int>(targetId, index);
				attackStamp = Time.unscaledTime;
			}
		}

		private void EnsureAttack(Entry e, float now)
		{
			if (e.AttackTarget < 0 || now < e.AttackNext || !fusionPresent)
			{
				return;
			}
			e.AttackNext = now + 0.5f;
			if (now > e.AttackUntil)
			{
				ReleaseAttack(e);
				return;
			}
			bool flag = false;
			try
			{
				object obj = rigF?.GetValue(e.Bot);
				flag = obj == null || AttackBridge.Step(obj, (byte)e.AttackTarget, e.AttackIndex);
			}
			catch (Exception ex)
			{
				if (loggedKeys.Add("attack"))
				{
					((MelonBase)this).LoggerInstance.Warning("Attack step failed (logged once): " + ex.Message);
				}
			}
			if (flag)
			{
				e.AttackMisses = 0;
			}
			else if (++e.AttackMisses > 20)
			{
				((MelonBase)this).LoggerInstance.Msg("'" + e.Name + "' lost its target; stopping.");
				ReleaseAttack(e);
			}
		}

		private void ReleaseAttack(Entry e)
		{
			e.AttackTarget = -1;
			try
			{
				AttackBridge.Release(rigF?.GetValue(e.Bot));
			}
			catch
			{
			}
		}

		internal void StopAttacks()
		{
			attackTargets.Clear();
			foreach (Entry value in tracked.Values)
			{
				if (value.AttackTarget >= 0)
				{
					ReleaseAttack(value);
				}
			}
		}

		internal void ExpectClone(string botName, string avatarBarcode)
		{
			if (!string.IsNullOrEmpty(botName) && !string.IsNullOrEmpty(avatarBarcode))
			{
				cloneTargets[botName] = avatarBarcode;
				cloneStamp = Time.unscaledTime;
			}
		}

		private void EnsureCloneAvatar(Entry e, float now)
		{
			if (e.CloneBarcode == null || e.CloneDone || now < e.CloneNextTry)
			{
				return;
			}
			e.CloneNextTry = now + 1.5f;
			if (now - e.Born > 25f || e.CloneTries >= 8)
			{
				e.CloneDone = true;
				((MelonBase)this).LoggerInstance.Warning("Could not copy the avatar onto '" + e.Name + "'; it keeps its own avatar.");
				return;
			}
			try
			{
				object rig = rigF?.GetValue(e.Bot);
				string text = AvatarClone.CurrentId(rig);
				if (text != null)
				{
					if (text == e.CloneBarcode)
					{
						e.CloneDone = true;
						((MelonBase)this).LoggerInstance.Msg("'" + e.Name + "' now wears the cloned avatar.");
					}
					else
					{
						e.CloneTries++;
						e.CloneNextTry = now + 4f;
						AvatarClone.Request(rig, e.CloneBarcode);
					}
				}
			}
			catch (Exception ex)
			{
				e.CloneTries++;
				((MelonBase)this).LoggerInstance.Warning("Avatar clone step failed: " + ex.Message);
			}
		}

		private string JoinText(string name)
		{
			if (prefSilly == null || !prefSilly.Value)
			{
				return name + " has joined the server";
			}
			return string.Format(JoinLines[rng.Next(JoinLines.Length)], name);
		}

		private string LeaveText(string name)
		{
			if (prefSilly == null || !prefSilly.Value)
			{
				return name + " has left the server";
			}
			return string.Format(LeaveLines[rng.Next(LeaveLines.Length)], name);
		}

		internal void Schedule(string name, float delaySeconds)
		{
			if (!string.IsNullOrEmpty(name))
			{
				scheduled.Add(new Scheduled
				{
					Name = name,
					Due = Time.unscaledTime + delaySeconds
				});
			}
		}

		internal List<string> BotList()
		{
			List<string> list = new List<string>();
			foreach (Entry value in tracked.Values)
			{
				if (!value.Puppet && value.MissingSince < 0f && !string.IsNullOrEmpty(value.Name))
				{
					list.Add(value.Name);
				}
			}
			return list;
		}

		internal bool Possess(string wanted, out string message)
		{
			List<Entry> list = new List<Entry>();
			foreach (Entry value in tracked.Values)
			{
				if (!value.Puppet && value.MissingSince < 0f && !string.IsNullOrEmpty(value.Name) && (wanted == null || string.Equals(value.Name, wanted, StringComparison.OrdinalIgnoreCase)))
				{
					list.Add(value);
				}
			}
			if (list.Count == 0)
			{
				message = "No bot to possess.";
				return false;
			}
			Entry entry = list[rng.Next(list.Count)];
			object obj = rigF?.GetValue(entry.Bot);
			if (obj == null)
			{
				message = "That bot has no body yet.";
				return false;
			}
			if (!Possession.Swap(obj, out message))
			{
				return false;
			}
			message = string.Format(PossessLines[rng.Next(PossessLines.Length)], entry.Name);
			return true;
		}

		internal void SetPopulation(int count)
		{
			popTarget = Math.Max(0, Math.Min(10, count));
			nextPopCheck = 0f;
		}

		internal void FakeJoin()
		{
			Popup(JoinText(PickName()));
		}

		internal void FakeLeave()
		{
			List<string> list = new List<string>();
			foreach (Entry value in tracked.Values)
			{
				if (!value.Puppet && !string.IsNullOrEmpty(value.Name))
				{
					list.Add(value.Name);
				}
			}
			string name = ((list.Count > 0) ? list[rng.Next(list.Count)] : PickName());
			Popup(LeaveText(name));
		}

		private void ProcessScheduled(float now)
		{
			if (popTarget > 0 && now >= nextPopCheck)
			{
				nextPopCheck = now + 3f;
				int num = 0;
				foreach (Entry value in tracked.Values)
				{
					if (!value.Puppet && value.MissingSince < 0f)
					{
						num++;
					}
				}
				int num2 = pendingNames.Count((KeyValuePair<string, float> p) => now - p.Value <= 15f);
				if (num + num2 + this.scheduled.Count + respawns.Count < popTarget)
				{
					Schedule(BotNames.Next((string n) => IsNameTaken(n)), 0f);
				}
			}
			if (this.scheduled.Count == 0 || now < quietUntil)
			{
				return;
			}
			for (int num3 = 0; num3 < this.scheduled.Count; num3++)
			{
				Scheduled scheduled = this.scheduled[num3];
				if (!(now < scheduled.Due))
				{
					this.scheduled.RemoveAt(num3);
					if (DoppelBridge.Call("SpawnBot", scheduled.Name))
					{
						ExpectSpawn(scheduled.Name);
						break;
					}
					this.scheduled.Clear();
					popTarget = 0;
					((MelonBase)this).LoggerInstance.Warning("Could not spawn a bot; cancelled the queued spawns.");
					break;
				}
			}
		}

		internal void ForgetAllBots()
		{
			respawns.Clear();
			scheduled.Clear();
			cloneTargets.Clear();
			attackTargets.Clear();
			popTarget = 0;
			respawnSuppressUntil = Time.unscaledTime + 10f + 5f;
		}

		internal int RespawnNow()
		{
			foreach (Respawn respawn in respawns)
			{
				respawn.Due = 0f;
			}
			return respawns.Count;
		}

		internal string DescribeBots()
		{
			List<string> list = new List<string>();
			foreach (Entry value in tracked.Values)
			{
				if (!value.Puppet && !string.IsNullOrEmpty(value.Name))
				{
					list.Add(value.Name);
				}
			}
			if (list.Count == 0)
			{
				return "No bots right now.";
			}
			return list.Count + ": " + string.Join(", ", list);
		}

		internal bool IsNameTaken(string name)
		{
			foreach (Entry value in tracked.Values)
			{
				if (string.Equals(value.Name, name, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			foreach (string value2 in remoteNames.Values)
			{
				if (string.Equals(value2, name, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			foreach (KeyValuePair<string, float> pendingName in pendingNames)
			{
				if (string.Equals(pendingName.Key, name, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			foreach (Scheduled item in scheduled)
			{
				if (string.Equals(item.Name, name, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}

		private string TakePendingName(float now, object bot)
		{
			pendingNames.RemoveAll((KeyValuePair<string, float> p) => now - p.Value > 15f);
			if (pendingNames.Count == 0)
			{
				return null;
			}
			string current = nameIsF?.GetValue(bot) as string;
			int index = 0;
			if (!string.IsNullOrEmpty(current))
			{
				int num = pendingNames.FindIndex((KeyValuePair<string, float> p) => p.Key == current);
				if (num >= 0)
				{
					index = num;
				}
			}
			string key = pendingNames[index].Key;
			pendingNames.RemoveAt(index);
			return key;
		}

		private string PickName()
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			foreach (Entry value in tracked.Values)
			{
				if (!string.IsNullOrEmpty(value.Name))
				{
					hashSet.Add(value.Name);
				}
			}
			foreach (string value2 in remoteNames.Values)
			{
				hashSet.Add(value2);
			}
			foreach (KeyValuePair<string, float> pendingName in pendingNames)
			{
				hashSet.Add(pendingName.Key);
			}
			for (int i = 0; i < 40; i++)
			{
				string text = Names[rng.Next(Names.Length)];
				if (!hashSet.Contains(text))
				{
					return text;
				}
			}
			return Names[rng.Next(Names.Length)] + rng.Next(2, 99);
		}
	}
	public class NamesData : INetSerializable
	{
		public byte[] bytes;

		public int? GetSize()
		{
			return ((bytes != null) ? bytes.Length : 0) + 8;
		}

		public void Serialize(INetSerializer serializer)
		{
			serializer.SerializeValue(ref bytes);
		}
	}
	public class NamesMessage : ModuleMessageHandler
	{
		protected override void OnHandleMessage(ReceivedMessage received)
		{
			try
			{
				byte? sender = ((ReceivedMessage)(ref received)).Sender;
				if (!sender.HasValue)
				{
					return;
				}
				object obj = sender.Value;
				int owner;
				if (obj is IConvertible convertible)
				{
					owner = convertible.ToInt32(null);
				}
				else
				{
					object obj2 = obj.GetType().GetProperty("SmallID")?.GetValue(obj);
					if (obj2 == null)
					{
						return;
					}
					owner = Convert.ToInt32(obj2);
				}
				NamesData namesData = ((ReceivedMessage)(ref received)).ReadData<NamesData>();
				if (namesData?.bytes != null && namesData.bytes.Length >= 2 && namesData.bytes.Length <= 8192)
				{
					Mod.Inbox.Enqueue(new Mod.Inbound
					{
						Owner = owner,
						Bytes = namesData.bytes
					});
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("DoppelNames: could not read a message: " + ex.Message);
			}
		}
	}
	internal static class Possession
	{
		private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		private static bool _loggedMethod;

		public static bool Swap(object botRig, out string message)
		{
			//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)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			object obj = null;
			try
			{
				obj = Player.RigManager;
			}
			catch
			{
			}
			if (obj == null)
			{
				message = "Could not find your own rig.";
				return false;
			}
			Component val = (Component)((obj is Component) ? obj : null);
			Component val2 = (Component)((botRig is Component) ? botRig : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				message = "Could not read the rig positions.";
				return false;
			}
			Vector3 position = val.transform.position;
			Vector3 position2 = val2.transform.position;
			MethodInfo methodInfo = FindTeleport(obj.GetType());
			if (methodInfo == null)
			{
				message = "No teleport function found (see the MelonLoader log).";
				return false;
			}
			try
			{
				Call(methodInfo, obj, position2);
				Call(methodInfo, botRig, position);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("DoppelNames: possession failed: " + (ex.InnerException?.Message ?? ex.Message));
				message = "The swap failed (see the MelonLoader log).";
				return false;
			}
			message = "ok";
			return true;
		}

		private static MethodInfo FindTeleport(Type rigType)
		{
			MethodInfo methodInfo = (from m in rigType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
				where m.Name == "Teleport" && m.GetParameters().Length != 0 && m.GetParameters()[0].ParameterType == typeof(Vector3)
				orderby m.GetParameters().Length
				select m).FirstOrDefault();
			if (methodInfo == null)
			{
				string[] value = (from m in rigType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
					select m.Name + "(" + string.Join(", ", from p in m.GetParameters()
						select p.ParameterType.Name) + ")" into n
					where n.IndexOf("elep", StringComparison.OrdinalIgnoreCase) >= 0 || n.IndexOf("Warp", StringComparison.OrdinalIgnoreCase) >= 0 || n.IndexOf("Position", StringComparison.OrdinalIgnoreCase) >= 0
					select n).Distinct().ToArray();
				MelonLogger.Warning("DoppelNames: no Teleport(Vector3, ...) on " + rigType.FullName + ". Similar methods: " + string.Join("; ", value));
			}
			else if (!_loggedMethod)
			{
				_loggedMethod = true;
				MelonLogger.Msg("DoppelNames: possession will use " + methodInfo.Name + "(" + string.Join(", ", from p in methodInfo.GetParameters()
					select p.ParameterType.Name + " " + p.Name) + ")");
			}
			return methodInfo;
		}

		private static void Call(MethodInfo method, object rig, Vector3 position)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			ParameterInfo[] parameters = method.GetParameters();
			object[] array = new object[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				Type parameterType = parameters[i].ParameterType;
				if (i == 0)
				{
					array[i] = position;
				}
				else if (parameterType == typeof(bool))
				{
					array[i] = true;
				}
				else if (parameters[i].HasDefaultValue)
				{
					array[i] = parameters[i].DefaultValue;
				}
				else
				{
					array[i] = (parameterType.IsValueType ? Activator.CreateInstance(parameterType) : null);
				}
			}
			method.Invoke(method.IsStatic ? null : rig, array);
		}
	}
}