Decompiled source of MoreTrinkets v1.1.0

MoreTrinkets.dll

Decompiled a day ago
using System;
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.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace MoreTrinkets;

[Serializable]
public class CustomDef
{
	public string id;

	public string title;

	public string description;

	public string flavor = "";

	public bool binding;

	public int cost = 1;

	public float scoreMultiplierBonus;

	public string[] from;

	public int extraPouches;

	public string iconFrom;

	public Dictionary<string, float> buffs;
}
[Serializable]
public class CustomFile
{
	public CustomDef[] trinkets;
}
internal static class CustomTrinkets
{
	public const string DatabaseId = "isaac_moretrinkets";

	public const string NamePrefix = "Isaac_Trinket_";

	internal static readonly List<Trinket> Customs = new List<Trinket>();

	internal static readonly Dictionary<string, Dictionary<string, float>> Buffs = new Dictionary<string, Dictionary<string, float>>();

	private static WKAssetDatabase db;

	private static bool built;

	private const string DefaultJson = "{\n  \"trinkets\": [\n    {\n      \"id\": \"ClimbersKit\",\n      \"title\": \"Climber's Kit\",\n      \"description\": \"Chalk, a Carabiner, Climbing Shoes and a Helmet, all for one slot.\",\n      \"from\": [\"Trinket_Chalk\", \"Trinket_Carabiner\", \"Trinket_ClimbingShoes\", \"Trinket_Helmet\"],\n      \"iconFrom\": \"Trinket_Carabiner\"\n    },\n    {\n      \"id\": \"PackMule\",\n      \"title\": \"Pack Mule\",\n      \"description\": \"Extra Pouch and Larger Pack together, plus two more pouches. Three extra pouches in total.\",\n      \"from\": [\"Trinket_Pouch\", \"Trinket_BagExpander\"],\n      \"extraPouches\": 2,\n      \"iconFrom\": \"Trinket_Pouch\"\n    },\n    {\n      \"id\": \"Scout\",\n      \"title\": \"Scout\",\n      \"description\": \"Head Lamp, The Beta and Calming Buddy together, for one slot.\",\n      \"from\": [\"Trinket_Headlamp\", \"Trinket_Beta\", \"Trinket_CalmingBuddy\"],\n      \"iconFrom\": \"Trinket_Headlamp\"\n    },\n    {\n      \"id\": \"LongArms\",\n      \"title\": \"Long Arms\",\n      \"description\": \"Your hands reach 40% further, for grabbing holds and picking things up.\",\n      \"buffs\": { \"addReach\": 0.4 },\n      \"iconFrom\": \"Trinket_Chalk\"\n    },\n    {\n      \"id\": \"MoonBoots\",\n      \"title\": \"Moon Boots\",\n      \"description\": \"Jumps are 20% stronger and gravity is 25% lower, so you jump higher and fall slower.\",\n      \"buffs\": { \"addJump\": 0.2, \"addGravity\": -0.25 },\n      \"iconFrom\": \"Trinket_ClimbingShoes\"\n    }\n  ]\n}\n";

	internal static string FilePath => Path.Combine(Paths.ConfigPath, "isaac.whiteknuckle.moretrinkets.custom.json");

