Decompiled source of DelayedShards v0.0.1

DelayedShards.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CG;
using CG.Game;
using CG.Game.Scenarios;
using CG.Game.Scenarios.Actions;
using CG.Game.Scenarios.Conditions;
using CG.Game.SpaceObjects.Controllers;
using CG.Input;
using CG.Ship.Hull;
using CG.Ship.Modules;
using CG.Space;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using VoidManager;
using VoidManager.Chat.Router;
using VoidManager.CustomGUI;
using VoidManager.MPModChecks;
using VoidManager.ModMessages;
using VoidManager.Utilities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("DelayedShards")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("Template")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DelayedShards")]
[assembly: AssemblyTitle("DelayedShards")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 DelayedShards
{
	internal class ActivateShardCommand : PublicCommand
	{
		public override string[] CommandAliases()
		{
			return new string[1] { "ActivateShard" };
		}

		public override string Description()
		{
			return "Activates a previously inserted data shard";
		}

		public override List<Argument> Arguments()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			List<Argument> list = new List<Argument>();
			list.Add(new Argument(new string[2] { "Escort", "Minefield" }));
			return list;
		}

		public override string[] UsageExamples()
		{
			return ((PublicCommand)this).Arguments()[0].names.Select((string name) => "!" + ((PublicCommand)this).CommandAliases()[0] + " " + name).ToArray();
		}

		public override void Execute(string arguments, int SenderID)
		{
			if (!PhotonNetwork.IsMasterClient)
			{
				return;
			}
			if (!Helper.IsInPilotsSeat(Game.GetPlayerFromID(SenderID).PhotonPlayer))
			{
				Messaging.Echo("You must be in the pilot's seat to activate data shards", false);
				return;
			}
			string text = arguments.Split(new char[1] { ' ' })[0].ToLower();
			string text2 = text;
			string text3 = text2;
			if (!(text3 == "escort"))
			{
				if (text3 == "minefield")
				{
					Helper.SendPublicMessage(Helper.SummonMinefield());
				}
				else
				{
					Messaging.Echo("Options are \"Escort\" and \"Minefield\"", false);
				}
			}
			else
			{
				Helper.SendPublicMessage(Helper.SummonEscort());
			}
		}
	}
	internal class CountShardCommand : ActivateShardCommand
	{
		public override string[] CommandAliases()
		{
			return new string[1] { "CountShards" };
		}

		public override string Description()
		{
			return "Lists the number of shards available";
		}

		public override void Execute(string arguments, int SenderID)
		{
			if (Utility.IsNullOrWhiteSpace(arguments))
			{
				Helper.SendPublicMessage();
				return;
			}
			string text = arguments.Split(new char[1] { ' ' })[0].ToLower();
			string text2 = text;
			string text3 = text2;
			if (!(text3 == "escort"))
			{
				if (text3 == "minefield")
				{
					Messaging.Echo($"{Helper.MinefieldsAvailable} Minefield shards available", false);
				}
			}
			else
			{
				Messaging.Echo($"{Helper.EscortsAvailable} Escort shards available", false);
			}
		}
	}
	internal static class MyPluginInfo
	{
		internal const string PLUGIN_GUID = "id107.delayedshards";

		internal const string PLUGIN_NAME = "DelayedShards";

		internal const string PLUGIN_VERSION = "0.0.1";
	}
	[BepInPlugin("id107.delayedshards", "DelayedShards", "0.0.1")]
	[BepInProcess("Void Crew.exe")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class BepinPlugin : BaseUnityPlugin
	{
		internal static ManualLogSource Log;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "id107.delayedshards");
			Configs.Load(this);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin id107.delayedshards is loaded!");
		}
	}
	[HarmonyPatch(typeof(CarryablesSocket), "Start")]
	internal class CarryablesSocketPatch
	{
		private static void Prefix(CarryablesSocket __instance)
		{
			if (((Object)__instance).name == "GalaxyMapTerminal_SingleSocket")
			{
				__instance.ClosedWhileInVoid = false;
			}
		}
	}
	[HarmonyPatch(typeof(Classifier), "OnTriggerConditionChanged")]
	internal class ClassifierPatch
	{
		private static readonly FieldInfo delayMsField = AccessTools.Field(typeof(Timer), "delayMs");

		private static bool Prefix(Classifier __instance, AbstractScenarioClassifierCondition abstractScenarioClassifierCondition, bool value, ClassifierContext context)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			if (!value)
			{
				return true;
			}
			if (__instance.Id == "Generic_DataShard_OnInsert_SummonEscort")
			{
				if (Helper.EscortActions == null)
				{
					Helper.EscortContext = context;
					Helper.EscortActions = __instance.Actions;
					delayMsField.SetValue((object?)(Timer)Helper.EscortActions[0], 0);
					delayMsField.SetValue((object?)(Timer)Helper.EscortActions[2], 2000);
				}
				__instance.HasBeenInvoked = true;
				Helper.EscortsAvailable++;
				ShardMessageHandler.SendShardCount();
				return false;
			}
			if (__instance.Id == "Generic_DataShard_OnInsert_DataShard_SummonMinefield")
			{
				if (Helper.MinefieldActions == null)
				{
					Helper.MinefieldContext = context;
					Helper.MinefieldActions = __instance.Actions;
					delayMsField.SetValue((object?)(Timer)Helper.MinefieldActions[0], 0);
					delayMsField.SetValue((object?)(Timer)Helper.MinefieldActions[1], 8000);
				}
				__instance.HasBeenInvoked = true;
				Helper.MinefieldsAvailable++;
				ShardMessageHandler.SendShardCount();
				return false;
			}
			return true;
		}
	}
	internal class Configs
	{
		internal static ConfigEntry<KeyCode> SummonEscortConfig;

		internal static ConfigEntry<KeyCode> SummonMinefieldConfig;

		internal static ConfigEntry<bool> RecieveNotificationsAsPilot;

		internal static ConfigEntry<bool> AlwaysRecieveNotifications;

		internal static void Load(BepinPlugin plugin)
		{
			SummonEscortConfig = ((BaseUnityPlugin)plugin).Config.Bind<KeyCode>("DelayedShards", "SummonEscort", (KeyCode)50, (ConfigDescription)null);
			SummonMinefieldConfig = ((BaseUnityPlugin)plugin).Config.Bind<KeyCode>("DelayedShards", "SummonMinefield", (KeyCode)51, (ConfigDescription)null);
			RecieveNotificationsAsPilot = ((BaseUnityPlugin)plugin).Config.Bind<bool>("DelayedShards", "RecieveNotificationsAsPilot", true, (ConfigDescription)null);
			AlwaysRecieveNotifications = ((BaseUnityPlugin)plugin).Config.Bind<bool>("DelayedShards", "AlwaysRecieveNotifications", false, (ConfigDescription)null);
		}
	}
	internal class GUI : ModSettingsMenu
	{
		public override string Name()
		{
			return "Delayed Shards";
		}

		public override void Draw()
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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)
			GUILayout.Label($"Escort shards available: {Helper.EscortsAvailable}", Array.Empty<GUILayoutOption>());
			GUILayout.Label($"Minefield shards available: {Helper.MinefieldsAvailable}", Array.Empty<GUILayoutOption>());
			bool value = Configs.RecieveNotificationsAsPilot.Value;
			if (GUITools.DrawCheckbox("Display notifications when in the pilots seat and shard count changes", ref value))
			{
				Configs.RecieveNotificationsAsPilot.Value = value;
			}
			bool value2 = Configs.AlwaysRecieveNotifications.Value;
			if (GUITools.DrawCheckbox("Always display notifications when shard count changes", ref value2))
			{
				Configs.AlwaysRecieveNotifications.Value = value2;
			}
			KeyCode value3 = Configs.SummonEscortConfig.Value;
			if (GUITools.DrawChangeKeybindButton("Change Summon Escort Keybind", ref value3))
			{
				Configs.SummonEscortConfig.Value = value3;
			}
			KeyCode value4 = Configs.SummonMinefieldConfig.Value;
			if (GUITools.DrawChangeKeybindButton("Change Summon Minefield Keybind", ref value4))
			{
				Configs.SummonMinefieldConfig.Value = value4;
			}
		}
	}
	internal class Helper
	{
		internal enum RejectReason
		{
			None,
			CooldownTimer,
			VoidJump,
			EscortShardCount,
			MinefieldShardCount,
			EscortError,
			MinefieldError
		}

		public const long messageTimeout = 8000L;

		internal static ClassifierContext EscortContext;

		internal static AbstractScenarioClassifierAction[] EscortActions;

		internal static int EscortsAvailable = 0;

		internal static ClassifierContext MinefieldContext;

		internal static AbstractScenarioClassifierAction[] MinefieldActions;

		internal static int MinefieldsAvailable = 0;

		private static DateTime lastShardActivated = DateTime.MinValue;

		internal static RejectReason SummonEscort()
		{
			if (EscortsAvailable <= 0)
			{
				return RejectReason.EscortShardCount;
			}
			if (EscortActions == null)
			{
				return RejectReason.EscortError;
			}
			if ((DateTime.Now - lastShardActivated).TotalSeconds < 8.0)
			{
				return RejectReason.CooldownTimer;
			}
			if (IsInVoidJump())
			{
				return RejectReason.VoidJump;
			}
			AbstractScenarioClassifierAction[] escortActions = EscortActions;
			foreach (AbstractScenarioClassifierAction val in escortActions)
			{
				val.Invoke(EscortContext);
			}
			EscortsAvailable--;
			lastShardActivated = DateTime.Now;
			ShardMessageHandler.SendShardCount();
			return RejectReason.None;
		}

		internal static RejectReason SummonMinefield()
		{
			if (MinefieldsAvailable <= 0)
			{
				return RejectReason.MinefieldShardCount;
			}
			if (MinefieldActions == null)
			{
				return RejectReason.MinefieldError;
			}
			if ((DateTime.Now - lastShardActivated).TotalSeconds < 8.0)
			{
				return RejectReason.CooldownTimer;
			}
			if (IsInVoidJump())
			{
				return RejectReason.VoidJump;
			}
			AbstractScenarioClassifierAction[] minefieldActions = MinefieldActions;
			foreach (AbstractScenarioClassifierAction val in minefieldActions)
			{
				val.Invoke(MinefieldContext);
			}
			MinefieldsAvailable--;
			lastShardActivated = DateTime.Now;
			ShardMessageHandler.SendShardCount();
			return RejectReason.None;
		}

		internal static void Reset()
		{
			EscortContext = null;
			EscortActions = null;
			EscortsAvailable = 0;
			MinefieldContext = null;
			MinefieldContext = null;
			MinefieldsAvailable = 0;
			ShardMessageHandler.subscribedPlayers = ShardMessageHandler.subscribedPlayers.Intersect(PhotonNetwork.PlayerListOthers).ToList();
			ShardMessageHandler.SendShardCount();
		}

		internal static bool IsInPilotsSeat(Player player)
		{
			AbstractPlayerControlledShip playerShip = ClientGame.Current.PlayerShip;
			object obj;
			if (playerShip == null)
			{
				obj = null;
			}
			else
			{
				Helm module = playerShip.GetModule<Helm>();
				obj = ((module != null) ? module.Chair : null);
			}
			TakeoverChair val = (TakeoverChair)((obj is TakeoverChair) ? obj : null);
			return (Object)(object)val != (Object)null && !val.IsAvailable && player == ((MonoBehaviourPun)val).photonView.Owner;
		}

		internal static bool IsInVoidJump()
		{
			VoidJumpState activeState = ((Component)ClientGame.Current.PlayerShip).GetComponent<VoidJumpSystem>().ActiveState;
			return activeState is VoidJumpInterdiction || activeState is VoidJumpTravellingStable || activeState is VoidJumpTravellingUnstable || activeState is VoidJumpApproachingDestination;
		}

		internal static void SendPublicMessage(RejectReason reason = RejectReason.None)
		{
			Messaging.Echo(GetDisplayMessage(reason), false);
		}

		internal static void DisplayLocalMessage(RejectReason reason = RejectReason.None)
		{
			if (reason != 0 || Configs.AlwaysRecieveNotifications.Value || (Configs.RecieveNotificationsAsPilot.Value && IsInPilotsSeat(PhotonNetwork.LocalPlayer)))
			{
				Messaging.Notification(GetDisplayMessage(reason), 8000L, false);
			}
		}

		private static string GetDisplayMessage(RejectReason reason)
		{
			if (1 == 0)
			{
			}
			string result = reason switch
			{
				RejectReason.None => $"{EscortsAvailable} escort shards available\n{MinefieldsAvailable} minefield shards availabe", 
				RejectReason.CooldownTimer => "Data shards on cooldown", 
				RejectReason.VoidJump => "Data shards not available during void jump", 
				RejectReason.EscortShardCount => "No escort shards available", 
				RejectReason.MinefieldShardCount => "No minefield shards available", 
				RejectReason.EscortError => "Error caused by host leaving, insert escort shard to fix", 
				RejectReason.MinefieldError => "Error caused by host leaving, insert minefield shard to fix", 
				_ => throw new ArgumentException(), 
			};
			if (1 == 0)
			{
			}
			return result;
		}
	}
	internal class Inputs
	{
		internal static void HandleInputs()
		{
			//IL_002d: 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_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			if (!Helper.IsInPilotsSeat(PhotonNetwork.LocalPlayer))
			{
				return;
			}
			if (!ServiceBase<InputService>.Instance.CursorVisibilityControl.IsCursorShown && (int)Configs.SummonEscortConfig.Value != 0 && UnityInput.Current.GetKeyDown(Configs.SummonEscortConfig.Value))
			{
				if (PhotonNetwork.IsMasterClient)
				{
					Helper.RejectReason rejectReason = Helper.SummonEscort();
					if (rejectReason != 0)
					{
						Helper.DisplayLocalMessage(rejectReason);
					}
				}
				else
				{
					ShardMessageHandler.ActivateShard("escort");
				}
			}
			if (ServiceBase<InputService>.Instance.CursorVisibilityControl.IsCursorShown || (int)Configs.SummonMinefieldConfig.Value == 0 || !UnityInput.Current.GetKeyDown(Configs.SummonMinefieldConfig.Value))
			{
				return;
			}
			if (PhotonNetwork.IsMasterClient)
			{
				Helper.RejectReason rejectReason2 = Helper.SummonMinefield();
				if (rejectReason2 != 0)
				{
					Helper.DisplayLocalMessage(rejectReason2);
				}
			}
			else
			{
				ShardMessageHandler.ActivateShard("minefield");
			}
		}
	}
	internal class ShardMessageHandler : ModMessage
	{
		private enum Requests
		{
			Subscribe,
			Sent,
			Activate,
			Reject
		}

		internal static List<Player> subscribedPlayers = new List<Player>();

		public override void Handle(object[] arguments, Player sender)
		{
			if (arguments.Length == 0)
			{
				return;
			}
			if ((string)arguments[0] != "0.0.1")
			{
				BepinPlugin.Log.LogInfo((object)("Got version " + (string)arguments[0] + " from " + sender.NickName + ", expected version 0.0.1"));
				return;
			}
			switch ((Requests)arguments[1])
			{
			case Requests.Subscribe:
				if (PhotonNetwork.IsMasterClient)
				{
					if (!subscribedPlayers.Contains(sender))
					{
						subscribedPlayers.Add(sender);
					}
					SendShardCount(sender);
				}
				break;
			case Requests.Sent:
				if (!PhotonNetwork.IsMasterClient && sender == PhotonNetwork.MasterClient)
				{
					int[] array = (int[])arguments[2];
					Helper.EscortsAvailable = array[0];
					Helper.MinefieldsAvailable = array[1];
					Helper.DisplayLocalMessage();
				}
				break;
			case Requests.Activate:
			{
				if (!PhotonNetwork.IsMasterClient)
				{
					break;
				}
				Helper.RejectReason rejectReason = Helper.RejectReason.None;
				string text = ((string)arguments[2]).ToLower();
				string text2 = text;
				if (!(text2 == "escort"))
				{
					if (text2 == "minefield")
					{
						rejectReason = Helper.SummonMinefield();
					}
				}
				else
				{
					rejectReason = Helper.SummonEscort();
				}
				if (rejectReason != 0)
				{
					SendRejectMessage(sender, rejectReason);
				}
				break;
			}
			case Requests.Reject:
				if (!PhotonNetwork.IsMasterClient && sender == PhotonNetwork.MasterClient)
				{
					Helper.DisplayLocalMessage((Helper.RejectReason)arguments[2]);
				}
				break;
			}
		}

		internal static void SubscribeToCountUpdates()
		{
			if (!PhotonNetwork.IsMasterClient)
			{
				ModMessage.Send("id107.delayedshards", ModMessage.GetIdentifier(typeof(ShardMessageHandler)), PhotonNetwork.MasterClient, new object[2]
				{
					"0.0.1",
					Requests.Subscribe
				}, false);
			}
		}

		internal static void ActivateShard(string shardName)
		{
			if (!PhotonNetwork.IsMasterClient)
			{
				ModMessage.Send("id107.delayedshards", ModMessage.GetIdentifier(typeof(ShardMessageHandler)), PhotonNetwork.MasterClient, new object[3]
				{
					"0.0.1",
					Requests.Activate,
					shardName
				}, false);
			}
		}

		internal static void SendShardCount(params Player[] player)
		{
			if (PhotonNetwork.IsMasterClient)
			{
				if (player == null || player.Length == 0)
				{
					player = subscribedPlayers.ToArray();
					Helper.DisplayLocalMessage();
				}
				ModMessage.Send("id107.delayedshards", ModMessage.GetIdentifier(typeof(ShardMessageHandler)), player, new object[3]
				{
					"0.0.1",
					Requests.Sent,
					new int[2]
					{
						Helper.EscortsAvailable,
						Helper.MinefieldsAvailable
					}
				}, false);
			}
		}

		internal static void SendRejectMessage(Player player, Helper.RejectReason reason)
		{
			if (PhotonNetwork.IsMasterClient)
			{
				ModMessage.Send("id107.delayedshards", ModMessage.GetIdentifier(typeof(ShardMessageHandler)), player, new object[3]
				{
					"0.0.1",
					Requests.Reject,
					reason
				}, false);
			}
		}
	}
	public class VoidManagerPlugin : VoidPlugin
	{
		public override MultiplayerType MPType => (MultiplayerType)4;

		public override string Author => "18107";

		public override string Description => "Inserting shards into the map adds them to a queue for the pilot to activate at any time";

		public VoidManagerPlugin()
		{
			Events.Instance.JoinedRoom += delegate
			{
				ShardMessageHandler.SubscribeToCountUpdates();
			};
			Events.Instance.LeftRoom += delegate
			{
				Helper.Reset();
			};
			Events.Instance.HostStartSession += delegate
			{
				Helper.Reset();
			};
			Events.Instance.MasterClientSwitched += delegate
			{
				ShardMessageHandler.SubscribeToCountUpdates();
			};
			Events.Instance.PlayerLeftRoom += delegate(object sender, PlayerEventArgs e)
			{
				ShardMessageHandler.subscribedPlayers.Remove(e.player);
			};
			Events.Instance.LateUpdate += delegate
			{
				Inputs.HandleInputs();
			};
		}
	}
}