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.

571 lines
20KB

  1. using System;
  2. using Gamecraft.Wires;
  3. using RobocraftX.Character;
  4. using RobocraftX.Character.Movement;
  5. using Unity.Mathematics;
  6. using RobocraftX.Common;
  7. using RobocraftX.Common.Players;
  8. using RobocraftX.GUI.Wires;
  9. using RobocraftX.Physics;
  10. using Svelto.ECS;
  11. using Techblox.BuildingDrone;
  12. using Techblox.Camera;
  13. using TechbloxModdingAPI.Blocks;
  14. using TechbloxModdingAPI.Players;
  15. using TechbloxModdingAPI.Utility;
  16. using UnityEngine;
  17. namespace TechbloxModdingAPI
  18. {
  19. /// <summary>
  20. /// An in-game player character. Any Leo you see is a player.
  21. /// </summary>
  22. public partial class Player : EcsObjectBase, IEquatable<Player>, IEquatable<EGID>
  23. {
  24. // static functionality
  25. private static readonly PlayerEngine playerEngine = new PlayerEngine();
  26. private static readonly PlayerEventsEngine playerEventsEngine = new PlayerEventsEngine();
  27. private static Player localPlayer;
  28. /// <summary>
  29. /// Checks if the specified player exists.
  30. /// </summary>
  31. /// <returns>Whether the player exists.</returns>
  32. /// <param name="player">Player type.</param>
  33. public static bool Exists(PlayerType player)
  34. {
  35. switch (player)
  36. {
  37. case PlayerType.Remote:
  38. return playerEngine.GetRemotePlayer() != uint.MaxValue;
  39. case PlayerType.Local:
  40. return playerEngine.GetLocalPlayer() != uint.MaxValue;
  41. }
  42. return false;
  43. }
  44. /// <summary>
  45. /// Checks if the specified player exists.
  46. /// </summary>
  47. /// <returns>Whether the player exists.</returns>
  48. /// <param name="player">The player's unique identifier.</param>
  49. public static bool Exists(uint player)
  50. {
  51. return playerEngine.ExistsById(player);
  52. }
  53. /// <summary>
  54. /// The amount of Players in the current game.
  55. /// </summary>
  56. /// <returns>The count.</returns>
  57. public static uint Count()
  58. {
  59. return (uint) playerEngine.GetAllPlayerCount();
  60. }
  61. /// <summary>
  62. /// Returns the current player belonging to this client.
  63. /// </summary>
  64. public static Player LocalPlayer
  65. {
  66. get
  67. {
  68. if (localPlayer == null || localPlayer.Id != playerEngine.GetLocalPlayer())
  69. localPlayer = GetInstance(playerEngine.GetLocalPlayer());
  70. return localPlayer;
  71. }
  72. }
  73. internal static Player GetInstance(uint id)
  74. {
  75. return EcsObjectBase.GetInstance(new EGID(id, CharacterExclusiveGroups.OnFootGroup),
  76. e => new Player(e.entityID));
  77. }
  78. /// <summary>
  79. /// Initializes a new instance of the <see cref="T:TechbloxModdingAPI.Player"/> class.
  80. /// </summary>
  81. /// <param name="id">The player's unique identifier.</param>
  82. public Player(uint id) : base(new EGID(id, CharacterExclusiveGroups.OnFootGroup))
  83. {
  84. this.Id = id;
  85. if (!Exists(id))
  86. {
  87. throw new PlayerNotFoundException($"No player with id {id} exists");
  88. }
  89. this.Type = playerEngine.GetLocalPlayer() == id ? PlayerType.Local : PlayerType.Remote;
  90. }
  91. /// <summary>
  92. /// Initializes a new instance of the <see cref="T:TechbloxModdingAPI.Player"/> class.
  93. /// </summary>
  94. /// <param name="player">The player type. Chooses the first available player matching the criteria.</param>
  95. public Player(PlayerType player) : base(ecs =>
  96. {
  97. uint id;
  98. switch (player)
  99. {
  100. case PlayerType.Local:
  101. id = playerEngine.GetLocalPlayer();
  102. break;
  103. case PlayerType.Remote:
  104. id = playerEngine.GetRemotePlayer();
  105. break;
  106. default:
  107. id = uint.MaxValue;
  108. break;
  109. }
  110. if (id == uint.MaxValue)
  111. {
  112. throw new PlayerNotFoundException($"No player of {player} type exists");
  113. }
  114. return new EGID(id, CharacterExclusiveGroups.OnFootGroup);
  115. })
  116. {
  117. this.Type = player;
  118. Id = base.Id.entityID;
  119. }
  120. // object fields & properties
  121. /// <summary>
  122. /// The player's type.
  123. /// The player type is always relative to the current client, not the game host.
  124. /// </summary>
  125. /// <value>The enumerated player type.</value>
  126. public PlayerType Type { get; }
  127. /// <summary>
  128. /// The player's unique identifier.
  129. /// </summary>
  130. /// <value>The identifier.</value>
  131. public new uint Id { get; }
  132. /// <summary>
  133. /// The player's current position.
  134. /// </summary>
  135. /// <value>The position.</value>
  136. public float3 Position
  137. {
  138. get => playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().position;
  139. set => playerEngine.SetLocation(Id, value, false);
  140. }
  141. /// <summary>
  142. /// The player's current rotation.
  143. /// </summary>
  144. /// <value>The rotation.</value>
  145. public float3 Rotation
  146. {
  147. get => ((Quaternion) (GameState.IsBuildMode()
  148. ? playerEngine.GetCameraStruct<CameraEntityStruct>(Id).Get().rotation
  149. : playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().rotation)).eulerAngles;
  150. set => _ = GameState.IsBuildMode()
  151. ? playerEngine.GetCameraStruct<CameraEntityStruct>(Id).Get().rotation = quaternion.Euler(value)
  152. : playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().rotation = quaternion.Euler(value);
  153. }
  154. /// <summary>
  155. /// The player's current velocity.
  156. /// </summary>
  157. /// <value>The velocity.</value>
  158. public float3 Velocity
  159. {
  160. get => playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().velocity;
  161. set => playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().velocity = value;
  162. }
  163. /// <summary>
  164. /// The player's current angular velocity.
  165. /// </summary>
  166. /// <value>The angular velocity.</value>
  167. public float3 AngularVelocity
  168. {
  169. get => playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().angularVelocity;
  170. set => playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().angularVelocity = value;
  171. }
  172. /// <summary>
  173. /// The player's mass.
  174. /// </summary>
  175. /// <value>The mass.</value>
  176. public float Mass =>
  177. 1f / playerEngine.GetCharacterStruct<RigidBodyEntityStruct>(Id).Get().physicsMass.InverseMass;
  178. /// <summary>
  179. /// The player's latest network ping time.
  180. /// </summary>
  181. /// <value>The ping (s).</value>
  182. public float Ping
  183. {
  184. get
  185. {
  186. return playerEngine.GetPing() / 1000f;
  187. }
  188. }
  189. /// <summary>
  190. /// The player's initial health when entering Simulation (aka Time Running) mode.
  191. /// </summary>
  192. /// <value>The initial health.</value>
  193. public float InitialHealth
  194. {
  195. get
  196. {
  197. var opt = playerEngine.GetCharacterStruct<CharacterHealthEntityStruct>(Id);
  198. return opt ? opt.Get().initialHealth : -1f;
  199. }
  200. set => playerEngine.GetCharacterStruct<CharacterHealthEntityStruct>(Id).Get().initialHealth = value;
  201. }
  202. /// <summary>
  203. /// The player's current health in Simulation (aka Time Running) mode.
  204. /// </summary>
  205. /// <value>The current health.</value>
  206. public float CurrentHealth
  207. {
  208. get
  209. {
  210. var opt = playerEngine.GetCharacterStruct<CharacterHealthEntityStruct>(Id);
  211. return opt ? opt.Get().currentHealth : -1f;
  212. }
  213. set => playerEngine.GetCharacterStruct<CharacterHealthEntityStruct>(Id).Get().currentHealth = value;
  214. }
  215. /// <summary>
  216. /// Whether this <see cref="T:TechbloxModdingAPI.Player"/> is damageable.
  217. /// </summary>
  218. /// <value><c>true</c> if damageable; otherwise, <c>false</c>.</value>
  219. public bool Damageable
  220. {
  221. get
  222. {
  223. var opt = playerEngine.GetCharacterStruct<CharacterHealthEntityStruct>(Id);
  224. return opt.Get().canTakeDamageStat;
  225. }
  226. set
  227. {
  228. ref var healthStruct = ref playerEngine.GetCharacterStruct<CharacterHealthEntityStruct>(Id).Get();
  229. healthStruct.canTakeDamage = value;
  230. healthStruct.canTakeDamageStat = value;
  231. }
  232. }
  233. /// <summary>
  234. /// The player's lives when initially entering Simulation (aka Time Running) mode.
  235. /// </summary>
  236. /// <value>The initial lives.</value>
  237. public uint InitialLives
  238. {
  239. get
  240. {
  241. var opt = playerEngine.GetCharacterStruct<CharacterLivesEntityComponent>(Id);
  242. return opt ? opt.Get().initialLives : uint.MaxValue;
  243. }
  244. set => playerEngine.GetCharacterStruct<CharacterLivesEntityComponent>(Id).Get().initialLives = value;
  245. }
  246. /// <summary>
  247. /// The player's current lives in Simulation (aka Time Running) mode.
  248. /// </summary>
  249. /// <value>The current lives.</value>
  250. public uint CurrentLives
  251. {
  252. get
  253. {
  254. var opt = playerEngine.GetCharacterStruct<CharacterLivesEntityComponent>(Id);
  255. return opt ? opt.Get().currentLives : uint.MaxValue;
  256. }
  257. set => playerEngine.GetCharacterStruct<CharacterLivesEntityComponent>(Id).Get().currentLives = value;
  258. }
  259. /*/// <summary>
  260. /// Whether the Game Over screen is displayed for the player.
  261. /// </summary>
  262. /// <value><c>true</c> if game over; otherwise, <c>false</c>.</value>
  263. public bool GameOver
  264. {
  265. get => playerEngine.GetGameOverScreen(Id);
  266. }*/
  267. /// <summary>
  268. /// Whether the player is dead.
  269. /// If <c>true</c>, hopefully it was quick.
  270. /// </summary>
  271. /// <value><c>true</c> if dead; otherwise, <c>false</c>.</value>
  272. public bool Dead
  273. {
  274. get => playerEngine.IsDead(Id);
  275. }
  276. /// <summary>
  277. /// The player's selected block ID in their hand.
  278. /// </summary>
  279. /// <value>The selected block.</value>
  280. public BlockIDs SelectedBlock
  281. {
  282. get
  283. {
  284. var optstruct = playerEngine.GetCharacterStruct<EquippedPartStruct>(Id);
  285. return optstruct ? (BlockIDs) optstruct.Get().selectedDBPartID : BlockIDs.Invalid;
  286. }
  287. }
  288. /// <summary>
  289. /// The player's selected block color in their hand.
  290. /// </summary>
  291. /// <value>The selected block's color.</value>
  292. public BlockColor SelectedColor
  293. {
  294. get
  295. {
  296. var optstruct = playerEngine.GetCharacterStruct<EquippedColourStruct>(Id);
  297. return optstruct ? new BlockColor(optstruct.Get().indexInPalette) : BlockColors.Default;
  298. }
  299. }
  300. /// <summary>
  301. /// The player's selected block colour in their hand.
  302. /// </summary>
  303. /// <value>The selected block's colour.</value>
  304. public BlockColor SelectedColour
  305. {
  306. get
  307. {
  308. var optstruct = playerEngine.GetCharacterStruct<EquippedColourStruct>(Id);
  309. return optstruct ? new BlockColor(optstruct.Get().indexInPalette) : BlockColors.Default;
  310. }
  311. }
  312. /// <summary>
  313. /// The player's selected blueprint in their hand. Set to null to clear. Dispose after usage.
  314. /// </summary>
  315. public Blueprint SelectedBlueprint
  316. {
  317. get
  318. {
  319. var lbiso = playerEngine.GetPlayerStruct<LocalBlueprintInputStruct>(Id, Type);
  320. return lbiso ? new Blueprint(lbiso.Get().selectedBlueprintId) : null;
  321. }
  322. set => BlockGroup._engine.SelectBlueprint(value?.Id ?? uint.MaxValue);
  323. }
  324. /// <summary>
  325. /// The player's mode in time stopped mode, determining what they place.
  326. /// </summary>
  327. public PlayerBuildingMode BuildingMode => (PlayerBuildingMode)Math.Log((double)playerEngine
  328. .GetCharacterStruct<TimeStoppedModeComponent>(Id).Get().timeStoppedContext, 2); // It's a bit field in game now
  329. public PlayerState State =>
  330. playerEngine.GetCharacterStruct<CharacterTagEntityStruct>(Id).Get().ID.groupID switch
  331. {
  332. var group when group == CharacterExclusiveGroups.MachineSpawningGroup => PlayerState.HoldingMachine,
  333. var group when group == CharacterExclusiveGroups.OnFootGroup => PlayerState.OnFoot,
  334. var group when group == CharacterExclusiveGroups.InPilotSeatGroup => PlayerState.InSeat,
  335. _ => throw new ArgumentOutOfRangeException("", "Unknown player state")
  336. };
  337. /// <summary>
  338. /// Whether the player is sprinting.
  339. /// </summary>
  340. public bool Sprinting
  341. {
  342. get => GameState.IsBuildMode()
  343. ? playerEngine.GetCharacterStruct<BuildingDroneMovementComponent>(Id).Get().sprinting
  344. : playerEngine.GetCharacterStruct<CharacterMovementEntityStruct>(Id).Get().isSprinting;
  345. set => _ = GameState.IsBuildMode()
  346. ? playerEngine.GetCharacterStruct<BuildingDroneMovementComponent>(Id).Get().sprinting = value
  347. : playerEngine.GetCharacterStruct<CharacterMovementEntityStruct>(Id).Get().isSprinting = value;
  348. }
  349. /// <summary>
  350. /// Movement speed setting. Build mode (camera) and simulation mode settings are separate.
  351. /// </summary>
  352. public float SpeedSetting
  353. {
  354. get => GameState.IsBuildMode()
  355. ? playerEngine.GetCharacterStruct<BuildingDroneMovementSettingsComponent>(Id).Get().speed
  356. : playerEngine.GetCharacterStruct<CharacterMovementSettingsEntityStruct>(Id).Get().moveSpeed;
  357. set => _ = GameState.IsBuildMode()
  358. ? playerEngine.GetCharacterStruct<BuildingDroneMovementSettingsComponent>(Id).Get().speed = value
  359. : playerEngine.GetCharacterStruct<CharacterMovementSettingsEntityStruct>(Id).Get().moveSpeed = value;
  360. }
  361. /// <summary>
  362. /// The multiplier setting to use when sprinting. Build mode (camera) and simulation mode settings are separate.
  363. /// </summary>
  364. public float SpeedSprintMultiplierSetting
  365. {
  366. get => GameState.IsBuildMode()
  367. ? playerEngine.GetCharacterStruct<BuildingDroneMovementSettingsComponent>(Id).Get().speedSprintMultiplier
  368. : playerEngine.GetCharacterStruct<CharacterMovementSettingsEntityStruct>(Id).Get().sprintSpeedMultiplier;
  369. set => _ = GameState.IsBuildMode()
  370. ? playerEngine.GetCharacterStruct<BuildingDroneMovementSettingsComponent>(Id).Get().speedSprintMultiplier = value
  371. : playerEngine.GetCharacterStruct<CharacterMovementSettingsEntityStruct>(Id).Get().sprintSpeedMultiplier = value;
  372. }
  373. /// <summary>
  374. /// The acceleration setting of the player. Build mode (camera) and simulation mode settings are separate.
  375. /// </summary>
  376. public float AccelerationSetting
  377. {
  378. get => GameState.IsBuildMode()
  379. ? playerEngine.GetCharacterStruct<BuildingDroneMovementSettingsComponent>(Id).Get().acceleration
  380. : playerEngine.GetCharacterStruct<CharacterMovementSettingsEntityStruct>(Id).Get().acceleration;
  381. set => _ = GameState.IsBuildMode()
  382. ? playerEngine.GetCharacterStruct<BuildingDroneMovementSettingsComponent>(Id).Get().acceleration = value
  383. : playerEngine.GetCharacterStruct<CharacterMovementSettingsEntityStruct>(Id).Get().acceleration = value;
  384. }
  385. // object methods
  386. /// <summary>
  387. /// Teleport the player to the specified coordinates.
  388. /// </summary>
  389. /// <param name="x">The x coordinate.</param>
  390. /// <param name="y">The y coordinate.</param>
  391. /// <param name="z">The z coordinate.</param>
  392. /// <param name="relative">If set to <c>true</c> teleport relative to the player's current position.</param>
  393. /// <param name="exitSeat">If set to <c>true</c> exit any seat the player is in.</param>
  394. public void Teleport(float x, float y, float z, bool relative = true, bool exitSeat = true)
  395. {
  396. float3 location = new float3(x, y, z);
  397. if (relative)
  398. {
  399. location += Position;
  400. }
  401. playerEngine.SetLocation(Id, location, exitSeat: exitSeat);
  402. }
  403. /// <summary>
  404. /// Enter the given seat.
  405. /// </summary>
  406. /// <param name="seat">The seat to enter.</param>
  407. public void EnterSeat(Seat seat)
  408. {
  409. playerEngine.EnterSeat(Id, seat.Id);
  410. }
  411. /// <summary>
  412. /// Exit the seat the player is currently in.
  413. /// </summary>
  414. public void ExitSeat()
  415. {
  416. playerEngine.ExitSeat(Id);
  417. }
  418. /// <summary>
  419. /// Spawn the machine the player is holding in time running mode.
  420. /// </summary>
  421. public bool SpawnMachine()
  422. {
  423. return playerEngine.SpawnMachine(Id);
  424. }
  425. /// <summary>
  426. /// Despawn the player's machine in time running mode and place it in their hand.
  427. /// </summary>
  428. public bool DespawnMachine()
  429. {
  430. return playerEngine.DespawnMachine(Id);
  431. }
  432. /// <summary>
  433. /// Returns the block the player is currently looking at in build mode.
  434. /// </summary>
  435. /// <param name="maxDistance">The maximum distance from the player (default is the player's building reach)</param>
  436. /// <returns>The block or null if not found</returns>
  437. public Block GetBlockLookedAt(float maxDistance = -1f)
  438. {
  439. var egid = playerEngine.GetThingLookedAt(Id, maxDistance);
  440. return egid != default && egid.groupID != CommonExclusiveGroups.SIMULATION_BODIES_GROUP
  441. && egid.groupID != WiresGUIExclusiveGroups.WireGroup
  442. ? Block.New(egid)
  443. : null;
  444. }
  445. /// <summary>
  446. /// Returns the rigid body the player is currently looking at during simulation.
  447. /// </summary>
  448. /// <param name="maxDistance">The maximum distance from the player (default is the player's building reach)</param>
  449. /// <returns>The body or null if not found</returns>
  450. public SimBody GetSimBodyLookedAt(float maxDistance = -1f)
  451. {
  452. var egid = playerEngine.GetThingLookedAt(Id, maxDistance);
  453. return egid != default && egid.groupID == CommonExclusiveGroups.SIMULATION_BODIES_GROUP
  454. ? EcsObjectBase.GetInstance(egid, e => new SimBody(e))
  455. : null;
  456. }
  457. /// <summary>
  458. /// Returns the wire the player is currently looking at in build mode.
  459. /// </summary>
  460. /// <param name="maxDistance">The maximum distance from the player (default is the player's building reach)</param>
  461. /// <returns>The wire or null if not found</returns>
  462. public Wire GetWireLookedAt(float maxDistance = -1f)
  463. {
  464. var egid = playerEngine.GetThingLookedAt(Id, maxDistance);
  465. return egid != default && egid.groupID == WiresGUIExclusiveGroups.WireGroup
  466. ? EcsObjectBase.GetInstance(new EGID(egid.entityID, BuildModeWiresGroups.WiresGroup.Group),
  467. e => new Wire(e))
  468. : null;
  469. }
  470. /// <summary>
  471. /// Returns the blocks that are in the player's current selection.
  472. /// </summary>
  473. /// <returns>An array of blocks or an empty array</returns>
  474. public Block[] GetSelectedBlocks()
  475. {
  476. return playerEngine.GetSelectedBlocks(Id);
  477. }
  478. public bool Equals(Player other)
  479. {
  480. if (ReferenceEquals(null, other)) return false;
  481. if (ReferenceEquals(this, other)) return true;
  482. return Id == other.Id;
  483. }
  484. public bool Equals(EGID other)
  485. {
  486. return Id == other.entityID && other.groupID == (Type == PlayerType.Local
  487. ? PlayersExclusiveGroups.LocalPlayers
  488. : PlayersExclusiveGroups.RemotePlayers);
  489. }
  490. public override bool Equals(object obj)
  491. {
  492. if (ReferenceEquals(null, obj)) return false;
  493. if (ReferenceEquals(this, obj)) return true;
  494. if (obj.GetType() != this.GetType()) return false;
  495. return Equals((Player) obj);
  496. }
  497. public override int GetHashCode()
  498. {
  499. return (int) Id;
  500. }
  501. public override string ToString()
  502. {
  503. return $"{nameof(Type)}: {Type}, {nameof(Id)}: {Id}, {nameof(Position)}: {Position}, {nameof(Rotation)}: {Rotation}, {nameof(Mass)}: {Mass}";
  504. }
  505. // internal methods
  506. internal static void Init()
  507. {
  508. Utility.GameEngineManager.AddGameEngine(playerEngine);
  509. Utility.GameEngineManager.AddGameEngine(playerEventsEngine);
  510. }
  511. }
  512. }