StationJobsSystem.Roundstart.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. using System.Linq;
  2. using Content.Server.Administration.Managers;
  3. using Content.Server.Antag;
  4. using Content.Server.Players.PlayTimeTracking;
  5. using Content.Server.Station.Components;
  6. using Content.Server.Station.Events;
  7. using Content.Shared.Preferences;
  8. using Content.Shared.Roles;
  9. using Robust.Server.Player;
  10. using Robust.Shared.Network;
  11. using Robust.Shared.Prototypes;
  12. using Robust.Shared.Random;
  13. using Robust.Shared.Utility;
  14. namespace Content.Server.Station.Systems;
  15. // Contains code for round-start spawning.
  16. public sealed partial class StationJobsSystem
  17. {
  18. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  19. [Dependency] private readonly IBanManager _banManager = default!;
  20. [Dependency] private readonly IPlayerManager _playerManager = default!;
  21. [Dependency] private readonly AntagSelectionSystem _antag = default!;
  22. private Dictionary<int, HashSet<string>> _jobsByWeight = default!;
  23. private List<int> _orderedWeights = default!;
  24. /// <summary>
  25. /// Sets up some tables used by AssignJobs, including jobs sorted by their weights, and a list of weights in order from highest to lowest.
  26. /// </summary>
  27. private void InitializeRoundStart()
  28. {
  29. _jobsByWeight = new Dictionary<int, HashSet<string>>();
  30. foreach (var job in _prototypeManager.EnumeratePrototypes<JobPrototype>())
  31. {
  32. if (!_jobsByWeight.ContainsKey(job.Weight))
  33. _jobsByWeight.Add(job.Weight, new HashSet<string>());
  34. _jobsByWeight[job.Weight].Add(job.ID);
  35. }
  36. _orderedWeights = _jobsByWeight.Keys.OrderByDescending(i => i).ToList();
  37. }
  38. /// <summary>
  39. /// Assigns jobs based on the given preferences and list of stations to assign for.
  40. /// This does NOT change the slots on the station, only figures out where each player should go.
  41. /// </summary>
  42. /// <param name="profiles">The profiles to use for selection.</param>
  43. /// <param name="stations">List of stations to assign for.</param>
  44. /// <param name="useRoundStartJobs">Whether or not to use the round-start jobs for the stations instead of their current jobs.</param>
  45. /// <returns>List of players and their assigned jobs.</returns>
  46. /// <remarks>
  47. /// You probably shouldn't use useRoundStartJobs mid-round if the station has been available to join,
  48. /// as there may end up being more round-start slots than available slots, which can cause weird behavior.
  49. /// A warning to all who enter ye cursed lands: This function is long and mildly incomprehensible. Best used without touching.
  50. /// </remarks>
  51. public Dictionary<NetUserId, (ProtoId<JobPrototype>?, EntityUid)> AssignJobs(Dictionary<NetUserId, HumanoidCharacterProfile> profiles, IReadOnlyList<EntityUid> stations, bool useRoundStartJobs = true)
  52. {
  53. DebugTools.Assert(stations.Count > 0);
  54. InitializeRoundStart();
  55. if (profiles.Count == 0)
  56. return new();
  57. // We need to modify this collection later, so make a copy of it.
  58. profiles = profiles.ShallowClone();
  59. // Player <-> (job, station)
  60. var assigned = new Dictionary<NetUserId, (ProtoId<JobPrototype>?, EntityUid)>(profiles.Count);
  61. // The jobs left on the stations. This collection is modified as jobs are assigned to track what's available.
  62. var stationJobs = new Dictionary<EntityUid, Dictionary<ProtoId<JobPrototype>, int?>>();
  63. foreach (var station in stations)
  64. {
  65. if (useRoundStartJobs)
  66. {
  67. stationJobs.Add(station, GetRoundStartJobs(station).ToDictionary(x => x.Key, x => x.Value));
  68. }
  69. else
  70. {
  71. stationJobs.Add(station, GetJobs(station).ToDictionary(x => x.Key, x => x.Value));
  72. }
  73. }
  74. // We reuse this collection. It tracks what jobs we're currently trying to select players for.
  75. var currentlySelectingJobs = new Dictionary<EntityUid, Dictionary<ProtoId<JobPrototype>, int?>>(stations.Count);
  76. foreach (var station in stations)
  77. {
  78. currentlySelectingJobs.Add(station, new Dictionary<ProtoId<JobPrototype>, int?>());
  79. }
  80. // And these.
  81. // Tracks what players are available for a given job in the current iteration of selection.
  82. var jobPlayerOptions = new Dictionary<ProtoId<JobPrototype>, HashSet<NetUserId>>();
  83. // Tracks the total number of slots for the given stations in the current iteration of selection.
  84. var stationTotalSlots = new Dictionary<EntityUid, int>(stations.Count);
  85. // The share of the players each station gets in the current iteration of job selection.
  86. var stationShares = new Dictionary<EntityUid, int>(stations.Count);
  87. // Ok so the general algorithm:
  88. // We start with the highest weight jobs and work our way down. We filter jobs by weight when selecting as well.
  89. // Weight > Priority > Station.
  90. foreach (var weight in _orderedWeights)
  91. {
  92. for (var selectedPriority = JobPriority.High; selectedPriority > JobPriority.Never; selectedPriority--)
  93. {
  94. if (profiles.Count == 0)
  95. goto endFunc;
  96. var candidates = GetPlayersJobCandidates(weight, selectedPriority, profiles);
  97. var optionsRemaining = 0;
  98. // Assigns a player to the given station, updating all the bookkeeping while at it.
  99. void AssignPlayer(NetUserId player, ProtoId<JobPrototype> job, EntityUid station)
  100. {
  101. // Remove the player from all possible jobs as that's faster than actually checking what they have selected.
  102. foreach (var (k, players) in jobPlayerOptions)
  103. {
  104. players.Remove(player);
  105. if (players.Count == 0)
  106. jobPlayerOptions.Remove(k);
  107. }
  108. stationJobs[station][job]--;
  109. profiles.Remove(player);
  110. assigned.Add(player, (job, station));
  111. optionsRemaining--;
  112. }
  113. jobPlayerOptions.Clear(); // We reuse this collection.
  114. // Goes through every candidate, and adds them to jobPlayerOptions, so that the candidate players
  115. // have an index sorted by job. We use this (much) later when actually assigning people to randomly
  116. // pick from the list of candidates for the job.
  117. foreach (var (user, jobs) in candidates)
  118. {
  119. foreach (var job in jobs)
  120. {
  121. if (!jobPlayerOptions.ContainsKey(job))
  122. jobPlayerOptions.Add(job, new HashSet<NetUserId>());
  123. jobPlayerOptions[job].Add(user);
  124. }
  125. optionsRemaining++;
  126. }
  127. // We reuse this collection, so clear it's children.
  128. foreach (var slots in currentlySelectingJobs)
  129. {
  130. slots.Value.Clear();
  131. }
  132. // Go through every station..
  133. foreach (var station in stations)
  134. {
  135. var slots = currentlySelectingJobs[station];
  136. // Get all of the jobs in the selected weight category.
  137. foreach (var (job, slot) in stationJobs[station])
  138. {
  139. if (_jobsByWeight[weight].Contains(job))
  140. slots.Add(job, slot);
  141. }
  142. }
  143. // Clear for reuse.
  144. stationTotalSlots.Clear();
  145. // Intentionally discounts the value of uncapped slots! They're only a single slot when deciding a station's share.
  146. foreach (var (station, jobs) in currentlySelectingJobs)
  147. {
  148. stationTotalSlots.Add(
  149. station,
  150. (int)jobs.Values.Sum(x => x ?? 1)
  151. );
  152. }
  153. var totalSlots = 0;
  154. // LINQ moment.
  155. // totalSlots = stationTotalSlots.Sum(x => x.Value);
  156. foreach (var (_, slot) in stationTotalSlots)
  157. {
  158. totalSlots += slot;
  159. }
  160. if (totalSlots == 0)
  161. continue; // No slots so just move to the next iteration.
  162. // Clear for reuse.
  163. stationShares.Clear();
  164. // How many players we've distributed so far. Used to grant any remaining slots if we have leftovers.
  165. var distributed = 0;
  166. // Goes through each station and figures out how many players we should give it for the current iteration.
  167. foreach (var station in stations)
  168. {
  169. // Calculates the percent share then multiplies.
  170. stationShares[station] = (int)Math.Floor(((float)stationTotalSlots[station] / totalSlots) * candidates.Count);
  171. distributed += stationShares[station];
  172. }
  173. // Avoids the fair share problem where if there's two stations and one player neither gets one.
  174. // We do this by simply selecting a station randomly and giving it the remaining share(s).
  175. if (distributed < candidates.Count)
  176. {
  177. var choice = _random.Pick(stations);
  178. stationShares[choice] += candidates.Count - distributed;
  179. }
  180. // Actual meat, goes through each station and shakes the tree until everyone has a job.
  181. foreach (var station in stations)
  182. {
  183. if (stationShares[station] == 0)
  184. continue;
  185. // The jobs we're selecting from for the current station.
  186. var currStationSelectingJobs = currentlySelectingJobs[station];
  187. // We only need this list because we need to go through this in a random order.
  188. // Oh the misery, another allocation.
  189. var allJobs = currStationSelectingJobs.Keys.ToList();
  190. _random.Shuffle(allJobs);
  191. // And iterates through all it's jobs in a random order until the count settles.
  192. // No, AFAIK it cannot be done any saner than this. I hate "shaking" collections as much
  193. // as you do but it's what seems to be the absolute best option here.
  194. // It doesn't seem to show up on the chart, perf-wise, anyway, so it's likely fine.
  195. int priorCount;
  196. do
  197. {
  198. priorCount = stationShares[station];
  199. foreach (var job in allJobs)
  200. {
  201. if (stationShares[station] == 0)
  202. break;
  203. if (currStationSelectingJobs[job] != null && currStationSelectingJobs[job] == 0)
  204. continue; // Can't assign this job.
  205. if (!jobPlayerOptions.ContainsKey(job))
  206. continue;
  207. // Picking players it finds that have the job set.
  208. var player = _random.Pick(jobPlayerOptions[job]);
  209. AssignPlayer(player, job, station);
  210. stationShares[station]--;
  211. if (currStationSelectingJobs[job] != null)
  212. currStationSelectingJobs[job]--;
  213. if (optionsRemaining == 0)
  214. goto done;
  215. }
  216. } while (priorCount != stationShares[station]);
  217. }
  218. done: ;
  219. }
  220. }
  221. endFunc:
  222. return assigned;
  223. }
  224. /// <summary>
  225. /// Attempts to assign overflow jobs to any player in allPlayersToAssign that is not in assignedJobs.
  226. /// </summary>
  227. /// <param name="assignedJobs">All assigned jobs.</param>
  228. /// <param name="allPlayersToAssign">All players that might need an overflow assigned.</param>
  229. /// <param name="profiles">Player character profiles.</param>
  230. /// <param name="stations">The stations to consider for spawn location.</param>
  231. public void AssignOverflowJobs(
  232. ref Dictionary<NetUserId, (ProtoId<JobPrototype>?, EntityUid)> assignedJobs,
  233. IEnumerable<NetUserId> allPlayersToAssign,
  234. IReadOnlyDictionary<NetUserId, HumanoidCharacterProfile> profiles,
  235. IReadOnlyList<EntityUid> stations)
  236. {
  237. var givenStations = stations.ToList();
  238. if (givenStations.Count == 0)
  239. return; // Don't attempt to assign them if there are no stations.
  240. // For players without jobs, give them the overflow job if they have that set...
  241. foreach (var player in allPlayersToAssign)
  242. {
  243. if (assignedJobs.ContainsKey(player))
  244. {
  245. continue;
  246. }
  247. var profile = profiles[player];
  248. if (profile.PreferenceUnavailable != PreferenceUnavailableMode.SpawnAsOverflow)
  249. {
  250. assignedJobs.Add(player, (null, EntityUid.Invalid));
  251. continue;
  252. }
  253. _random.Shuffle(givenStations);
  254. foreach (var station in givenStations)
  255. {
  256. // Pick a random overflow job from that station
  257. var overflows = GetOverflowJobs(station).ToList();
  258. _random.Shuffle(overflows);
  259. // Stations with no overflow slots should simply get skipped over.
  260. if (overflows.Count == 0)
  261. continue;
  262. // If the overflow exists, put them in as it.
  263. assignedJobs.Add(player, (overflows[0], givenStations[0]));
  264. break;
  265. }
  266. }
  267. }
  268. public void CalcExtendedAccess(Dictionary<EntityUid, int> jobsCount)
  269. {
  270. // Calculate whether stations need to be on extended access or not.
  271. foreach (var (station, count) in jobsCount)
  272. {
  273. var jobs = Comp<StationJobsComponent>(station);
  274. var thresh = jobs.ExtendedAccessThreshold;
  275. jobs.ExtendedAccess = count <= thresh;
  276. Log.Debug("Station {Station} on extended access: {ExtendedAccess}",
  277. Name(station), jobs.ExtendedAccess);
  278. }
  279. }
  280. /// <summary>
  281. /// Gets all jobs that the input players have that match the given weight and priority.
  282. /// </summary>
  283. /// <param name="weight">Weight to find, if any.</param>
  284. /// <param name="selectedPriority">Priority to find, if any.</param>
  285. /// <param name="profiles">Profiles to look in.</param>
  286. /// <returns>Players and a list of their matching jobs.</returns>
  287. private Dictionary<NetUserId, List<string>> GetPlayersJobCandidates(int? weight, JobPriority? selectedPriority, Dictionary<NetUserId, HumanoidCharacterProfile> profiles)
  288. {
  289. var outputDict = new Dictionary<NetUserId, List<string>>(profiles.Count);
  290. foreach (var (player, profile) in profiles)
  291. {
  292. var roleBans = _banManager.GetJobBans(player);
  293. var antagBlocked = _antag.GetPreSelectedAntagSessions();
  294. var profileJobs = profile.JobPriorities.Keys.Select(k => new ProtoId<JobPrototype>(k)).ToList();
  295. var ev = new StationJobsGetCandidatesEvent(player, profileJobs);
  296. RaiseLocalEvent(ref ev);
  297. List<string>? availableJobs = null;
  298. foreach (var jobId in profileJobs)
  299. {
  300. var priority = profile.JobPriorities[jobId];
  301. if (!(priority == selectedPriority || selectedPriority is null))
  302. continue;
  303. if (!_prototypeManager.TryIndex(jobId, out var job))
  304. continue;
  305. if (!job.CanBeAntag && (!_playerManager.TryGetSessionById(player, out var session) || antagBlocked.Contains(session)))
  306. continue;
  307. if (weight is not null && job.Weight != weight.Value)
  308. continue;
  309. if (!(roleBans == null || !roleBans.Contains(jobId)))
  310. continue;
  311. availableJobs ??= new List<string>(profile.JobPriorities.Count);
  312. availableJobs.Add(jobId);
  313. }
  314. if (availableJobs is not null)
  315. outputDict.Add(player, availableJobs);
  316. }
  317. return outputDict;
  318. }
  319. }