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.

Block.cs 15KB

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