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.

483 lines
18KB

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