Decompiled source of MagnetTweaks v2.1.2

plugins\MagnetTweaks\MagnetTweaks.dll

Decompiled 3 weeks ago
using System;
using System.Diagnostics;
using System.IO;
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.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using DRS.UI;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("MagnetTweaks")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("2.1.2.0")]
[assembly: AssemblyInformationalVersion("2.1.2")]
[assembly: AssemblyProduct("MagnetTweaks")]
[assembly: AssemblyTitle("MagnetTweaks")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.1.2.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.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = 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 MagnetTweaks
{
	internal static class ConfigReload
	{
		private static ConfigFile config;

		private static FileSystemWatcher watcher;

		private static volatile bool pending;

		private static DateTime dueAt;

		public static void Start(ConfigFile cfg)
		{
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			config = cfg;
			try
			{
				watcher = new FileSystemWatcher(Path.GetDirectoryName(cfg.ConfigFilePath), Path.GetFileName(cfg.ConfigFilePath))
				{
					NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite)
				};
				watcher.Changed += delegate
				{
					Queue();
				};
				watcher.Created += delegate
				{
					Queue();
				};
				watcher.Renamed += delegate
				{
					Queue();
				};
				watcher.EnableRaisingEvents = true;
				Plugin.Logger.LogInfo((object)"Watching config file for live changes.");
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(32, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Live config reload unavailable: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				logger.LogWarning(val);
			}
		}

		private static void Queue()
		{
			dueAt = DateTime.UtcNow.AddMilliseconds(300.0);
			pending = true;
		}

		public static void Tick()
		{
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			if (!pending || DateTime.UtcNow < dueAt)
			{
				return;
			}
			pending = false;
			bool flag = default(bool);
			try
			{
				config.Reload();
				ManualLogSource logger = Plugin.Logger;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(37, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Config reloaded. Mode = ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<MagnetMode>(Plugin.Mode.Value);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", PullType = ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<PullType>(Plugin.Pull.Value);
				}
				logger.LogInfo(val);
			}
			catch (Exception ex)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Config reload failed (file mid-save?): ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				logger2.LogError(val2);
				pending = true;
				dueAt = DateTime.UtcNow.AddSeconds(1.0);
			}
		}
	}
	public enum MagnetMode
	{
		Off,
		AlwaysActive,
		EndOfMission
	}
	public enum PullType
	{
		Full,
		XpOnly
	}
	[BepInPlugin("tobipolar.drgs.magnettweaks", "Magnet Tweaks", "2.1.2")]
	public class Plugin : BasePlugin
	{
		public const string Guid = "tobipolar.drgs.magnettweaks";

		public const string Name = "Magnet Tweaks";

		public const string Version = "2.1.2";

		internal static ManualLogSource Logger;

		internal static ConfigEntry<MagnetMode> Mode;

		internal static ConfigEntry<PullType> Pull;

		internal static ConfigEntry<float> PulseInterval;

		internal static ConfigEntry<float> MagnetValue;

		internal static ConfigEntry<float> EndOfMissionDelay;

		internal static ConfigEntry<bool> EndOfMissionKeepPulling;

		internal static ConfigEntry<bool> RemoveMagnetOffers;

		internal static ConfigEntry<bool> VerboseLogging;

		private void MigrateOldConfig(params string[] oldNames)
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				string configFilePath = ((BasePlugin)this).Config.ConfigFilePath;
				if (File.Exists(configFilePath) && new FileInfo(configFilePath).Length != 0)
				{
					return;
				}
				foreach (string text in oldNames)
				{
					string text2 = Path.Combine(Paths.ConfigPath, text);
					if (File.Exists(text2))
					{
						File.Copy(text2, configFilePath, overwrite: true);
						((BasePlugin)this).Config.Reload();
						ManualLogSource log = ((BasePlugin)this).Log;
						BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(56, 1, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Settings copied from the old ");
							((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
							((BepInExLogInterpolatedStringHandler)val).AppendLiteral(". You can delete that file.");
						}
						log.LogInfo(val);
						break;
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = ((BasePlugin)this).Log;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(28, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Couldn't copy old settings: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(ex.Message);
				}
				log2.LogWarning(val2);
			}
		}

		public override void Load()
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_0194: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			MigrateOldConfig("toby.drgs.magnettweaks.cfg", "toby.drgs.bettermagnet.cfg");
			Mode = ((BasePlugin)this).Config.Bind<MagnetMode>("Magnet", "Mode", MagnetMode.EndOfMission, "Off = vanilla.\nAlwaysActive = magnet effect fires every PulseInterval seconds for the whole stage.\nEndOfMission = magnet effect starts automatically once the extraction countdown starts.");
			Pull = ((BasePlugin)this).Config.Bind<PullType>("Magnet", "PullType", PullType.XpOnly, "XpOnly = silently pull all XP (recommended for AlwaysActive).\nFull = exactly what a real magnet does, including the magnet sound. Each pull counts as a magnet pickup for milestones.");
			PulseInterval = ((BasePlugin)this).Config.Bind<float>("Magnet", "PulseInterval", 15f, new ConfigDescription("Seconds between pulls (AlwaysActive, and EndOfMission when KeepPulling is on).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 60f), Array.Empty<object>()));
			EndOfMissionDelay = ((BasePlugin)this).Config.Bind<float>("Magnet", "EndOfMissionDelaySeconds", 5f, new ConfigDescription("EndOfMission only: wait this long after the countdown starts before the first pull.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 120f), Array.Empty<object>()));
			EndOfMissionKeepPulling = ((BasePlugin)this).Config.Bind<bool>("Magnet", "EndOfMissionKeepPulling", true, "EndOfMission only. true = keep pulling every PulseInterval until you board the pod. false = one single pull.");
			MagnetValue = ((BasePlugin)this).Config.Bind<float>("Magnet", "FullMagnetValue", 1f, "Value passed to the game's magnet handler when PullType = Full. Leave at 1 unless Full pulls seem weak (then try 0).");
			RemoveMagnetOffers = ((BasePlugin)this).Config.Bind<bool>("Offers", "RemoveMagnetOffers", true, "While Mode isn't Off: pickup-radius upgrades and the Company Issued Magnet artifact never appear in level-ups, shop, supply pods, loot crates or Huuli.");
			VerboseLogging = ((BasePlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Log every magnet pull to the BepInEx console.");
			Harmony.CreateAndPatchAll(typeof(Patches), "tobipolar.drgs.magnettweaks");
			ConfigReload.Start(((BasePlugin)this).Config);
			MagnetRunner.Init();
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(30, 4, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Magnet Tweaks");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("2.1.2");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded. Mode = ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<MagnetMode>(Mode.Value);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", PullType = ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<PullType>(Pull.Value);
			}
			logger.LogInfo(val);
		}
	}
	internal static class State
	{
		public static Player Player;

		public static PickupSpawner Spawner;

		public static bool OutOfPod;

		public static bool ExtractionStarted;

		public static bool SinglePullDone;

		public static float PulseTimer;

		public static float DelayTimer;

		public static int ErrorCount;

		public static void ResetStage()
		{
			OutOfPod = false;
			ExtractionStarted = false;
			SinglePullDone = false;
			PulseTimer = 0f;
			DelayTimer = 0f;
		}

		public static bool Alive(Object o)
		{
			if (o != (Object)null && !((Il2CppObjectBase)o).WasCollected)
			{
				return Object.op_Implicit(o);
			}
			return false;
		}

		public static Player GetPlayer()
		{
			if (Alive((Object)(object)Player))
			{
				return Player;
			}
			try
			{
				Player = Object.FindObjectOfType<Player>();
			}
			catch
			{
				Player = null;
			}
			if (!Alive((Object)(object)Player))
			{
				return null;
			}
			return Player;
		}

		public static PickupSpawner GetSpawner()
		{
			if (Alive((Object)(object)Spawner))
			{
				return Spawner;
			}
			try
			{
				Spawner = Object.FindObjectOfType<PickupSpawner>();
			}
			catch
			{
				Spawner = null;
			}
			if (!Alive((Object)(object)Spawner))
			{
				return null;
			}
			return Spawner;
		}

		public static void OnCountdownStarted(string source)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			if (!ExtractionStarted && OutOfPod)
			{
				ExtractionStarted = true;
				DelayTimer = Plugin.EndOfMissionDelay.Value;
				PulseTimer = 0f;
				SinglePullDone = false;
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(32, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Extraction countdown started (");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(source);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(").");
				}
				logger.LogInfo(val);
			}
		}
	}
	internal static class Magnet
	{
		public static void Pulse()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			Player player = State.GetPlayer();
			if ((Object)(object)player == (Object)null || !player.IsAlive)
			{
				return;
			}
			if (Plugin.Pull.Value == PullType.Full)
			{
				player.OnMagnetPickup(Plugin.MagnetValue.Value);
			}
			else
			{
				PickupSpawner spawner = State.GetSpawner();
				XPManager val = ((spawner != null) ? spawner.XpManager : null);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				val.MagnetTriggered();
			}
			if (Plugin.VerboseLogging.Value)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(14, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Magnet pull (");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<PullType>(Plugin.Pull.Value);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(")");
				}
				logger.LogInfo(val2);
			}
		}

		public static void Tick()
		{
			MagnetMode value = Plugin.Mode.Value;
			if (value == MagnetMode.Off || !State.OutOfPod)
			{
				return;
			}
			float deltaTime = Time.deltaTime;
			if (deltaTime <= 0f)
			{
				return;
			}
			switch (value)
			{
			case MagnetMode.AlwaysActive:
				RunPulseTimer(deltaTime);
				break;
			case MagnetMode.EndOfMission:
				if (State.ExtractionStarted)
				{
					if (State.DelayTimer > 0f)
					{
						State.DelayTimer -= deltaTime;
					}
					else if (Plugin.EndOfMissionKeepPulling.Value)
					{
						RunPulseTimer(deltaTime);
					}
					else if (!State.SinglePullDone)
					{
						Pulse();
						State.SinglePullDone = true;
					}
				}
				break;
			}
		}

		private static void RunPulseTimer(float dt)
		{
			State.PulseTimer -= dt;
			if (!(State.PulseTimer > 0f))
			{
				Pulse();
				State.PulseTimer = Plugin.PulseInterval.Value;
			}
		}
	}
	internal static class Offers
	{
		private static readonly ERarity[] Rarities;

		private static bool logged;

		public static bool Active
		{
			get
			{
				if (Plugin.RemoveMagnetOffers.Value)
				{
					return Plugin.Mode.Value != MagnetMode.Off;
				}
				return false;
			}
		}

		public static bool IsPickupRadius(SupportSkillData skill)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: 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 ((Object)(object)skill == (Object)null)
			{
				return false;
			}
			ERarity[] rarities = Rarities;
			foreach (ERarity val in rarities)
			{
				if (skill.HasRarity(val) && skill.HasStatModForType((EStatType)9, val))
				{
					return true;
				}
			}
			return false;
		}

		public static void LogOnce(string msg)
		{
			if (!logged)
			{
				logged = true;
				Plugin.Logger.LogError((object)msg);
			}
		}

		static Offers()
		{
			ERarity[] array = new ERarity[5];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			Rarities = (ERarity[])(object)array;
		}
	}
	internal static class Patches
	{
		[HarmonyPatch(typeof(GameController), "Update")]
		[HarmonyPostfix]
		private static void GameControllerUpdate()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			try
			{
				Magnet.Tick();
			}
			catch (Exception ex)
			{
				if (State.ErrorCount++ < 5)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(13, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Tick failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogError(val);
				}
			}
		}

		[HarmonyPatch(typeof(CoreGameEvents), "TriggerStageBegin")]
		[HarmonyPostfix]
		private static void StageBegin()
		{
			State.ResetStage();
			State.Spawner = null;
		}

		[HarmonyPatch(typeof(Player), "OnExitDropPod")]
		[HarmonyPostfix]
		private static void PlayerExitDropPod(Player __instance)
		{
			State.Player = __instance;
			State.ResetStage();
			State.OutOfPod = true;
			Plugin.Logger.LogInfo((object)"Stage started (left landing pod).");
		}

		[HarmonyPatch(typeof(CoreGameEvents), "TriggerPlayerEnteredDropPod")]
		[HarmonyPostfix]
		private static void PlayerEnteredDropPod()
		{
			State.ResetStage();
		}

		[HarmonyPatch(typeof(CoreGameEvents), "TriggerDropPodLanded")]
		[HarmonyPostfix]
		private static void DropPodLanded()
		{
			State.OnCountdownStarted("pod landed");
		}

		[HarmonyPatch(typeof(UIDropPodCountdown), "Show")]
		[HarmonyPostfix]
		private static void CountdownShown()
		{
			State.OnCountdownStarted("countdown shown");
		}

		[HarmonyPatch(typeof(PickupSpawner), "SpawnXP")]
		[HarmonyPostfix]
		private static void CacheSpawner(PickupSpawner __instance)
		{
			State.Spawner = __instance;
		}

		[HarmonyPatch(typeof(SkillCollectionManager), "GetAvailableSupports")]
		[HarmonyPostfix]
		private static void FilterSupports(List<SupportSkillData> __result)
		{
			if (!Offers.Active || __result == null)
			{
				return;
			}
			try
			{
				for (int num = __result.Count - 1; num >= 0; num--)
				{
					if (Offers.IsPickupRadius(__result[num]))
					{
						__result.RemoveAt(num);
					}
				}
			}
			catch (Exception value)
			{
				Offers.LogOnce($"Support filter failed: {value}");
			}
		}

		[HarmonyPatch(typeof(SkillCollectionManager), "GetAvailableArtifacts")]
		[HarmonyPostfix]
		private static void FilterArtifacts(List<ArtifactSkillData> __result)
		{
			if (!Offers.Active || __result == null)
			{
				return;
			}
			try
			{
				for (int num = __result.Count - 1; num >= 0; num--)
				{
					ArtifactSkillData obj = __result[num];
					if ((Object)(object)((obj != null) ? ((Il2CppObjectBase)obj).TryCast<CompanyIssuedMagnetArtifactData>() : null) != (Object)null)
					{
						__result.RemoveAt(num);
					}
				}
			}
			catch (Exception value)
			{
				Offers.LogOnce($"Artifact filter failed: {value}");
			}
		}
	}
	public class MagnetRunner : MonoBehaviour
	{
		public MagnetRunner(IntPtr ptr)
			: base(ptr)
		{
		}

		public static void Init()
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_0015: 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_0036: Expected O, but got Unknown
			try
			{
				ClassInjector.RegisterTypeInIl2Cpp<MagnetRunner>();
				GameObject val = new GameObject("MagnetTweaks.Runner");
				Object.DontDestroyOnLoad((Object)val);
				((Object)val).hideFlags = (HideFlags)61;
				val.AddComponent<MagnetRunner>();
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Runner setup failed (live config off): ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val2);
			}
		}

		private void Update()
		{
			ConfigReload.Tick();
		}
	}
}