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.

466 lines
17KB

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