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.

438 lines
15KB

  1. using System;
  2. using System.Collections.Generic;
  3. using DataLoader;
  4. using Gamecraft.Blocks.BlockGroups;
  5. using Svelto.ECS;
  6. using Svelto.ECS.EntityStructs;
  7. using RobocraftX.Common;
  8. using RobocraftX.Blocks;
  9. using Unity.Mathematics;
  10. using Gamecraft.Blocks.GUI;
  11. using TechbloxModdingAPI.Blocks;
  12. using TechbloxModdingAPI.Blocks.Engines;
  13. using TechbloxModdingAPI.Tests;
  14. using TechbloxModdingAPI.Utility;
  15. namespace TechbloxModdingAPI
  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 TechbloxModdingAPI.Blocks namespace.
  20. /// </summary>
  21. public class Block : EcsObjectBase, 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="position">The block's position - default block size is 0.2</param>
  39. /// <param name="autoWire">Whether the block should be auto-wired (if functional)</param>
  40. /// <param name="player">The player who placed the block</param>
  41. /// <returns>The placed block or null if failed</returns>
  42. public static Block PlaceNew(BlockIDs block, float3 position, bool autoWire = false, Player player = null)
  43. {
  44. if (PlacementEngine.IsInGame && GameState.IsBuildMode())
  45. {
  46. var initializer = PlacementEngine.PlaceBlock(block, position, player, autoWire);
  47. var egid = initializer.EGID;
  48. var bl = New(egid);
  49. bl.InitData = initializer;
  50. Placed += bl.OnPlacedInit;
  51. return bl;
  52. }
  53. return null;
  54. }
  55. /// <summary>
  56. /// Returns the most recently placed block.
  57. /// </summary>
  58. /// <returns>The block object or null if doesn't exist</returns>
  59. public static Block GetLastPlacedBlock()
  60. {
  61. EGID? egid = BlockEngine.FindBlockEGID(BlockIdentifiers.LatestBlockID);
  62. return egid.HasValue ? New(egid.Value) : null;
  63. }
  64. /// <summary>
  65. /// An event that fires each time a block is placed.
  66. /// </summary>
  67. public static event EventHandler<BlockPlacedRemovedEventArgs> Placed
  68. {
  69. add => BlockEventsEngine.Placed += ExceptionUtil.WrapHandler(value);
  70. remove => BlockEventsEngine.Placed -= value;
  71. }
  72. /// <summary>
  73. /// An event that fires each time a block is removed.
  74. /// </summary>
  75. public static event EventHandler<BlockPlacedRemovedEventArgs> Removed
  76. {
  77. add => BlockEventsEngine.Removed += ExceptionUtil.WrapHandler(value);
  78. remove => BlockEventsEngine.Removed -= value;
  79. }
  80. private static readonly Dictionary<ExclusiveBuildGroup, (Func<EGID, Block> Constructor, Type Type)> GroupToConstructor =
  81. new Dictionary<ExclusiveBuildGroup, (Func<EGID, Block>, Type)>
  82. {
  83. {CommonExclusiveGroups.DAMPEDSPRING_BLOCK_GROUP, (id => new DampedSpring(id), typeof(DampedSpring))},
  84. {CommonExclusiveGroups.ENGINE_BLOCK_BUILD_GROUP, (id => new Engine(id), typeof(Engine))}
  85. };
  86. internal static Block New(EGID egid)
  87. {
  88. return GroupToConstructor.ContainsKey(egid.groupID)
  89. ? GroupToConstructor[egid.groupID].Constructor(egid)
  90. : new Block(egid);
  91. }
  92. public Block(EGID id)
  93. {
  94. Id = id;
  95. Type expectedType;
  96. if (GroupToConstructor.ContainsKey(id.groupID) &&
  97. !GetType().IsAssignableFrom(expectedType = GroupToConstructor[id.groupID].Type))
  98. throw new BlockSpecializationException($"Incorrect block type! Expected: {expectedType} Actual: {GetType()}");
  99. }
  100. /// <summary>
  101. /// This overload searches for the correct group the block is in.
  102. /// It will throw an exception if the block doesn't exist.
  103. /// Use the EGID constructor where possible or subclasses of Block as those specify the group.
  104. /// </summary>
  105. public Block(uint id) : this(BlockEngine.FindBlockEGID(id)
  106. ?? throw new BlockTypeException(
  107. "Could not find the appropriate group for the block." +
  108. " The block probably doesn't exist or hasn't been submitted."))
  109. {
  110. }
  111. /// <summary>
  112. /// Places a new block in the world.
  113. /// </summary>
  114. /// <param name="type">The block's type</param>
  115. /// <param name="position">The block's position (a block is 0.2 wide in terms of position)</param>
  116. /// <param name="autoWire">Whether the block should be auto-wired (if functional)</param>
  117. /// <param name="player">The player who placed the block</param>
  118. public Block(BlockIDs type, float3 position, bool autoWire = false, Player player = null)
  119. {
  120. if (!PlacementEngine.IsInGame || !GameState.IsBuildMode())
  121. throw new BlockException("Blocks can only be placed in build mode.");
  122. var initializer = PlacementEngine.PlaceBlock(type, position, player, autoWire);
  123. Id = initializer.EGID;
  124. InitData = initializer;
  125. Placed += OnPlacedInit;
  126. }
  127. public override EGID Id { get; }
  128. private EGID copiedFrom;
  129. /// <summary>
  130. /// The block's current position or zero if the block no longer exists.
  131. /// A block is 0.2 wide by default in terms of position.
  132. /// </summary>
  133. public float3 Position
  134. {
  135. get => MovementEngine.GetPosition(this);
  136. set
  137. {
  138. MovementEngine.MoveBlock(this, value);
  139. if (blockGroup != null)
  140. blockGroup.PosAndRotCalculated = false;
  141. BlockEngine.UpdateDisplayedBlock(Id);
  142. }
  143. }
  144. /// <summary>
  145. /// The block's current rotation in degrees or zero if the block doesn't exist.
  146. /// </summary>
  147. public float3 Rotation
  148. {
  149. get => RotationEngine.GetRotation(this);
  150. set
  151. {
  152. RotationEngine.RotateBlock(this, value);
  153. if (blockGroup != null)
  154. blockGroup.PosAndRotCalculated = false;
  155. BlockEngine.UpdateDisplayedBlock(Id);
  156. }
  157. }
  158. /// <summary>
  159. /// The block's non-uniform scale or zero if the block's invalid. Independent of the uniform scaling.
  160. /// The default scale of 1 means 0.2 in terms of position.
  161. /// </summary>
  162. public float3 Scale
  163. {
  164. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(this).scale;
  165. set
  166. {
  167. int uscale = UniformScale;
  168. if (value.x < 4e-5) value.x = uscale;
  169. if (value.y < 4e-5) value.y = uscale;
  170. if (value.z < 4e-5) value.z = uscale;
  171. BlockEngine.GetBlockInfo<ScalingEntityStruct>(this).scale = value;
  172. //BlockEngine.GetBlockInfo<GridScaleStruct>(this).gridScale = value - (int3) value + 1;
  173. if (!Exists) return; //UpdateCollision needs the block to exist
  174. ScalingEngine.UpdateCollision(Id);
  175. BlockEngine.UpdateDisplayedBlock(Id);
  176. }
  177. }
  178. /// <summary>
  179. /// The block's uniform scale or zero if the block's invalid. Also sets the non-uniform scale.
  180. /// The default scale of 1 means 0.2 in terms of position.
  181. /// </summary>
  182. public int UniformScale
  183. {
  184. get => BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(this).scaleFactor;
  185. set
  186. {
  187. if (value < 1) value = 1;
  188. BlockEngine.GetBlockInfo<UniformBlockScaleEntityStruct>(this).scaleFactor = value;
  189. Scale = new float3(value, value, value);
  190. }
  191. }
  192. /**
  193. * Whether the block is flipped.
  194. */
  195. public bool Flipped
  196. {
  197. get => BlockEngine.GetBlockInfo<ScalingEntityStruct>(this).scale.x < 0;
  198. set
  199. {
  200. ref var st = ref BlockEngine.GetBlockInfo<ScalingEntityStruct>(this);
  201. st.scale.x = math.abs(st.scale.x) * (value ? -1 : 1);
  202. BlockEngine.UpdatePrefab(this, (byte) Material, value);
  203. }
  204. }
  205. /// <summary>
  206. /// The block's type (ID). Returns BlockIDs.Invalid if the block doesn't exist anymore.
  207. /// </summary>
  208. public BlockIDs Type
  209. {
  210. get
  211. {
  212. var opt = BlockEngine.GetBlockInfoOptional<DBEntityStruct>(this);
  213. return opt ? (BlockIDs) opt.Get().DBID : BlockIDs.Invalid;
  214. }
  215. }
  216. /// <summary>
  217. /// The block's color. Returns BlockColors.Default if the block no longer exists.
  218. /// </summary>
  219. public BlockColor Color
  220. {
  221. get
  222. {
  223. var opt = BlockEngine.GetBlockInfoOptional<ColourParameterEntityStruct>(this);
  224. return new BlockColor(opt ? opt.Get().indexInPalette : byte.MaxValue);
  225. }
  226. set
  227. {
  228. //TODO: Check if setting to 255 works
  229. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(this);
  230. color.indexInPalette = value.Index;
  231. color.hasNetworkChange = true;
  232. color.paletteColour = BlockEngine.ConvertBlockColor(color.indexInPalette);
  233. }
  234. }
  235. /// <summary>
  236. /// The block's exact color. Gets reset to the palette color (Color property) after reentering the game.
  237. /// </summary>
  238. public float4 CustomColor
  239. {
  240. get => BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(this).paletteColour;
  241. set
  242. {
  243. ref var color = ref BlockEngine.GetBlockInfo<ColourParameterEntityStruct>(this);
  244. color.paletteColour = value;
  245. color.hasNetworkChange = true;
  246. }
  247. }
  248. /**
  249. * The block's material.
  250. */
  251. public BlockMaterial Material
  252. {
  253. get
  254. {
  255. var opt = BlockEngine.GetBlockInfoOptional<CubeMaterialStruct>(this);
  256. return opt ? (BlockMaterial) opt.Get().materialId : BlockMaterial.Default;
  257. }
  258. set
  259. {
  260. if (!FullGameFields._dataDb.ContainsKey<MaterialPropertiesData>((byte) value))
  261. throw new BlockException($"Block material {value} does not exist!");
  262. BlockEngine.GetBlockInfo<CubeMaterialStruct>(this).materialId = (byte) value;
  263. BlockEngine.UpdatePrefab(this, (byte) value, Flipped); //TODO: Test default
  264. }
  265. }
  266. /// <summary>
  267. /// The text displayed on the block if applicable, or null.
  268. /// Setting it is temporary to the session, it won't be saved.
  269. /// </summary>
  270. [TestValue(null)]
  271. public string Label
  272. {
  273. get => BlockEngine.GetBlockInfoViewComponent<TextLabelEntityViewStruct>(this).textLabelComponent?.text;
  274. set
  275. {
  276. var comp = BlockEngine.GetBlockInfoViewComponent<TextLabelEntityViewStruct>(this).textLabelComponent;
  277. if (comp != null) comp.text = value;
  278. }
  279. }
  280. private BlockGroup blockGroup;
  281. /// <summary>
  282. /// Returns the block group this block is a part of. Block groups can also be placed using blueprints.
  283. /// Returns null if not part of a group, although all blocks should have their own by default.<br />
  284. /// Setting the group after the block has been initialized will not update everything properly,
  285. /// so you can only set this property on blocks newly placed by your code.<br />
  286. /// To set it for existing blocks, you can use the Copy() method and set the property on the resulting block
  287. /// (and remove this block).
  288. /// </summary>
  289. public BlockGroup BlockGroup
  290. {
  291. get
  292. {
  293. if (blockGroup != null) return blockGroup;
  294. var bgec = BlockEngine.GetBlockInfo<BlockGroupEntityComponent>(this);
  295. return blockGroup = bgec.currentBlockGroup == -1 ? null : new BlockGroup(bgec.currentBlockGroup, this);
  296. }
  297. set
  298. {
  299. if (Exists)
  300. {
  301. Logging.LogWarning("Attempted to set group of existing block. This is not supported."
  302. + " Copy the block and set the group of the resulting block.");
  303. return;
  304. }
  305. blockGroup?.RemoveInternal(this);
  306. BlockEngine.GetBlockInfo<BlockGroupEntityComponent>(this).currentBlockGroup = (int?) value?.Id.entityID ?? -1;
  307. value?.AddInternal(this);
  308. blockGroup = value;
  309. }
  310. }
  311. /// <summary>
  312. /// Whether the block exists. The other properties will return a default value if the block doesn't exist.
  313. /// If the block was just placed, then this will also return false but the properties will work correctly.
  314. /// </summary>
  315. public bool Exists => BlockEngine.BlockExists(Id);
  316. /// <summary>
  317. /// Returns an array of blocks that are connected to this one. Returns an empty array if the block doesn't exist.
  318. /// </summary>
  319. public Block[] GetConnectedCubes() => BlockEngine.GetConnectedBlocks(Id);
  320. /// <summary>
  321. /// Removes this block.
  322. /// </summary>
  323. /// <returns>True if the block exists and could be removed.</returns>
  324. public bool Remove() => RemovalEngine.RemoveBlock(Id);
  325. /// <summary>
  326. /// Returns the rigid body of the chunk of blocks this one belongs to during simulation.
  327. /// Can be used to apply forces or move the block around while the simulation is running.
  328. /// </summary>
  329. /// <returns>The SimBody of the chunk or null if the block doesn't exist or not in simulation mode.</returns>
  330. public SimBody GetSimBody()
  331. {
  332. var st = BlockEngine.GetBlockInfo<GridConnectionsEntityStruct>(this);
  333. return st.machineRigidBodyId != uint.MaxValue
  334. ? new SimBody(st.machineRigidBodyId, st.clusterId)
  335. : null;
  336. }
  337. /// <summary>
  338. /// Creates a copy of the block in the game with the same properties, stats and wires.
  339. /// </summary>
  340. /// <returns></returns>
  341. public Block Copy()
  342. {
  343. var block = PlaceNew(Type, Position);
  344. block.Rotation = Rotation;
  345. block.Color = Color;
  346. block.Material = Material;
  347. block.UniformScale = UniformScale;
  348. block.Scale = Scale;
  349. block.copiedFrom = Id;
  350. return block;
  351. }
  352. private void OnPlacedInit(object sender, BlockPlacedRemovedEventArgs e)
  353. { //Member method instead of lambda to avoid constantly creating delegates
  354. if (e.ID != Id) return;
  355. Placed -= OnPlacedInit; //And we can reference it
  356. InitData = default; //Remove initializer as it's no longer valid - if the block gets removed it shouldn't be used again
  357. if (copiedFrom != EGID.Empty)
  358. BlockCloneEngine.CopyBlockStats(copiedFrom, Id);
  359. }
  360. public override string ToString()
  361. {
  362. return $"{nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Type)}: {Type}, {nameof(Color)}: {Color}, {nameof(Exists)}: {Exists}";
  363. }
  364. public bool Equals(Block other)
  365. {
  366. if (ReferenceEquals(null, other)) return false;
  367. if (ReferenceEquals(this, other)) return true;
  368. return Id.Equals(other.Id);
  369. }
  370. public bool Equals(EGID other)
  371. {
  372. return Id.Equals(other);
  373. }
  374. public override bool Equals(object obj)
  375. {
  376. if (ReferenceEquals(null, obj)) return false;
  377. if (ReferenceEquals(this, obj)) return true;
  378. if (obj.GetType() != this.GetType()) return false;
  379. return Equals((Block) obj);
  380. }
  381. public override int GetHashCode()
  382. {
  383. return Id.GetHashCode();
  384. }
  385. public static void Init()
  386. {
  387. GameEngineManager.AddGameEngine(PlacementEngine);
  388. GameEngineManager.AddGameEngine(MovementEngine);
  389. GameEngineManager.AddGameEngine(RotationEngine);
  390. GameEngineManager.AddGameEngine(RemovalEngine);
  391. GameEngineManager.AddGameEngine(BlockEngine);
  392. GameEngineManager.AddGameEngine(BlockEventsEngine);
  393. GameEngineManager.AddGameEngine(ScalingEngine);
  394. GameEngineManager.AddGameEngine(SignalEngine);
  395. GameEngineManager.AddGameEngine(BlockCloneEngine);
  396. Wire.signalEngine = SignalEngine; // requires same functionality, no need to duplicate the engine
  397. }
  398. }
  399. }