Decompiled source of CoreAssetsPlugin CCM v1.0.1

CoreAssets_CCM.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Bounce.Singletons;
using HarmonyLib;
using ModdingTales;
using TaleSpire.ContentManagement;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CoreAssets_CCM")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nth Dimension")]
[assembly: AssemblyProduct("CoreAssets_CCM")]
[assembly: AssemblyCopyright("Copyright ©  2025")]
[assembly: AssemblyTrademark("CoreAssets_CCM")]
[assembly: ComVisible(false)]
[assembly: Guid("c303405d-e66c-4316-9cdb-4e3ca15c6360")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.1.0")]
namespace LordAshes;

[BepInPlugin("org.lordashes.plugins.coreassets.ccm", "Core Assets Plugin", "1.0.1.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class CoreAssetsPlugin : BaseUnityPlugin
{
	[HarmonyPatch]
	public class Patch_DbGroupImpl_Add
	{
		private static MethodBase TargetMethod()
		{
			Type type = AccessTools.TypeByName("TaleSpire.ContentManagement.AssetDb+DbGroupImpl");
			return AccessTools.Method(type, "Add", (Type[])null, (Type[])null);
		}

		private static void Prefix(object dbEntry)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			try
			{
				Provider._db.Add((DbEntry)dbEntry);
			}
			catch (Exception arg)
			{
				LoggingPlugin.LogWarning($"[Harmony Patch] Error accessing DbEntry properties: {arg}");
			}
		}
	}

	public static class Provider
	{
		public static int _counter = 5;

		public static List<DbEntry> _db = new List<DbEntry>();

		private static Func<Dictionary<string, AssetInfo>, IEnumerator> _callback = null;

		public static IEnumerator GetNewAssets(ReadOnlyDictionary<string, AssetInfo> existingAssets, Func<Dictionary<string, AssetInfo>, IEnumerator> callback)
		{
			_self.notification = "Registering... [Provider: COREASSETS]";
			_callback = callback;
			yield return (object)new WaitForEndOfFrame();
			((MonoBehaviour)_self).StartCoroutine(SendCollectedAssetList(existingAssets));
		}

		private static IEnumerator SendCollectedAssetList(ReadOnlyDictionary<string, AssetInfo> existingAssets)
		{
			LoggingPlugin.LogInfo("Starting Countdown Loop (Counter Is " + _counter + ")");
			while (_counter > 0)
			{
				LoggingPlugin.LogInfo("Countdown To Send Asset Info Is " + _counter);
				yield return (object)new WaitForSeconds(1f);
				_counter--;
			}
			LoggingPlugin.LogInfo("Packing Asset Results");
			_self.notification = null;
			Dictionary<string, AssetInfo> assets = new Dictionary<string, AssetInfo>();
			foreach (DbEntry entry in _db)
			{
				if ((int)entry.Kind != 4 && (int)entry.Kind != 2)
				{
					continue;
				}
				LoggingPlugin.LogInfo("Adding Asset: Group='" + ToSpaceBasedCamelCase(entry.Group.Name) + "' Name='" + ToSpaceBasedCamelCase(entry.Name) + "'");
				string groupName = entry.Group.Name;
				if (groupName.ToUpper() == "COMMUNITY")
				{
					groupName = "[MOD.IO]";
				}
				if (groupName.ToUpper() == "LOCAL")
				{
					groupName = "[LOCAL]";
				}
				string id = GetId(entry);
				if (!existingAssets.ContainsKey(id))
				{
					AssetInfo val = new AssetInfo
					{
						provider = "COREASSETS"
					};
					InternedPackId dataPackId = entry.DataPackId;
					val.pack = ((object)(InternedPackId)(ref dataPackId)).ToString();
					val.prefab = id;
					val.filename = "Core";
					DbContentKind kind = entry.Kind;
					val.kind = ((object)(DbContentKind)(ref kind)).ToString();
					kind = entry.Kind;
					val.category = ((object)(DbContentKind)(ref kind)).ToString();
					val.header = "CORE";
					val.name = ToSpaceBasedCamelCase(entry.Name);
					val.description = entry.Description;
					val.author = "BouncyRock";
					val.groupName = ToSpaceBasedCamelCase(groupName);
					dataPackId = entry.DataPackId;
					string? text = ((object)(SourceLocalPackId)(ref dataPackId.SourceLocalPackId)).ToString();
					dataPackId = entry.DataPackId;
					val.comment = text + "," + ((object)(InternedPackSource)(ref dataPackId.PackSource)).ToString();
					val.tags = string.Join(",", entry.Tags);
					val.hasAnimations = false;
					val.hasAudio = false;
					val.hasBlendshapes = false;
					assets.Add(id, val);
					LoggingPlugin.LogInfo("Writing Portrait File '" + CommonCustomsMenuPlugin.GetCacheFolder() + "Portrait." + id + ".png'");
					try
					{
						File.WriteAllBytes(CommonCustomsMenuPlugin.GetCacheFolder() + "Portrait." + id + ".png", _self.defaultIcon);
					}
					catch (Exception ex2)
					{
						Exception ex = ex2;
						LoggingPlugin.LogInfo("Exception: " + ex.Message);
					}
				}
			}
			LoggingPlugin.LogInfo("Posting Asset Results");
			_self.notification = null;
			((MonoBehaviour)_self).StartCoroutine(_callback((from kvp in assets
				orderby kvp.Value.header, kvp.Value.category, kvp.Value.name
				select kvp).ToDictionary((KeyValuePair<string, AssetInfo> kvp) => kvp.Key, (KeyValuePair<string, AssetInfo> kvp) => kvp.Value)));
		}

		public static void SpawnNewAsset(AssetInfo info)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			LoggingPlugin.LogDebug("Spawning " + ((object)info)?.ToString() + " Based On Stored Guid " + info.prefab);
			CommonCustomsMenuPlugin._self.Close();
			try
			{
				DbEntry val = _db.Where((DbEntry entry) => GetId(entry) == info.prefab).First();
				CreatureDataV3 val2 = new CreatureDataV3(ref val.DataAddress);
				CreatureSpawnerBoardTool.SwitchCreatureTool(ref val2, false, false);
			}
			catch (Exception ex)
			{
				LoggingPlugin.LogWarning("Unable to find " + info.prefab + " in core assets database");
				LoggingPlugin.LogWarning("Details: " + ex.Message);
			}
		}

		public static string GetId(DbEntry entry)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			InternedPackId dataPackId = entry.DataPackId;
			return (((object)(InternedPackId)(ref dataPackId)).ToString() + ":" + ((object)(InternedContentAddress)(ref entry.DataAddress)).ToString()).Replace(":", "");
		}

		public static string ToSpaceBasedCamelCase(string raw)
		{
			raw = ((raw == null || raw.Trim() == "") ? "content" : raw.ToLower());
			string text = raw.Substring(0, 1).ToUpper();
			if (raw.Length > 1)
			{
				for (int i = 1; i < raw.Length; i++)
				{
					text = ((!(raw.Substring(i - 1, 1) == " ")) ? (text + raw.Substring(i, 1)) : (text + raw.Substring(i, 1).ToUpper()));
				}
			}
			return text;
		}
	}

	public static class Utility
	{
		public static bool isBoardLoaded()
		{
			return SimpleSingletonBehaviour<CameraController>.HasInstance && SingletonStateMBehaviour<BoardSessionManager, State<BoardSessionManager>>.HasInstance && !BoardSessionManager.IsLoading;
		}

		public static float ParseFloat(string value)
		{
			return float.Parse(value, CultureInfo.InvariantCulture);
		}

		public static GameObject FindInHierarchy(GameObject start, string seekName)
		{
			List<GameObject> results = new List<GameObject>();
			bool done = false;
			Traverse(start.transform, seekName, null, single: true, ref results, ref done);
			return (results.Count > 0) ? results.ElementAt(0) : null;
		}

		public static GameObject FindInHierarchyViaPartialName(GameObject start, string seekName)
		{
			List<GameObject> results = new List<GameObject>();
			bool done = false;
			Traverse(start.transform, seekName, null, single: true, ref results, ref done, partial: true);
			return (results.Count > 0) ? results.ElementAt(0) : null;
		}

		public static GameObject[] FindAllInHierarchy(GameObject start, string seekName)
		{
			List<GameObject> results = new List<GameObject>();
			bool done = false;
			Traverse(start.transform, seekName, null, single: false, ref results, ref done);
			return results.ToArray();
		}

		public static GameObject[] FindAllInHierarchyViaPartialName(GameObject start, string seekName)
		{
			List<GameObject> results = new List<GameObject>();
			bool done = false;
			Traverse(start.transform, seekName, null, single: false, ref results, ref done, partial: true);
			return results.ToArray();
		}

		public static GameObject FindWithComponentInHierarchy(GameObject start, string seekType)
		{
			List<GameObject> results = new List<GameObject>();
			bool done = false;
			Traverse(start.transform, null, seekType, single: true, ref results, ref done);
			return (results.Count > 0) ? results.ElementAt(0) : null;
		}

		public static GameObject[] FindAllWithComponentInHierarchy<T>(GameObject start, string seekType)
		{
			List<GameObject> results = new List<GameObject>();
			bool done = false;
			Traverse(start.transform, null, seekType, single: false, ref results, ref done);
			return results.ToArray();
		}

		public static void Traverse(Transform root, string seekName, string seekType, bool single, ref List<GameObject> results, ref bool done, bool partial = false)
		{
			try
			{
				if ((seekName == null || seekName == ((Object)((Component)root).gameObject).name || (partial && ((Object)((Component)root).gameObject).name.Contains(seekName))) && (seekType == null || (Object)(object)((Component)root).GetComponent(seekType) != (Object)null))
				{
					LoggingPlugin.LogTrace("Matched '" + ((Object)((Component)root).gameObject).name + "'");
					results.Add(((Component)root).gameObject);
					if (single)
					{
						done = true;
						return;
					}
				}
				foreach (Transform item in ExtensionMethods.Children(root))
				{
					if (!done)
					{
						Traverse(item, seekName, seekType, single, ref results, ref done, partial);
					}
				}
			}
			catch
			{
			}
		}

		public static object LookUp(in Dictionary<string, object> dictionary, string key)
		{
			foreach (KeyValuePair<string, object> item in dictionary)
			{
				if (item.Key.ToUpper() == key.ToUpper())
				{
					return item.Value;
				}
			}
			return null;
		}

		public static void PostOnMainPage(BaseUnityPlugin plugin)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			string text = "Lord Ashes" + ("Lord Ashes".ToUpper().EndsWith("S") ? "'" : "'s");
			ModdingUtils.Initialize(plugin, new ManualLogSource("Core Assets Plugin"), text, false);
		}
	}

	public const string Name = "Core Assets Plugin";

	public const string Guid = "org.lordashes.plugins.coreassets.ccm";

	public const string Version = "1.0.1.0";

	public const string Author = "Lord Ashes";

	public static CoreAssetsPlugin _self;

	private string notification = null;

	public byte[] defaultIcon = ImageConversion.EncodeToPNG(Image.LoadTexture("org.lordashes.plugins.coreassets.ccm.Default.png", (CacheType)999));

	public string cacheFolder = CommonCustomsMenuPlugin.GetCacheFolder();

	private void Awake()
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: 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_005c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Invalid comparison between Unknown and I4
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Expected O, but got Unknown
		_self = this;
		LoggingPlugin.SetLogLevel(((BaseUnityPlugin)this).Config.Bind<DiagnosticLevel>("Settings", "Diagnostic Level", (DiagnosticLevel)3, (ConfigDescription)null).Value);
		string? assemblyQualifiedName = ((object)this).GetType().AssemblyQualifiedName;
		DiagnosticLevel logLevel = LoggingPlugin.GetLogLevel();
		Debug.Log((object)(assemblyQualifiedName + ": Active. (Diagnostic Mode = " + ((object)(DiagnosticLevel)(ref logLevel)).ToString() + ")"));
		if ((int)LoggingPlugin.GetLogLevel() >= 4)
		{
			((MonoBehaviour)this).StartCoroutine(WarnAboutLogLevel());
		}
		CommonCustomsMenuPlugin.RegisterProvider("COREASSETS", "Core Talespire minis", (Func<ReadOnlyDictionary<string, AssetInfo>, Func<Dictionary<string, AssetInfo>, IEnumerator>, IEnumerator>)Provider.GetNewAssets, (Action<AssetInfo>)Provider.SpawnNewAsset);
		Harmony val = new Harmony("org.lordashes.plugins.coreassets.ccm");
		val.PatchAll();
		Utility.PostOnMainPage((BaseUnityPlugin)(object)this);
	}

	private void OnGUI()
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		if (notification != null)
		{
			GUI.Label(new Rect(1100f, 1030f, 1900f, 30f), notification);
		}
	}

	private IEnumerator WarnAboutLogLevel()
	{
		while (true)
		{
			try
			{
				DiagnosticLevel logLevel = LoggingPlugin.GetLogLevel();
				SystemMessage.DisplayInfoText("Core Assets Plugin: Using '" + ((object)(DiagnosticLevel)(ref logLevel)).ToString() + "' diagnostics.\r\nUse 'Info' for better performance", 10f, 0f);
				SystemMessage.DisplayInfoText("Core Assets Plugin: Use 'Debug' or 'Trace' for\r\ntroubleshooting only.", 10f, 0f);
				break;
			}
			catch
			{
			}
			yield return (object)new WaitForSeconds(1f);
		}
	}
}