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.

317 lines
12KB

  1. using System;
  2. using System.Reflection;
  3. using System.Threading.Tasks;
  4. using Svelto.ECS;
  5. using Svelto.ECS.EntityStructs;
  6. using RobocraftX.Common;
  7. using RobocraftX.Blocks;
  8. using Unity.Mathematics;
  9. using Gamecraft.Blocks.GUI;
  10. using GamecraftModdingAPI.Blocks;
  11. using GamecraftModdingAPI.Utility;
  12. namespace GamecraftModdingAPI
  13. {
  14. /// <summary>
  15. /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored.
  16. /// For specific block type operations, use the specialised block classes in the GamecraftModdingAPI.Blocks namespace.
  17. /// </summary>
  18. public class Block
  19. {
  20. protected static readonly PlacementEngine PlacementEngine = new PlacementEngine();
  21. protected static readonly MovementEngine MovementEngine = new MovementEngine();
  22. protected static readonly RotationEngine RotationEngine = new RotationEngine();
  23. protected static readonly RemovalEngine RemovalEngine = new RemovalEngine();
  24. protected static readonly SignalEngine SignalEngine = new SignalEngine();
  25. protected internal static readonly BlockEngine BlockEngine = new BlockEngine();
  26. /// <summary>
  27. /// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position.
  28. /// Place blocks next to each other to connect them.
  29. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  30. /// <para></para>
  31. /// <para>When placing multiple blocks, do not access properties immediately after creation as this
  32. /// triggers a sync each time which can affect performance and may cause issues with the game.
  33. /// You may either use AsyncUtils.WaitForSubmission() after placing all of the blocks
  34. /// or simply access the block properties which will trigger the synchronization the first time a property is used.</para>
  35. /// </summary>
  36. /// <param name="block">The block's type</param>
  37. /// <param name="color">The block's color</param>
  38. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  39. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  40. /// <param name="rotation">The block's rotation in degrees</param>
  41. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  42. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  43. /// <param name="player">The player who placed the block</param>
  44. /// <returns>The placed block or null if failed</returns>
  45. public static Block PlaceNew(BlockIDs block, float3 position,
  46. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  47. int uscale = 1, float3 scale = default, Player player = null)
  48. {
  49. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  50. {
  51. return new Block(PlacementEngine.PlaceBlock(block, color, darkness,
  52. position, uscale, scale, player, rotation));
  53. }
  54. return null;
  55. }
  56. /// <summary>
  57. /// Place a new block at the given position. If scaled, position means the center of the block. The default block size is 0.2 in terms of position.
  58. /// Place blocks next to each other to connect them.
  59. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  60. /// <para></para>
  61. /// <para>This method waits for the block to be constructed in the game which may take a significant amount of time.
  62. /// Only use this to place a single block.
  63. /// For placing multiple blocks, use PlaceNew() then AsyncUtils.WaitForSubmission() when done with placing blocks.</para>
  64. /// </summary>
  65. /// <param name="block">The block's type</param>
  66. /// <param name="color">The block's color</param>
  67. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  68. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  69. /// <param name="rotation">The block's rotation in degrees</param>
  70. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  71. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  72. /// <param name="player">The player who placed the block</param>
  73. /// <returns>The placed block or null if failed</returns>
  74. public static async Task<Block> PlaceNewAsync(BlockIDs block, float3 position,
  75. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  76. int uscale = 1, float3 scale = default, Player player = null)
  77. {
  78. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  79. {
  80. try
  81. {
  82. var ret = new Block(PlacementEngine.PlaceBlock(block, color, darkness,
  83. position, uscale, scale, player, rotation));
  84. await AsyncUtils.WaitForSubmission();
  85. return ret;
  86. }
  87. catch (Exception e)
  88. {
  89. Logging.MetaDebugLog(e);
  90. }
  91. }
  92. return null;
  93. }
  94. /// <summary>
  95. /// Returns the most recently placed block.
  96. /// </summary>
  97. /// <returns>The block object</returns>
  98. public static Block GetLastPlacedBlock()
  99. {
  100. return new Block(BlockIdentifiers.LatestBlockID);
  101. }
  102. public Block(EGID id)
  103. {
  104. Id = id;
  105. if (!BlockEngine.BlockExists(Id))
  106. {
  107. /*Sync();
  108. if (!BlockEngine.BlockExists(Id))
  109. {
  110. throw new BlockDoesNotExistException($"Block {Id.entityID} must be placed using PlaceNew(...) since it does not exist yet");
  111. }*/
  112. }
  113. }
  114. public Block(uint id) : this(new EGID(id, CommonExclusiveGroups.OWNED_BLOCKS_GROUP))
  115. {
  116. }
  117. public EGID Id { get; protected set; }
  118. /// <summary>
  119. /// The block's current position or zero if the block no longer exists.
  120. /// A block is 0.2 wide by default in terms of position.
  121. /// </summary>
  122. public float3 Position
  123. {
  124. get => Exists ? MovementEngine.GetPosition(Id.entityID) : float3.zero;
  125. set
  126. {
  127. if (Exists) MovementEngine.MoveBlock(Id.entityID, value);
  128. }
  129. }
  130. /// <summary>
  131. /// The block's current rotation in degrees or zero if the block doesn't exist.
  132. /// </summary>
  133. public float3 Rotation
  134. {
  135. get => Exists ? RotationEngine.GetRotation(Id.entityID) : float3.zero;
  136. set
  137. {
  138. if (Exists) RotationEngine.RotateBlock(Id.entityID, value);
  139. }
  140. }
  141. /// <summary>
  142. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  143. /// The default scale of 1 means 0.2 in terms of position.
  144. /// </summary>
  145. public float3 Scale
  146. {
  147. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id).scale;
  148. set
  149. {
  150. BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id).scale = value;
  151. }
  152. }
  153. /// <summary>
  154. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  155. /// The default scale of 1 means 0.2 in terms of position.
  156. /// </summary>
  157. public int UniformScale
  158. {
  159. get => BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id).scaleFactor;
  160. set
  161. {
  162. ref var scaleStruct = ref BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id);
  163. scaleStruct.scaleFactor = value;
  164. Scale = new float3(value, value, value);
  165. }
  166. }
  167. /// <summary>
  168. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  169. /// </summary>
  170. public BlockIDs Type
  171. {
  172. get
  173. {
  174. var id = (BlockIDs) BlockEngine.GetBlockInfo<DBEntityStruct>(Id, out var exists).DBID;
  175. return exists ? id : BlockIDs.Invalid;
  176. }
  177. }
  178. /// <summary>
  179. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  180. /// </summary>
  181. public BlockColor Color
  182. {
  183. get
  184. {
  185. byte index = BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id, out var exists).indexInPalette;
  186. if (!exists) index = byte.MaxValue;
  187. if (index == byte.MaxValue) return new BlockColor { Color = BlockColors.Default };
  188. return new BlockColor { Color = (BlockColors)(index % 10), Darkness = (byte)(index / 10) };
  189. }
  190. set
  191. {
  192. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  193. color.indexInPalette = (byte)(value.Color + value.Darkness * 10);
  194. color.overridePaletteColour = false;
  195. color.needsUpdate = true;
  196. BlockEngine.SetBlockColorFromPalette(ref color);
  197. }
  198. }
  199. /// <summary>
  200. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  201. /// </summary>
  202. public float4 CustomColor
  203. {
  204. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id).overriddenColour;
  205. set
  206. {
  207. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  208. color.overriddenColour = value;
  209. color.overridePaletteColour = true;
  210. color.needsUpdate = true;
  211. }
  212. }
  213. /// <summary>
  214. /// The short text displayed on the block if applicable, or null.
  215. /// Setting it is temporary to the session, it won't be saved.
  216. /// </summary>
  217. public string Label
  218. {
  219. get => BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id).textLabelComponent?.text;
  220. set
  221. {
  222. ref var text = ref BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id);
  223. if (text.textLabelComponent != null) text.textLabelComponent.text = value;
  224. }
  225. }
  226. /// <summary>
  227. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  228. /// </summary>
  229. public bool Exists => BlockEngine.BlockExists(Id);
  230. /// <summary>
  231. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  232. /// </summary>
  233. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  234. /// <summary>
  235. /// Removes this block.
  236. /// </summary>
  237. /// <returns>True if the block exists and could be removed.</returns>
  238. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  239. /// <summary>
  240. /// Returns the rigid body of the cluster of blocks this one belongs to during simulation.
  241. /// Can be used to apply forces or move the block around while the simulation is running.
  242. /// </summary>
  243. /// <returns>The SimBody of the cluster</returns>
  244. public SimBody GetSimBody()
  245. {
  246. uint id = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(Id).machineRigidBodyId;
  247. return new SimBody(id);
  248. }
  249. public override string ToString()
  250. {
  251. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  252. }
  253. public static void Init()
  254. {
  255. GameEngineManager.AddGameEngine(PlacementEngine);
  256. GameEngineManager.AddGameEngine(MovementEngine);
  257. GameEngineManager.AddGameEngine(RotationEngine);
  258. GameEngineManager.AddGameEngine(RemovalEngine);
  259. GameEngineManager.AddGameEngine(BlockEngine);
  260. }
  261. /// <summary>
  262. /// Convert the block to a specialised block class.
  263. /// </summary>
  264. /// <returns>The block.</returns>
  265. /// <typeparam name="T">The specialised block type.</typeparam>
  266. public T Specialise<T>() where T : Block
  267. {
  268. // What have I gotten myself into?
  269. // C# can't cast to a child of Block unless the object was originally that child type
  270. // And C# doesn't let me make implicit cast operators for child types
  271. // So thanks to Microsoft, we've got this horrible implementation using reflection
  272. ConstructorInfo ctor = typeof(T).GetConstructor(types: new System.Type[] { typeof(EGID) });
  273. if (ctor == null)
  274. {
  275. throw new BlockSpecializationException("Specialized block constructor does not accept an EGID");
  276. }
  277. return (T)ctor.Invoke(new object[] { Id });
  278. }
  279. #if DEBUG
  280. public static EntitiesDB entitiesDB
  281. {
  282. get
  283. {
  284. return BlockEngine.GetEntitiesDB();
  285. }
  286. }
  287. #endif
  288. }
  289. }