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.

554 lines
20KB

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