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.

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