Files
Delta-v/Content.Server/StationEvents/EventManagerSystem.cs
T
SolStar d5716a8d41 New psionic ablility: Precognition (#2131)
* TESTING enable events for dev enviroment

* Add NextEventComponent

* Check for schedulers NextEventComponent

* Seperate gernateing event to its own method

* Add NextEventSystem and use in BasicStationEventSchedulerSystem

* TESTING: Override time and player restrictions

* Stash events in NextEventComponent (#1)

* Add NextEventComponent

* Check for schedulers NextEventComponent

* Seperate gernateing event to its own method

* Add NextEventSystem and use in BasicStationEventSchedulerSystem

* Format code

* Add nextEvent time perdiction

* Use RunTime instead of float minutes

* Bug fixes

* Add NextEvent to Ramping and Meteors

* Fix timing on BasticStationEvents

* initialize NextEventComponent when created

* Event scheduler caching (#2)

* Check for schedulers NextEventComponent

* Seperate gernateing event to its own method

* Add NextEventSystem and use in BasicStationEventSchedulerSystem

* Format code

* Add nextEvent time perdiction

* Use RunTime instead of float minutes

* Bug fixes

* Add NextEvent to Ramping and Meteors

* Fix timing on BasticStationEvents

* initialize NextEventComponent when created

---------

Signed-off-by: SolStar <44028047+ewokswagger@users.noreply.github.com>

* Revert "Event scheduler caching (#2)"

This reverts commit bf9cd26ed4.

* Revert "Merge branch 'seer' into stash-next-event"

This reverts commit 656ca26173, reversing
changes made to 36f45be10e.

* Revert "Caching next exent"

This reverts commit 9f1bee4131, reversing
changes made to 82678d9c18.

* Reapply "Event scheduler caching (#2)"

This reverts commit 82678d9c18.

* More merge conflict nonsence

* oops

* oops 2

* Oops 3

* Precognition Psionic ability (#3)

* Precognition ability added

* Precog get next event

* Get soonest event and display

* update prototypes with precog results

* Add random

* Use Timespan for UseDelay

* Damage breaks doafter

* typo

* fix localization

* fix do after

* Add effects durring do after

* Revert "TESTING enable events for dev enviroment"

This reverts commit 03453133bd.

* Revert testing changes

* add deltav comments

* Cleaning up!

* Move NextEvent to server space

* Fix NextEventId init value

* Reverted upstream file to block scoped namespace

* Add precognitnon result messages

* reverting testing changes for real

* Add admin alert for upcoming events

* Add sound effect

* make alert more subtule

* extended max window size

* fix message mixup

* yaml fixes

* more yaml fixes

* Delta Changes

* totaly a yaml error trust

* remove unsessesary weights

---------

Signed-off-by: SolStar <44028047+ewokswagger@users.noreply.github.com>
2024-12-19 03:55:15 +00:00

338 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 Content.Shared.DeltaV.CCVars; // DeltaV
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.Server.Psionics.Glimmer; // DeltaV
using Content.Shared.Psionics.Glimmer;
using System.Diagnostics.CodeAnalysis; // DeltaV
namespace Content.Server.StationEvents;
public sealed class EventManagerSystem : EntitySystem
{
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IPrototypeManager _prototype = default!;
[Dependency] private readonly EntityTableSystem _entityTable = default!;
[Dependency] public readonly GameTicker GameTicker = default!;
[Dependency] private readonly RoundEndSystem _roundEnd = default!;
[Dependency] private readonly GlimmerSystem _glimmer = default!; //Nyano - Summary: pulls in the glimmer system.
public bool EventsEnabled { get; private set; }
private void SetEnabled(bool value) => EventsEnabled = value;
public override void Initialize()
{
base.Initialize();
Subs.CVar(_configurationManager, CCVars.EventsEnabled, SetEnabled, true);
}
/// <summary>
/// Randomly runs a valid event.
/// </summary>
[Obsolete("use overload taking EnityTableSelector instead or risk unexpected results")]
public void RunRandomEvent()
{
var randomEvent = PickRandomEvent();
if (randomEvent == null)
{
var errStr = Loc.GetString("station-event-system-run-random-event-no-valid-events");
Log.Error(errStr);
return;
}
GameTicker.AddGameRule(randomEvent);
}
/// <summary>
/// Randomly runs an event from provided EntityTableSelector.
/// </summary>
public void RunRandomEvent(EntityTableSelector limitedEventsTable)
{
if (TryGenerateRandomEvent(limitedEventsTable, out string? randomLimitedEvent)) // DeltaV - seperated into own method
GameTicker.AddGameRule(randomLimitedEvent);
}
// DeltaV - overloaded for backwards compatiblity
public bool TryGenerateRandomEvent(EntityTableSelector limitedEventsTable, [NotNullWhen(true)] out string? randomLimitedEvent)
{
return TryGenerateRandomEvent(limitedEventsTable, out randomLimitedEvent, null);
}
// DeltaV - end overloaded for backwards compatiblity
// DeltaV - separate event generation method
/// <summary>
/// Returns a random event from the list of events given that can be run at a given time.
/// </summary>
/// <param name="limitedEventsTable">The list of events that can be chosen.</param>
/// <param name="randomLimitedEvent">Generated event</param>
/// <param name="eventRunTime">The time to use for checking time restrictions. Uses current time if null.</param>
/// <returns></returns>
public bool TryGenerateRandomEvent(EntityTableSelector limitedEventsTable, [NotNullWhen(true)] out string? randomLimitedEvent, TimeSpan? eventRunTime)
{
randomLimitedEvent = null;
if (!TryBuildLimitedEvents(limitedEventsTable, out var limitedEvents, eventRunTime))
{
Log.Warning("Provided event table could not build dict!");
return false;
}
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.
// DeltaV - randomLimitedEvent declared by enclosing method
if (randomLimitedEvent == null)
{
Log.Warning("The selected random event is null!");
return false;
}
if (!_prototype.TryIndex(randomLimitedEvent, out _))
{
Log.Warning("A requested event is not available!");
return false;
}
return true;
}
// DeltaV - end separate event generation method
// DeltaV - overloaded for backwards compatiblity
public bool TryBuildLimitedEvents(EntityTableSelector limitedEventsTable, out Dictionary<EntityPrototype, StationEventComponent> limitedEvents)
{
return TryBuildLimitedEvents(limitedEventsTable, out limitedEvents, null);
}
// DeltaV - end overloaded for backwards compatiblity
/// <summary>
/// Returns true if the provided EntityTableSelector gives at least one prototype with a StationEvent comp.
/// </summary>
public bool TryBuildLimitedEvents(EntityTableSelector limitedEventsTable, out Dictionary<EntityPrototype, StationEventComponent> limitedEvents, TimeSpan? eventRunTime) // DeltaV - Add a time overide
{
limitedEvents = new Dictionary<EntityPrototype, StationEventComponent>();
// DeltaV - Overide time for stashing events
var availableEvents = AvailableEvents(eventRunTime); // handles the player counts and individual event restrictions
if (availableEvents.Count == 0)
{
Log.Warning("No events were available to run!");
return false;
}
var selectedEvents = _entityTable.GetSpawns(limitedEventsTable);
if (selectedEvents.Any() != true) // This is here so if you fuck up the table it wont die.
return false;
foreach (var eventid in selectedEvents)
{
if (!_prototype.TryIndex(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.TryGetComponent<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
continue;
if (!availableEvents.ContainsKey(eventproto))
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;
}
// DeltaV - overloaded for backwards compatiblity
public Dictionary<EntityPrototype, StationEventComponent> AvailableEvents(
bool ignoreEarliestStart = false,
int? playerCountOverride = null,
TimeSpan? currentTimeOverride = null)
{
return AvailableEvents(null, ignoreEarliestStart, playerCountOverride, currentTimeOverride);
}
// DeltaV - end overloaded for backwards compatiblity
/// <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(
TimeSpan? eventRunTime,
bool ignoreEarliestStart = false,
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 ?? (
(!ignoreEarliestStart
? eventRunTime // DeltaV - Use eventRunTime instead of RoundDuration if provided
?? GameTicker.RoundDuration()
: TimeSpan.Zero)
);
var result = new Dictionary<EntityPrototype, StationEventComponent>();
foreach (var (proto, stationEvent) in AllEvents())
{
if (CanRun(proto, stationEvent, playerCount, currentTime))
{
result.Add(proto, stationEvent);
}
}
return result;
}
public Dictionary<EntityPrototype, StationEventComponent> AllEvents()
{
var allEvents = new Dictionary<EntityPrototype, StationEventComponent>();
foreach (var prototype in _prototype.EnumeratePrototypes<EntityPrototype>())
{
if (prototype.Abstract)
continue;
if (!prototype.TryGetComponent<StationEventComponent>(out var stationEvent))
continue;
allEvents.Add(prototype, stationEvent);
}
return allEvents;
}
private int GetOccurrences(EntityPrototype stationEvent)
{
return GetOccurrences(stationEvent.ID);
}
private int GetOccurrences(string stationEvent)
{
return GameTicker.AllPreviousGameRules.Count(p => p.Item2 == stationEvent);
}
public TimeSpan TimeSinceLastEvent(EntityPrototype stationEvent)
{
foreach (var (time, rule) in GameTicker.AllPreviousGameRules.Reverse())
{
if (rule == stationEvent.ID)
return time;
}
return TimeSpan.Zero;
}
private bool CanRun(EntityPrototype prototype, StationEventComponent stationEvent, int playerCount, TimeSpan currentTime)
{
if (GameTicker.IsGameRuleActive(prototype.ID))
return false;
if (stationEvent.MaxOccurrences.HasValue && GetOccurrences(prototype) >= stationEvent.MaxOccurrences.Value)
{
return false;
}
if (playerCount < stationEvent.MinimumPlayers)
{
return false;
}
if (currentTime != TimeSpan.Zero && currentTime.TotalMinutes < stationEvent.EarliestStart)
{
return false;
}
var lastRun = TimeSinceLastEvent(prototype);
if (lastRun != TimeSpan.Zero && currentTime.TotalMinutes <
stationEvent.ReoccurrenceDelay + lastRun.TotalMinutes)
{
return false;
}
// Nyano - Summary: - Begin modified code block: check for glimmer events.
// This could not be cleanly done anywhere else.
if (_configurationManager.GetCVar(DCCVars.GlimmerEnabled) &&
prototype.TryGetComponent<GlimmerEventComponent>(out var glimmerEvent) &&
(_glimmer.Glimmer < glimmerEvent.MinimumGlimmer ||
_glimmer.Glimmer > glimmerEvent.MaximumGlimmer))
{
return false;
}
// Nyano - End modified code block.
if (_roundEnd.IsRoundEndRequested() && !stationEvent.OccursDuringRoundEnd)
{
return false;
}
return true;
}
}