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.

468 lines
17KB

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