forked from space-wizards/space-station-14
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStationEventSystem.cs
More file actions
386 lines (321 loc) · 12.2 KB
/
StationEventSystem.cs
File metadata and controls
386 lines (321 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using System.Linq;
using System.Text;
using Content.Server.Administration.Logs;
using Content.Server.GameTicking;
using Content.Server.StationEvents.Events;
using Content.Shared.CCVar;
using Content.Shared.Database;
using Content.Shared.GameTicking;
using Content.Shared.StationEvents;
using JetBrains.Annotations;
using Robust.Server.Console;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Network;
using Robust.Shared.Random;
using Robust.Shared.Reflection;
namespace Content.Server.StationEvents
{
[UsedImplicitly]
// Somewhat based off of TG's implementation of events
public sealed class StationEventSystem : EntitySystem
{
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly IServerNetManager _netManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IConGroupController _conGroupController = default!;
[Dependency] private readonly GameTicker _gameTicker = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly AdminLogSystem _adminLog = default!;
public StationEvent? CurrentEvent { get; private set; }
public IReadOnlyCollection<StationEvent> StationEvents => _stationEvents;
private readonly List<StationEvent> _stationEvents = new();
private const float MinimumTimeUntilFirstEvent = 300;
/// <summary>
/// How long until the next check for an event runs
/// </summary>
/// Default value is how long until first event is allowed
private float _timeUntilNextEvent = MinimumTimeUntilFirstEvent;
/// <summary>
/// Whether random events can run
/// </summary>
/// If disabled while an event is running (even if admin run) it will disable it
public bool Enabled
{
get => _enabled;
set
{
if (_enabled == value)
{
return;
}
_enabled = value;
CurrentEvent?.Shutdown();
CurrentEvent = null;
}
}
private bool _enabled = true;
/// <summary>
/// Admins can get a list of all events available to run, regardless of whether their requirements have been met
/// </summary>
/// <returns></returns>
public string GetEventNames()
{
StringBuilder result = new StringBuilder();
foreach (var stationEvent in _stationEvents)
{
result.Append(stationEvent.Name + "\n");
}
return result.ToString();
}
/// <summary>
/// Admins can forcibly run events by passing in the Name
/// </summary>
/// <param name="name">The exact string for Name, without localization</param>
/// <returns></returns>
public string RunEvent(string name)
{
_adminLog.Add(LogType.EventRan, LogImpact.High, $"Event run: {name}");
// Could use a dictionary but it's such a minor thing, eh.
// Wasn't sure on whether to localize this given it's a command
var upperName = name.ToUpperInvariant();
foreach (var stationEvent in _stationEvents)
{
if (stationEvent.Name.ToUpperInvariant() != upperName)
{
continue;
}
CurrentEvent?.Shutdown();
CurrentEvent = stationEvent;
stationEvent.Announce();
return Loc.GetString("station-event-system-run-event", ("eventName", stationEvent.Name));
}
// I had string interpolation but lord it made it hard to read
return Loc.GetString("station-event-system-run-event-no-event-name", ("eventName", name));
}
/// <summary>
/// Randomly run a valid event <b>immediately</b>, ignoring earlieststart
/// </summary>
/// <returns></returns>
public string RunRandomEvent()
{
var randomEvent = PickRandomEvent();
if (randomEvent == null)
{
return Loc.GetString("station-event-system-run-random-event-no-valid-events");
}
CurrentEvent?.Shutdown();
CurrentEvent = randomEvent;
CurrentEvent.Startup();
return Loc.GetString("station-event-system-run-event",("eventName", randomEvent.Name));
}
/// <summary>
/// Randomly picks a valid event.
/// </summary>
public StationEvent? PickRandomEvent()
{
var availableEvents = AvailableEvents(true);
return FindEvent(availableEvents);
}
/// <summary>
/// Admins can stop the currently running event (if applicable) and reset the timer
/// </summary>
/// <returns></returns>
public string StopEvent()
{
string resultText;
if (CurrentEvent == null)
{
resultText = Loc.GetString("station-event-system-stop-event-no-running-event");
}
else
{
resultText = Loc.GetString("station-event-system-stop-event", ("eventName", CurrentEvent.Name));
CurrentEvent.Shutdown();
CurrentEvent = null;
}
ResetTimer();
return resultText;
}
public override void Initialize()
{
base.Initialize();
var reflectionManager = IoCManager.Resolve<IReflectionManager>();
var typeFactory = IoCManager.Resolve<IDynamicTypeFactory>();
foreach (var type in reflectionManager.GetAllChildren(typeof(StationEvent)))
{
if (type.IsAbstract) continue;
var stationEvent = (StationEvent) typeFactory.CreateInstance(type);
IoCManager.InjectDependencies(stationEvent);
_stationEvents.Add(stationEvent);
}
// Can't just check debug / release for a default given mappers need to use release mode
// As such we'll always pause it by default.
_configurationManager.OnValueChanged(CCVars.EventsEnabled, value => Enabled = value, true);
_netManager.RegisterNetMessage<MsgRequestStationEvents>(RxRequest);
_netManager.RegisterNetMessage<MsgStationEvents>();
SubscribeLocalEvent<RoundRestartCleanupEvent>(Reset);
}
private void RxRequest(MsgRequestStationEvents msg)
{
if (_playerManager.TryGetSessionByChannel(msg.MsgChannel, out var player))
SendEvents(player);
}
private void SendEvents(IPlayerSession player)
{
if (!_conGroupController.CanCommand(player, "events"))
return;
var newMsg = new MsgStationEvents();
newMsg.Events = StationEvents.Select(e => e.Name).ToArray();
_netManager.ServerSendMessage(newMsg, player.ConnectedClient);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
if (!Enabled && CurrentEvent == null)
{
return;
}
// Stop events from happening in lobby and force active event to end if the round ends
if (Get<GameTicker>().RunLevel != GameRunLevel.InRound)
{
if (CurrentEvent != null)
{
Enabled = false;
}
return;
}
// Keep running the current event
if (CurrentEvent != null)
{
CurrentEvent.Update(frameTime);
// Shutdown the event and set the timer for the next event
if (!CurrentEvent.Running)
{
CurrentEvent.Shutdown();
CurrentEvent = null;
ResetTimer();
}
return;
}
// Make sure we only count down when no event is running.
if (_timeUntilNextEvent > 0 && CurrentEvent == null)
{
_timeUntilNextEvent -= frameTime;
return;
}
// No point hammering this trying to find events if none are available
var stationEvent = FindEvent(AvailableEvents());
if (stationEvent == null)
{
ResetTimer();
}
else
{
CurrentEvent = stationEvent;
CurrentEvent.Announce();
}
}
/// <summary>
/// Reset the event timer once the event is done.
/// </summary>
private void ResetTimer()
{
// 5 - 15 minutes. TG does 3-10 but that's pretty frequent
_timeUntilNextEvent = _random.Next(300, 900);
}
/// <summary>
/// Pick a random event from the available events at this time, also considering their weightings.
/// </summary>
/// <returns></returns>
private StationEvent? FindEvent(List<StationEvent> availableEvents)
{
if (availableEvents.Count == 0)
{
return null;
}
var sumOfWeights = 0;
foreach (var stationEvent in availableEvents)
{
sumOfWeights += (int) stationEvent.Weight;
}
sumOfWeights = _random.Next(sumOfWeights);
foreach (var stationEvent in availableEvents)
{
sumOfWeights -= (int) stationEvent.Weight;
if (sumOfWeights <= 0)
{
return stationEvent;
}
}
return null;
}
/// <summary>
/// Gets the events that have met their player count, time-until start, etc.
/// </summary>
/// <param name="ignoreEarliestStart"></param>
/// <returns></returns>
private List<StationEvent> AvailableEvents(bool ignoreEarliestStart = false)
{
TimeSpan currentTime;
var playerCount = _playerManager.PlayerCount;
// playerCount does a lock so we'll just keep the variable here
if (!ignoreEarliestStart)
{
currentTime = _gameTicker.RoundDuration();
}
else
{
currentTime = TimeSpan.Zero;
}
var result = new List<StationEvent>();
foreach (var stationEvent in _stationEvents)
{
if (CanRun(stationEvent, playerCount, currentTime))
{
result.Add(stationEvent);
}
}
return result;
}
private bool CanRun(StationEvent stationEvent, int playerCount, TimeSpan currentTime)
{
if (stationEvent.MaxOccurrences.HasValue && stationEvent.Occurrences >= stationEvent.MaxOccurrences.Value)
{
return false;
}
if (playerCount < stationEvent.MinimumPlayers)
{
return false;
}
if (currentTime != TimeSpan.Zero && currentTime.TotalMinutes < stationEvent.EarliestStart)
{
return false;
}
if (stationEvent.LastRun != TimeSpan.Zero && currentTime.TotalMinutes <
stationEvent.ReoccurrenceDelay + stationEvent.LastRun.TotalMinutes)
{
return false;
}
return true;
}
public override void Shutdown()
{
CurrentEvent?.Shutdown();
base.Shutdown();
}
public void Reset(RoundRestartCleanupEvent ev)
{
if (CurrentEvent?.Running == true)
{
CurrentEvent.Shutdown();
CurrentEvent = null;
}
foreach (var stationEvent in _stationEvents)
{
stationEvent.Occurrences = 0;
}
_timeUntilNextEvent = MinimumTimeUntilFirstEvent;
}
}
}