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.

424 lines
15KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection.Emit;
  5. using Svelto.ECS;
  6. using Svelto.ECS.EntityStructs;
  7. using RobocraftX.Common;
  8. using RobocraftX.Blocks;
  9. using Unity.Mathematics;
  10. using Unity.Entities;
  11. using Gamecraft.Blocks.GUI;
  12. using GamecraftModdingAPI.Blocks;
  13. using GamecraftModdingAPI.Utility;
  14. namespace GamecraftModdingAPI
  15. {
  16. /// <summary>
  17. /// A single (perhaps scaled) block. Properties may return default values if the block is removed and then setting them is ignored.
  18. /// For specific block type operations, use the specialised block classes in the GamecraftModdingAPI.Blocks namespace.
  19. /// </summary>
  20. public class Block : IEquatable<Block>, IEquatable<EGID>
  21. {
  22. protected static readonly PlacementEngine PlacementEngine = new PlacementEngine();
  23. protected static readonly MovementEngine MovementEngine = new MovementEngine();
  24. protected static readonly RotationEngine RotationEngine = new RotationEngine();
  25. protected static readonly RemovalEngine RemovalEngine = new RemovalEngine();
  26. protected static readonly SignalEngine SignalEngine = new SignalEngine();
  27. protected static readonly BlockEventsEngine BlockEventsEngine = new BlockEventsEngine();
  28. protected static readonly ScalingEngine ScalingEngine = new ScalingEngine();
  29. protected internal static readonly BlockEngine BlockEngine = new BlockEngine();
  30. /// <summary>
  31. /// 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.
  32. /// Place blocks next to each other to connect them.
  33. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  34. /// <para></para>
  35. /// <para>When placing multiple blocks, do not access properties immediately after creation as this
  36. /// triggers a sync each time which can affect performance and may cause issues with the game.
  37. /// You may either use AsyncUtils.WaitForSubmission() after placing all of the blocks
  38. /// or simply access the block properties which will trigger the synchronization the first time a property is used.</para>
  39. /// </summary>
  40. /// <param name="block">The block's type</param>
  41. /// <param name="color">The block's color</param>
  42. /// <param name="darkness">The block color's darkness (0-9) - 0 is default color</param>
  43. /// <param name="position">The block's position in the grid - default block size is 0.2</param>
  44. /// <param name="rotation">The block's rotation in degrees</param>
  45. /// <param name="uscale">The block's uniform scale - default scale is 1 (with 0.2 width)</param>
  46. /// <param name="scale">The block's non-uniform scale - 0 means <paramref name="uscale"/> is used</param>
  47. /// <param name="player">The player who placed the block</param>
  48. /// <returns>The placed block or null if failed</returns>
  49. public static Block PlaceNew(BlockIDs block, float3 position,
  50. float3 rotation = default, BlockColors color = BlockColors.Default, byte darkness = 0,
  51. int uscale = 1, float3 scale = default, Player player = null)
  52. {
  53. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  54. {
  55. return new Block(PlacementEngine.PlaceBlock(block, color, darkness,
  56. position, uscale, scale, player, rotation));
  57. }
  58. return null;
  59. }
  60. /// <summary>
  61. /// 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.
  62. /// Place blocks next to each other to connect them.
  63. /// The placed block will be a complete block with a placement grid and collision which will be saved along with the game.
  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 T PlaceNew<T>(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) where T : Block
  77. {
  78. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  79. {
  80. var egid = PlacementEngine.PlaceBlock(block, color, darkness,
  81. position, uscale, scale, player, rotation);
  82. return New<T>(egid.entityID, egid.groupID);
  83. }
  84. return null;
  85. }
  86. /// <summary>
  87. /// Returns the most recently placed block.
  88. /// </summary>
  89. /// <returns>The block object</returns>
  90. public static Block GetLastPlacedBlock()
  91. {
  92. return New<Block>(BlockIdentifiers.LatestBlockID);
  93. }
  94. /// <summary>
  95. /// An event that fires each time a block is placed.
  96. /// </summary>
  97. public static event EventHandler<BlockPlacedRemovedEventArgs> Placed
  98. {
  99. add => BlockEventsEngine.Placed += value;
  100. remove => BlockEventsEngine.Placed -= value;
  101. }
  102. /// <summary>
  103. /// An event that fires each time a block is removed.
  104. /// </summary>
  105. public static event EventHandler<BlockPlacedRemovedEventArgs> Removed
  106. {
  107. add => BlockEventsEngine.Removed += value;
  108. remove => BlockEventsEngine.Removed -= value;
  109. }
  110. private static Dictionary<Type, Func<EGID, Block>> initializers = new Dictionary<Type, Func<EGID, Block>>();
  111. private static Dictionary<Type, ExclusiveGroupStruct[]> typeToGroup =
  112. new Dictionary<Type, ExclusiveGroupStruct[]>
  113. {
  114. {typeof(ConsoleBlock), new[] {CommonExclusiveGroups.BUILD_CONSOLE_BLOCK_GROUP}},
  115. {typeof(Motor), new[] {CommonExclusiveGroups.BUILD_MOTOR_BLOCK_GROUP}},
  116. {typeof(Piston), new[] {CommonExclusiveGroups.BUILD_PISTON_BLOCK_GROUP}},
  117. {typeof(Servo), new[] {CommonExclusiveGroups.BUILD_SERVO_BLOCK_GROUP}},
  118. {
  119. typeof(SpawnPoint),
  120. new[]
  121. {
  122. CommonExclusiveGroups.BUILD_SPAWNPOINT_BLOCK_GROUP,
  123. CommonExclusiveGroups.BUILD_BUILDINGSPAWN_BLOCK_GROUP
  124. }
  125. },
  126. {typeof(TextBlock), new[] {CommonExclusiveGroups.BUILD_TEXT_BLOCK_GROUP}},
  127. {typeof(Timer), new[] {CommonExclusiveGroups.BUILD_TIMER_BLOCK_GROUP}}
  128. };
  129. private static T New<T>(uint id, ExclusiveGroupStruct? group = null) where T : Block
  130. {
  131. var type = typeof(T);
  132. EGID egid;
  133. if (!group.HasValue)
  134. {
  135. if (typeToGroup.TryGetValue(type, out var gr) && gr.Length == 1)
  136. egid = new EGID(id, gr[0]);
  137. else
  138. egid = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find block group!");
  139. }
  140. else
  141. {
  142. egid = new EGID(id, group.Value);
  143. if (typeToGroup.TryGetValue(type, out var gr)
  144. && gr.All(egs => egs != group.Value)) //If this subclass has a specific group, then use that - so Block should still work
  145. throw new BlockTypeException($"Incompatible block type! Type {type.Name} belongs to group {gr.Select(g => g.ToString()).Aggregate((a, b) => a + ", " + b)} instead of {group.Value}");
  146. }
  147. if (initializers.TryGetValue(type, out var func))
  148. {
  149. var bl = (T) func(egid);
  150. return bl;
  151. }
  152. //https://stackoverflow.com/a/10593806/2703239
  153. var ctor = type.GetConstructor(new[] {typeof(EGID)});
  154. if (ctor == null)
  155. throw new MissingMethodException("There is no constructor with an EGID parameter for this object");
  156. DynamicMethod dynamic = new DynamicMethod(string.Empty,
  157. type,
  158. new[] {typeof(EGID)},
  159. type);
  160. ILGenerator il = dynamic.GetILGenerator();
  161. il.DeclareLocal(type);
  162. il.Emit(OpCodes.Ldarg_0); //Load EGID and pass to constructor
  163. il.Emit(OpCodes.Newobj, ctor); //Call constructor
  164. il.Emit(OpCodes.Stloc_0);
  165. il.Emit(OpCodes.Ldloc_0);
  166. il.Emit(OpCodes.Ret);
  167. func = (Func<EGID, T>) dynamic.CreateDelegate(typeof(Func<EGID, T>));
  168. initializers.Add(type, func);
  169. var block = (T) func(egid);
  170. return block;
  171. }
  172. public Block(EGID id)
  173. {
  174. Id = id;
  175. }
  176. /// <summary>
  177. /// This overload searches for the correct group the block is in.
  178. /// It will throw an exception if the block doesn't exist.
  179. /// Use the EGID constructor where possible or subclasses of Block as those specify the group.
  180. /// </summary>
  181. public Block(uint id)
  182. {
  183. Id = BlockEngine.FindBlockEGID(id) ?? throw new BlockTypeException("Could not find the appropriate group for the block. The block probably doesn't exist or hasn't been submitted.");
  184. }
  185. public EGID Id { get; }
  186. /// <summary>
  187. /// The block's current position or zero if the block no longer exists.
  188. /// A block is 0.2 wide by default in terms of position.
  189. /// </summary>
  190. public float3 Position
  191. {
  192. get => Exists ? MovementEngine.GetPosition(Id) : float3.zero;
  193. set
  194. {
  195. if (Exists) MovementEngine.MoveBlock(Id, value);
  196. }
  197. }
  198. /// <summary>
  199. /// The block's current rotation in degrees or zero if the block doesn't exist.
  200. /// </summary>
  201. public float3 Rotation
  202. {
  203. get => Exists ? RotationEngine.GetRotation(Id) : float3.zero;
  204. set
  205. {
  206. if (Exists) RotationEngine.RotateBlock(Id, value);
  207. }
  208. }
  209. /// <summary>
  210. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  211. /// The default scale of 1 means 0.2 in terms of position.
  212. /// </summary>
  213. public float3 Scale
  214. {
  215. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id).scale;
  216. set
  217. {
  218. if (!Exists) return; //UpdateCollision needs the block to exist
  219. ref var scaling = ref BlockEngine.GetBlockInfo<ScalingEntityStruct>(Id);
  220. scaling.scale = value;
  221. ScalingEngine.UpdateCollision(Id);
  222. }
  223. }
  224. /// <summary>
  225. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  226. /// The default scale of 1 means 0.2 in terms of position.
  227. /// </summary>
  228. public int UniformScale
  229. {
  230. get => BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id).scaleFactor;
  231. set
  232. {
  233. ref var scaleStruct = ref BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(Id);
  234. scaleStruct.scaleFactor = value;
  235. Scale = new float3(value, value, value);
  236. }
  237. }
  238. /// <summary>
  239. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  240. /// </summary>
  241. public BlockIDs Type
  242. {
  243. get
  244. {
  245. var id = (BlockIDs) BlockEngine.GetBlockInfo<DBEntityStruct>(Id, out var exists).DBID;
  246. return exists ? id : BlockIDs.Invalid;
  247. }
  248. }
  249. /// <summary>
  250. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  251. /// </summary>
  252. public BlockColor Color
  253. {
  254. get
  255. {
  256. byte index = BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id, out var exists).indexInPalette;
  257. if (!exists) index = byte.MaxValue;
  258. return new BlockColor(index);
  259. }
  260. set
  261. {
  262. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  263. color.indexInPalette = (byte)(value.Color + value.Darkness * 10);
  264. color.overridePaletteColour = false;
  265. color.needsUpdate = true;
  266. BlockEngine.SetBlockColorFromPalette(ref color);
  267. }
  268. }
  269. /// <summary>
  270. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  271. /// </summary>
  272. public float4 CustomColor
  273. {
  274. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id).overriddenColour;
  275. set
  276. {
  277. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(Id);
  278. color.overriddenColour = value;
  279. color.overridePaletteColour = true;
  280. color.needsUpdate = true;
  281. }
  282. }
  283. /// <summary>
  284. /// The short text displayed on the block if applicable, or null.
  285. /// Setting it is temporary to the session, it won't be saved.
  286. /// </summary>
  287. public string Label
  288. {
  289. get => BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id).textLabelComponent?.text;
  290. set
  291. {
  292. ref var text = ref BlockEngine.GetBlockInfo<TextLabelEntityViewStruct>(Id);
  293. if (text.textLabelComponent != null) text.textLabelComponent.text = value;
  294. }
  295. }
  296. /// <summary>
  297. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  298. /// </summary>
  299. public bool Exists => BlockEngine.BlockExists(Id);
  300. /// <summary>
  301. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  302. /// </summary>
  303. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  304. /// <summary>
  305. /// Removes this block.
  306. /// </summary>
  307. /// <returns>True if the block exists and could be removed.</returns>
  308. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  309. /// <summary>
  310. /// Returns the rigid body of the cluster of blocks this one belongs to during simulation.
  311. /// Can be used to apply forces or move the block around while the simulation is running.
  312. /// </summary>
  313. /// <returns>The SimBody of the cluster or null if the block doesn't exist.</returns>
  314. public SimBody GetSimBody()
  315. {
  316. uint id = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(Id, out var exists).machineRigidBodyId;
  317. return exists ? new SimBody(id) : null;
  318. }
  319. public override string ToString()
  320. {
  321. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  322. }
  323. public bool Equals(Block other)
  324. {
  325. if (ReferenceEquals(null, other)) return false;
  326. if (ReferenceEquals(this, other)) return true;
  327. return Id.Equals(other.Id);
  328. }
  329. public bool Equals(EGID other)
  330. {
  331. return Id.Equals(other);
  332. }
  333. public override bool Equals(object obj)
  334. {
  335. if (ReferenceEquals(null, obj)) return false;
  336. if (ReferenceEquals(this, obj)) return true;
  337. if (obj.GetType() != this.GetType()) return false;
  338. return Equals((Block) obj);
  339. }
  340. public override int GetHashCode()
  341. {
  342. return Id.GetHashCode();
  343. }
  344. public static void Init()
  345. {
  346. GameEngineManager.AddGameEngine(PlacementEngine);
  347. GameEngineManager.AddGameEngine(MovementEngine);
  348. GameEngineManager.AddGameEngine(RotationEngine);
  349. GameEngineManager.AddGameEngine(RemovalEngine);
  350. GameEngineManager.AddGameEngine(BlockEngine);
  351. GameEngineManager.AddGameEngine(BlockEventsEngine);
  352. GameEngineManager.AddGameEngine(ScalingEngine);
  353. }
  354. /// <summary>
  355. /// Convert the block to a specialised block class.
  356. /// </summary>
  357. /// <returns>The block.</returns>
  358. /// <typeparam name="T">The specialised block type.</typeparam>
  359. public T Specialise<T>() where T : Block
  360. {
  361. // What have I gotten myself into?
  362. // C# can't cast to a child of Block unless the object was originally that child type
  363. // And C# doesn't let me make implicit cast operators for child types
  364. // So thanks to Microsoft, we've got this horrible implementation using reflection
  365. //Lets improve that using delegates
  366. return New<T>(Id.entityID, Id.groupID);
  367. }
  368. #if DEBUG
  369. public static EntitiesDB entitiesDB
  370. {
  371. get
  372. {
  373. return BlockEngine.GetEntitiesDB();
  374. }
  375. }
  376. #endif
  377. internal static void Setup(World physicsWorld)
  378. {
  379. ScalingEngine.Setup(physicsWorld.EntityManager);
  380. }
  381. }
  382. }