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.

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