AtmosAlertsComputerSystem.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using Content.Server.Atmos.Monitor.Components;
  2. using Content.Server.DeviceNetwork.Components;
  3. using Content.Server.DeviceNetwork.Systems;
  4. using Content.Server.Pinpointer;
  5. using Content.Server.Power.Components;
  6. using Content.Shared.Atmos;
  7. using Content.Shared.Atmos.Components;
  8. using Content.Shared.Atmos.Consoles;
  9. using Content.Shared.Atmos.Monitor;
  10. using Content.Shared.Atmos.Monitor.Components;
  11. using Content.Shared.DeviceNetwork.Components;
  12. using Content.Shared.Pinpointer;
  13. using Robust.Server.GameObjects;
  14. using Robust.Shared.Map.Components;
  15. using System.Diagnostics.CodeAnalysis;
  16. using System.Linq;
  17. namespace Content.Server.Atmos.Monitor.Systems;
  18. public sealed class AtmosAlertsComputerSystem : SharedAtmosAlertsComputerSystem
  19. {
  20. [Dependency] private readonly UserInterfaceSystem _userInterfaceSystem = default!;
  21. [Dependency] private readonly AirAlarmSystem _airAlarmSystem = default!;
  22. [Dependency] private readonly AtmosDeviceNetworkSystem _atmosDevNet = default!;
  23. [Dependency] private readonly SharedAppearanceSystem _appearance = default!;
  24. [Dependency] private readonly MapSystem _mapSystem = default!;
  25. [Dependency] private readonly TransformSystem _transformSystem = default!;
  26. [Dependency] private readonly NavMapSystem _navMapSystem = default!;
  27. [Dependency] private readonly DeviceListSystem _deviceListSystem = default!;
  28. private const float UpdateTime = 1.0f;
  29. // Note: this data does not need to be saved
  30. private float _updateTimer = 1.0f;
  31. public override void Initialize()
  32. {
  33. base.Initialize();
  34. // Console events
  35. SubscribeLocalEvent<AtmosAlertsComputerComponent, ComponentInit>(OnConsoleInit);
  36. SubscribeLocalEvent<AtmosAlertsComputerComponent, EntParentChangedMessage>(OnConsoleParentChanged);
  37. SubscribeLocalEvent<AtmosAlertsComputerComponent, AtmosAlertsComputerFocusChangeMessage>(OnFocusChangedMessage);
  38. // Grid events
  39. SubscribeLocalEvent<GridSplitEvent>(OnGridSplit);
  40. // Alarm events
  41. SubscribeLocalEvent<AtmosAlertsDeviceComponent, EntityTerminatingEvent>(OnDeviceTerminatingEvent);
  42. SubscribeLocalEvent<AtmosAlertsDeviceComponent, AnchorStateChangedEvent>(OnDeviceAnchorChanged);
  43. }
  44. #region Event handling
  45. private void OnConsoleInit(EntityUid uid, AtmosAlertsComputerComponent component, ComponentInit args)
  46. {
  47. InitalizeConsole(uid, component);
  48. }
  49. private void OnConsoleParentChanged(EntityUid uid, AtmosAlertsComputerComponent component, EntParentChangedMessage args)
  50. {
  51. InitalizeConsole(uid, component);
  52. }
  53. private void OnFocusChangedMessage(EntityUid uid, AtmosAlertsComputerComponent component, AtmosAlertsComputerFocusChangeMessage args)
  54. {
  55. component.FocusDevice = args.FocusDevice;
  56. }
  57. private void OnGridSplit(ref GridSplitEvent args)
  58. {
  59. // Collect grids
  60. var allGrids = args.NewGrids.ToList();
  61. if (!allGrids.Contains(args.Grid))
  62. allGrids.Add(args.Grid);
  63. // Update atmos monitoring consoles that stand upon an updated grid
  64. var query = AllEntityQuery<AtmosAlertsComputerComponent, TransformComponent>();
  65. while (query.MoveNext(out var ent, out var entConsole, out var entXform))
  66. {
  67. if (entXform.GridUid == null)
  68. continue;
  69. if (!allGrids.Contains(entXform.GridUid.Value))
  70. continue;
  71. InitalizeConsole(ent, entConsole);
  72. }
  73. }
  74. private void OnDeviceAnchorChanged(EntityUid uid, AtmosAlertsDeviceComponent component, AnchorStateChangedEvent args)
  75. {
  76. OnDeviceAdditionOrRemoval(uid, component, args.Anchored);
  77. }
  78. private void OnDeviceTerminatingEvent(EntityUid uid, AtmosAlertsDeviceComponent component, ref EntityTerminatingEvent args)
  79. {
  80. OnDeviceAdditionOrRemoval(uid, component, false);
  81. }
  82. private void OnDeviceAdditionOrRemoval(EntityUid uid, AtmosAlertsDeviceComponent component, bool isAdding)
  83. {
  84. var xform = Transform(uid);
  85. var gridUid = xform.GridUid;
  86. if (gridUid == null)
  87. return;
  88. if (!TryComp<NavMapComponent>(xform.GridUid, out var navMap))
  89. return;
  90. if (!TryGetAtmosDeviceNavMapData(uid, component, xform, out var data))
  91. return;
  92. var netEntity = GetNetEntity(uid);
  93. var query = AllEntityQuery<AtmosAlertsComputerComponent, TransformComponent>();
  94. while (query.MoveNext(out var ent, out var entConsole, out var entXform))
  95. {
  96. if (gridUid != entXform.GridUid)
  97. continue;
  98. if (isAdding)
  99. {
  100. entConsole.AtmosDevices.Add(data.Value);
  101. }
  102. else
  103. {
  104. entConsole.AtmosDevices.RemoveWhere(x => x.NetEntity == netEntity);
  105. _navMapSystem.RemoveNavMapRegion(gridUid.Value, navMap, netEntity);
  106. }
  107. Dirty(ent, entConsole);
  108. }
  109. }
  110. #endregion
  111. public override void Update(float frameTime)
  112. {
  113. base.Update(frameTime);
  114. _updateTimer += frameTime;
  115. if (_updateTimer >= UpdateTime)
  116. {
  117. _updateTimer -= UpdateTime;
  118. // Keep a list of UI entries for each gridUid, in case multiple consoles stand on the same grid
  119. var airAlarmEntriesForEachGrid = new Dictionary<EntityUid, AtmosAlertsComputerEntry[]>();
  120. var fireAlarmEntriesForEachGrid = new Dictionary<EntityUid, AtmosAlertsComputerEntry[]>();
  121. var query = AllEntityQuery<AtmosAlertsComputerComponent, TransformComponent>();
  122. while (query.MoveNext(out var ent, out var entConsole, out var entXform))
  123. {
  124. if (entXform?.GridUid == null)
  125. continue;
  126. // Make a list of alarm state data for all the air and fire alarms on the grid
  127. if (!airAlarmEntriesForEachGrid.TryGetValue(entXform.GridUid.Value, out var airAlarmEntries))
  128. {
  129. airAlarmEntries = GetAlarmStateData(entXform.GridUid.Value, AtmosAlertsComputerGroup.AirAlarm).ToArray();
  130. airAlarmEntriesForEachGrid[entXform.GridUid.Value] = airAlarmEntries;
  131. }
  132. if (!fireAlarmEntriesForEachGrid.TryGetValue(entXform.GridUid.Value, out var fireAlarmEntries))
  133. {
  134. fireAlarmEntries = GetAlarmStateData(entXform.GridUid.Value, AtmosAlertsComputerGroup.FireAlarm).ToArray();
  135. fireAlarmEntriesForEachGrid[entXform.GridUid.Value] = fireAlarmEntries;
  136. }
  137. // Determine the highest level of alert for the console (based on non-silenced alarms)
  138. var highestAlert = AtmosAlarmType.Invalid;
  139. foreach (var entry in airAlarmEntries)
  140. {
  141. if (entry.AlarmState > highestAlert && !entConsole.SilencedDevices.Contains(entry.NetEntity))
  142. highestAlert = entry.AlarmState;
  143. }
  144. foreach (var entry in fireAlarmEntries)
  145. {
  146. if (entry.AlarmState > highestAlert && !entConsole.SilencedDevices.Contains(entry.NetEntity))
  147. highestAlert = entry.AlarmState;
  148. }
  149. // Update the appearance of the console based on the highest recorded level of alert
  150. if (TryComp<AppearanceComponent>(ent, out var entAppearance))
  151. _appearance.SetData(ent, AtmosAlertsComputerVisuals.ComputerLayerScreen, (int) highestAlert, entAppearance);
  152. // If the console UI is open, send UI data to each subscribed session
  153. UpdateUIState(ent, airAlarmEntries, fireAlarmEntries, entConsole, entXform);
  154. }
  155. }
  156. }
  157. public void UpdateUIState
  158. (EntityUid uid,
  159. AtmosAlertsComputerEntry[] airAlarmStateData,
  160. AtmosAlertsComputerEntry[] fireAlarmStateData,
  161. AtmosAlertsComputerComponent component,
  162. TransformComponent xform)
  163. {
  164. if (!_userInterfaceSystem.IsUiOpen(uid, AtmosAlertsComputerUiKey.Key))
  165. return;
  166. var gridUid = xform.GridUid!.Value;
  167. if (!HasComp<MapGridComponent>(gridUid))
  168. return;
  169. // The grid must have a NavMapComponent to visualize the map in the UI
  170. EnsureComp<NavMapComponent>(gridUid);
  171. // Gathering remaining data to be send to the client
  172. var focusAlarmData = GetFocusAlarmData(uid, GetEntity(component.FocusDevice), gridUid);
  173. // Set the UI state
  174. _userInterfaceSystem.SetUiState(uid, AtmosAlertsComputerUiKey.Key,
  175. new AtmosAlertsComputerBoundInterfaceState(airAlarmStateData, fireAlarmStateData, focusAlarmData));
  176. }
  177. private List<AtmosAlertsComputerEntry> GetAlarmStateData(EntityUid gridUid, AtmosAlertsComputerGroup group)
  178. {
  179. var alarmStateData = new List<AtmosAlertsComputerEntry>();
  180. var queryAlarms = AllEntityQuery<AtmosAlertsDeviceComponent, AtmosAlarmableComponent, DeviceNetworkComponent, TransformComponent>();
  181. while (queryAlarms.MoveNext(out var ent, out var entDevice, out var entAtmosAlarmable, out var entDeviceNetwork, out var entXform))
  182. {
  183. if (entXform.GridUid != gridUid)
  184. continue;
  185. if (!entXform.Anchored)
  186. continue;
  187. if (entDevice.Group != group)
  188. continue;
  189. if (!TryComp<MapGridComponent>(entXform.GridUid, out var mapGrid))
  190. continue;
  191. if (!TryComp<NavMapComponent>(entXform.GridUid, out var navMap))
  192. continue;
  193. // If emagged, change the alarm type to normal
  194. var alarmState = (entAtmosAlarmable.LastAlarmState == AtmosAlarmType.Emagged) ? AtmosAlarmType.Normal : entAtmosAlarmable.LastAlarmState;
  195. // Unpowered alarms can't sound
  196. if (TryComp<ApcPowerReceiverComponent>(ent, out var entAPCPower) && !entAPCPower.Powered)
  197. alarmState = AtmosAlarmType.Invalid;
  198. // Create entry
  199. var netEnt = GetNetEntity(ent);
  200. var entry = new AtmosAlertsComputerEntry
  201. (netEnt,
  202. GetNetCoordinates(entXform.Coordinates),
  203. entDevice.Group,
  204. alarmState,
  205. MetaData(ent).EntityName,
  206. entDeviceNetwork.Address);
  207. // Get the list of sensors attached to the alarm
  208. var sensorList = TryComp<DeviceListComponent>(ent, out var entDeviceList) ? _deviceListSystem.GetDeviceList(ent, entDeviceList) : null;
  209. if (sensorList?.Any() == true)
  210. {
  211. var alarmRegionSeeds = new HashSet<Vector2i>();
  212. // If valid and anchored, use the position of sensors as seeds for the region
  213. foreach (var (address, sensorEnt) in sensorList)
  214. {
  215. if (!sensorEnt.IsValid() || !HasComp<AtmosMonitorComponent>(sensorEnt))
  216. continue;
  217. var sensorXform = Transform(sensorEnt);
  218. if (sensorXform.Anchored && sensorXform.GridUid == entXform.GridUid)
  219. alarmRegionSeeds.Add(_mapSystem.CoordinatesToTile(entXform.GridUid.Value, mapGrid, _transformSystem.GetMapCoordinates(sensorEnt, sensorXform)));
  220. }
  221. var regionProperties = new SharedNavMapSystem.NavMapRegionProperties(netEnt, AtmosAlertsComputerUiKey.Key, alarmRegionSeeds);
  222. _navMapSystem.AddOrUpdateNavMapRegion(gridUid, navMap, netEnt, regionProperties);
  223. }
  224. else
  225. {
  226. _navMapSystem.RemoveNavMapRegion(entXform.GridUid.Value, navMap, netEnt);
  227. }
  228. alarmStateData.Add(entry);
  229. }
  230. return alarmStateData;
  231. }
  232. private AtmosAlertsFocusDeviceData? GetFocusAlarmData(EntityUid uid, EntityUid? focusDevice, EntityUid gridUid)
  233. {
  234. if (focusDevice == null)
  235. return null;
  236. var focusDeviceXform = Transform(focusDevice.Value);
  237. if (!focusDeviceXform.Anchored ||
  238. focusDeviceXform.GridUid != gridUid ||
  239. !TryComp<AirAlarmComponent>(focusDevice.Value, out var focusDeviceAirAlarm))
  240. {
  241. return null;
  242. }
  243. // Force update the sensors attached to the alarm
  244. if (!_userInterfaceSystem.IsUiOpen(focusDevice.Value, SharedAirAlarmInterfaceKey.Key))
  245. {
  246. _atmosDevNet.Register(focusDevice.Value, null);
  247. _atmosDevNet.Sync(focusDevice.Value, null);
  248. foreach ((var address, var _) in focusDeviceAirAlarm.SensorData)
  249. _atmosDevNet.Register(uid, null);
  250. }
  251. // Get the sensor data
  252. var temperatureData = (_airAlarmSystem.CalculateTemperatureAverage(focusDeviceAirAlarm), AtmosAlarmType.Normal);
  253. var pressureData = (_airAlarmSystem.CalculatePressureAverage(focusDeviceAirAlarm), AtmosAlarmType.Normal);
  254. var gasData = new Dictionary<Gas, (float, float, AtmosAlarmType)>();
  255. foreach ((var address, var sensorData) in focusDeviceAirAlarm.SensorData)
  256. {
  257. if (sensorData.TemperatureThreshold.CheckThreshold(sensorData.Temperature, out var temperatureState) &&
  258. (int) temperatureState > (int) temperatureData.Item2)
  259. {
  260. temperatureData = (temperatureData.Item1, temperatureState);
  261. }
  262. if (sensorData.PressureThreshold.CheckThreshold(sensorData.Pressure, out var pressureState) &&
  263. (int) pressureState > (int) pressureData.Item2)
  264. {
  265. pressureData = (pressureData.Item1, pressureState);
  266. }
  267. if (focusDeviceAirAlarm.SensorData.Sum(g => g.Value.TotalMoles) > 1e-8)
  268. {
  269. foreach ((var gas, var threshold) in sensorData.GasThresholds)
  270. {
  271. if (!gasData.ContainsKey(gas))
  272. {
  273. float mol = _airAlarmSystem.CalculateGasMolarConcentrationAverage(focusDeviceAirAlarm, gas, out var percentage);
  274. if (mol < 1e-8)
  275. continue;
  276. gasData[gas] = (mol, percentage, AtmosAlarmType.Normal);
  277. }
  278. if (threshold.CheckThreshold(gasData[gas].Item2, out var gasState) &&
  279. (int) gasState > (int) gasData[gas].Item3)
  280. {
  281. gasData[gas] = (gasData[gas].Item1, gasData[gas].Item2, gasState);
  282. }
  283. }
  284. }
  285. }
  286. return new AtmosAlertsFocusDeviceData(GetNetEntity(focusDevice.Value), temperatureData, pressureData, gasData);
  287. }
  288. private HashSet<AtmosAlertsDeviceNavMapData> GetAllAtmosDeviceNavMapData(EntityUid gridUid)
  289. {
  290. var atmosDeviceNavMapData = new HashSet<AtmosAlertsDeviceNavMapData>();
  291. var query = AllEntityQuery<AtmosAlertsDeviceComponent, TransformComponent>();
  292. while (query.MoveNext(out var ent, out var entComponent, out var entXform))
  293. {
  294. if (entXform.GridUid != gridUid)
  295. continue;
  296. if (TryGetAtmosDeviceNavMapData(ent, entComponent, entXform, out var data))
  297. atmosDeviceNavMapData.Add(data.Value);
  298. }
  299. return atmosDeviceNavMapData;
  300. }
  301. private bool TryGetAtmosDeviceNavMapData
  302. (EntityUid uid,
  303. AtmosAlertsDeviceComponent component,
  304. TransformComponent xform,
  305. [NotNullWhen(true)] out AtmosAlertsDeviceNavMapData? output)
  306. {
  307. output = null;
  308. if (!xform.Anchored)
  309. return false;
  310. output = new AtmosAlertsDeviceNavMapData(GetNetEntity(uid), GetNetCoordinates(xform.Coordinates), component.Group);
  311. return true;
  312. }
  313. private void InitalizeConsole(EntityUid uid, AtmosAlertsComputerComponent component)
  314. {
  315. var xform = Transform(uid);
  316. if (xform.GridUid == null)
  317. return;
  318. var grid = xform.GridUid.Value;
  319. component.AtmosDevices = GetAllAtmosDeviceNavMapData(grid);
  320. Dirty(uid, component);
  321. }
  322. }