ChemMasterSystem.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. using Content.Server.Chemistry.Components;
  2. using Content.Server.Labels;
  3. using Content.Server.Popups;
  4. using Content.Server.Storage.EntitySystems;
  5. using Content.Shared.Administration.Logs;
  6. using Content.Shared.Chemistry;
  7. using Content.Shared.Chemistry.Components;
  8. using Content.Shared.Chemistry.EntitySystems;
  9. using Content.Shared.Chemistry.Reagent;
  10. using Content.Shared.Containers.ItemSlots;
  11. using Content.Shared.Database;
  12. using Content.Shared.FixedPoint;
  13. using Content.Shared.Storage;
  14. using JetBrains.Annotations;
  15. using Robust.Server.Audio;
  16. using Robust.Server.GameObjects;
  17. using Robust.Shared.Audio;
  18. using Robust.Shared.Containers;
  19. using Robust.Shared.Prototypes;
  20. using System.Diagnostics.CodeAnalysis;
  21. using System.Linq;
  22. namespace Content.Server.Chemistry.EntitySystems
  23. {
  24. /// <summary>
  25. /// Contains all the server-side logic for ChemMasters.
  26. /// <seealso cref="ChemMasterComponent"/>
  27. /// </summary>
  28. [UsedImplicitly]
  29. public sealed class ChemMasterSystem : EntitySystem
  30. {
  31. [Dependency] private readonly PopupSystem _popupSystem = default!;
  32. [Dependency] private readonly AudioSystem _audioSystem = default!;
  33. [Dependency] private readonly SharedSolutionContainerSystem _solutionContainerSystem = default!;
  34. [Dependency] private readonly ItemSlotsSystem _itemSlotsSystem = default!;
  35. [Dependency] private readonly UserInterfaceSystem _userInterfaceSystem = default!;
  36. [Dependency] private readonly StorageSystem _storageSystem = default!;
  37. [Dependency] private readonly LabelSystem _labelSystem = default!;
  38. [Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
  39. [ValidatePrototypeId<EntityPrototype>]
  40. private const string PillPrototypeId = "Pill";
  41. public override void Initialize()
  42. {
  43. base.Initialize();
  44. SubscribeLocalEvent<ChemMasterComponent, ComponentStartup>(SubscribeUpdateUiState);
  45. SubscribeLocalEvent<ChemMasterComponent, SolutionContainerChangedEvent>(SubscribeUpdateUiState);
  46. SubscribeLocalEvent<ChemMasterComponent, EntInsertedIntoContainerMessage>(SubscribeUpdateUiState);
  47. SubscribeLocalEvent<ChemMasterComponent, EntRemovedFromContainerMessage>(SubscribeUpdateUiState);
  48. SubscribeLocalEvent<ChemMasterComponent, BoundUIOpenedEvent>(SubscribeUpdateUiState);
  49. SubscribeLocalEvent<ChemMasterComponent, ChemMasterSetModeMessage>(OnSetModeMessage);
  50. SubscribeLocalEvent<ChemMasterComponent, ChemMasterSortingTypeCycleMessage>(OnCycleSortingTypeMessage);
  51. SubscribeLocalEvent<ChemMasterComponent, ChemMasterSetPillTypeMessage>(OnSetPillTypeMessage);
  52. SubscribeLocalEvent<ChemMasterComponent, ChemMasterReagentAmountButtonMessage>(OnReagentButtonMessage);
  53. SubscribeLocalEvent<ChemMasterComponent, ChemMasterCreatePillsMessage>(OnCreatePillsMessage);
  54. SubscribeLocalEvent<ChemMasterComponent, ChemMasterOutputToBottleMessage>(OnOutputToBottleMessage);
  55. }
  56. private void SubscribeUpdateUiState<T>(Entity<ChemMasterComponent> ent, ref T ev)
  57. {
  58. UpdateUiState(ent);
  59. }
  60. private void UpdateUiState(Entity<ChemMasterComponent> ent, bool updateLabel = false)
  61. {
  62. var (owner, chemMaster) = ent;
  63. if (!_solutionContainerSystem.TryGetSolution(owner, SharedChemMaster.BufferSolutionName, out _, out var bufferSolution))
  64. return;
  65. var inputContainer = _itemSlotsSystem.GetItemOrNull(owner, SharedChemMaster.InputSlotName);
  66. var outputContainer = _itemSlotsSystem.GetItemOrNull(owner, SharedChemMaster.OutputSlotName);
  67. var bufferReagents = bufferSolution.Contents;
  68. var bufferCurrentVolume = bufferSolution.Volume;
  69. var state = new ChemMasterBoundUserInterfaceState(
  70. chemMaster.Mode, chemMaster.SortingType, BuildInputContainerInfo(inputContainer), BuildOutputContainerInfo(outputContainer),
  71. bufferReagents, bufferCurrentVolume, chemMaster.PillType, chemMaster.PillDosageLimit, updateLabel);
  72. _userInterfaceSystem.SetUiState(owner, ChemMasterUiKey.Key, state);
  73. }
  74. private void OnSetModeMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterSetModeMessage message)
  75. {
  76. // Ensure the mode is valid, either Transfer or Discard.
  77. if (!Enum.IsDefined(typeof(ChemMasterMode), message.ChemMasterMode))
  78. return;
  79. chemMaster.Comp.Mode = message.ChemMasterMode;
  80. UpdateUiState(chemMaster);
  81. ClickSound(chemMaster);
  82. }
  83. private void OnCycleSortingTypeMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterSortingTypeCycleMessage message)
  84. {
  85. chemMaster.Comp.SortingType++;
  86. if (chemMaster.Comp.SortingType > ChemMasterSortingType.Latest)
  87. chemMaster.Comp.SortingType = ChemMasterSortingType.None;
  88. UpdateUiState(chemMaster);
  89. ClickSound(chemMaster);
  90. }
  91. private void OnSetPillTypeMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterSetPillTypeMessage message)
  92. {
  93. // Ensure valid pill type. There are 20 pills selectable, 0-19.
  94. if (message.PillType > SharedChemMaster.PillTypes - 1)
  95. return;
  96. chemMaster.Comp.PillType = message.PillType;
  97. UpdateUiState(chemMaster);
  98. ClickSound(chemMaster);
  99. }
  100. private void OnReagentButtonMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterReagentAmountButtonMessage message)
  101. {
  102. // Ensure the amount corresponds to one of the reagent amount buttons.
  103. if (!Enum.IsDefined(typeof(ChemMasterReagentAmount), message.Amount))
  104. return;
  105. switch (chemMaster.Comp.Mode)
  106. {
  107. case ChemMasterMode.Transfer:
  108. TransferReagents(chemMaster, message.ReagentId, message.Amount.GetFixedPoint(), message.FromBuffer);
  109. break;
  110. case ChemMasterMode.Discard:
  111. DiscardReagents(chemMaster, message.ReagentId, message.Amount.GetFixedPoint(), message.FromBuffer);
  112. break;
  113. default:
  114. // Invalid mode.
  115. return;
  116. }
  117. ClickSound(chemMaster);
  118. }
  119. private void TransferReagents(Entity<ChemMasterComponent> chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer)
  120. {
  121. var container = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.InputSlotName);
  122. if (container is null ||
  123. !_solutionContainerSystem.TryGetFitsInDispenser(container.Value, out var containerSoln, out var containerSolution) ||
  124. !_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out _, out var bufferSolution))
  125. {
  126. return;
  127. }
  128. if (fromBuffer) // Buffer to container
  129. {
  130. amount = FixedPoint2.Min(amount, containerSolution.AvailableVolume);
  131. amount = bufferSolution.RemoveReagent(id, amount, preserveOrder: true);
  132. _solutionContainerSystem.TryAddReagent(containerSoln.Value, id, amount, out var _);
  133. }
  134. else // Container to buffer
  135. {
  136. amount = FixedPoint2.Min(amount, containerSolution.GetReagentQuantity(id));
  137. _solutionContainerSystem.RemoveReagent(containerSoln.Value, id, amount);
  138. bufferSolution.AddReagent(id, amount);
  139. }
  140. UpdateUiState(chemMaster, updateLabel: true);
  141. }
  142. private void DiscardReagents(Entity<ChemMasterComponent> chemMaster, ReagentId id, FixedPoint2 amount, bool fromBuffer)
  143. {
  144. if (fromBuffer)
  145. {
  146. if (_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out _, out var bufferSolution))
  147. bufferSolution.RemoveReagent(id, amount, preserveOrder: true);
  148. else
  149. return;
  150. }
  151. else
  152. {
  153. var container = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.InputSlotName);
  154. if (container is not null &&
  155. _solutionContainerSystem.TryGetFitsInDispenser(container.Value, out var containerSolution, out _))
  156. {
  157. _solutionContainerSystem.RemoveReagent(containerSolution.Value, id, amount);
  158. }
  159. else
  160. return;
  161. }
  162. UpdateUiState(chemMaster, updateLabel: fromBuffer);
  163. }
  164. private void OnCreatePillsMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterCreatePillsMessage message)
  165. {
  166. var user = message.Actor;
  167. var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.OutputSlotName);
  168. if (maybeContainer is not { Valid: true } container
  169. || !TryComp(container, out StorageComponent? storage))
  170. {
  171. return; // output can't fit pills
  172. }
  173. // Ensure the number is valid.
  174. if (message.Number == 0 || !_storageSystem.HasSpace((container, storage)))
  175. return;
  176. // Ensure the amount is valid.
  177. if (message.Dosage == 0 || message.Dosage > chemMaster.Comp.PillDosageLimit)
  178. return;
  179. // Ensure label length is within the character limit.
  180. if (message.Label.Length > SharedChemMaster.LabelMaxLength)
  181. return;
  182. var needed = message.Dosage * message.Number;
  183. if (!WithdrawFromBuffer(chemMaster, needed, user, out var withdrawal))
  184. return;
  185. _labelSystem.Label(container, message.Label);
  186. for (var i = 0; i < message.Number; i++)
  187. {
  188. var item = Spawn(PillPrototypeId, Transform(container).Coordinates);
  189. _storageSystem.Insert(container, item, out _, user: user, storage);
  190. _labelSystem.Label(item, message.Label);
  191. _solutionContainerSystem.EnsureSolutionEntity(item, SharedChemMaster.PillSolutionName,out var itemSolution ,message.Dosage);
  192. if (!itemSolution.HasValue)
  193. return;
  194. _solutionContainerSystem.TryAddSolution(itemSolution.Value, withdrawal.SplitSolution(message.Dosage));
  195. var pill = EnsureComp<PillComponent>(item);
  196. pill.PillType = chemMaster.Comp.PillType;
  197. Dirty(item, pill);
  198. // Log pill creation by a user
  199. _adminLogger.Add(LogType.Action, LogImpact.Low,
  200. $"{ToPrettyString(user):user} printed {ToPrettyString(item):pill} {SharedSolutionContainerSystem.ToPrettyString(itemSolution.Value.Comp.Solution)}");
  201. }
  202. UpdateUiState(chemMaster);
  203. ClickSound(chemMaster);
  204. }
  205. private void OnOutputToBottleMessage(Entity<ChemMasterComponent> chemMaster, ref ChemMasterOutputToBottleMessage message)
  206. {
  207. var user = message.Actor;
  208. var maybeContainer = _itemSlotsSystem.GetItemOrNull(chemMaster, SharedChemMaster.OutputSlotName);
  209. if (maybeContainer is not { Valid: true } container
  210. || !_solutionContainerSystem.TryGetSolution(container, SharedChemMaster.BottleSolutionName, out var soln, out var solution))
  211. {
  212. return; // output can't fit reagents
  213. }
  214. // Ensure the amount is valid.
  215. if (message.Dosage == 0 || message.Dosage > solution.AvailableVolume)
  216. return;
  217. // Ensure label length is within the character limit.
  218. if (message.Label.Length > SharedChemMaster.LabelMaxLength)
  219. return;
  220. if (!WithdrawFromBuffer(chemMaster, message.Dosage, user, out var withdrawal))
  221. return;
  222. _labelSystem.Label(container, message.Label);
  223. _solutionContainerSystem.TryAddSolution(soln.Value, withdrawal);
  224. // Log bottle creation by a user
  225. _adminLogger.Add(LogType.Action, LogImpact.Low,
  226. $"{ToPrettyString(user):user} bottled {ToPrettyString(container):bottle} {SharedSolutionContainerSystem.ToPrettyString(solution)}");
  227. UpdateUiState(chemMaster);
  228. ClickSound(chemMaster);
  229. }
  230. private bool WithdrawFromBuffer(
  231. Entity<ChemMasterComponent> chemMaster,
  232. FixedPoint2 neededVolume, EntityUid? user,
  233. [NotNullWhen(returnValue: true)] out Solution? outputSolution)
  234. {
  235. outputSolution = null;
  236. if (!_solutionContainerSystem.TryGetSolution(chemMaster.Owner, SharedChemMaster.BufferSolutionName, out _, out var solution))
  237. {
  238. return false;
  239. }
  240. if (solution.Volume == 0)
  241. {
  242. if (user.HasValue)
  243. _popupSystem.PopupCursor(Loc.GetString("chem-master-window-buffer-empty-text"), user.Value);
  244. return false;
  245. }
  246. // ReSharper disable once InvertIf
  247. if (neededVolume > solution.Volume)
  248. {
  249. if (user.HasValue)
  250. _popupSystem.PopupCursor(Loc.GetString("chem-master-window-buffer-low-text"), user.Value);
  251. return false;
  252. }
  253. outputSolution = solution.SplitSolution(neededVolume);
  254. return true;
  255. }
  256. private void ClickSound(Entity<ChemMasterComponent> chemMaster)
  257. {
  258. _audioSystem.PlayPvs(chemMaster.Comp.ClickSound, chemMaster, AudioParams.Default.WithVolume(-2f));
  259. }
  260. private ContainerInfo? BuildInputContainerInfo(EntityUid? container)
  261. {
  262. if (container is not { Valid: true })
  263. return null;
  264. if (!TryComp(container, out FitsInDispenserComponent? fits)
  265. || !_solutionContainerSystem.TryGetSolution(container.Value, fits.Solution, out _, out var solution))
  266. {
  267. return null;
  268. }
  269. return BuildContainerInfo(Name(container.Value), solution);
  270. }
  271. private ContainerInfo? BuildOutputContainerInfo(EntityUid? container)
  272. {
  273. if (container is not { Valid: true })
  274. return null;
  275. var name = Name(container.Value);
  276. {
  277. if (_solutionContainerSystem.TryGetSolution(
  278. container.Value, SharedChemMaster.BottleSolutionName, out _, out var solution))
  279. {
  280. return BuildContainerInfo(name, solution);
  281. }
  282. }
  283. if (!TryComp(container, out StorageComponent? storage))
  284. return null;
  285. var pills = storage.Container.ContainedEntities.Select((Func<EntityUid, (string, FixedPoint2 quantity)>) (pill =>
  286. {
  287. _solutionContainerSystem.TryGetSolution(pill, SharedChemMaster.PillSolutionName, out _, out var solution);
  288. var quantity = solution?.Volume ?? FixedPoint2.Zero;
  289. return (Name(pill), quantity);
  290. })).ToList();
  291. return new ContainerInfo(name, _storageSystem.GetCumulativeItemAreas((container.Value, storage)), storage.Grid.GetArea())
  292. {
  293. Entities = pills
  294. };
  295. }
  296. private static ContainerInfo BuildContainerInfo(string name, Solution solution)
  297. {
  298. return new ContainerInfo(name, solution.Volume, solution.MaxVolume)
  299. {
  300. Reagents = solution.Contents
  301. };
  302. }
  303. }
  304. }