Decompiled source of MoreRadarNames v1.0.0

MoreRadarNames/MoreRadarNames.dll

Decompiled 10 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("MoreRadarNames")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("My first plugin")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MoreRadarNames")]
[assembly: AssemblyTitle("MoreRadarNames")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace MoreRadarNames;

[Serializable]
[HarmonyPatch]
public class ModConfig : SyncedInstance<ModConfig>
{
	public ConfigEntry<string> possibleBoosterNames;

	public ConfigEntry<bool> allowRenaming;

	public ConfigEntry<int> maxNameLength;

	public ModConfig(ConfigFile cfg)
	{
		InitInstance(this);
		possibleBoosterNames = cfg.Bind<string>("General", "BoosterNames", string.Join(";", "Betty", "George", "Billy", "Kablam", "Susie", "Igor", "Gilbert", "Daryl", "Seth", "Sam", "Brody", "Blue", "Freddy", "Bobbie", "Louie", "Albert", "Reimu", "Sakuya", "Marisa", "Cirno", "Yukari", "Koishi", "Remilia", "Flandre", "Nitori", "Rumia", "ZUN", "Cinder", "Jengu", "Djinn", "Aegis", "Argus", "Xaphan", "Volcan", "Zephyr", "Wisp", "Grue", "Spriggan", "Nymph", "Banshee", "Tremor", "Sylph", "Spectre", "Kobold"), "Potential names for purchased radar boosters to choose from, separated by ;");
		allowRenaming = cfg.Bind<bool>("General", "AllowRename", true, "Set to false to disable the `rename <old name> <new name>` terminal command that radar boosters can be renamed with.");
		maxNameLength = cfg.Bind<int>("General", "MaxRenameLength", 8, "How many characters long a booster name can maximally be made using the rename command. Does not affect the names boosters spawn with.");
	}

	public static void RequestSync()
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		if (!SyncedInstance<ModConfig>.IsClient)
		{
			return;
		}
		FastBufferWriter val = default(FastBufferWriter);
		((FastBufferWriter)(ref val))..ctor(SyncedInstance<ModConfig>.IntSize, (Allocator)2, -1);
		try
		{
			SyncedInstance<ModConfig>.MessageManager.SendNamedMessage("MoreRadarNames_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
		}
		finally
		{
			((IDisposable)(FastBufferWriter)(ref val)).Dispose();
		}
	}

	public static void OnRequestSync(ulong clientId, FastBufferReader _)
	{
		//IL_0042: 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_0063: Unknown result type (might be due to invalid IL or missing references)
		if (!SyncedInstance<ModConfig>.IsHost)
		{
			return;
		}
		Console.WriteLine($"Config sync request received from client: {clientId}");
		byte[] array = SyncedInstance<ModConfig>.SerializeToBytes(SyncedInstance<ModConfig>.Instance);
		int num = array.Length;
		FastBufferWriter val = default(FastBufferWriter);
		((FastBufferWriter)(ref val))..ctor(num + SyncedInstance<ModConfig>.IntSize, (Allocator)2, -1);
		try
		{
			((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
			((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
			SyncedInstance<ModConfig>.MessageManager.SendNamedMessage("MoreRadarNames_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
		}
		catch (Exception arg)
		{
			Console.WriteLine($"Error occurred syncing config with client: {clientId}\n{arg}");
		}
		finally
		{
			((IDisposable)(FastBufferWriter)(ref val)).Dispose();
		}
	}

	public static void OnReceiveSync(ulong _, FastBufferReader reader)
	{
		//IL_001f: 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)
		if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<ModConfig>.IntSize))
		{
			Console.WriteLine("Config sync error: Could not begin reading buffer.");
			return;
		}
		int num = default(int);
		((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
		if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
		{
			Console.WriteLine("Config sync error: Host could not sync.");
			return;
		}
		byte[] data = new byte[num];
		((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
		SyncedInstance<ModConfig>.SyncInstance(data);
		Console.WriteLine("Successfully synced config with host.");
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyMemberJoined")]
	public static void InitializeLocalPlayer()
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_0022: Expected O, but got Unknown
		if (SyncedInstance<ModConfig>.IsHost)
		{
			SyncedInstance<ModConfig>.MessageManager.RegisterNamedMessageHandler("MoreRadarNames_OnRequestConfigSync", new HandleNamedMessageDelegate(OnRequestSync));
			SyncedInstance<ModConfig>.Synced = true;
		}
		else
		{
			SyncedInstance<ModConfig>.Synced = false;
			SyncedInstance<ModConfig>.MessageManager.RegisterNamedMessageHandler("MoreRadarNames_OnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveSync));
			RequestSync();
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
	public static void PlayerLeave()
	{
		SyncedInstance<ModConfig>.RevertSync();
	}
}
[BepInPlugin("MoreRadarNames", "MoreRadarNames", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(StartOfRound), "Start")]
	private class NameChoicePatch
	{
		private static void Prefix()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			Console.WriteLine("registered named message handler");
			NetworkManager.Singleton.CustomMessagingManager.RegisterNamedMessageHandler("MoreRadarNames_OnRenameBoosterSync", new HandleNamedMessageDelegate(RenameRadarPatch.ReceiveRename));
		}

		private static void Postfix(ref string[] ___randomNames)
		{
			List<string> list = new List<string>(___randomNames);
			Console.WriteLine("Original booster names: " + string.Join(";", list));
			list.Clear();
			list.AddRange(SyncedInstance<ModConfig>.Instance.possibleBoosterNames.Value.Split(new char[1] { ';' }));
			___randomNames = list.ToArray();
		}
	}

	[HarmonyPatch(typeof(Terminal), "ParsePlayerSentence")]
	public class RenameRadarPatch
	{
		private static MethodInfo ParseWordOverrideOptions;

		private static MethodInfo CheckForPlayerNameCommand;

		private static TerminalNode RenameSuccess;

		static RenameRadarPatch()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			ParseWordOverrideOptions = typeof(Terminal).GetMethod("ParseWordOverrideOptions", BindingFlags.Instance | BindingFlags.NonPublic);
			CheckForPlayerNameCommand = typeof(Terminal).GetMethod("CheckForPlayerNameCommand", BindingFlags.Instance | BindingFlags.NonPublic);
			RenameSuccess = new TerminalNode();
		}

		public static void ReceiveRename(ulong _, FastBufferReader reader)
		{
			//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_004d: 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)
			Console.WriteLine("Receiving rename for a radar booster");
			if (!((FastBufferReader)(ref reader)).TryBeginRead(8))
			{
				Console.WriteLine("Rename sync error: Could not begin reading buffer.");
				return;
			}
			ulong num = default(ulong);
			((FastBufferReader)(ref reader)).ReadValueSafe<ulong>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(4))
			{
				Console.WriteLine("Config sync error: Could not find name length parameter.");
				return;
			}
			int num2 = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num2, default(ForPrimitives));
			byte[] bytes = new byte[num2];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref bytes, num2, 0);
			string @string = Encoding.UTF8.GetString(bytes);
			List<TransformAndName> radarTargets = StartOfRound.Instance.mapScreen.radarTargets;
			for (int i = 0; i < radarTargets.Count; i++)
			{
				TransformAndName val = radarTargets[i];
				if (val.isNonPlayer)
				{
					RadarBoosterItem component = ((Component)val.transform).GetComponent<RadarBoosterItem>();
					if ((Object)(object)component != (Object)null && ((NetworkBehaviour)component).NetworkObjectId == num)
					{
						UpdateBoosterScanNode(component, @string);
						component.radarBoosterName = @string;
						break;
					}
				}
			}
		}

		public static void SyncRename(RadarBoosterItem item)
		{
			//IL_0044: 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_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			Console.WriteLine("Syncing rename for radar booster " + item.radarBoosterName);
			byte[] bytes = Encoding.UTF8.GetBytes(item.radarBoosterName);
			int num = bytes.Length;
			ulong networkObjectId = ((NetworkBehaviour)item).NetworkObjectId;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(12 + num, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref networkObjectId, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(bytes, -1, 0);
				NetworkManager.Singleton.CustomMessagingManager.SendNamedMessageToAll("MoreRadarNames_OnRenameBoosterSync", val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				Console.WriteLine($"Error occurred syncing booster rename with others!=\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void UpdateBoosterScanNode(RadarBoosterItem component, string newName)
		{
			ScanNodeProperties componentInChildren = ((Component)component).gameObject.GetComponentInChildren<ScanNodeProperties>();
			componentInChildren.headerText = newName;
			componentInChildren.subText = "Last named " + component.radarBoosterName;
		}

		private static bool Prefix(Terminal __instance, ref TMP_InputField ___screenText, ref int ___textAdded, ref TerminalNode ___currentNode, ref TerminalNode __result)
		{
			if (!SyncedInstance<ModConfig>.Instance.allowRenaming.Value)
			{
				return true;
			}
			string s = ___screenText.text.Substring(___screenText.text.Length - ___textAdded);
			string text = RemovePunctuation(s, toLower: false);
			string text2 = RemovePunctuation(s);
			string[] array = text.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			string[] array2 = text2.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
			if (array2[0] == "resign")
			{
				if (!Object.FindObjectOfType<HangarShipDoor>().buttonsEnabled)
				{
					TerminalNode val = __instance.terminalNodes.specialNodes[12];
					val.displayText = "Resignation cannot be performed in orbit, to avoid risking damage to proprietary company hardware.\n";
					__result = val;
					return false;
				}
				if (startedResigning)
				{
					TerminalNode val2 = __instance.terminalNodes.specialNodes[12];
					val2.displayText = "This disciplinary method cannot be cancelled. Attitude adjustment will be swift and painless, please let it steer your future attitude toward Company employment.\n";
					__result = val2;
					return false;
				}
				TerminalNode val3 = __instance.terminalNodes.specialNodes[12];
				val3.displayText = "Resignation is disallowed until the completion of a full season contract. Attitude adjustment measures deploying in 10 seconds, please step away from nearby Company contractors and equipment to avoid damage to proprietary hardware.\n";
				__result = val3;
				startedResigning = true;
				((MonoBehaviour)StartOfRound.Instance).StartCoroutine(Resign());
				return false;
			}
			if (array2.Length > 2 && array2[0] == "rename")
			{
				int num = (int)CheckForPlayerNameCommand.Invoke(__instance, new object[2]
				{
					array2[0],
					array2[1]
				});
				if (num != -1)
				{
					int num2 = num;
					List<TransformAndName> radarTargets = StartOfRound.Instance.mapScreen.radarTargets;
					if (num2 < radarTargets.Count && radarTargets[num2].isNonPlayer)
					{
						string text3 = array[2];
						int value = SyncedInstance<ModConfig>.Instance.maxNameLength.Value;
						if (text3.Length > value)
						{
							TerminalNode val4 = __instance.terminalNodes.specialNodes[12];
							val4.displayText = "Could not change radar booster name: new identifier exceeds the maximum of " + value + " characters.\n";
							__result = val4;
							return false;
						}
						RadarBoosterItem component = ((Component)radarTargets[num2].transform).gameObject.GetComponent<RadarBoosterItem>();
						StartOfRound.Instance.mapScreen.RemoveTargetFromRadar(((Component)component).transform);
						string radarBoosterName = component.radarBoosterName;
						int num3 = 0;
						for (int i = 0; i < radarTargets.Count; i++)
						{
							if (radarTargets[i].name == text3)
							{
								num3++;
							}
						}
						if (num3 != 0)
						{
							text3 += num3 + 1;
						}
						UpdateBoosterScanNode(component, text3);
						component.radarBoosterName = text3;
						SyncRename(component);
						StartOfRound.Instance.mapScreen.AddTransformAsTargetToRadar(((Component)component).transform, text3, true);
						StartOfRound.Instance.mapScreen.SyncOrderOfRadarBoostersInList();
						TerminalNode val5 = __instance.terminalNodes.specialNodes[12];
						val5.displayText = "Renamed booster '" + radarBoosterName + "' to '" + text3 + "'.\n";
						__result = val5;
						return false;
					}
					return true;
				}
			}
			return true;
		}
	}

	private int a;

	private static bool startedResigning;

	public static ModConfig MyConfig { get; internal set; }

	private void BindConfigs()
	{
		MyConfig = new ModConfig(((BaseUnityPlugin)this).Config);
	}

	private void Awake()
	{
		//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)
		BindConfigs();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin MoreRadarNames is loaded!");
		Harmony val = new Harmony("MoreRadarNames");
		val.PatchAll();
		foreach (MethodBase patchedMethod in val.GetPatchedMethods())
		{
			Console.WriteLine("### " + patchedMethod.Name);
		}
	}

	private static string RemovePunctuation(string s, bool toLower = true)
	{
		StringBuilder stringBuilder = new StringBuilder();
		foreach (char c in s)
		{
			if (!char.IsPunctuation(c))
			{
				stringBuilder.Append(c);
			}
		}
		if (toLower)
		{
			return stringBuilder.ToString().ToLower();
		}
		return stringBuilder.ToString();
	}

	private static IEnumerator Resign()
	{
		yield return (object)new WaitForSeconds(10f);
		Object.Instantiate<GameObject>(StartOfRound.Instance.explosionPrefab, ((Component)GameNetworkManager.Instance.localPlayerController).transform.position + Vector3.up, Quaternion.Euler(-90f, 0f, 0f), RoundManager.Instance.mapPropsContainer.transform).SetActive(true);
		HUDManager.Instance.ShakeCamera((ScreenShakeType)3);
		GameNetworkManager.Instance.localPlayerController.KillPlayer(Vector3.zero, true, (CauseOfDeath)3, 0);
		startedResigning = false;
	}
}
[Serializable]
public class SyncedInstance<T>
{
	[NonSerialized]
	protected static int IntSize = 4;

	internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

	internal static bool IsClient => NetworkManager.Singleton.IsClient;

	internal static bool IsHost => NetworkManager.Singleton.IsHost;

	public static T Default { get; private set; }

	public static T Instance { get; private set; }

	public static bool Synced { get; internal set; }

	protected void InitInstance(T instance)
	{
		Default = instance;
		Instance = instance;
		IntSize = 4;
	}

	internal static void SyncInstance(byte[] data)
	{
		Instance = DeserializeFromBytes(data);
		Synced = true;
	}

	internal static void RevertSync()
	{
		Instance = Default;
		Synced = false;
	}

	public static byte[] SerializeToBytes(T val)
	{
		BinaryFormatter binaryFormatter = new BinaryFormatter();
		using MemoryStream memoryStream = new MemoryStream();
		try
		{
			binaryFormatter.Serialize(memoryStream, val);
			return memoryStream.ToArray();
		}
		catch (Exception arg)
		{
			Console.WriteLine($"Error serializing instance: {arg}");
			return null;
		}
	}

	public static T DeserializeFromBytes(byte[] data)
	{
		BinaryFormatter binaryFormatter = new BinaryFormatter();
		using MemoryStream serializationStream = new MemoryStream(data);
		try
		{
			return (T)binaryFormatter.Deserialize(serializationStream);
		}
		catch (Exception arg)
		{
			Console.WriteLine($"Error deserializing instance: {arg}");
			return default(T);
		}
	}
}
public static class MyPluginInfo
{
	public const string PLUGIN_GUID = "MoreRadarNames";

	public const string PLUGIN_NAME = "MoreRadarNames";

	public const string PLUGIN_VERSION = "1.0.0";
}