A stable modding interface between Techblox and mods https://mod.exmods.org/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

442 行
15KB

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