A stable modding interface between Techblox and mods https://mod.exmods.org/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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