CatStation/Content.Server/StationEvents/EventManagerSystem.cs
Princess Cheeseballs 2c6ffecf62
Move GameTicker to Shared (#45834)
* Scope creep my ass

* why was this shit not pushed????

* gone...

* fix that

* review plus buildd

* asfsafsafsafsafas

* grug

* burber

* I'll fix this later

* shrimply die

* also this

* it's snerf or snuthin

* assaads

* round snend

* aaaa

* fix this shit for real

* actually, don't start GameRules until MapInit now that I think aboot it.

* forgot u

* don't actually need this part nullable

* Deffer comp removal

* one liner

* do that too

* chungus

* Honestly makes more sense here, plus WHY are we doing all that shit on "GameRuleAdded" rather than GameRuleStarted(?)

* deferred removal :V

* aaaaaaaaaaaaaaa

* whhop

* Whoop

* better

* landmine that I placed for myself then forgot about lmao

* cleanup

* FUCKING `!`

* gotovo

* amogus

* please don't check by metadata I beg

* waawsasfdfsasfa

* sfafsasfafsas

* fdsaasffsasfa

* code

* fix

* fasasffasfasfsad

* chungaas

* I may be stupid

* gra

* graaaaaaaaaaaaaaaaa

* comment

* gra

* clearing is not predicted and would require major refactors, so don't cache on client.

* lame shit :P

* last holes

* nukeopsfsafsasafsfafsa

* why  was that shit public bruh

* bubrbgwahrghfaka

* dynamic

* revert change that did nothing lmao
2026-09-16 19:34:19 +00:00

330 lines
12 KiB
C#

using System.Linq;
using Content.Server.GameTicking;
using Content.Server.RoundEnd;
using Content.Server.StationEvents.Components;
using Content.Shared.CCVar;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Content.Shared.EntityTable.EntitySelectors;
using Content.Shared.EntityTable;
using Content.Shared.GameTicking.Components;
namespace Content.Server.StationEvents;
public sealed partial class EventManagerSystem : EntitySystem
{
[Dependency] private IConfigurationManager _configurationManager = default!;
[Dependency] private IPlayerManager _playerManager = default!;
[Dependency] private IRobustRandom _random = default!;
[Dependency] private EntityTableSystem _entityTable = default!;
[Dependency] private ServerGameTicker _gameTicker = default!;
[Dependency] private RoundEndSystem _roundEnd = default!;
public bool EventsEnabled { get; private set; }
private void SetEnabled(bool value) => EventsEnabled = value;
public Dictionary<EntityPrototype, StationEventComponent>? AllEventCache;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<PrototypesReloadedEventArgs>(OnPrototypesReloaded);
Subs.CVar(_configurationManager, CCVars.EventsEnabled, SetEnabled, true);
}
private void OnPrototypesReloaded(PrototypesReloadedEventArgs args)
{
if (args.WasModified<EntityPrototype>())
AllEventCache = GetAllEvents();
}
/// <summary>
/// Randomly runs an event from provided EntityTableSelector.
/// </summary>
public void RunRandomEvent(EntityTableSelector limitedEventsTable)
{
if (!TryBuildLimitedEvents(limitedEventsTable, out var limitedEvents))
{
Log.Warning("Provided event table could not build dict!");
return;
}
// This picks the event. Arguably we should be doing this with GetSpawns but that would be a massive amount of YAML slop.
// Or you'd need a new table prototype which inherits from EntityTables with its own logic for events.
// It's a ton of effort that only results in Events being able to use GroupSelectors so not worth it unless you're insane.
if (FindEvent(limitedEvents) is not { } randomLimitedEvent)
{
Log.Warning("The selected random event is null!");
return;
}
if (!ProtoMan.Resolve(randomLimitedEvent, out _))
{
Log.Warning("A requested event is not available!");
return;
}
_gameTicker.AddGameRule(randomLimitedEvent);
}
/// <summary>
/// Builds a list of all possible events and their probabilities.
/// </summary>
public IEnumerable<(EntProtoId, double)> ListLimitedEvents(
EntityTableSelector limitedEventsTable,
TimeSpan? currentTime = null,
int? playerCount = null)
{
var selectedEvents = _entityTable.ListSpawns(limitedEventsTable);
return ListLimitedEvents(selectedEvents, currentTime, playerCount);
}
/// <inheritdoc cref="TryBuildLimitedEvents(IEnumerable{EntProtoId},out Dictionary{EntityPrototype,StationEventComponent},TimeSpan?,int?)"/>
public bool TryBuildLimitedEvents(
EntityTableSelector limitedEventsTable,
out Dictionary<EntityPrototype, StationEventComponent> limitedEvents,
TimeSpan? currentTime = null,
int? playerCount = null)
{
var selectedEvents = _entityTable.GetSpawns(limitedEventsTable);
return TryBuildLimitedEvents(selectedEvents, out limitedEvents, currentTime, playerCount);
}
public IEnumerable<(EntProtoId, double)> ListLimitedEvents(
IEnumerable<(EntProtoId, double)> selectedEvents,
TimeSpan? currentTime = null,
int? playerCount = null)
{
var limitedEvents = new List<(EntProtoId, double)>();
playerCount ??= _playerManager.PlayerCount;
// playerCount does a lock so we'll just keep the variable here
currentTime ??= _gameTicker.RoundDuration();
var totalWeight = 0f;
foreach (var (eventId, prob) in selectedEvents)
{
if (!ProtoMan.Resolve(eventId, out var eventproto))
continue;
if (eventproto.Abstract)
continue;
if (!eventproto.TryComp<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
continue;
if (!CanRun(eventproto, stationEvent, playerCount.Value, currentTime.Value))
continue;
limitedEvents.Add((eventproto, prob * stationEvent.Weight));
totalWeight += stationEvent.Weight;
}
if (!limitedEvents.Any() || totalWeight <= 0)
yield break;
for (var i = 0; i < limitedEvents.Count; i++)
{
var eventWeight = limitedEvents[i];
eventWeight.Item2 /= totalWeight;
yield return eventWeight;
}
}
/// <summary>
/// Builds a dictionary of valid event prototypes from a list of <see cref="EntProtoId"/>.
/// Dictionary output consists of the valid prototype as the key, and the <see cref="StationEventComponent"/> as the value.
/// </summary>
/// <param name="selectedEvents">List of events we're selecting from.</param>
/// <param name="limitedEvents">Dictionary we're outputting.</param>
/// <param name="currentTime">Optional override for station time.</param>
/// <param name="playerCount">Optional override for playerCount.</param>
/// <returns>Returns true if the provided EntProtoId list has at least one prototype with a StationEventComp that can successfully run!</returns>
public bool TryBuildLimitedEvents(
IEnumerable<EntProtoId> selectedEvents,
out Dictionary<EntityPrototype, StationEventComponent> limitedEvents,
TimeSpan? currentTime = null,
int? playerCount = null)
{
limitedEvents = new Dictionary<EntityPrototype, StationEventComponent>();
playerCount ??= _playerManager.PlayerCount;
// playerCount does a lock so we'll just keep the variable here
currentTime ??= _gameTicker.RoundDuration();
foreach (var eventid in selectedEvents)
{
if (_gameTicker.IsIgnored(eventid))
continue;
if (!ProtoMan.Resolve(eventid, out var eventproto))
{
Log.Warning("An event ID has no prototype index!");
continue;
}
if (limitedEvents.ContainsKey(eventproto)) // This stops it from dying if you add duplicate entries in a fucked table
continue;
if (eventproto.Abstract)
continue;
if (!eventproto.TryComp<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
continue;
if (!CanRun(eventproto, stationEvent, playerCount.Value, currentTime.Value))
continue;
limitedEvents.Add(eventproto, stationEvent);
}
if (!limitedEvents.Any())
return false;
return true;
}
/// <summary>
/// Randomly picks a valid event.
/// </summary>
public string? PickRandomEvent()
{
var availableEvents = AvailableEvents();
Log.Info($"Picking from {availableEvents.Count} total available events");
return FindEvent(availableEvents);
}
/// <summary>
/// Pick a random event from the available events at this time, also considering their weightings.
/// </summary>
/// <returns></returns>
public string? FindEvent(Dictionary<EntityPrototype, StationEventComponent> availableEvents)
{
if (availableEvents.Count == 0)
{
Log.Warning("No events were available to run!");
return null;
}
var sumOfWeights = 0.0f;
foreach (var stationEvent in availableEvents.Values)
{
sumOfWeights += stationEvent.Weight;
}
sumOfWeights = _random.NextFloat(sumOfWeights);
foreach (var (proto, stationEvent) in availableEvents)
{
sumOfWeights -= stationEvent.Weight;
if (sumOfWeights <= 0.0f)
{
return proto.ID;
}
}
Log.Error("Event was not found after weighted pick process!");
return null;
}
/// <summary>
/// Gets the events that have met their player count, time-until start, etc.
/// </summary>
/// <param name="playerCountOverride">Override for player count, if using this to simulate events rather than in an actual round.</param>
/// <param name="currentTimeOverride">Override for round time, if using this to simulate events rather than in an actual round.</param>
/// <returns></returns>
public Dictionary<EntityPrototype, StationEventComponent> AvailableEvents(
int? playerCountOverride = null,
TimeSpan? currentTimeOverride = null)
{
var playerCount = playerCountOverride ?? _playerManager.PlayerCount;
// playerCount does a lock so we'll just keep the variable here
var currentTime = currentTimeOverride ?? _gameTicker.RoundDuration();
var result = new Dictionary<EntityPrototype, StationEventComponent>();
foreach (var (proto, stationEvent) in AllEvents())
{
if (CanRun(proto, stationEvent, playerCount, currentTime))
{
result.Add(proto, stationEvent);
}
}
return result;
}
/// <summary>
/// Returns all events prototypes which exist. Prioritizes the cache.
/// </summary>
/// <returns>All event prototypes, and their event component.</returns>
public Dictionary<EntityPrototype, StationEventComponent> AllEvents()
{
return AllEventCache ?? GetAllEvents();
}
/// <summary>
/// Gets all event prototypes that exist. Private because you should be using the cache!
/// </summary>
private Dictionary<EntityPrototype, StationEventComponent> GetAllEvents()
{
var allEvents = new Dictionary<EntityPrototype, StationEventComponent>();
foreach (var prototype in ProtoMan.EnumeratePrototypes<EntityPrototype>())
{
if (prototype.Abstract)
continue;
if (!prototype.TryComp<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
continue;
allEvents.Add(prototype, stationEvent);
}
return allEvents;
}
// TODO: WRITE A TEST TO ENSURE THAT IF A EVENT HAS MAX OCCURRENCES, THAT IT WILL PROPERLY CANCEL ONLY WHEN THEY'RE HIT
private bool CanRun(EntityPrototype prototype, StationEventComponent stationEvent, int playerCount, TimeSpan currentTime)
{
// Do the really simple comparisons BEFORE we create an IEnumerable for GameRules :V
if (playerCount < stationEvent.MinimumPlayers)
return false;
if (currentTime != TimeSpan.Zero && currentTime.TotalMinutes < stationEvent.EarliestStart)
return false;
// Slightly slower if we don't care about MaxOccurrences, but that's not a huge issue in the context of the event scheduler.
var count = 0;
var lastRun = TimeSpan.Zero;
var ruleQuery = EntityQueryEnumerator<GameRuleComponent, MetaDataComponent>();
while (ruleQuery.MoveNext(out var rule, out var meta))
{
if (meta.EntityPrototype?.Name != prototype.ID)
continue;
count++;
if (lastRun < rule.ActivatedAt)
lastRun = rule.ActivatedAt;
}
if (stationEvent.MaxOccurrences.HasValue && count >= stationEvent.MaxOccurrences.Value)
return false;
if (lastRun != TimeSpan.Zero && currentTime.TotalMinutes < stationEvent.ReoccurrenceDelay + lastRun.TotalMinutes)
return false;
return !_roundEnd.IsRoundEndRequested() || stationEvent.OccursDuringRoundEnd || _roundEnd.CanCallOrRecall();
}
}