1
0

EventManagerSystem.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. using System.Linq;
  2. using Content.Server.GameTicking;
  3. using Content.Server.RoundEnd;
  4. using Content.Server.StationEvents.Components;
  5. using Content.Shared.CCVar;
  6. using Robust.Server.Player;
  7. using Robust.Shared.Configuration;
  8. using Robust.Shared.Prototypes;
  9. using Robust.Shared.Random;
  10. using Content.Shared.EntityTable.EntitySelectors;
  11. using Content.Shared.EntityTable;
  12. namespace Content.Server.StationEvents;
  13. public sealed class EventManagerSystem : EntitySystem
  14. {
  15. [Dependency] private readonly IConfigurationManager _configurationManager = default!;
  16. [Dependency] private readonly IPlayerManager _playerManager = default!;
  17. [Dependency] private readonly IRobustRandom _random = default!;
  18. [Dependency] private readonly IPrototypeManager _prototype = default!;
  19. [Dependency] private readonly EntityTableSystem _entityTable = default!;
  20. [Dependency] public readonly GameTicker GameTicker = default!;
  21. [Dependency] private readonly RoundEndSystem _roundEnd = default!;
  22. public bool EventsEnabled { get; private set; }
  23. private void SetEnabled(bool value) => EventsEnabled = value;
  24. public override void Initialize()
  25. {
  26. base.Initialize();
  27. Subs.CVar(_configurationManager, CCVars.EventsEnabled, SetEnabled, true);
  28. }
  29. /// <summary>
  30. /// Randomly runs a valid event.
  31. /// </summary>
  32. [Obsolete("use overload taking EnityTableSelector instead or risk unexpected results")]
  33. public void RunRandomEvent()
  34. {
  35. var randomEvent = PickRandomEvent();
  36. if (randomEvent == null)
  37. {
  38. var errStr = Loc.GetString("station-event-system-run-random-event-no-valid-events");
  39. Log.Error(errStr);
  40. return;
  41. }
  42. GameTicker.AddGameRule(randomEvent);
  43. }
  44. /// <summary>
  45. /// Randomly runs an event from provided EntityTableSelector.
  46. /// </summary>
  47. public void RunRandomEvent(EntityTableSelector limitedEventsTable)
  48. {
  49. if (!TryBuildLimitedEvents(limitedEventsTable, out var limitedEvents))
  50. {
  51. Log.Warning("Provided event table could not build dict!");
  52. return;
  53. }
  54. var randomLimitedEvent = FindEvent(limitedEvents); // this picks the event, It might be better to use the GetSpawns to do it, but that will be a major rebalancing fuck.
  55. if (randomLimitedEvent == null)
  56. {
  57. Log.Warning("The selected random event is null!");
  58. return;
  59. }
  60. if (!_prototype.TryIndex(randomLimitedEvent, out _))
  61. {
  62. Log.Warning("A requested event is not available!");
  63. return;
  64. }
  65. GameTicker.AddGameRule(randomLimitedEvent);
  66. }
  67. /// <summary>
  68. /// Returns true if the provided EntityTableSelector gives at least one prototype with a StationEvent comp.
  69. /// </summary>
  70. public bool TryBuildLimitedEvents(EntityTableSelector limitedEventsTable, out Dictionary<EntityPrototype, StationEventComponent> limitedEvents)
  71. {
  72. limitedEvents = new Dictionary<EntityPrototype, StationEventComponent>();
  73. var availableEvents = AvailableEvents(); // handles the player counts and individual event restrictions
  74. if (availableEvents.Count == 0)
  75. {
  76. Log.Warning("No events were available to run!");
  77. return false;
  78. }
  79. var selectedEvents = _entityTable.GetSpawns(limitedEventsTable);
  80. if (selectedEvents.Any() != true) // This is here so if you fuck up the table it wont die.
  81. return false;
  82. foreach (var eventid in selectedEvents)
  83. {
  84. if (!_prototype.TryIndex(eventid, out var eventproto))
  85. {
  86. Log.Warning("An event ID has no prototype index!");
  87. continue;
  88. }
  89. if (limitedEvents.ContainsKey(eventproto)) // This stops it from dying if you add duplicate entries in a fucked table
  90. continue;
  91. if (eventproto.Abstract)
  92. continue;
  93. if (!eventproto.TryGetComponent<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
  94. continue;
  95. if (!availableEvents.ContainsKey(eventproto))
  96. continue;
  97. limitedEvents.Add(eventproto, stationEvent);
  98. }
  99. if (!limitedEvents.Any())
  100. return false;
  101. return true;
  102. }
  103. /// <summary>
  104. /// Randomly picks a valid event.
  105. /// </summary>
  106. public string? PickRandomEvent()
  107. {
  108. var availableEvents = AvailableEvents();
  109. Log.Info($"Picking from {availableEvents.Count} total available events");
  110. return FindEvent(availableEvents);
  111. }
  112. /// <summary>
  113. /// Pick a random event from the available events at this time, also considering their weightings.
  114. /// </summary>
  115. /// <returns></returns>
  116. public string? FindEvent(Dictionary<EntityPrototype, StationEventComponent> availableEvents)
  117. {
  118. if (availableEvents.Count == 0)
  119. {
  120. Log.Warning("No events were available to run!");
  121. return null;
  122. }
  123. var sumOfWeights = 0.0f;
  124. foreach (var stationEvent in availableEvents.Values)
  125. {
  126. sumOfWeights += stationEvent.Weight;
  127. }
  128. sumOfWeights = _random.NextFloat(sumOfWeights);
  129. foreach (var (proto, stationEvent) in availableEvents)
  130. {
  131. sumOfWeights -= stationEvent.Weight;
  132. if (sumOfWeights <= 0.0f)
  133. {
  134. return proto.ID;
  135. }
  136. }
  137. Log.Error("Event was not found after weighted pick process!");
  138. return null;
  139. }
  140. /// <summary>
  141. /// Gets the events that have met their player count, time-until start, etc.
  142. /// </summary>
  143. /// <param name="playerCountOverride">Override for player count, if using this to simulate events rather than in an actual round.</param>
  144. /// <param name="currentTimeOverride">Override for round time, if using this to simulate events rather than in an actual round.</param>
  145. /// <returns></returns>
  146. public Dictionary<EntityPrototype, StationEventComponent> AvailableEvents(
  147. bool ignoreEarliestStart = false,
  148. int? playerCountOverride = null,
  149. TimeSpan? currentTimeOverride = null)
  150. {
  151. var playerCount = playerCountOverride ?? _playerManager.PlayerCount;
  152. // playerCount does a lock so we'll just keep the variable here
  153. var currentTime = currentTimeOverride ?? (!ignoreEarliestStart
  154. ? GameTicker.RoundDuration()
  155. : TimeSpan.Zero);
  156. var result = new Dictionary<EntityPrototype, StationEventComponent>();
  157. foreach (var (proto, stationEvent) in AllEvents())
  158. {
  159. if (CanRun(proto, stationEvent, playerCount, currentTime))
  160. {
  161. result.Add(proto, stationEvent);
  162. }
  163. }
  164. return result;
  165. }
  166. public Dictionary<EntityPrototype, StationEventComponent> AllEvents()
  167. {
  168. var allEvents = new Dictionary<EntityPrototype, StationEventComponent>();
  169. foreach (var prototype in _prototype.EnumeratePrototypes<EntityPrototype>())
  170. {
  171. if (prototype.Abstract)
  172. continue;
  173. if (!prototype.TryGetComponent<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
  174. continue;
  175. allEvents.Add(prototype, stationEvent);
  176. }
  177. return allEvents;
  178. }
  179. private int GetOccurrences(EntityPrototype stationEvent)
  180. {
  181. return GetOccurrences(stationEvent.ID);
  182. }
  183. private int GetOccurrences(string stationEvent)
  184. {
  185. return GameTicker.AllPreviousGameRules.Count(p => p.Item2 == stationEvent);
  186. }
  187. public TimeSpan TimeSinceLastEvent(EntityPrototype stationEvent)
  188. {
  189. foreach (var (time, rule) in GameTicker.AllPreviousGameRules.Reverse())
  190. {
  191. if (rule == stationEvent.ID)
  192. return time;
  193. }
  194. return TimeSpan.Zero;
  195. }
  196. private bool CanRun(EntityPrototype prototype, StationEventComponent stationEvent, int playerCount, TimeSpan currentTime)
  197. {
  198. if (GameTicker.IsGameRuleActive(prototype.ID))
  199. return false;
  200. if (stationEvent.MaxOccurrences.HasValue && GetOccurrences(prototype) >= stationEvent.MaxOccurrences.Value)
  201. {
  202. return false;
  203. }
  204. if (playerCount < stationEvent.MinimumPlayers)
  205. {
  206. return false;
  207. }
  208. if (currentTime != TimeSpan.Zero && currentTime.TotalMinutes < stationEvent.EarliestStart)
  209. {
  210. return false;
  211. }
  212. var lastRun = TimeSinceLastEvent(prototype);
  213. if (lastRun != TimeSpan.Zero && currentTime.TotalMinutes <
  214. stationEvent.ReoccurrenceDelay + lastRun.TotalMinutes)
  215. {
  216. return false;
  217. }
  218. if (_roundEnd.IsRoundEndRequested() && !stationEvent.OccursDuringRoundEnd)
  219. {
  220. return false;
  221. }
  222. return true;
  223. }
  224. }