	internal static void EnsureBuilt()
	{
		if ((Object)(object)CL_AssetManager.baseDatabase == (Object)null)
		{
			return;
		}
		if (!built)
		{
			built = true;
			foreach (CustomDef item in LoadDefs())
			{
				try
				{
					Trinket val = Make(item);
					if ((Object)(object)val != (Object)null)
					{
						Customs.Add(val);
					}
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("Custom trinket '" + item?.id + "' failed: " + ex));
				}
			}
			db = ScriptableObject.CreateInstance<WKAssetDatabase>();
			((Object)db).name = "isaac_moretrinkets";
			db.id = "isaac_moretrinkets";
			((Object)db).hideFlags = (HideFlags)61;
			db.trinketAssets.AddRange(Customs);
			Plugin.Log.LogInfo((object)("Built " + Customs.Count + " custom trinket(s): " + string.Join(", ", Customs.Select((Trinket c) => c.title))));
		}
		if ((Object)(object)db != (Object)null)
		{
			CL_AssetManager.AddNewDatabase("isaac_moretrinkets", db);
		}
	}

	private static IEnumerable<CustomDef> LoadDefs()
	{
		try
		{
			if (!File.Exists(FilePath))
			{
				File.WriteAllText(FilePath, "{\n  \"trinkets\": [\n    {\n      \"id\": \"ClimbersKit\",\n      \"title\": \"Climber's Kit\",\n      \"description\": \"Chalk, a Carabiner, Climbing Shoes and a Helmet, all for one slot.\",\n      \"from\": [\"Trinket_Chalk\", \"Trinket_Carabiner\", \"Trinket_ClimbingShoes\", \"Trinket_Helmet\"],\n      \"iconFrom\": \"Trinket_Carabiner\"\n    },\n    {\n      \"id\": \"PackMule\",\n      \"title\": \"Pack Mule\",\n      \"description\": \"Extra Pouch and Larger Pack together, plus two more pouches. Three extra pouches in total.\",\n      \"from\": [\"Trinket_Pouch\", \"Trinket_BagExpander\"],\n      \"extraPouches\": 2,\n      \"iconFrom\": \"Trinket_Pouch\"\n    },\n    {\n      \"id\": \"Scout\",\n      \"title\": \"Scout\",\n      \"description\": \"Head Lamp, The Beta and Calming Buddy together, for one slot.\",\n      \"from\": [\"Trinket_Headlamp\", \"Trinket_Beta\", \"Trinket_CalmingBuddy\"],\n      \"iconFrom\": \"Trinket_Headlamp\"\n    },\n    {\n      \"id\": \"LongArms\",\n      \"title\": \"Long Arms\",\n      \"description\": \"Your hands reach 40% further, for grabbing holds and picking things up.\",\n      \"buffs\": { \"addReach\": 0.4 },\n      \"iconFrom\": \"Trinket_Chalk\"\n    },\n    {\n      \"id\": \"MoonBoots\",\n      \"title\": \"Moon Boots\",\n      \"description\": \"Jumps are 20% stronger and gravity is 25% lower, so you jump higher and fall slower.\",\n      \"buffs\": { \"addJump\": 0.2, \"addGravity\": -0.25 },\n      \"iconFrom\": \"Trinket_ClimbingShoes\"\n    }\n  ]\n}\n", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
				Plugin.Log.LogInfo((object)("Wrote default custom trinket file: " + FilePath));
			}
			CustomFile customFile = JsonConvert.DeserializeObject<CustomFile>(File.ReadAllText(FilePath));
			int valueOrDefault = (customFile?.trinkets?.Length).GetValueOrDefault();
			Plugin.Log.LogInfo((object)("Read " + valueOrDefault + " custom trinket definition(s) from " + Path.GetFileName(FilePath)));
			return customFile?.trinkets ?? new CustomDef[0];
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Could not read " + FilePath + ": " + ex.Message));
			return new CustomDef[0];
		}
	}

	private static Trinket Make(CustomDef def)
	{
		if (def == null || string.IsNullOrWhiteSpace(def.id) || string.IsNullOrWhiteSpace(def.title))
		{
			Plugin.Log.LogWarning((object)"Skipped a custom trinket with no id or title.");
			return null;
		}
		List<Item_Object> list = new List<Item_Object>();
		List<Perk> list2 = new List<Perk>();
		List<string> list3 = new List<string>();
		int num = 0;
		Sprite val = null;
		string[] array = def.from ?? new string[0];
		foreach (string text in array)
		{
			Trinket trinketAsset = CL_AssetManager.GetTrinketAsset(text, "");
			if ((Object)(object)trinketAsset == (Object)null)
			{
				Plugin.Log.LogWarning((object)("Custom trinket '" + def.id + "': source '" + text + "' not found, skipping that part."));
				continue;
			}
			list.AddRange(trinketAsset.itemsToGrant);
			list2.AddRange(trinketAsset.perksToGrant);
			num += trinketAsset.pouchesToGrant;
			list3.Add(trinketAsset.title);
			if ((Object)(object)val == (Object)null)
			{
				val = trinketAsset.icon;
			}
		}
		if (!string.IsNullOrWhiteSpace(def.iconFrom))
		{
			Trinket trinketAsset2 = CL_AssetManager.GetTrinketAsset(def.iconFrom, "");
			if ((Object)(object)trinketAsset2 != (Object)null && (Object)(object)trinketAsset2.icon != (Object)null)
			{
				val = trinketAsset2.icon;
			}
		}
		num += Math.Max(0, def.extraPouches);
		bool flag = def.buffs != null && def.buffs.Count > 0;
		if (list.Count == 0 && list2.Count == 0 && num == 0 && !flag)
		{
			Plugin.Log.LogWarning((object)("Custom trinket '" + def.id + "' grants nothing (no valid sources), not added."));
			return null;
		}
		Trinket val2 = ScriptableObject.CreateInstance<Trinket>();
		((Object)val2).name = "Isaac_Trinket_" + def.id;
		((Object)val2).hideFlags = (HideFlags)61;
		val2.title = def.title;
		val2.description = ((!string.IsNullOrWhiteSpace(def.description)) ? def.description : ("Combines: " + string.Join(", ", list3) + ((def.extraPouches > 0) ? (" and " + def.extraPouches + " extra pouch(es).") : ".")));
		val2.flavorText = def.flavor ?? "";
		val2.isBinding = def.binding;
		val2.cost = Math.Max(1, def.cost);
		val2.scoreMultiplierBonus = def.scoreMultiplierBonus;
		val2.scoreBonus = 0f;
		val2.itemsToGrant = list;
		val2.perksToGrant = list2;
		val2.pouchesToGrant = num;
		val2.progressionUnlock = null;
		val2.comingSoon = false;
		val2.settingBlacklist = new List<string>();
		val2.activateOrder = 0;
		val2.icon = val;
		val2.lockIcon = val;
		if (flag)
		{
			Buffs[((Object)val2).name] = new Dictionary<string, float>(def.buffs);
		}
		return val2;
	}
}
[HarmonyPatch(typeof(Trinket), "Activate")]
internal static class ApplyCustomBuffs
{
	private static void Postfix(Trinket __instance)
	{
		//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_0047: 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)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Expected O, but got Unknown
		try
		{
			if ((Object)(object)__instance == (Object)null || !CustomTrinkets.Buffs.TryGetValue(((Object)__instance).name, out var value))
			{
				return;
			}
			ENT_Player player = ENT_Player.GetPlayer();
			if ((Object)(object)player == (Object)null)
			{
				return;
			}
			BuffContainer val = new BuffContainer
			{
				id = ((Object)__instance).name,
				desc = __instance.title,
				buffs = new List<Buff>(),
				loseOverTime = false,
				loseRate = 0f,
				buffTime = 1f,
				multiplier = 1f
			};
			foreach (KeyValuePair<string, float> item in value)
			{
				val.buffs.Add(new Buff
				{
					id = item.Key,
					maxAmount = item.Value,
					amount = item.Value
				});
			}
			((GameEntity)player).AddNewBuff(val);
			Plugin.Log.LogInfo((object)("Applied buffs for '" + __instance.title + "': " + string.Join(", ", value.Select((KeyValuePair<string, float> kv) => kv.Key + "=" + kv.Value))));
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Applying custom trinket buffs failed: " + ex));
		}
	}
}
[HarmonyPatch(typeof(CL_AssetManager), "InitializeAssetManager")]
internal static class RegisterOnAssetInit
{
	private static void Postfix()
	{
		try
		{
			CustomTrinkets.EnsureBuilt();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Registering custom trinkets failed: " + ex));
		}
	}
}
[HarmonyPatch(typeof(UI_TrinketPicker), "ReloadTrinkets")]
internal static class AddToPicker
{
	private static void Prefix(UI_TrinketPicker __instance)
	{
		try
		{
			CustomTrinkets.EnsureBuilt();
			TrinketList val = Traverse.Create((object)__instance).Field("currentGamemode").GetValue<M_Gamemode>()?.availableTrinkets;
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			if (val.trinkets == null)
			{
				val.trinkets = new List<Trinket>();
			}
			if (val.bindings == null)
			{
				val.bindings = new List<Trinket>();
			}
			foreach (Trinket custom in CustomTrinkets.Customs)
			{
				List<Trinket> list = (custom.isBinding ? val.bindings : val.trinkets);
				if (!list.Contains(custom))
				{
					list.Add(custom);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Adding custom trinkets to the picker failed: " + ex));
		}
	}
}
[BepInPlugin("isaac.whiteknuckle.moretrinkets", "More Trinkets", "1.1.0")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "isaac.whiteknuckle.moretrinkets";

	internal static ManualLogSource Log;

	internal static ConfigEntry<int> ExtraBudget;

	internal static ConfigEntry<bool> UnlockAll;

	internal static ConfigEntry<bool> LogCatalog;

	private void Awake()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		ExtraBudget = ((BaseUnityPlugin)this).Config.Bind<int>("Trinkets", "ExtraBudget", 4, new ConfigDescription("Extra trinket slots on top of the game's 1 (plus 1 per binding you take). 4 = five trinkets with no bindings.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 30), Array.Empty<object>()));
		UnlockAll = ((BaseUnityPlugin)this).Config.Bind<bool>("Trinkets", "UnlockAll", false, "Make locked trinkets selectable (off by default so you earn them). Trinkets marked 'coming soon' by the game stay locked.");
		LogCatalog = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogCatalog", true, "Write every trinket and binding name, cost and lock state to LogOutput.log the first time the picker opens.");
		new Harmony("isaac.whiteknuckle.moretrinkets").PatchAll();
		Log.LogInfo((object)"More Trinkets loaded");
	}
}
[HarmonyPatch(typeof(Trinket), "IsUnlocked")]
internal static class UnlockPatch
{
	private static void Postfix(Trinket __instance, ref bool __result)
	{
		if (Plugin.UnlockAll.Value && !__instance.comingSoon)
		{
			__result = true;
		}
	}
}
[HarmonyPatch(typeof(UI_TrinketPicker), "UpdateTrinketActivation")]
internal static class BudgetPatch
{
	private static readonly MethodInfo UpdatePips = AccessTools.Method(typeof(UI_TrinketPicker), "UpdatePips", (Type[])null, (Type[])null);

	private static void Postfix(UI_TrinketPicker __instance)
	{
		try
		{
			int value = Plugin.ExtraBudget.Value;
			if (value <= 0)
			{
				return;
			}
			int num = 0;
			int num2 = 1;
			foreach (Trinket selectedTrinket in __instance.selectedTrinkets)
			{
				if (selectedTrinket.isBinding)
				{
					num2++;
				}
				else
				{
					num++;
				}
			}
			num2 += value;
			bool flag = num <= num2;
			__instance.costText.text = (flag ? "" : "<color=\"red\">Too expensive!");
			((Selectable)__instance.playButton).interactable = flag;
			UpdatePips?.Invoke(__instance, new object[2] { num2, num });
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Budget patch failed: " + ex));
		}
	}
}
[HarmonyPatch(typeof(UI_TrinketPicker), "ReloadTrinkets")]
internal static class CatalogLogPatch
{
	private static bool logged;

	private static void Postfix(UI_TrinketPicker __instance)
	{
		if (logged || !Plugin.LogCatalog.Value || __instance.trinketIcons == null || __instance.trinketIcons.Count == 0)
		{
			return;
		}
		logged = true;
		Plugin.Log.LogInfo((object)("--- Trinket catalog (" + __instance.trinketIcons.Count + ") ---"));
		foreach (UI_TrinketPicker_Icon item in __instance.trinketIcons.Where((UI_TrinketPicker_Icon i) => (Object)(object)i != (Object)null && (Object)(object)i.trinket != (Object)null))
		{
			Trinket trinket = item.trinket;
			Plugin.Log.LogInfo((object)((trinket.isBinding ? "[binding] " : "[trinket] ") + trinket.title + " | id=" + ((Object)trinket).name + " | cost=" + trinket.cost + " | comingSoon=" + trinket.comingSoon + " | grants: items=" + trinket.itemsToGrant.Count + " perks=" + trinket.perksToGrant.Count + " pouches=" + trinket.pouchesToGrant));
		}
	}
}