A stable modding interface between Techblox and mods https://mod.exmods.org/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

207 lines
8.9KB

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Reflection;
  6. using HarmonyLib;
  7. using DataLoader;
  8. using RobocraftX.Rendering;
  9. using RobocraftX.Schedulers;
  10. using Svelto.ECS;
  11. using Svelto.ECS.Experimental;
  12. using Svelto.Tasks;
  13. using Svelto.Tasks.ExtraLean;
  14. using UnityEngine;
  15. using UnityEngine.AddressableAssets;
  16. using Material = UnityEngine.Material;
  17. using GamecraftModdingAPI.Utility;
  18. namespace GamecraftModdingAPI.Blocks
  19. {
  20. /// <summary>
  21. /// Experimental support for adding custom blocks to the game.
  22. /// </summary>
  23. public class CustomBlock : Block
  24. {
  25. private static ushort nextID = 500;
  26. /// <summary>
  27. /// Key: Prefab path
  28. /// </summary>
  29. private static readonly Dictionary<string, Type> CustomBlocks = new Dictionary<string, Type>();
  30. //private static readonly CustomBlockEngine Engine = new CustomBlockEngine();
  31. private static readonly List<(ushort id, Action<CubeListData> action)> BlockChangeActions =
  32. new List<(ushort, Action<CubeListData>)>();
  33. private static bool _canRegister = true;
  34. /// <summary>
  35. /// Register a custom block type. Call it as soon as possible (in OnApplicationStart()).<br />
  36. /// You need a Unity project with Addressables and Havok installed and need a prefab added as an addressable asset.
  37. /// Build the addressables and the project and copy the catalog.json from StreamingAssets, you'll need to reference this file.
  38. /// Also copy the asset files from the subfolder to the same path in the game.
  39. /// </summary>
  40. /// <typeparam name="T">The custom block type</typeparam>
  41. public static void RegisterCustomBlock<T>() where T : CustomBlock
  42. {
  43. if (!_canRegister)
  44. throw new InvalidOperationException(
  45. "It's too late to register custom blocks. Register it before the game starts loading.");
  46. var type = typeof(T);
  47. var attr = type.GetCustomAttribute<CustomBlockAttribute>();
  48. if (attr == null)
  49. throw new ArgumentException("The custom block type is missing the CustomBlock annotation");
  50. string typeName = type.FullName ??
  51. throw new ArgumentException("The given block type doesn't have a concrete full name.");
  52. if (!File.Exists(attr.Catalog))
  53. throw new FileNotFoundException("The specified catalog cannot be found for " + typeName);
  54. CustomBlocks.Add(attr.AssetPath, type);
  55. Logging.MetaDebugLog("Registered custom block type " + typeName);
  56. }
  57. /// <summary>
  58. /// A low-level method for changing any property of an existing block. Use with caution.
  59. /// </summary>
  60. /// <param name="id">The block ID</param>
  61. /// <param name="modifier">An action that modifies a property of the block</param>
  62. public static void ChangeExistingBlock(ushort id, Action<CubeListData> modifier)
  63. {
  64. BlockChangeActions.Add((id, modifier));
  65. }
  66. public CustomBlock(EGID id) : base(id)
  67. {
  68. /*if (id.groupID != Group)
  69. throw new BlockTypeException("The block is not a custom block! It has a group of " + id.groupID);*/
  70. }
  71. public CustomBlock(uint id) : base(id)
  72. {
  73. }
  74. //public static ExclusiveGroup Group { get; } = new ExclusiveGroup("Custom block");
  75. [HarmonyPatch]
  76. public static class MaterialCopyPatch
  77. {
  78. private static Material[] materials;
  79. public static void Prefix(List<PrefabData> prefabData, IList<GameObject> prefabs)
  80. {
  81. for (var index = 0; index < prefabs.Count; index++)
  82. {
  83. if (prefabData[index].prefabName == "ConsoleBlock")
  84. materials = prefabs[index].GetComponentsInChildren<MeshRenderer>()[0].sharedMaterials;
  85. }
  86. for (var index = 0; index < prefabs.Count; index++)
  87. {
  88. if (CustomBlocks.ContainsKey(prefabData[index].prefabName)) //This is a custom block
  89. prefabs[index].GetComponentsInChildren<MeshRenderer>()[0].sharedMaterials = materials;
  90. }
  91. }
  92. public static MethodBase TargetMethod()
  93. { //General block registration
  94. return AccessTools.Method("RobocraftX.Rendering.ECSGPUIResourceManager:InitPreRegisteredPrefabs");
  95. }
  96. }
  97. [HarmonyPatch]
  98. public static class CubeRegistrationPatch
  99. {
  100. public static void Prefix(IDataDB dataDB)
  101. {
  102. //var abd = dataDB.GetValue<CubeListData>((int) BlockIDs.AluminiumCube);
  103. foreach (var (key, type) in CustomBlocks)
  104. {
  105. var attr = type.GetCustomAttribute<CustomBlockAttribute>();
  106. var cld = new CubeListData
  107. { //"Assets/Prefabs/Cube.prefab" - "CTR_CommandBlock" - "strConsoleBlock"
  108. cubeType = attr.Type,
  109. //cubeCategory = (CubeCategory) 1000,
  110. cubeCategory = attr.Category,
  111. inventoryCategory = attr.InventoryCategory,
  112. ID = nextID++,
  113. Path = attr.AssetPath, //Index out of range exception: Asset failed to load (wrong path)
  114. SpriteName = attr.SpriteName,
  115. CubeNameKey = attr.NameKey,
  116. CubeDescriptionKey = attr.DescKey,
  117. SelectableFaces = new[] {0, 1, 2, 3, 4, 5},
  118. GridScale = new[] {5, 5, 5},
  119. Mass = attr.Mass,
  120. Material = attr.Material,
  121. scalingPermission = attr.ScalingPermission,
  122. SortIndex = attr.SortIndex,
  123. DefaultColour = attr.DefaultColor.Index,
  124. Volume = attr.Volume,
  125. EdgeConnectingFaces = new[] {0, 1, 2, 3, 4, 5},
  126. PointDataVolumeMultiplier = 1f
  127. };
  128. dataDB.GetValues<CubeListData>().Add(cld.ID.ToString(), cld); //The registration needs to happen after the ID has been set
  129. dataDB.GetFasterValues<CubeListData>().Add(cld.ID, cld); //So can't use the builtin method to create a CubeListData
  130. //Engine.RegisterBlock((ushort) cld.ID, key); - TODO
  131. }
  132. foreach (var (id, action) in BlockChangeActions)
  133. action(dataDB.GetValue<CubeListData>(id));
  134. _canRegister = false;
  135. }
  136. public static MethodBase TargetMethod()
  137. {
  138. return AccessTools.Method("RobocraftX.CR.MainGame.MainGameCompositionRoot:Init");
  139. }
  140. }
  141. /*[HarmonyPatch] - The block has no collision even in simulation if using a custom category
  142. private static class FactorySetupPatch
  143. {
  144. public static void Prefix(BlockEntityFactory __instance)
  145. {
  146. var builders = (Dictionary<CubeCategory, IBlockBuilder>)
  147. AccessTools.Field(__instance.GetType(), "_blockBuilders").GetValue(__instance);
  148. builders.Add((CubeCategory) 1000, new BlockBuilder<StandardBlockEntityDescriptor>(Group));
  149. }
  150. public static MethodBase TargetMethod()
  151. {
  152. return AccessTools.Method(typeof(BlockEntityFactory), "ParseDataDB");
  153. }
  154. }*/
  155. private static IEnumerator Prepare()
  156. { //Should be pretty quick
  157. foreach (var type in CustomBlocks.Values)
  158. {
  159. var attr = type.GetCustomAttribute<CustomBlockAttribute>();
  160. Logging.Log("Loading custom block catalog " + attr.Catalog);
  161. var res = Addressables.LoadContentCatalogAsync(attr.Catalog);
  162. while (!res.IsDone) yield return Yield.It;
  163. Logging.Log("Loaded custom block catalog: " + res.Result.LocatorId);
  164. Addressables.AddResourceLocator(res.Result);
  165. }
  166. }
  167. internal new static void Init()
  168. {
  169. Prepare().RunOn(ExtraLean.UIScheduler);
  170. //GameEngineManager.AddGameEngine(Engine); - TODO: Fix serialization and implement block ID update
  171. }
  172. /*internal static void OnBlockFactoryObtained(BlockEntityFactory factory)
  173. {
  174. var builders = (Dictionary<CubeCategory, IBlockBuilder>)
  175. AccessTools.Field(factory.GetType(), "_blockBuilders").GetValue(factory);
  176. builders.Add((CubeCategory) 1000, new BlockBuilder<StandardBlockEntityDescriptor>(Group));
  177. }*/
  178. internal struct DataStruct : IEntityComponent
  179. {
  180. public ECSString Name;
  181. public ushort ID;
  182. }
  183. }
  184. }