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.

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