A stable modding interface between Techblox and mods https://mod.exmods.org/
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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