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.

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