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.

CustomBlock.cs 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using DataLoader;
  7. using GPUInstancer;
  8. using HarmonyLib;
  9. using RobocraftX.Blocks;
  10. using RobocraftX.Common;
  11. using RobocraftX.Rendering;
  12. using Svelto.DataStructures;
  13. using Svelto.Tasks;
  14. using Unity.Entities;
  15. using Unity.Entities.Conversion;
  16. using Unity.Physics;
  17. using UnityEngine;
  18. using UnityEngine.AddressableAssets;
  19. using BoxCollider = UnityEngine.BoxCollider;
  20. using Material = UnityEngine.Material;
  21. using Object = UnityEngine.Object;
  22. namespace GamecraftModdingAPI.Blocks
  23. {
  24. public class CustomBlock
  25. {
  26. private static ushort nextID = 500;
  27. public static void RegisterCustomBlock(string path)
  28. {
  29. var prefabData = new List<PrefabData>();
  30. //category ID:
  31. //0 - regular
  32. //1 - joint
  33. //2 - controller
  34. uint prefabId = PrefabsID.FetchNewPrefabID(PrefabsID.GenerateDBID(0, nextID++));
  35. prefabData.Add(new PrefabData()
  36. {
  37. prefabName = path,
  38. prefabId = prefabId
  39. });
  40. var loadTask = Addressables.LoadAssetAsync<GameObject>(path);
  41. AccessTools.Method("RobocraftX.Common.ECSGPUIResourceManager:RegisterPrefab")
  42. .Invoke(ECSGPUIResourceManager.Instance, new object[] {prefabId, loadTask.Result, 1});
  43. }
  44. [HarmonyPatch]
  45. public static class Patch
  46. {
  47. /*public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
  48. {
  49. var list = new List<CodeInstruction>(instructions);
  50. try
  51. {
  52. *int index = -1;
  53. CodeInstruction loadTask = null;
  54. for (var i = 0; i < list.Count - 1; i++)
  55. {
  56. if (list[i].opcode == OpCodes.Ldfld
  57. && ((string) list[i].operand).Contains("renderingWorld")
  58. && list[i + 1].opcode == OpCodes.Brfalse_S)
  59. index = i - 1; //It loads 'this' first
  60. if (list[i].opcode == OpCodes.Ldflda
  61. && ((string) list[i].operand).Contains("loadTask"))
  62. loadTask = new CodeInstruction(list[i]);
  63. }*
  64. var array = new[]
  65. {
  66. //Set Yield.It to be returned (current)
  67. new CodeInstruction(OpCodes.Ldarg_0), // this
  68. new CodeInstruction(OpCodes.Ldsfld,
  69. typeof(Yield).GetField("It", BindingFlags.Public | BindingFlags.Static)),
  70. new CodeInstruction(OpCodes.Stfld, "object RobocraftX.Common.ECSResourceManagerUtility/'<RegisterPrefabs>d__0'::'<>2__current'"),
  71. //Set which yield return we're at (state)
  72. new CodeInstruction(OpCodes.Ldarg_0), // this
  73. new CodeInstruction(OpCodes.Ldc_I4_1),
  74. //new CodeInstruction(OpCodes.Call, ((Action<StringBuffer>)AddInfo).Method)
  75. };
  76. list.InsertRange(index, array);
  77. *
  78. IL_00ad: ldarg.0 // this
  79. IL_00ae: ldsfld class [Svelto.Tasks]Svelto.Tasks.Yield [Svelto.Tasks]Svelto.Tasks.Yield::It
  80. IL_00b3: stfld object RobocraftX.Common.ECSResourceManagerUtility/'<RegisterPrefabs>d__0'::'<>2__current'
  81. IL_0072: ldarg.0 // this
  82. IL_0073: ldnull
  83. IL_0074: stfld object RobocraftX.Common.ECSResourceManagerUtility/'<RegisterPrefabs>d__0'::'<>2__current'
  84. IL_0079: ldarg.0 // this
  85. IL_007a: ldc.i4.2
  86. IL_007b: stfld object RobocraftX.Common.ECSResourceManagerUtility/'<RegisterPrefabs>d__0'::'<>1__state'
  87. IL_0080: ldc.i4.1
  88. IL_0081: ret
  89. *
  90. yield break;
  91. }
  92. catch (Exception e)
  93. {
  94. Logging.LogWarning("Failed to inject AddInfo method for the debug display!\n" + e);
  95. }
  96. }*/
  97. private static Material[] materials;
  98. public static void Prefix(List<PrefabData> prefabData, IList<GameObject> prefabs)
  99. {
  100. /*foreach (var block in blocks.Values.Cast<CubeListData>())
  101. {
  102. Console.WriteLine("Block info: " + block);
  103. }*/
  104. /*var res = Addressables.LoadContentCatalogAsync("customCatalog.json");
  105. while (!res.IsDone) yield return Yield.It;*/
  106. for (int i = 0; i < prefabData.Count; i++)
  107. {
  108. var gameObject = prefabs[i];
  109. switch (gameObject.name)
  110. {
  111. case "Cube":
  112. gameObject.GetComponentsInChildren<MeshRenderer>()[0].sharedMaterials = materials;
  113. break;
  114. case "CTR_CommandBlock":
  115. materials = gameObject.GetComponentsInChildren<MeshRenderer>()[0].sharedMaterials;
  116. break;
  117. }
  118. }
  119. }
  120. public static MethodBase TargetMethod()
  121. { //General block registration
  122. //return AccessTools.Method("RobocraftX.Blocks.BlocksCompositionRoot:RegisterPartPrefabs");
  123. return AccessTools.Method("RobocraftX.Rendering.ECSGPUIResourceManager:InitPreRegisteredPrefabs");
  124. }
  125. }
  126. /*[HarmonyPatch]
  127. public static class RendererPatch
  128. {
  129. private static Material[] materials;
  130. public static void Prefix(uint prefabID, GameObject gameObject)
  131. {
  132. Console.WriteLine("ID: " + prefabID + " - Name: " + gameObject.name);
  133. if (gameObject.name == "Cube")
  134. {
  135. //Console.WriteLine("Length: " + gameObject.GetComponentsInChildren<MeshRenderer>().Length);
  136. if (materials != null)
  137. gameObject.GetComponentsInChildren<MeshRenderer>()[0].sharedMaterials = materials;
  138. /*ECSGPUIResourceManager.Instance.RegisterGhostsPrefabsAtRuntime(
  139. new[] {new PrefabData {prefabId = prefabID, prefabName = "Assets/Prefabs/Cube.prefab"}},
  140. new List<GameObject> {gameObject});#1#
  141. GameObject go = Object.Instantiate(gameObject);
  142. go.SetActive(false);
  143. AccessTools.Method("RobocraftX.Rendering.ECSGPUIResourceManager:RegisterNewPrefabAtRuntime")
  144. .Invoke(ECSGPUIResourceManager.Instance,
  145. new object[] {(uint) ((int) prefabID * 2 + 1), gameObject, true});
  146. //ECSGPUIResourceManager.Instance.RegisterNewPrefabAtRuntime((uint) ((int)prefabID * 2 + 1), gameObject, true); //.isOcclusionCulling = false;
  147. UnityEngine.Object.Destroy(gameObject);
  148. GPUInstancerAPI.AddInstancesToPrefabPrototypeAtRuntime(ECSGPUIResourceManager.Instance.prefabManager,
  149. gameObject.GetComponent<GPUInstancerPrefab>().prefabPrototype, new[] {gameObject});
  150. Console.WriteLine("Registered prefab to instancer");
  151. /*var register = AccessTools.Method("RobocraftX.Common.ECSPhysicResourceManager:RegisterPrefab",
  152. new[] {typeof(uint), typeof(GameObject), typeof(World), typeof(BlobAssetStore)});
  153. register.Invoke(ECSPhysicResourceManager.Instance,
  154. new object[] {prefabID, gameObject, MGPatch.data.Item1, MGPatch.data.Item2});#1#
  155. /*Console.WriteLine(
  156. "Entity: " + ECSPhysicResourceManager.Instance.GetUECSPhysicEntityPrefab(prefabID));
  157. Console.WriteLine("Prefab ID: " + PrefabsID.DBIDMAP[500]);
  158. PhysicsCollider componentData = MGPatch.data.Item1.EntityManager.GetComponentData<PhysicsCollider>(ECSPhysicResourceManager.Instance.GetUECSPhysicEntityPrefab(prefabID));
  159. Console.WriteLine("Collider valid: " + componentData.IsValid);
  160. unsafe
  161. {
  162. Console.WriteLine("Collider type: " + componentData.ColliderPtr->Type);
  163. CollisionFilter filter = componentData.Value.Value.Filter;
  164. Console.WriteLine("Filter not empty: " + !filter.IsEmpty);
  165. }#1#
  166. //MGPatch.data.Item1.EntityManager.GetComponentData<>()
  167. gameObject.AddComponent<BoxCollider>();
  168. gameObject.AddComponent<Transform>();
  169. Console.WriteLine("Registered prefab to physics");
  170. ECSGPUIResourceManager.Instance.RegisterGhostsPrefabsAtRuntime();
  171. }
  172. else if (gameObject.name == "CTR_CommandBlock")
  173. materials = gameObject.GetComponentsInChildren<MeshRenderer>()[0].sharedMaterials;
  174. }
  175. public static MethodBase TargetMethod()
  176. {RobocraftX.Common.ECSGPUIResourceManager.RegisterPrefab
  177. return AccessTools.Method("RobocraftX.Common.ECSGPUIResourceManager:RegisterPrefab",
  178. new[] {typeof(uint), typeof(GameObject)});
  179. }
  180. }*/
  181. [HarmonyPatch]
  182. public static class RMPatch
  183. {
  184. public static void Prefix(World physicsWorld,
  185. GameObjectConversionSystem getExistingSystem,
  186. FasterList<GameObject> gos,
  187. List<PrefabData> prefabData)
  188. {
  189. Console.WriteLine("First game object data:\n" + gos[0].GetComponents<Component>()
  190. .Select(c => c + " - " + c.name + " " + c.GetType())
  191. .Aggregate((a, b) => a + "\n" + b));
  192. for (var index = 0; index < prefabData.Count; index++)
  193. {
  194. var data = prefabData[index];
  195. if (!data.prefabName.EndsWith("Cube.prefab")) continue;
  196. //getExistingSystem.DeclareLinkedEntityGroup(gos[index]);
  197. /*Entity entity = GameObjectConversionUtility.ConvertGameObjectHierarchy(gos[index],
  198. GameObjectConversionSettings.FromWorld(physicsWorld, MGPatch.data.Item2));*/
  199. Console.WriteLine("Transform: " + gos[index].transform.childCount);
  200. Entity primaryEntity = getExistingSystem.GetPrimaryEntity(gos[index]);
  201. MultiListEnumerator<Entity> entities = getExistingSystem.GetEntities(gos[index]);
  202. Console.WriteLine("ID: " + data.prefabId + " - Name: " + data.prefabName);
  203. Console.WriteLine("Primary entity: " + primaryEntity);
  204. EntityManager entityManager = physicsWorld.EntityManager;
  205. Console.WriteLine("Has collider: " + entityManager.HasComponent<PhysicsCollider>(primaryEntity));
  206. while (entities.MoveNext())
  207. {
  208. Entity current = entities.Current;
  209. Console.WriteLine("Entity " + current + " has collider: " +
  210. entityManager.HasComponent<PhysicsCollider>(current));
  211. }
  212. Console.WriteLine("Adding GPUI prefab");
  213. ((GPUInstancerPrefabManager) GPUInstancerManager.activeManagerList.Single(gim =>
  214. gim is GPUInstancerPrefabManager))
  215. .AddRuntimeRegisteredPrefab(gos[index].GetComponent<GPUInstancerPrefab>());
  216. Console.WriteLine("Added GPUI prefab");
  217. }
  218. }
  219. public static MethodBase TargetMethod()
  220. {
  221. return AccessTools.Method("RobocraftX.Blocks.ECSResourceManagerUtility:RelinkEntities",
  222. new[]
  223. {
  224. typeof(World),
  225. typeof(GameObjectConversionSystem),
  226. typeof(FasterList<GameObject>),
  227. typeof(List<PrefabData>)
  228. });
  229. }
  230. }
  231. [HarmonyPatch]
  232. public static class MGPatch
  233. {
  234. internal static (World, BlobAssetStore) data;
  235. public static void Prefix(World physicsWorld, BlobAssetStore blobStore, IDataDB dataDB)
  236. {
  237. data = (physicsWorld, blobStore);
  238. var blocks = dataDB.GetValues<CubeListData>();
  239. blocks.Add("modded_ConsoleBlock", new CubeListData
  240. {
  241. cubeType = CubeType.Block,
  242. cubeCategory = CubeCategory.ConsoleBlock,
  243. inventoryCategory = InventoryCategory.Logic,
  244. ID = 500,
  245. Path = "Assets/Prefabs/Cube.prefab", //Index out of range exception: Asset failed to load (wrong path)
  246. SpriteName = "CTR_CommandBlock",
  247. CubeNameKey = "strConsoleBlock",
  248. SelectableFaces = new[] {0, 1, 2, 3, 4, 5},
  249. GridScale = new[] {1, 1, 1},
  250. Mass = 1,
  251. JointBreakAngle = 1
  252. });
  253. }
  254. public static MethodBase TargetMethod()
  255. {
  256. return AccessTools.Method("RobocraftX.CR.MainGame.MainGameCompositionRoot:Init");
  257. }
  258. }
  259. public static IEnumerator Prep()
  260. { //TODO: Don't let the game load until this finishes
  261. Console.WriteLine("Loading custom catalog...");
  262. var res = Addressables.LoadContentCatalogAsync("customCatalog.json");
  263. while (!res.IsDone) yield return Yield.It;
  264. Console.WriteLine("Loaded custom catalog: " + res.Result.LocatorId);
  265. Addressables.AddResourceLocator(res.Result);
  266. /*Console.WriteLine("Loading Cube asset...");
  267. var loadTask = Addressables.LoadAssetAsync<GameObject>("Assets/Cube.prefab");
  268. while (!loadTask.IsDone) yield return Yield.It;
  269. Console.WriteLine("Exception: "+loadTask.OperationException);
  270. Console.WriteLine("Result: " + loadTask.Result.name);*/
  271. }
  272. }
  273. }