ThrusterSystem.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. using System.Numerics;
  2. using Content.Server.Audio;
  3. using Content.Server.Power.Components;
  4. using Content.Server.Power.EntitySystems;
  5. using Content.Server.Shuttles.Components;
  6. using Content.Shared.Damage;
  7. using Content.Shared.Examine;
  8. using Content.Shared.Interaction;
  9. using Content.Shared.Maps;
  10. using Content.Shared.Physics;
  11. using Content.Shared.Shuttles.Components;
  12. using Content.Shared.Temperature;
  13. using Robust.Shared.Map;
  14. using Robust.Shared.Map.Components;
  15. using Robust.Shared.Physics.Collision.Shapes;
  16. using Robust.Shared.Physics.Components;
  17. using Robust.Shared.Physics.Events;
  18. using Robust.Shared.Physics.Systems;
  19. using Robust.Shared.Timing;
  20. using Robust.Shared.Utility;
  21. using Content.Shared.Localizations;
  22. using Content.Shared.Power;
  23. namespace Content.Server.Shuttles.Systems;
  24. public sealed class ThrusterSystem : EntitySystem
  25. {
  26. [Dependency] private readonly IGameTiming _timing = default!;
  27. [Dependency] private readonly ITileDefinitionManager _tileDefManager = default!;
  28. [Dependency] private readonly SharedMapSystem _mapSystem = default!;
  29. [Dependency] private readonly AmbientSoundSystem _ambient = default!;
  30. [Dependency] private readonly FixtureSystem _fixtureSystem = default!;
  31. [Dependency] private readonly DamageableSystem _damageable = default!;
  32. [Dependency] private readonly SharedPointLightSystem _light = default!;
  33. [Dependency] private readonly SharedAppearanceSystem _appearance = default!;
  34. // Essentially whenever thruster enables we update the shuttle's available impulses which are used for movement.
  35. // This is done for each direction available.
  36. public const string BurnFixture = "thruster-burn";
  37. public override void Initialize()
  38. {
  39. base.Initialize();
  40. SubscribeLocalEvent<ThrusterComponent, ActivateInWorldEvent>(OnActivateThruster);
  41. SubscribeLocalEvent<ThrusterComponent, ComponentInit>(OnThrusterInit);
  42. SubscribeLocalEvent<ThrusterComponent, MapInitEvent>(OnMapInit);
  43. SubscribeLocalEvent<ThrusterComponent, ComponentShutdown>(OnThrusterShutdown);
  44. SubscribeLocalEvent<ThrusterComponent, PowerChangedEvent>(OnPowerChange);
  45. SubscribeLocalEvent<ThrusterComponent, AnchorStateChangedEvent>(OnAnchorChange);
  46. SubscribeLocalEvent<ThrusterComponent, MoveEvent>(OnRotate);
  47. SubscribeLocalEvent<ThrusterComponent, IsHotEvent>(OnIsHotEvent);
  48. SubscribeLocalEvent<ThrusterComponent, StartCollideEvent>(OnStartCollide);
  49. SubscribeLocalEvent<ThrusterComponent, EndCollideEvent>(OnEndCollide);
  50. SubscribeLocalEvent<ThrusterComponent, ExaminedEvent>(OnThrusterExamine);
  51. SubscribeLocalEvent<ShuttleComponent, TileChangedEvent>(OnShuttleTileChange);
  52. }
  53. private void OnThrusterExamine(EntityUid uid, ThrusterComponent component, ExaminedEvent args)
  54. {
  55. // Powered is already handled by other power components
  56. var enabled = Loc.GetString(component.Enabled ? "thruster-comp-enabled" : "thruster-comp-disabled");
  57. using (args.PushGroup(nameof(ThrusterComponent)))
  58. {
  59. args.PushMarkup(enabled);
  60. if (component.Type == ThrusterType.Linear &&
  61. EntityManager.TryGetComponent(uid, out TransformComponent? xform) &&
  62. xform.Anchored)
  63. {
  64. var nozzleLocalization = ContentLocalizationManager.FormatDirection(xform.LocalRotation.Opposite().ToWorldVec().GetDir()).ToLower();
  65. var nozzleDir = Loc.GetString("thruster-comp-nozzle-direction",
  66. ("direction", nozzleLocalization));
  67. args.PushMarkup(nozzleDir);
  68. var exposed = NozzleExposed(xform);
  69. var nozzleText =
  70. Loc.GetString(exposed ? "thruster-comp-nozzle-exposed" : "thruster-comp-nozzle-not-exposed");
  71. args.PushMarkup(nozzleText);
  72. }
  73. }
  74. }
  75. private void OnIsHotEvent(EntityUid uid, ThrusterComponent component, IsHotEvent args)
  76. {
  77. args.IsHot = component.Type != ThrusterType.Angular && component.IsOn;
  78. }
  79. private void OnShuttleTileChange(EntityUid uid, ShuttleComponent component, ref TileChangedEvent args)
  80. {
  81. // If the old tile was space but the new one isn't then disable all adjacent thrusters
  82. if (args.NewTile.IsSpace(_tileDefManager) || !args.OldTile.IsSpace(_tileDefManager))
  83. return;
  84. var tilePos = args.NewTile.GridIndices;
  85. var grid = Comp<MapGridComponent>(uid);
  86. var xformQuery = GetEntityQuery<TransformComponent>();
  87. var thrusterQuery = GetEntityQuery<ThrusterComponent>();
  88. for (var x = -1; x <= 1; x++)
  89. {
  90. for (var y = -1; y <= 1; y++)
  91. {
  92. if (x != 0 && y != 0)
  93. continue;
  94. var checkPos = tilePos + new Vector2i(x, y);
  95. var enumerator = _mapSystem.GetAnchoredEntitiesEnumerator(uid, grid, checkPos);
  96. while (enumerator.MoveNext(out var ent))
  97. {
  98. if (!thrusterQuery.TryGetComponent(ent.Value, out var thruster) || !thruster.RequireSpace)
  99. continue;
  100. // Work out if the thruster is facing this direction
  101. var xform = xformQuery.GetComponent(ent.Value);
  102. var direction = xform.LocalRotation.ToWorldVec();
  103. if (new Vector2i((int)direction.X, (int)direction.Y) != new Vector2i(x, y))
  104. continue;
  105. DisableThruster(ent.Value, thruster, xform.GridUid);
  106. }
  107. }
  108. }
  109. }
  110. private void OnActivateThruster(EntityUid uid, ThrusterComponent component, ActivateInWorldEvent args)
  111. {
  112. if (args.Handled || !args.Complex)
  113. return;
  114. component.Enabled ^= true;
  115. if (!component.Enabled)
  116. {
  117. DisableThruster(uid, component);
  118. args.Handled = true;
  119. }
  120. else if (CanEnable(uid, component))
  121. {
  122. EnableThruster(uid, component);
  123. args.Handled = true;
  124. }
  125. }
  126. /// <summary>
  127. /// If the thruster rotates change the direction where the linear thrust is applied
  128. /// </summary>
  129. private void OnRotate(EntityUid uid, ThrusterComponent component, ref MoveEvent args)
  130. {
  131. // TODO: Disable visualizer for old direction
  132. // TODO: Don't make them rotatable and make it require anchoring.
  133. if (!component.Enabled ||
  134. !EntityManager.TryGetComponent(uid, out TransformComponent? xform) ||
  135. !EntityManager.TryGetComponent(xform.GridUid, out ShuttleComponent? shuttleComponent))
  136. {
  137. return;
  138. }
  139. var canEnable = CanEnable(uid, component);
  140. // If it's not on then don't enable it inadvertantly (given we don't have an old rotation)
  141. if (!canEnable && !component.IsOn)
  142. return;
  143. // Enable it if it was turned off but new tile is valid
  144. if (!component.IsOn && canEnable)
  145. {
  146. EnableThruster(uid, component);
  147. return;
  148. }
  149. // Disable if new tile invalid
  150. if (component.IsOn && !canEnable)
  151. {
  152. DisableThruster(uid, component, args.OldPosition.EntityId, xform, args.OldRotation);
  153. return;
  154. }
  155. var oldDirection = (int)args.OldRotation.GetCardinalDir() / 2;
  156. var direction = (int)args.NewRotation.GetCardinalDir() / 2;
  157. var oldShuttleComponent = shuttleComponent;
  158. if (args.ParentChanged)
  159. {
  160. oldShuttleComponent = Comp<ShuttleComponent>(args.OldPosition.EntityId);
  161. // If no parent change doesn't matter for angular.
  162. if (component.Type == ThrusterType.Angular)
  163. {
  164. oldShuttleComponent.AngularThrust -= component.Thrust;
  165. DebugTools.Assert(oldShuttleComponent.AngularThrusters.Contains(uid));
  166. oldShuttleComponent.AngularThrusters.Remove(uid);
  167. shuttleComponent.AngularThrust += component.Thrust;
  168. DebugTools.Assert(!shuttleComponent.AngularThrusters.Contains(uid));
  169. shuttleComponent.AngularThrusters.Add(uid);
  170. return;
  171. }
  172. }
  173. if (component.Type == ThrusterType.Linear)
  174. {
  175. oldShuttleComponent.LinearThrust[oldDirection] -= component.Thrust;
  176. DebugTools.Assert(oldShuttleComponent.LinearThrusters[oldDirection].Contains(uid));
  177. oldShuttleComponent.LinearThrusters[oldDirection].Remove(uid);
  178. shuttleComponent.LinearThrust[direction] += component.Thrust;
  179. DebugTools.Assert(!shuttleComponent.LinearThrusters[direction].Contains(uid));
  180. shuttleComponent.LinearThrusters[direction].Add(uid);
  181. }
  182. }
  183. private void OnAnchorChange(EntityUid uid, ThrusterComponent component, ref AnchorStateChangedEvent args)
  184. {
  185. if (args.Anchored && CanEnable(uid, component))
  186. {
  187. EnableThruster(uid, component);
  188. }
  189. else
  190. {
  191. DisableThruster(uid, component);
  192. }
  193. }
  194. private void OnThrusterInit(EntityUid uid, ThrusterComponent component, ComponentInit args)
  195. {
  196. _ambient.SetAmbience(uid, false);
  197. if (!component.Enabled)
  198. {
  199. return;
  200. }
  201. if (CanEnable(uid, component))
  202. {
  203. EnableThruster(uid, component);
  204. }
  205. }
  206. private void OnMapInit(Entity<ThrusterComponent> ent, ref MapInitEvent args)
  207. {
  208. ent.Comp.NextFire = _timing.CurTime + ent.Comp.FireCooldown;
  209. }
  210. private void OnThrusterShutdown(EntityUid uid, ThrusterComponent component, ComponentShutdown args)
  211. {
  212. DisableThruster(uid, component);
  213. }
  214. private void OnPowerChange(EntityUid uid, ThrusterComponent component, ref PowerChangedEvent args)
  215. {
  216. if (args.Powered && CanEnable(uid, component))
  217. {
  218. EnableThruster(uid, component);
  219. }
  220. else
  221. {
  222. DisableThruster(uid, component);
  223. }
  224. }
  225. /// <summary>
  226. /// Tries to enable the thruster and turn it on. If it's already enabled it does nothing.
  227. /// </summary>
  228. public void EnableThruster(EntityUid uid, ThrusterComponent component, TransformComponent? xform = null)
  229. {
  230. if (component.IsOn ||
  231. !Resolve(uid, ref xform))
  232. {
  233. return;
  234. }
  235. component.IsOn = true;
  236. if (!EntityManager.TryGetComponent(xform.GridUid, out ShuttleComponent? shuttleComponent))
  237. return;
  238. // Logger.DebugS("thruster", $"Enabled thruster {uid}");
  239. switch (component.Type)
  240. {
  241. case ThrusterType.Linear:
  242. var direction = (int)xform.LocalRotation.GetCardinalDir() / 2;
  243. shuttleComponent.LinearThrust[direction] += component.Thrust;
  244. DebugTools.Assert(!shuttleComponent.LinearThrusters[direction].Contains(uid));
  245. shuttleComponent.LinearThrusters[direction].Add(uid);
  246. // Don't just add / remove the fixture whenever the thruster fires because perf
  247. if (EntityManager.TryGetComponent(uid, out PhysicsComponent? physicsComponent) &&
  248. component.BurnPoly.Count > 0)
  249. {
  250. var shape = new PolygonShape();
  251. shape.Set(component.BurnPoly);
  252. _fixtureSystem.TryCreateFixture(uid, shape, BurnFixture, hard: false, collisionLayer: (int)CollisionGroup.FullTileMask, body: physicsComponent);
  253. }
  254. break;
  255. case ThrusterType.Angular:
  256. shuttleComponent.AngularThrust += component.Thrust;
  257. DebugTools.Assert(!shuttleComponent.AngularThrusters.Contains(uid));
  258. shuttleComponent.AngularThrusters.Add(uid);
  259. break;
  260. default:
  261. throw new ArgumentOutOfRangeException();
  262. }
  263. if (EntityManager.TryGetComponent(uid, out AppearanceComponent? appearance))
  264. {
  265. _appearance.SetData(uid, ThrusterVisualState.State, true, appearance);
  266. }
  267. if (_light.TryGetLight(uid, out var pointLightComponent))
  268. {
  269. _light.SetEnabled(uid, true, pointLightComponent);
  270. }
  271. _ambient.SetAmbience(uid, true);
  272. RefreshCenter(uid, shuttleComponent);
  273. }
  274. /// <summary>
  275. /// Refreshes the center of thrust for movement calculations.
  276. /// </summary>
  277. private void RefreshCenter(EntityUid uid, ShuttleComponent shuttle)
  278. {
  279. // TODO: Only refresh relevant directions.
  280. var center = Vector2.Zero;
  281. var thrustQuery = GetEntityQuery<ThrusterComponent>();
  282. var xformQuery = GetEntityQuery<TransformComponent>();
  283. foreach (var dir in new[]
  284. { Direction.South, Direction.East, Direction.North, Direction.West })
  285. {
  286. var index = (int)dir / 2;
  287. var pop = shuttle.LinearThrusters[index];
  288. var totalThrust = 0f;
  289. foreach (var ent in pop)
  290. {
  291. if (!thrustQuery.TryGetComponent(ent, out var thruster) || !xformQuery.TryGetComponent(ent, out var xform))
  292. continue;
  293. center += xform.LocalPosition * thruster.Thrust;
  294. totalThrust += thruster.Thrust;
  295. }
  296. center /= pop.Count * totalThrust;
  297. shuttle.CenterOfThrust[index] = center;
  298. }
  299. }
  300. public void DisableThruster(EntityUid uid, ThrusterComponent component, TransformComponent? xform = null, Angle? angle = null)
  301. {
  302. if (!Resolve(uid, ref xform)) return;
  303. DisableThruster(uid, component, xform.GridUid, xform);
  304. }
  305. /// <summary>
  306. /// Tries to disable the thruster.
  307. /// </summary>
  308. public void DisableThruster(EntityUid uid, ThrusterComponent component, EntityUid? gridId, TransformComponent? xform = null, Angle? angle = null)
  309. {
  310. if (!component.IsOn ||
  311. !Resolve(uid, ref xform))
  312. {
  313. return;
  314. }
  315. component.IsOn = false;
  316. if (!EntityManager.TryGetComponent(gridId, out ShuttleComponent? shuttleComponent))
  317. return;
  318. // Logger.DebugS("thruster", $"Disabled thruster {uid}");
  319. switch (component.Type)
  320. {
  321. case ThrusterType.Linear:
  322. angle ??= xform.LocalRotation;
  323. var direction = (int)angle.Value.GetCardinalDir() / 2;
  324. shuttleComponent.LinearThrust[direction] -= component.Thrust;
  325. DebugTools.Assert(shuttleComponent.LinearThrusters[direction].Contains(uid));
  326. shuttleComponent.LinearThrusters[direction].Remove(uid);
  327. break;
  328. case ThrusterType.Angular:
  329. shuttleComponent.AngularThrust -= component.Thrust;
  330. DebugTools.Assert(shuttleComponent.AngularThrusters.Contains(uid));
  331. shuttleComponent.AngularThrusters.Remove(uid);
  332. break;
  333. default:
  334. throw new ArgumentOutOfRangeException();
  335. }
  336. if (EntityManager.TryGetComponent(uid, out AppearanceComponent? appearance))
  337. {
  338. _appearance.SetData(uid, ThrusterVisualState.State, false, appearance);
  339. }
  340. if (_light.TryGetLight(uid, out var pointLightComponent))
  341. {
  342. _light.SetEnabled(uid, false, pointLightComponent);
  343. }
  344. _ambient.SetAmbience(uid, false);
  345. if (EntityManager.TryGetComponent(uid, out PhysicsComponent? physicsComponent))
  346. {
  347. _fixtureSystem.DestroyFixture(uid, BurnFixture, body: physicsComponent);
  348. }
  349. component.Colliding.Clear();
  350. RefreshCenter(uid, shuttleComponent);
  351. }
  352. public bool CanEnable(EntityUid uid, ThrusterComponent component)
  353. {
  354. if (!component.Enabled)
  355. return false;
  356. if (component.LifeStage > ComponentLifeStage.Running)
  357. return false;
  358. var xform = Transform(uid);
  359. if (!xform.Anchored || !this.IsPowered(uid, EntityManager))
  360. {
  361. return false;
  362. }
  363. if (!component.RequireSpace)
  364. return true;
  365. return NozzleExposed(xform);
  366. }
  367. private bool NozzleExposed(TransformComponent xform)
  368. {
  369. if (xform.GridUid == null)
  370. return true;
  371. var (x, y) = xform.LocalPosition + xform.LocalRotation.Opposite().ToWorldVec();
  372. var mapGrid = Comp<MapGridComponent>(xform.GridUid.Value);
  373. var tile = _mapSystem.GetTileRef(xform.GridUid.Value, mapGrid, new Vector2i((int)Math.Floor(x), (int)Math.Floor(y)));
  374. return tile.Tile.IsSpace();
  375. }
  376. #region Burning
  377. public override void Update(float frameTime)
  378. {
  379. base.Update(frameTime);
  380. var query = EntityQueryEnumerator<ThrusterComponent>();
  381. var curTime = _timing.CurTime;
  382. while (query.MoveNext(out var comp))
  383. {
  384. if (comp.NextFire > curTime)
  385. continue;
  386. comp.NextFire += comp.FireCooldown;
  387. if (!comp.Firing || comp.Colliding.Count == 0 || comp.Damage == null)
  388. continue;
  389. foreach (var uid in comp.Colliding.ToArray())
  390. {
  391. _damageable.TryChangeDamage(uid, comp.Damage);
  392. }
  393. }
  394. }
  395. private void OnStartCollide(EntityUid uid, ThrusterComponent component, ref StartCollideEvent args)
  396. {
  397. if (args.OurFixtureId != BurnFixture)
  398. return;
  399. component.Colliding.Add(args.OtherEntity);
  400. }
  401. private void OnEndCollide(EntityUid uid, ThrusterComponent component, ref EndCollideEvent args)
  402. {
  403. if (args.OurFixtureId != BurnFixture)
  404. return;
  405. component.Colliding.Remove(args.OtherEntity);
  406. }
  407. /// <summary>
  408. /// Considers a thrust direction as being active.
  409. /// </summary>
  410. public void EnableLinearThrustDirection(ShuttleComponent component, DirectionFlag direction)
  411. {
  412. if ((component.ThrustDirections & direction) != 0x0)
  413. return;
  414. component.ThrustDirections |= direction;
  415. var index = GetFlagIndex(direction);
  416. var appearanceQuery = GetEntityQuery<AppearanceComponent>();
  417. var thrusterQuery = GetEntityQuery<ThrusterComponent>();
  418. foreach (var uid in component.LinearThrusters[index])
  419. {
  420. if (!thrusterQuery.TryGetComponent(uid, out var comp))
  421. continue;
  422. comp.Firing = true;
  423. appearanceQuery.TryGetComponent(uid, out var appearance);
  424. _appearance.SetData(uid, ThrusterVisualState.Thrusting, true, appearance);
  425. }
  426. }
  427. /// <summary>
  428. /// Disables a thrust direction.
  429. /// </summary>
  430. public void DisableLinearThrustDirection(ShuttleComponent component, DirectionFlag direction)
  431. {
  432. if ((component.ThrustDirections & direction) == 0x0)
  433. return;
  434. component.ThrustDirections &= ~direction;
  435. var index = GetFlagIndex(direction);
  436. var appearanceQuery = GetEntityQuery<AppearanceComponent>();
  437. var thrusterQuery = GetEntityQuery<ThrusterComponent>();
  438. foreach (var uid in component.LinearThrusters[index])
  439. {
  440. if (!thrusterQuery.TryGetComponent(uid, out var comp))
  441. continue;
  442. appearanceQuery.TryGetComponent(uid, out var appearance);
  443. comp.Firing = false;
  444. _appearance.SetData(uid, ThrusterVisualState.Thrusting, false, appearance);
  445. }
  446. }
  447. public void DisableLinearThrusters(ShuttleComponent component)
  448. {
  449. foreach (DirectionFlag dir in Enum.GetValues(typeof(DirectionFlag)))
  450. {
  451. DisableLinearThrustDirection(component, dir);
  452. }
  453. DebugTools.Assert(component.ThrustDirections == DirectionFlag.None);
  454. }
  455. public void SetAngularThrust(ShuttleComponent component, bool on)
  456. {
  457. var appearanceQuery = GetEntityQuery<AppearanceComponent>();
  458. var thrusterQuery = GetEntityQuery<ThrusterComponent>();
  459. if (on)
  460. {
  461. foreach (var uid in component.AngularThrusters)
  462. {
  463. if (!thrusterQuery.TryGetComponent(uid, out var comp))
  464. continue;
  465. appearanceQuery.TryGetComponent(uid, out var appearance);
  466. comp.Firing = true;
  467. _appearance.SetData(uid, ThrusterVisualState.Thrusting, true, appearance);
  468. }
  469. }
  470. else
  471. {
  472. foreach (var uid in component.AngularThrusters)
  473. {
  474. if (!thrusterQuery.TryGetComponent(uid, out var comp))
  475. continue;
  476. appearanceQuery.TryGetComponent(uid, out var appearance);
  477. comp.Firing = false;
  478. _appearance.SetData(uid, ThrusterVisualState.Thrusting, false, appearance);
  479. }
  480. }
  481. }
  482. #endregion
  483. private int GetFlagIndex(DirectionFlag flag)
  484. {
  485. return (int)Math.Log2((int)flag);
  486. }
  487. }