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.

530 lines
19KB

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