1
0

ChemicalReactionSystem.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. using Content.Shared.Administration.Logs;
  2. using Content.Shared.Chemistry.Components;
  3. using Content.Shared.Chemistry.Reagent;
  4. using Content.Shared.Database;
  5. using Content.Shared.EntityEffects;
  6. using Content.Shared.FixedPoint;
  7. using Robust.Shared.Audio.Systems;
  8. using Robust.Shared.Prototypes;
  9. using Robust.Shared.Utility;
  10. using System.Collections.Frozen;
  11. using System.Linq;
  12. namespace Content.Shared.Chemistry.Reaction
  13. {
  14. public sealed class ChemicalReactionSystem : EntitySystem
  15. {
  16. /// <summary>
  17. /// The maximum number of reactions that may occur when a solution is changed.
  18. /// </summary>
  19. private const int MaxReactionIterations = 20;
  20. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  21. [Dependency] private readonly SharedAudioSystem _audio = default!;
  22. [Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
  23. [Dependency] private readonly SharedTransformSystem _transformSystem = default!;
  24. /// <summary>
  25. /// A cache of all reactions indexed by at most ONE of their required reactants.
  26. /// I.e., even if a reaction has more than one reagent, it will only ever appear once in this dictionary.
  27. /// </summary>
  28. private FrozenDictionary<string, List<ReactionPrototype>> _reactionsSingle = default!;
  29. /// <summary>
  30. /// A cache of all reactions indexed by one of their required reactants.
  31. /// </summary>
  32. private FrozenDictionary<string, List<ReactionPrototype>> _reactions = default!;
  33. public override void Initialize()
  34. {
  35. base.Initialize();
  36. InitializeReactionCache();
  37. SubscribeLocalEvent<PrototypesReloadedEventArgs>(OnPrototypesReloaded);
  38. }
  39. /// <summary>
  40. /// Handles building the reaction cache.
  41. /// </summary>
  42. private void InitializeReactionCache()
  43. {
  44. // Construct single-reaction dictionary.
  45. var dict = new Dictionary<string, List<ReactionPrototype>>();
  46. foreach (var reaction in _prototypeManager.EnumeratePrototypes<ReactionPrototype>())
  47. {
  48. // For this dictionary we only need to cache based on the first reagent.
  49. var reagent = reaction.Reactants.Keys.First();
  50. var list = dict.GetOrNew(reagent);
  51. list.Add(reaction);
  52. }
  53. _reactionsSingle = dict.ToFrozenDictionary();
  54. dict.Clear();
  55. foreach (var reaction in _prototypeManager.EnumeratePrototypes<ReactionPrototype>())
  56. {
  57. foreach (var reagent in reaction.Reactants.Keys)
  58. {
  59. var list = dict.GetOrNew(reagent);
  60. list.Add(reaction);
  61. }
  62. }
  63. _reactions = dict.ToFrozenDictionary();
  64. }
  65. /// <summary>
  66. /// Updates the reaction cache when the prototypes are reloaded.
  67. /// </summary>
  68. /// <param name="eventArgs">The set of modified prototypes.</param>
  69. private void OnPrototypesReloaded(PrototypesReloadedEventArgs eventArgs)
  70. {
  71. if (eventArgs.WasModified<ReactionPrototype>())
  72. InitializeReactionCache();
  73. }
  74. /// <summary>
  75. /// Checks if a solution can undergo a specified reaction.
  76. /// </summary>
  77. /// <param name="solution">The solution to check.</param>
  78. /// <param name="reaction">The reaction to check.</param>
  79. /// <param name="lowestUnitReactions">How many times this reaction can occur.</param>
  80. /// <returns></returns>
  81. private bool CanReact(Entity<SolutionComponent> soln, ReactionPrototype reaction, ReactionMixerComponent? mixerComponent, out FixedPoint2 lowestUnitReactions)
  82. {
  83. var solution = soln.Comp.Solution;
  84. lowestUnitReactions = FixedPoint2.MaxValue;
  85. if (solution.Temperature < reaction.MinimumTemperature)
  86. {
  87. lowestUnitReactions = FixedPoint2.Zero;
  88. return false;
  89. }
  90. if (solution.Temperature > reaction.MaximumTemperature)
  91. {
  92. lowestUnitReactions = FixedPoint2.Zero;
  93. return false;
  94. }
  95. if ((mixerComponent == null && reaction.MixingCategories != null) ||
  96. mixerComponent != null && reaction.MixingCategories != null && reaction.MixingCategories.Except(mixerComponent.ReactionTypes).Any())
  97. {
  98. lowestUnitReactions = FixedPoint2.Zero;
  99. return false;
  100. }
  101. var attempt = new ReactionAttemptEvent(reaction, soln);
  102. RaiseLocalEvent(soln, ref attempt);
  103. if (attempt.Cancelled)
  104. {
  105. lowestUnitReactions = FixedPoint2.Zero;
  106. return false;
  107. }
  108. foreach (var reactantData in reaction.Reactants)
  109. {
  110. var reactantName = reactantData.Key;
  111. var reactantCoefficient = reactantData.Value.Amount;
  112. var reactantQuantity = solution.GetTotalPrototypeQuantity(reactantName);
  113. if (reactantQuantity <= FixedPoint2.Zero)
  114. return false;
  115. if (reactantData.Value.Catalyst)
  116. {
  117. // catalyst is not consumed, so will not limit the reaction. But it still needs to be present, and
  118. // for quantized reactions we need to have a minimum amount
  119. if (reactantQuantity == FixedPoint2.Zero || reaction.Quantized && reactantQuantity < reactantCoefficient)
  120. return false;
  121. continue;
  122. }
  123. var unitReactions = reactantQuantity / reactantCoefficient;
  124. if (unitReactions < lowestUnitReactions)
  125. {
  126. lowestUnitReactions = unitReactions;
  127. }
  128. }
  129. if (reaction.Quantized)
  130. lowestUnitReactions = (int) lowestUnitReactions;
  131. return lowestUnitReactions > 0;
  132. }
  133. /// <summary>
  134. /// Perform a reaction on a solution. This assumes all reaction criteria are met.
  135. /// Removes the reactants from the solution, adds products, and returns a list of products.
  136. /// </summary>
  137. private List<string> PerformReaction(Entity<SolutionComponent> soln, ReactionPrototype reaction, FixedPoint2 unitReactions)
  138. {
  139. var (uid, comp) = soln;
  140. var solution = comp.Solution;
  141. var energy = reaction.ConserveEnergy ? solution.GetThermalEnergy(_prototypeManager) : 0;
  142. //Remove reactants
  143. foreach (var reactant in reaction.Reactants)
  144. {
  145. if (!reactant.Value.Catalyst)
  146. {
  147. var amountToRemove = unitReactions * reactant.Value.Amount;
  148. solution.RemoveReagent(reactant.Key, amountToRemove, ignoreReagentData: true);
  149. }
  150. }
  151. //Create products
  152. var products = new List<string>();
  153. foreach (var product in reaction.Products)
  154. {
  155. products.Add(product.Key);
  156. solution.AddReagent(product.Key, product.Value * unitReactions);
  157. }
  158. if (reaction.ConserveEnergy)
  159. {
  160. var newCap = solution.GetHeatCapacity(_prototypeManager);
  161. if (newCap > 0)
  162. solution.Temperature = energy / newCap;
  163. }
  164. OnReaction(soln, reaction, null, unitReactions);
  165. return products;
  166. }
  167. private void OnReaction(Entity<SolutionComponent> soln, ReactionPrototype reaction, ReagentPrototype? reagent, FixedPoint2 unitReactions)
  168. {
  169. var args = new EntityEffectReagentArgs(soln, EntityManager, null, soln.Comp.Solution, unitReactions, reagent, null, 1f);
  170. var posFound = _transformSystem.TryGetMapOrGridCoordinates(soln, out var gridPos);
  171. _adminLogger.Add(LogType.ChemicalReaction, reaction.Impact,
  172. $"Chemical reaction {reaction.ID:reaction} occurred with strength {unitReactions:strength} on entity {ToPrettyString(soln):metabolizer} at Pos:{(posFound ? $"{gridPos:coordinates}" : "[Grid or Map not Found]")}");
  173. foreach (var effect in reaction.Effects)
  174. {
  175. if (!effect.ShouldApply(args))
  176. continue;
  177. if (effect.ShouldLog)
  178. {
  179. var entity = args.TargetEntity;
  180. _adminLogger.Add(LogType.ReagentEffect, effect.LogImpact,
  181. $"Reaction effect {effect.GetType().Name:effect} of reaction {reaction.ID:reaction} applied on entity {ToPrettyString(entity):entity} at Pos:{(posFound ? $"{gridPos:coordinates}" : "[Grid or Map not Found")}");
  182. }
  183. effect.Effect(args);
  184. }
  185. _audio.PlayPvs(reaction.Sound, soln);
  186. }
  187. /// <summary>
  188. /// Performs all chemical reactions that can be run on a solution.
  189. /// Removes the reactants from the solution, then returns a solution with all products.
  190. /// WARNING: Does not trigger reactions between solution and new products.
  191. /// </summary>
  192. private bool ProcessReactions(Entity<SolutionComponent> soln, SortedSet<ReactionPrototype> reactions, ReactionMixerComponent? mixerComponent)
  193. {
  194. HashSet<ReactionPrototype> toRemove = new();
  195. List<string>? products = null;
  196. // attempt to perform any applicable reaction
  197. foreach (var reaction in reactions)
  198. {
  199. if (!CanReact(soln, reaction, mixerComponent, out var unitReactions))
  200. {
  201. toRemove.Add(reaction);
  202. continue;
  203. }
  204. products = PerformReaction(soln, reaction, unitReactions);
  205. break;
  206. }
  207. // did any reaction occur?
  208. if (products == null)
  209. return false;
  210. if (products.Count == 0)
  211. return true;
  212. // Add any reactions associated with the new products. This may re-add reactions that were already iterated
  213. // over previously. The new product may mean the reactions are applicable again and need to be processed.
  214. foreach (var product in products)
  215. {
  216. if (_reactions.TryGetValue(product, out var reactantReactions))
  217. reactions.UnionWith(reactantReactions);
  218. }
  219. return true;
  220. }
  221. /// <summary>
  222. /// Continually react a solution until no more reactions occur, with a volume constraint.
  223. /// </summary>
  224. public void FullyReactSolution(Entity<SolutionComponent> soln, ReactionMixerComponent? mixerComponent = null)
  225. {
  226. // construct the initial set of reactions to check.
  227. SortedSet<ReactionPrototype> reactions = new();
  228. foreach (var reactant in soln.Comp.Solution.Contents)
  229. {
  230. if (_reactionsSingle.TryGetValue(reactant.Reagent.Prototype, out var reactantReactions))
  231. reactions.UnionWith(reactantReactions);
  232. }
  233. // Repeatedly attempt to perform reactions, ending when there are no more applicable reactions, or when we
  234. // exceed the iteration limit.
  235. for (var i = 0; i < MaxReactionIterations; i++)
  236. {
  237. if (!ProcessReactions(soln, reactions, mixerComponent))
  238. return;
  239. }
  240. Log.Error($"{nameof(Solution)} {soln.Owner} could not finish reacting in under {MaxReactionIterations} loops.");
  241. }
  242. }
  243. /// <summary>
  244. /// Raised directed at the owner of a solution to determine whether the reaction should be allowed to occur.
  245. /// </summary>
  246. /// <reamrks>
  247. /// Some solution containers (e.g., bloodstream, smoke, foam) use this to block certain reactions from occurring.
  248. /// </reamrks>
  249. [ByRefEvent]
  250. public record struct ReactionAttemptEvent(ReactionPrototype Reaction, Entity<SolutionComponent> Solution)
  251. {
  252. public readonly ReactionPrototype Reaction = Reaction;
  253. public readonly Entity<SolutionComponent> Solution = Solution;
  254. public bool Cancelled = false;
  255. }
  256. }