Decompiled source of ArtifactOfIndecision v0.6.1

ArtifactOfIndecision.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using On.RoR2;
using R2API;
using RoR2;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ArtifactOfIndecision")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+e8543d5aa72f906bc63e83c1aeac7d41d163058c")]
[assembly: AssemblyProduct("ArtifactOfIndecision")]
[assembly: AssemblyTitle("ArtifactOfIndecision")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 ArtifactOfIndecision
{
	[BepInPlugin("com.creeper2002.artifactofindecision", "Artifact of Indecision", "0.6.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("Risk of Rain 2.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch]
		internal static class CommandFlagPatch
		{
			private static FieldInfo _artifactFlagField;

			private static MethodBase TargetMethod()
			{
				return typeof(PickupDropletController).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(delegate(MethodInfo m)
				{
					if (m.Name != "CreatePickupDroplet")
					{
						return false;
					}
					ParameterInfo[] parameters = m.GetParameters();
					return parameters.Length == 3 && parameters[0].ParameterType == typeof(CreatePickupInfo) && parameters[1].ParameterType == typeof(Vector3) && parameters[2].ParameterType == typeof(Vector3);
				});
			}

			private static void Prefix(ref CreatePickupInfo pickupInfo)
			{
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_009c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
				if (!NetworkServer.active || !IsEnabled() || RealCommandEnabled())
				{
					return;
				}
				if ((object)_artifactFlagField == null)
				{
					_artifactFlagField = typeof(CreatePickupInfo).GetField("artifactFlag", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				}
				if (_artifactFlagField == null)
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogError((object)"Indecision could not find CreatePickupInfo.artifactFlag.");
					}
					return;
				}
				object obj = pickupInfo;
				uint num = Convert.ToUInt32(_artifactFlagField.GetValue(obj));
				if (num == 0)
				{
					object value = Enum.ToObject(_artifactFlagField.FieldType, num | 1);
					_artifactFlagField.SetValue(obj, value);
					pickupInfo = (CreatePickupInfo)obj;
					ManualLogSource log2 = Log;
					if (log2 != null)
					{
						log2.LogDebug((object)$"Indecision flagged pickup {((CreatePickupInfo)(ref pickupInfo)).pickupIndex} as Command.");
					}
				}
			}
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static hook_SetOptionsFromPickupForCommandArtifact_UniquePickup <0>__OnSetCommandOptions;
		}

		public const string Guid = "com.creeper2002.artifactofindecision";

		public const string Name = "Artifact of Indecision";

		public const string Version = "0.6.1";

		internal static ArtifactDef IndecisionArtifact;

		internal static ConfigEntry<string> ChoiceDistribution;

		internal static ManualLogSource Log;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ChoiceDistribution = ((BaseUnityPlugin)this).Config.Bind<string>("Choice Count", "ChoiceDistribution", "3:40, 4:30, 5:20, 6:10", "Weighted distribution for the number of choices. Format: choices:weight. Weights are normalized automatically and do not need to total 100.");
			RegisterArtifact();
			_harmony = new Harmony("com.creeper2002.artifactofindecision");
			_harmony.PatchAll(typeof(CommandFlagPatch));
			object obj = <>O.<0>__OnSetCommandOptions;
			if (obj == null)
			{
				hook_SetOptionsFromPickupForCommandArtifact_UniquePickup val = OnSetCommandOptions;
				<>O.<0>__OnSetCommandOptions = val;
				obj = (object)val;
			}
			PickupPickerController.SetOptionsFromPickupForCommandArtifact_UniquePickup += (hook_SetOptionsFromPickupForCommandArtifact_UniquePickup)obj;
			RegisterDirectorRemovals();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Artifact of Indecision 0.6.1 loaded.");
		}

		private void OnDestroy()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			object obj = <>O.<0>__OnSetCommandOptions;
			if (obj == null)
			{
				hook_SetOptionsFromPickupForCommandArtifact_UniquePickup val = OnSetCommandOptions;
				<>O.<0>__OnSetCommandOptions = val;
				obj = (object)val;
			}
			PickupPickerController.SetOptionsFromPickupForCommandArtifact_UniquePickup -= (hook_SetOptionsFromPickupForCommandArtifact_UniquePickup)obj;
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		internal static bool IsEnabled()
		{
			if ((Object)(object)IndecisionArtifact != (Object)null && Object.op_Implicit((Object)(object)RunArtifactManager.instance))
			{
				return RunArtifactManager.instance.IsArtifactEnabled(IndecisionArtifact);
			}
			return false;
		}

		internal static bool RealCommandEnabled()
		{
			if (Object.op_Implicit((Object)(object)RunArtifactManager.instance))
			{
				return RunArtifactManager.instance.IsArtifactEnabled(Artifacts.Command);
			}
			return false;
		}

		private static void OnSetCommandOptions(orig_SetOptionsFromPickupForCommandArtifact_UniquePickup orig, PickupPickerController self, UniquePickup pickup)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: 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)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			orig.Invoke(self, pickup);
			if (!IsEnabled() || RealCommandEnabled() || (Object)(object)self == (Object)null || self.options == null)
			{
				return;
			}
			int num = self.options.Length;
			if (num <= 1)
			{
				return;
			}
			int num2 = Math.Min(RollChoiceCount(), num);
			if (num2 >= num)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogInfo((object)$"Indecision picker kept all {num} options.");
				}
				return;
			}
			Option[] array = (Option[])self.options.Clone();
			for (int i = 0; i < num2; i++)
			{
				int num3 = Random.Range(i, array.Length);
				Option val = array[i];
				array[i] = array[num3];
				array[num3] = val;
			}
			Option[] array2 = (Option[])(object)new Option[num2];
			Array.Copy(array, array2, num2);
			self.options = array2;
			ManualLogSource log2 = Log;
			if (log2 != null)
			{
				log2.LogInfo((object)$"Indecision reduced picker: {num} -> {num2}");
			}
		}

		private static void RegisterDirectorRemovals()
		{
			Predicate<DirectorCardCategorySelection> predicate = (DirectorCardCategorySelection _) => IsEnabled();
			Helpers.RemoveExistingInteractable(InteractableNames.Printer3D, predicate);
			Helpers.RemoveExistingInteractable(InteractableNames.Printer3DLarge, predicate);
			Helpers.RemoveExistingInteractable(InteractableNames.PrinterMiliTech, predicate);
			Helpers.RemoveExistingInteractable(InteractableNames.PrinterOvergrown3D, predicate);
			Helpers.RemoveExistingInteractable(InteractableNames.TripleShop, predicate);
			Helpers.RemoveExistingInteractable(InteractableNames.TripleShopLarge, predicate);
			Helpers.RemoveExistingInteractable(InteractableNames.TripleShopEquipment, predicate);
			ManualLogSource log = Log;
			if (log != null)
			{
				log.LogInfo((object)"Registered Indecision printer/multishop director removals.");
			}
		}

		internal static int RollChoiceCount()
		{
			List<(int, double)> list = ParseDistribution(ChoiceDistribution.Value);
			if (list.Count == 0)
			{
				list = ParseDistribution("3:40, 4:30, 5:20, 6:10");
			}
			double num = list.Sum<(int, double)>(((int choices, double weight) x) => x.weight);
			double num2 = (double)Random.value * num;
			double num3 = 0.0;
			foreach (var item in list)
			{
				num3 += item.Item2;
				if (num2 <= num3)
				{
					return item.Item1;
				}
			}
			return list[list.Count - 1].Item1;
		}

		private static List<(int choices, double weight)> ParseDistribution(string value)
		{
			List<(int, double)> list = new List<(int, double)>();
			if (string.IsNullOrWhiteSpace(value))
			{
				return list;
			}
			string[] array = value.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Trim().Split(':');
				if (array2.Length == 2 && int.TryParse(array2[0].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && double.TryParse(array2[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) && result > 0 && !(result2 <= 0.0) && !double.IsNaN(result2) && !double.IsInfinity(result2))
				{
					list.Add((result, result2));
				}
			}
			return list;
		}

		private void RegisterArtifact()
		{
			LanguageAPI.Add("ARTIFACT_INDECISION_NAME", "Artifact of Indecision");
			LanguageAPI.Add("ARTIFACT_INDECISION_DESCRIPTION", "Items become choices between a <style=cIsUtility>small random selection</style> of valid alternatives.");
			ArtifactDef val = ScriptableObject.CreateInstance<ArtifactDef>();
			val.cachedName = "ARTIFACT_OF_INDECISION";
			val.nameToken = "ARTIFACT_INDECISION_NAME";
			val.descriptionToken = "ARTIFACT_INDECISION_DESCRIPTION";
			val.smallIconSelectedSprite = LoadEmbeddedSprite("indecision_icon.png", deselected: false);
			val.smallIconDeselectedSprite = LoadEmbeddedSprite("indecision_icon.png", deselected: true);
			val.unlockableDef = null;
			val.requiredExpansion = null;
			if (!ContentAddition.AddArtifactDef(val))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"R2API rejected Artifact of Indecision.");
			}
			else
			{
				IndecisionArtifact = val;
			}
		}

		private Sprite LoadEmbeddedSprite(string suffix, bool deselected)
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected O, but got Unknown
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			string text = Assembly.GetExecutingAssembly().GetManifestResourceNames().FirstOrDefault((string n) => n.EndsWith(suffix, StringComparison.OrdinalIgnoreCase));
			if (text == null)
			{
				return null;
			}
			byte[] array;
			using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(text))
			{
				using MemoryStream memoryStream = new MemoryStream();
				stream.CopyTo(memoryStream);
				array = memoryStream.ToArray();
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if (!ImageConversion.LoadImage(val, array))
			{
				return null;
			}
			((Texture)val).wrapMode = (TextureWrapMode)1;
			((Texture)val).filterMode = (FilterMode)1;
			if (deselected)
			{
				Color[] pixels = val.GetPixels();
				for (int num = 0; num < pixels.Length; num++)
				{
					float num2 = (pixels[num].r + pixels[num].g + pixels[num].b) / 3f;
					pixels[num] = new Color(num2 * 0.35f, num2 * 0.35f, num2 * 0.35f, pixels[num].a);
				}
				val.SetPixels(pixels);
				val.Apply();
			}
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
		}
	}
}