StackSystem.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. using Content.Shared.Popups;
  2. using Content.Shared.Stacks;
  3. using Content.Shared.Verbs;
  4. using JetBrains.Annotations;
  5. using Robust.Shared.Map;
  6. using Robust.Shared.Prototypes;
  7. namespace Content.Server.Stack
  8. {
  9. /// <summary>
  10. /// Entity system that handles everything relating to stacks.
  11. /// This is a good example for learning how to code in an ECS manner.
  12. /// </summary>
  13. [UsedImplicitly]
  14. public sealed class StackSystem : SharedStackSystem
  15. {
  16. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  17. public static readonly int[] DefaultSplitAmounts = { 1, 5, 10, 20, 30, 50 };
  18. public override void Initialize()
  19. {
  20. base.Initialize();
  21. SubscribeLocalEvent<StackComponent, GetVerbsEvent<AlternativeVerb>>(OnStackAlternativeInteract);
  22. }
  23. public override void SetCount(EntityUid uid, int amount, StackComponent? component = null)
  24. {
  25. if (!Resolve(uid, ref component, false))
  26. return;
  27. base.SetCount(uid, amount, component);
  28. // Queue delete stack if count reaches zero.
  29. if (component.Count <= 0 && !component.Lingering)
  30. QueueDel(uid);
  31. }
  32. /// <summary>
  33. /// Try to split this stack into two. Returns a non-null <see cref="Robust.Shared.GameObjects.EntityUid"/> if successful.
  34. /// </summary>
  35. public EntityUid? Split(EntityUid uid, int amount, EntityCoordinates spawnPosition, StackComponent? stack = null)
  36. {
  37. if (!Resolve(uid, ref stack))
  38. return null;
  39. // Try to remove the amount of things we want to split from the original stack...
  40. if (!Use(uid, amount, stack))
  41. return null;
  42. // Get a prototype ID to spawn the new entity. Null is also valid, although it should rarely be picked...
  43. var prototype = _prototypeManager.TryIndex<StackPrototype>(stack.StackTypeId, out var stackType)
  44. ? stackType.Spawn.ToString()
  45. : Prototype(uid)?.ID;
  46. // Set the output parameter in the event instance to the newly split stack.
  47. var entity = Spawn(prototype, spawnPosition);
  48. if (TryComp(entity, out StackComponent? stackComp))
  49. {
  50. // Set the split stack's count.
  51. SetCount(entity, amount, stackComp);
  52. // Don't let people dupe unlimited stacks
  53. stackComp.Unlimited = false;
  54. }
  55. var ev = new StackSplitEvent(entity);
  56. RaiseLocalEvent(uid, ref ev);
  57. return entity;
  58. }
  59. /// <summary>
  60. /// Spawns a stack of a certain stack type. See <see cref="StackPrototype"/>.
  61. /// </summary>
  62. public EntityUid Spawn(int amount, ProtoId<StackPrototype> id, EntityCoordinates spawnPosition)
  63. {
  64. var proto = _prototypeManager.Index(id);
  65. return Spawn(amount, proto, spawnPosition);
  66. }
  67. /// <summary>
  68. /// Spawns a stack of a certain stack type. See <see cref="StackPrototype"/>.
  69. /// </summary>
  70. public EntityUid Spawn(int amount, StackPrototype prototype, EntityCoordinates spawnPosition)
  71. {
  72. // Set the output result parameter to the new stack entity...
  73. var entity = Spawn(prototype.Spawn, spawnPosition);
  74. var stack = Comp<StackComponent>(entity);
  75. // And finally, set the correct amount!
  76. SetCount(entity, amount, stack);
  77. return entity;
  78. }
  79. /// <summary>
  80. /// Say you want to spawn 97 units of something that has a max stack count of 30.
  81. /// This would spawn 3 stacks of 30 and 1 stack of 7.
  82. /// </summary>
  83. public List<EntityUid> SpawnMultiple(string entityPrototype, int amount, EntityCoordinates spawnPosition)
  84. {
  85. if (amount <= 0)
  86. {
  87. Log.Error(
  88. $"Attempted to spawn an invalid stack: {entityPrototype}, {amount}. Trace: {Environment.StackTrace}");
  89. return new();
  90. }
  91. var spawns = CalculateSpawns(entityPrototype, amount);
  92. var spawnedEnts = new List<EntityUid>();
  93. foreach (var count in spawns)
  94. {
  95. var entity = SpawnAtPosition(entityPrototype, spawnPosition);
  96. spawnedEnts.Add(entity);
  97. SetCount(entity, count);
  98. }
  99. return spawnedEnts;
  100. }
  101. /// <inheritdoc cref="SpawnMultiple(string,int,EntityCoordinates)"/>
  102. public List<EntityUid> SpawnMultiple(string entityPrototype, int amount, EntityUid target)
  103. {
  104. if (amount <= 0)
  105. {
  106. Log.Error(
  107. $"Attempted to spawn an invalid stack: {entityPrototype}, {amount}. Trace: {Environment.StackTrace}");
  108. return new();
  109. }
  110. var spawns = CalculateSpawns(entityPrototype, amount);
  111. var spawnedEnts = new List<EntityUid>();
  112. foreach (var count in spawns)
  113. {
  114. var entity = SpawnNextToOrDrop(entityPrototype, target);
  115. spawnedEnts.Add(entity);
  116. SetCount(entity, count);
  117. }
  118. return spawnedEnts;
  119. }
  120. /// <summary>
  121. /// Calculates how many stacks to spawn that total up to <paramref name="amount"/>.
  122. /// </summary>
  123. /// <param name="entityPrototype">The stack to spawn.</param>
  124. /// <param name="amount">The amount of pieces across all stacks.</param>
  125. /// <returns>The list of stack counts per entity.</returns>
  126. private List<int> CalculateSpawns(string entityPrototype, int amount)
  127. {
  128. var proto = _prototypeManager.Index<EntityPrototype>(entityPrototype);
  129. proto.TryGetComponent<StackComponent>(out var stack, EntityManager.ComponentFactory);
  130. var maxCountPerStack = GetMaxCount(stack);
  131. var amounts = new List<int>();
  132. while (amount > 0)
  133. {
  134. var countAmount = Math.Min(maxCountPerStack, amount);
  135. amount -= countAmount;
  136. amounts.Add(countAmount);
  137. }
  138. return amounts;
  139. }
  140. private void OnStackAlternativeInteract(EntityUid uid, StackComponent stack, GetVerbsEvent<AlternativeVerb> args)
  141. {
  142. if (!args.CanAccess || !args.CanInteract || args.Hands == null || stack.Count == 1)
  143. return;
  144. AlternativeVerb halve = new()
  145. {
  146. Text = Loc.GetString("comp-stack-split-halve"),
  147. Category = VerbCategory.Split,
  148. Act = () => UserSplit(uid, args.User, stack.Count / 2, stack),
  149. Priority = 1
  150. };
  151. args.Verbs.Add(halve);
  152. var priority = 0;
  153. foreach (var amount in DefaultSplitAmounts)
  154. {
  155. if (amount >= stack.Count)
  156. continue;
  157. AlternativeVerb verb = new()
  158. {
  159. Text = amount.ToString(),
  160. Category = VerbCategory.Split,
  161. Act = () => UserSplit(uid, args.User, amount, stack),
  162. // we want to sort by size, not alphabetically by the verb text.
  163. Priority = priority
  164. };
  165. priority--;
  166. args.Verbs.Add(verb);
  167. }
  168. }
  169. private void UserSplit(EntityUid uid, EntityUid userUid, int amount,
  170. StackComponent? stack = null,
  171. TransformComponent? userTransform = null)
  172. {
  173. if (!Resolve(uid, ref stack))
  174. return;
  175. if (!Resolve(userUid, ref userTransform))
  176. return;
  177. if (amount <= 0)
  178. {
  179. Popup.PopupCursor(Loc.GetString("comp-stack-split-too-small"), userUid, PopupType.Medium);
  180. return;
  181. }
  182. if (Split(uid, amount, userTransform.Coordinates, stack) is not {} split)
  183. return;
  184. Hands.PickupOrDrop(userUid, split);
  185. Popup.PopupCursor(Loc.GetString("comp-stack-split"), userUid);
  186. }
  187. }
  188. }