-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXPXLevelsPlugin.cs
More file actions
3676 lines (3178 loc) · 130 KB
/
XPXLevelsPlugin.cs
File metadata and controls
3676 lines (3178 loc) · 130 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Globalization;
using System.Text.RegularExpressions;
using System.Text.Json;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Menu;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.ValveConstants.Protobuf;
using Microsoft.Extensions.Logging;
using GameTimer = CounterStrikeSharp.API.Modules.Timers.Timer;
namespace XPXLevels;
[MinimumApiVersion(80)]
public sealed partial class XPXLevelsPlugin : BasePlugin, IPluginConfig<XPXLevelsConfig>
{
private enum ForcedLoadoutType
{
Rifle,
Pistol,
Knife
}
private const int DefaultBotCount = 10;
private const string DefaultGameModeAlias = "casual";
private const int ReadOnlyLinesPerPage = 4;
private const int ReadOnlyWrapWidth = 28;
private const float TransientPanelDurationSeconds = 6.0f;
private const int TransitionSnapshotLifetimeMinutes = 10;
private const string PermissionRoot = "@XPX/root";
private const string PermissionMenu = "@XPX/menu";
private const string PermissionXp = "@XPX/xp";
private const string PermissionMap = "@XPX/map";
private const string PermissionKick = "@XPX/kick";
private const string PermissionVote = "@XPX/vote";
private static readonly Regex ColorTokenRegex = new(@"\{[A-Za-z]+\}", RegexOptions.Compiled);
private static readonly Dictionary<string, string> ColorTokens = new(StringComparer.OrdinalIgnoreCase)
{
["{Default}"] = ChatColors.Default.ToString(),
["{White}"] = ChatColors.White.ToString(),
["{DarkRed}"] = ChatColors.DarkRed.ToString(),
["{Green}"] = ChatColors.Green.ToString(),
["{LightYellow}"] = ChatColors.LightYellow.ToString(),
["{LightBlue}"] = ChatColors.LightBlue.ToString(),
["{Olive}"] = ChatColors.Olive.ToString(),
["{Lime}"] = ChatColors.Lime.ToString(),
["{Red}"] = ChatColors.Red.ToString(),
["{LightPurple}"] = ChatColors.LightPurple.ToString(),
["{Purple}"] = ChatColors.Purple.ToString(),
["{Grey}"] = ChatColors.Grey.ToString(),
["{Yellow}"] = ChatColors.Yellow.ToString(),
["{Gold}"] = ChatColors.Gold.ToString(),
["{Silver}"] = ChatColors.Silver.ToString(),
["{Blue}"] = ChatColors.Blue.ToString(),
["{DarkBlue}"] = ChatColors.DarkBlue.ToString(),
["{BlueGrey}"] = ChatColors.BlueGrey.ToString(),
["{Magenta}"] = ChatColors.Magenta.ToString(),
["{LightRed}"] = ChatColors.LightRed.ToString(),
["{Orange}"] = ChatColors.Orange.ToString()
};
private readonly Dictionary<ulong, PlayerProgress> _players = new();
private readonly Dictionary<int, ulong> _slotToSteamId = new();
private readonly Dictionary<ulong, GameTimer> _helpTimers = new();
private readonly Dictionary<ulong, GameTimer> _helpRefreshTimers = new();
private readonly Dictionary<ulong, CounterStrikeSharp.API.Core.Listeners.OnTick> _helpTickHandlers = new();
private readonly Dictionary<ulong, DateTimeOffset> _lastHelpToggleAt = new();
private readonly Dictionary<ulong, GameTimer> _levelUpCloseTimers = new();
private readonly Dictionary<ulong, GameTimer> _levelUpRefreshTimers = new();
private readonly Dictionary<ulong, CounterStrikeSharp.API.Core.Listeners.OnTick> _levelUpTickHandlers = new();
private readonly HashSet<ulong> _rtvVotes = new();
private readonly HashSet<ulong> _openHelpPanels = new();
private readonly Dictionary<ulong, string> _levelUpHtml = new();
private readonly Random _random = new();
private readonly LevelCurve _levelCurve = new();
private readonly Dictionary<ulong, TransitionSnapshotEntry> _transitionSnapshotBySteamId = new();
private XPXLevelsRepository? _repository;
private bool _forcedLoadoutModeEnabled;
private ForcedLoadoutType _forcedLoadout = ForcedLoadoutType.Rifle;
private MapVoteSession? _activeMapVote;
private GameTimer? _activeMapVoteTimer;
private GameTimer? _activeMapVoteReminderTimer;
private GameTimer? _autosaveTimer;
private string _selectedGameModeAlias = DefaultGameModeAlias;
private string? _transitionSnapshotPath;
private bool _notificationsEnabled = true;
public override string ModuleName => "XPX Levels";
public override string ModuleVersion => "1.4.3";
public override string ModuleAuthor => "OpenAI";
public override string ModuleDescription => "Levels, XP rewards, RTV, and admin tools for XPX CS2.";
public XPXLevelsConfig Config { get; set; } = new();
public void OnConfigParsed(XPXLevelsConfig config)
{
config.MaxLevel = Math.Clamp(config.MaxLevel, 1, 500);
config.BaseXpToLevel = Math.Max(1, config.BaseXpToLevel);
config.XpLinearGrowthPerLevel = Math.Max(0d, config.XpLinearGrowthPerLevel);
config.XpQuadraticGrowthPerLevel = Math.Max(0d, config.XpQuadraticGrowthPerLevel);
config.CasualCompetitiveKillXp = Math.Max(0, config.CasualCompetitiveKillXp);
config.FastModeKillXp = Math.Max(0, config.FastModeKillXp);
config.KnifeKillBonusXp = Math.Max(0, config.KnifeKillBonusXp);
config.HeadshotBonusXp = Math.Max(0, config.HeadshotBonusXp);
config.RoundWinXp = Math.Max(0, config.RoundWinXp);
config.BombPlantXp = Math.Max(0, config.BombPlantXp);
config.BombDefuseXp = Math.Max(0, config.BombDefuseXp);
config.AssistXp = Math.Max(0, config.AssistXp);
config.MvpXp = Math.Max(0, config.MvpXp);
config.ClutchXp = Math.Max(0, config.ClutchXp);
config.FirstBloodXp = Math.Max(0, config.FirstBloodXp);
config.CasualCompetitiveKillCredits = Math.Max(0, config.CasualCompetitiveKillCredits);
config.FastModeKillCredits = Math.Max(0, config.FastModeKillCredits);
config.RoundWinCredits = Math.Max(0, config.RoundWinCredits);
config.AssistCredits = Math.Max(0, config.AssistCredits);
config.MvpCredits = Math.Max(0, config.MvpCredits);
config.FirstBloodCredits = Math.Max(0, config.FirstBloodCredits);
config.ClutchCredits = Math.Max(0, config.ClutchCredits);
config.ChickenKillXp = Math.Max(0, config.ChickenKillXp);
config.BotXpMultiplier = Math.Clamp(config.BotXpMultiplier, 0d, 1d);
config.GambleWinChancePercent = Math.Clamp(config.GambleWinChancePercent, 1, 99);
config.GambleMinXp = Math.Max(1, config.GambleMinXp);
config.GambleMaxXp = Math.Max(config.GambleMinXp, config.GambleMaxXp);
config.GambleCooldownSeconds = Math.Max(0, config.GambleCooldownSeconds);
config.RtvRequiredRatio = Math.Clamp(config.RtvRequiredRatio, 0.10d, 1.0d);
config.RtvVoteDurationSeconds = Math.Max(10, config.RtvVoteDurationSeconds);
config.RtvReminderSeconds = Math.Clamp(config.RtvReminderSeconds, 0, Math.Max(0, config.RtvVoteDurationSeconds - 1));
config.RtvMapOptionCount = Math.Clamp(config.RtvMapOptionCount, 2, 8);
config.MapChangeDelaySeconds = Math.Max(1, config.MapChangeDelaySeconds);
config.TopCount = Math.Clamp(config.TopCount, 3, 15);
config.ChatPrefix = string.IsNullOrWhiteSpace(config.ChatPrefix) ? "{Green}[XPX]{Default}" : config.ChatPrefix.Trim();
config.ServerName = string.IsNullOrWhiteSpace(config.ServerName) ? "XPX CS2" : config.ServerName.Trim();
config.CurrencyName = string.IsNullOrWhiteSpace(config.CurrencyName) ? "Credits" : config.CurrencyName.Trim();
config.KickReason = string.IsNullOrWhiteSpace(config.KickReason) ? "Removed by an XPX admin." : config.KickReason.Trim();
config.WelcomeMessages = config.WelcomeMessages.Where(static message => !string.IsNullOrWhiteSpace(message)).ToList();
config.MapPool = config.MapPool.Where(static map => !string.IsNullOrWhiteSpace(map))
.Select(static map => map.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
config.WorkshopMaps = config.WorkshopMaps
.Where(workshopMap => !string.IsNullOrWhiteSpace(workshopMap.Id) && !string.IsNullOrWhiteSpace(workshopMap.Label))
.Select(workshopMap => new WorkshopMapOption
{
Id = workshopMap.Id.Trim(),
Label = workshopMap.Label.Trim()
})
.Where(workshopMap => workshopMap.Id.All(char.IsDigit))
.GroupBy(workshopMap => workshopMap.Id, StringComparer.OrdinalIgnoreCase)
.Select(static group => group.First())
.OrderBy(workshopMap => workshopMap.Label, StringComparer.OrdinalIgnoreCase)
.ToList();
config.AdminXpAmounts = config.AdminXpAmounts.Where(static amount => amount > 0)
.Distinct()
.OrderBy(static amount => amount)
.ToList();
config.GameModes = config.GameModes.Where(static mode => !string.IsNullOrWhiteSpace(mode.Label) && !string.IsNullOrWhiteSpace(mode.Alias))
.ToList();
config.Rewards = config.Rewards.Where(reward => reward.Level > 0 && reward.Level <= config.MaxLevel)
.OrderBy(reward => reward.Level)
.ToList();
config.KillstreakBonuses = config.KillstreakBonuses
.Where(static bonus => bonus.Threshold > 1)
.OrderBy(static bonus => bonus.Threshold)
.ToList();
config.MultikillBonuses = config.MultikillBonuses
.Where(static bonus => bonus.Kills > 1)
.OrderBy(static bonus => bonus.Kills)
.ToList();
config.DailyMissions = config.DailyMissions
.Where(static mission => !string.IsNullOrWhiteSpace(mission.Key) && mission.Goal > 0)
.ToList();
config.WeeklyMissions = config.WeeklyMissions
.Where(static mission => !string.IsNullOrWhiteSpace(mission.Key) && mission.Goal > 0)
.ToList();
config.Achievements = config.Achievements
.Where(static achievement => !string.IsNullOrWhiteSpace(achievement.Key) && achievement.Goal > 0)
.ToList();
config.ShopItems = config.ShopItems
.Where(static item => !string.IsNullOrWhiteSpace(item.Key) && item.CostCredits >= 0)
.ToList();
config.Crates = config.Crates
.Where(crate => !string.IsNullOrWhiteSpace(crate.Key) && crate.Rewards.Count > 0)
.Select(crate => new CrateDefinition
{
Key = crate.Key.Trim(),
Name = string.IsNullOrWhiteSpace(crate.Name) ? "XPX Case" : crate.Name.Trim(),
Description = string.IsNullOrWhiteSpace(crate.Description) ? "Weighted XPX reward crate." : crate.Description.Trim(),
CostCredits = Math.Max(0, crate.CostCredits),
Rewards = crate.Rewards
.Where(reward => !string.IsNullOrWhiteSpace(reward.Label))
.Select(reward => new CrateRewardDefinition
{
Label = reward.Label.Trim(),
Rarity = NormalizeCrateRarity(reward.Rarity),
RewardType = reward.RewardType,
RewardAmount = Math.Max(0, reward.RewardAmount),
DurationMinutes = Math.Max(0, reward.DurationMinutes),
Weight = Math.Max(1, reward.Weight)
})
.ToList()
})
.Where(crate => crate.Rewards.Count > 0)
.ToList();
Config = config;
_levelCurve.Rebuild(Config);
}
public override void Load(bool hotReload)
{
_repository = new XPXLevelsRepository(ModuleDirectory);
_repository.Initialize();
InitializeTransitionSnapshot();
_selectedGameModeAlias = ResolveInitialGameModeAlias();
RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterListener<Listeners.OnClientAuthorized>(OnClientAuthorized);
RegisterListener<Listeners.OnClientPutInServer>(OnClientPutInServer);
RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
AddCommandListener(null, OnAnyCommandPre, HookMode.Pre);
_autosaveTimer = AddTimer(60.0f, SaveAllPlayerProgress, TimerFlags.REPEAT);
ResetRtvState();
ScheduleOnlinePlayerSyncs();
}
public override void Unload(bool hotReload)
{
_autosaveTimer?.Kill();
_activeMapVoteTimer?.Kill();
_activeMapVoteReminderTimer?.Kill();
foreach (var timer in _helpRefreshTimers.Values)
{
timer.Kill();
}
foreach (var timer in _helpTimers.Values)
{
timer.Kill();
}
foreach (var timer in _levelUpRefreshTimers.Values)
{
timer.Kill();
}
foreach (var timer in _levelUpCloseTimers.Values)
{
timer.Kill();
}
if (_repository is null)
{
return;
}
SaveAllPlayerProgress();
}
[GameEventHandler]
public HookResult OnPlayerConnect(EventPlayerConnect @event, GameEventInfo info)
{
if (@event.Bot || @event.Xuid <= 0 || !IsRealPlayer(@event.Userid))
{
return HookResult.Continue;
}
var player = @event.Userid!;
_slotToSteamId[player.Slot] = @event.Xuid;
EnsurePlayerProgress(player, reloadFromRepository: true);
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnPlayerInfo(EventPlayerInfo @event, GameEventInfo info)
{
if (@event.Bot || @event.Steamid <= 0 || !IsRealPlayer(@event.Userid))
{
return HookResult.Continue;
}
var player = @event.Userid!;
_slotToSteamId[player.Slot] = @event.Steamid;
EnsurePlayerProgress(player, reloadFromRepository: true);
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnPlayerSpawn(EventPlayerSpawn @event, GameEventInfo info)
{
var player = @event.Userid;
if (!IsRealPlayer(player))
{
return HookResult.Continue;
}
var progress = EnsurePlayerProgress(player);
if (progress is null)
{
return HookResult.Continue;
}
AddTimer(0.25f, () =>
{
if (player is not null && IsRealPlayer(player))
{
ApplyRewardState(player, progress);
ApplySpecialLoadout(player);
}
}, TimerFlags.STOP_ON_MAPCHANGE);
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnPlayerDeath(EventPlayerDeath @event, GameEventInfo info)
{
if (IsWarmupActive())
{
return HookResult.Continue;
}
var attacker = @event.Attacker;
var victim = @event.Userid;
if (!IsRealPlayer(attacker) || !IsXpEligibleTarget(victim))
{
return HookResult.Continue;
}
var killer = attacker!;
var deadPlayer = victim!;
if (IsChickenTarget(deadPlayer))
{
AdjustXp(killer, Config.ChickenKillXp, "killing a chicken", true, applyXpBoost: true);
return HookResult.Continue;
}
if (!CanAwardKillXp(killer, deadPlayer))
{
return HookResult.Continue;
}
var knifeKill = IsKnifeKill(@event.Weapon);
var (xpToAward, reason) = GetKillXpAward(deadPlayer, knifeKill, @event.Headshot);
if (xpToAward <= 0)
{
return HookResult.Continue;
}
AdjustXp(killer, xpToAward, reason, Config.ShowKillXpMessages, applyXpBoost: true);
HandleKillFeatureProgress(killer, deadPlayer, @event.Weapon, @event.Headshot, knifeKill);
if (IsRealPlayer(@event.Assister) && @event.Assister != attacker && @event.Assister != victim)
{
HandleAssistFeatureProgress(@event.Assister!);
}
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnBombPlanted(EventBombPlanted @event, GameEventInfo info)
{
if (IsWarmupActive() || !IsRealPlayer(@event.Userid))
{
return HookResult.Continue;
}
AdjustXp(@event.Userid!, Config.BombPlantXp, "bomb plant", true, applyXpBoost: true);
HandleBombFeatureProgress(@event.Userid!, MissionObjective.BombPlants);
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnBombDefused(EventBombDefused @event, GameEventInfo info)
{
if (IsWarmupActive() || !IsRealPlayer(@event.Userid))
{
return HookResult.Continue;
}
AdjustXp(@event.Userid!, Config.BombDefuseXp, "bomb defuse", true, applyXpBoost: true);
HandleBombFeatureProgress(@event.Userid!, MissionObjective.BombDefuses);
return HookResult.Continue;
}
[GameEventHandler]
public HookResult OnRoundEnd(EventRoundEnd @event, GameEventInfo info)
{
if (IsWarmupActive() || Config.RoundWinXp <= 0)
{
return HookResult.Continue;
}
if (@event.Winner is not 2 and not 3)
{
return HookResult.Continue;
}
var winningTeam = (CsTeam)@event.Winner;
foreach (var player in GetHumanPlayers().Where(player => player.Team == winningTeam))
{
AdjustXp(player, Config.RoundWinXp, "round win", true, applyXpBoost: true);
}
HandleRoundWinFeatureProgress(winningTeam);
return HookResult.Continue;
}
[GameEventHandler(HookMode.Pre)]
public HookResult OnPlayerChat(EventPlayerChat @event, GameEventInfo info)
{
var player = Utilities.GetPlayerFromUserid(@event.Userid);
if (!IsRealPlayer(player))
{
return HookResult.Continue;
}
var text = @event.Text?.Trim();
if (string.IsNullOrWhiteSpace(text) || text.StartsWith('!') || text.StartsWith('/'))
{
return HookResult.Continue;
}
return HookResult.Continue;
}
[ConsoleCommand("css_level", "Show your current XPX level")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnLevelCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenLevelOverviewMenu(player!);
}
[ConsoleCommand("css_rank", "Show your current XPX rank")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnRankCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenRankOverviewMenu(player!);
}
[ConsoleCommand("css_top", "Show the XPX leaderboard")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnTopCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenTopOverviewMenu(player!);
}
[ConsoleCommand("css_help", "Show XPX help and progression info")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnHelpCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenHelpMenu(player!);
}
[ConsoleCommand("css_me", "Open your XPX quick menu")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnMeCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenMeMenu(player!);
}
[ConsoleCommand("css_commands", "Show the XPX command reference")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnCommandsCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenCommandsMenu(player!);
}
[ConsoleCommand("css_rewards", "Show the XPX reward ladder")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnRewardsCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenRewardsMenu(player!);
}
[ConsoleCommand("css_gamble", "Gamble a chunk of your XP")]
[CommandHelper(minArgs: 1, usage: "[xp]", whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnGambleCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
var progress = EnsurePlayerProgress(player);
if (progress is null)
{
return;
}
if (!int.TryParse(command.GetArg(1), out var requestedXp))
{
Reply(command, "{Red}Usage: {White}!gamble <xp>");
return;
}
requestedXp = Math.Clamp(requestedXp, Config.GambleMinXp, Config.GambleMaxXp);
if (progress.TotalXp < requestedXp)
{
Reply(command, "{Red}You do not have enough XP to gamble that amount.");
return;
}
var now = DateTimeOffset.UtcNow;
var nextAllowed = progress.LastGambleAttemptUtc.AddSeconds(Config.GambleCooldownSeconds);
if (Config.GambleCooldownSeconds > 0 && now < nextAllowed)
{
var secondsLeft = Math.Max(1, (int)Math.Ceiling((nextAllowed - now).TotalSeconds));
Reply(command, "{Red}You need to wait {White}" + secondsLeft + "{Red}s before gambling again.");
return;
}
progress.LastGambleAttemptUtc = now;
var gambler = player!;
var won = _random.Next(1, 101) <= Config.GambleWinChancePercent;
var delta = won ? requestedXp : -requestedXp;
AdjustXp(gambler, delta, "gamble", false);
Reply(command,
won
? "{Green}Lucky hit. You won {White}" + requestedXp.ToString("N0", CultureInfo.InvariantCulture) + "{Green} XP."
: "{Red}Bad beat. You lost {White}" + requestedXp.ToString("N0", CultureInfo.InvariantCulture) + "{Red} XP.");
}
[ConsoleCommand("css_rtv", "Rock the vote for a map change")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnRtvCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player) || !TryGetSteamId(player, out var steamId))
{
return;
}
SubmitRtvVote(player!, steamId);
}
[ConsoleCommand("css_vote", "Re-open the active XPX map vote")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnVoteCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
if (_activeMapVote is null)
{
Reply(command, "{Yellow}There is no active map vote right now.");
return;
}
OpenMapVoteMenu(player!);
}
[ConsoleCommand("css_admin", "Open the XPX admin menu")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
[RequiresPermissions(PermissionMenu)]
public void OnAdminCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
OpenAdminMenu(player!);
}
[ConsoleCommand("css_bindmenu", "Bind 1-9 to weapon slots and XPX menu input")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public void OnBindMenuCommand(CCSPlayerController? player, CommandInfo command)
{
if (!IsRealPlayer(player))
{
return;
}
ApplyPersistentMenuKeyBinds(player!);
Reply(player!, "{Green}XPX menu binds were applied with the server-side bind command.");
Reply(player!, "{Silver}Your {White}1-9{Silver} keys should now use weapon slots and also drive XPX menus.");
Reply(player!, "{Silver}If CS2 does not pick them up in the current session, restart CS2 once and they should load from your saved config.");
}
[ConsoleCommand("css_givexp", "Give XP to a player or target group")]
[RequiresPermissions(PermissionXp)]
[CommandHelper(minArgs: 2, usage: "[target] [amount]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnGiveXpCommand(CCSPlayerController? caller, CommandInfo command)
{
HandleAdminXpCommand(caller, command, true);
}
[ConsoleCommand("css_removexp", "Remove XP from a player or target group")]
[RequiresPermissions(PermissionXp)]
[CommandHelper(minArgs: 2, usage: "[target] [amount]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnRemoveXpCommand(CCSPlayerController? caller, CommandInfo command)
{
HandleAdminXpCommand(caller, command, false);
}
[ConsoleCommand("css_givecredits", "Give credits to a player or target group")]
[RequiresPermissions(PermissionXp)]
[CommandHelper(minArgs: 2, usage: "[target] [amount]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnGiveCreditsCommand(CCSPlayerController? caller, CommandInfo command)
{
HandleAdminCreditsCommand(caller, command, true);
}
[ConsoleCommand("css_removecredits", "Remove credits from a player or target group")]
[RequiresPermissions(PermissionXp)]
[CommandHelper(minArgs: 2, usage: "[target] [amount]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnRemoveCreditsCommand(CCSPlayerController? caller, CommandInfo command)
{
HandleAdminCreditsCommand(caller, command, false);
}
[ConsoleCommand("css_changemap", "Change to a specific map")]
[RequiresPermissions(PermissionMap)]
[CommandHelper(minArgs: 1, usage: "[map]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnChangeMapCommand(CCSPlayerController? caller, CommandInfo command)
{
ChangeMapTo(command.GetArg(1), caller?.PlayerName ?? "Console", command);
}
[ConsoleCommand("css_restartmap", "Restart the current map")]
[RequiresPermissions(PermissionMap)]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnRestartMapCommand(CCSPlayerController? caller, CommandInfo command)
{
RestartCurrentMap(caller?.PlayerName ?? "Console");
Reply(command, "{Gold}Restarting the current map.");
}
[ConsoleCommand("css_setmode", "Set the current game mode alias")]
[RequiresPermissions(PermissionMap)]
[CommandHelper(minArgs: 1, usage: "[alias]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnSetModeCommand(CCSPlayerController? caller, CommandInfo command)
{
if (!TryGetGameMode(command.GetArg(1), out var gameMode))
{
Reply(command, "{Red}Unknown mode. Valid aliases: {White}" + string.Join(", ", Config.GameModes.Select(mode => mode.Alias)));
return;
}
ApplyGameMode(gameMode, caller?.PlayerName ?? "Console");
Reply(command, "{Gold}Switching to {White}" + gameMode.Label + "{Gold}.");
}
[ConsoleCommand("css_kick", "Kick a player")]
[RequiresPermissions(PermissionKick)]
[CommandHelper(minArgs: 1, usage: "[target]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnKickCommand(CCSPlayerController? caller, CommandInfo command)
{
var targets = command.GetArgTargetResult(1).Players.Where(IsRealPlayer).ToList();
if (targets.Count == 0)
{
Reply(command, "{Red}No valid targets matched.");
return;
}
foreach (var target in targets)
{
if (caller is not null && !AdminManager.CanPlayerTarget(caller, target))
{
continue;
}
KickPlayer(target, caller?.PlayerName ?? "Console");
}
Reply(command, "{Gold}Kick command processed.");
}
[ConsoleCommand("css_kickbots", "Kick all bots and set bot quota to 0")]
[RequiresPermissions(PermissionKick)]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnKickBotsCommand(CCSPlayerController? caller, CommandInfo command)
{
KickAllBots(caller?.PlayerName ?? "Console", command, caller);
}
[ConsoleCommand("css_addbots", "Add bots back to the server")]
[RequiresPermissions(PermissionKick)]
[CommandHelper(usage: "[count]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnAddBotsCommand(CCSPlayerController? caller, CommandInfo command)
{
var desiredBots = DefaultBotCount;
if (command.ArgCount > 1)
{
if (!int.TryParse(command.GetArg(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out desiredBots))
{
Reply(command, "{Red}Invalid bot count. Use a whole number like {White}!addbots 6");
return;
}
}
AddBots(caller?.PlayerName ?? "Console", desiredBots, command, caller);
}
[ConsoleCommand("css_forceloadout", "Force a global rifle, pistol, or knife loadout for all players")]
[RequiresPermissions(PermissionMap)]
[CommandHelper(minArgs: 1, usage: "[rifle|pistol|knife|off]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnForceLoadoutCommand(CCSPlayerController? caller, CommandInfo command)
{
if (!TryParseForcedLoadout(command.GetArg(1), out var loadout, out var disable))
{
Reply(command, "{Red}Unknown loadout. Use {White}rifle{Red}, {White}pistol{Red}, {White}knife{Red}, or {White}off");
return;
}
if (disable)
{
DisableForcedLoadoutMode(caller?.PlayerName ?? "Console", command, caller);
return;
}
EnableForcedLoadoutMode(loadout, caller?.PlayerName ?? "Console", command, caller);
}
[ConsoleCommand("css_forcevote", "Start a map vote immediately")]
[RequiresPermissions(PermissionVote)]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnForceVoteCommand(CCSPlayerController? caller, CommandInfo command)
{
StartMapVote(caller, true);
Reply(command, "{Gold}Force vote command processed.");
}
[ConsoleCommand("css_cancelvote", "Cancel the active map vote")]
[RequiresPermissions(PermissionVote)]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
public void OnCancelVoteCommand(CCSPlayerController? caller, CommandInfo command)
{
CancelActiveVote(caller?.PlayerName ?? "Console", command);
}
private void OnMapStart(string mapName)
{
ResetRtvState();
ResetTransientUiState();
ResetFeatureRoundState();
ScheduleOnlinePlayerSyncs();
var desiredModeAlias = GetDesiredGameModeAliasForMapChange();
if (!string.IsNullOrWhiteSpace(desiredModeAlias))
{
AddTimer(1.0f, () =>
{
ApplyGameModeConVars(desiredModeAlias);
if (_forcedLoadoutModeEnabled)
{
ApplyForcedLoadoutServerRules();
ReapplyForcedLoadoutToAlivePlayers();
}
}, TimerFlags.STOP_ON_MAPCHANGE);
}
if (_forcedLoadoutModeEnabled)
{
_selectedGameModeAlias = "deathmatch";
}
AddTimer(90.0f, ClearTransitionSnapshot, TimerFlags.STOP_ON_MAPCHANGE);
}
private void OnClientAuthorized(int playerSlot, SteamID steamId)
{
_slotToSteamId[playerSlot] = steamId.SteamId64;
var player = Utilities.GetPlayerFromSlot(playerSlot);
if (IsRealPlayer(player))
{
EnsurePlayerProgress(player, reloadFromRepository: true);
}
}
private void OnClientPutInServer(int playerSlot)
{
AddTimer(3.0f, () =>
{
var player = Utilities.GetPlayerFromSlot(playerSlot);
if (!IsRealPlayer(player))
{
return;
}
var progress = EnsurePlayerProgress(player, reloadFromRepository: true);
if (progress is null)
{
return;
}
var joinedPlayer = player!;
EnsureFeatureStateLoaded(joinedPlayer);
ApplyRewardState(joinedPlayer, progress);
foreach (var message in Config.WelcomeMessages)
{
Reply(joinedPlayer, ExpandTokens(joinedPlayer, progress, message));
}
AddTimer(1.2f, () =>
{
if (!IsRealPlayer(joinedPlayer) || MenuManager.GetActiveMenu(joinedPlayer) is not null)
{
return;
}
OpenHelpMenu(joinedPlayer, autoOpened: true);
}, TimerFlags.STOP_ON_MAPCHANGE);
}, TimerFlags.STOP_ON_MAPCHANGE);
}
private void OnClientDisconnect(int playerSlot)
{
if (!_slotToSteamId.Remove(playerSlot, out var steamId))
{
return;
}
CloseHelpPanel(steamId);
StopLevelUpPanel(steamId, false);
_lastHelpToggleAt.Remove(steamId);
_rtvVotes.Remove(steamId);
_activeMapVote?.VotesBySteamId.Remove(steamId);
if (_repository is not null && _players.Remove(steamId, out var progress))
{
PersistProgressSafely(progress);
}
UnloadFeatureStateForPlayer(steamId);
}
private HookResult OnAnyCommandPre(CCSPlayerController? player, CommandInfo command)
{
if (IsRealPlayer(player) && TryHandleMenuSpecialKeySelection(player!, command))
{
return HookResult.Handled;
}
if (IsRealPlayer(player) && TryHandleMenuChatSelection(player!, command))
{
return HookResult.Handled;
}
return HookResult.Continue;
}
private void SaveAllPlayerProgress()
{
if (_repository is null)
{
return;
}
foreach (var progress in _players.Values)
{
PersistProgressSafely(progress);
}
SaveAllFeatureState();
SaveTransitionSnapshot();
}
private void PersistProgressSafely(PlayerProgress progress)
{
if (_repository is null)
{
return;
}
progress.PlayerName = NormalizeStoredPlayerName(progress.PlayerName);
NormalizeActiveBoosts(progress);
var storedProgress = _repository.GetPlayer(progress.SteamId);
if (storedProgress is null)
{
_repository.SavePlayer(progress);
return;
}
NormalizeActiveBoosts(storedProgress);
if (progress.TotalXp > storedProgress.TotalXp)
{
_repository.SavePlayer(progress);
return;
}
if (progress.Credits != storedProgress.Credits ||
progress.CrateTokens != storedProgress.CrateTokens ||
progress.XpBoostPercent != storedProgress.XpBoostPercent ||
progress.XpBoostExpiresUtc != storedProgress.XpBoostExpiresUtc)
{
_repository.SavePlayer(progress);
return;
}
if (progress.TotalXp < storedProgress.TotalXp)
{
Logger.LogWarning("XPX skipped stale backup save for {SteamId}: in-memory {CurrentXp} XP is lower than stored {StoredXp} XP", progress.SteamId, progress.TotalXp, storedProgress.TotalXp);
return;
}
if (progress.TotalXp == storedProgress.TotalXp &&
!string.Equals(progress.PlayerName, storedProgress.PlayerName, StringComparison.Ordinal))
{
_repository.SavePlayer(progress);
}
}
private void SyncOnlinePlayers()
{
foreach (var player in GetHumanPlayers())
{
var progress = EnsurePlayerProgress(player, reloadFromRepository: true);
if (progress is not null)
{
ApplyRewardState(player, progress, refreshEquipment: false);
}
}
}
private void InitializeTransitionSnapshot()
{
var dataDirectory = Path.Combine(Application.RootDirectory, "data", "XPXLevels");
Directory.CreateDirectory(dataDirectory);
_transitionSnapshotPath = Path.Combine(dataDirectory, "transition-snapshot.json");
LoadTransitionSnapshot();
}
private void LoadTransitionSnapshot()
{
_transitionSnapshotBySteamId.Clear();
if (string.IsNullOrWhiteSpace(_transitionSnapshotPath) || !File.Exists(_transitionSnapshotPath))
{
return;
}
try
{
var snapshot = JsonSerializer.Deserialize<TransitionSnapshot>(File.ReadAllText(_transitionSnapshotPath));
if (snapshot is null)
{
return;
}
if (DateTimeOffset.UtcNow - snapshot.CreatedUtc > TimeSpan.FromMinutes(TransitionSnapshotLifetimeMinutes))
{
ClearTransitionSnapshot();
return;
}
foreach (var entry in snapshot.Players.Where(static entry => entry.SteamId > 0))
{
_transitionSnapshotBySteamId[entry.SteamId] = entry;
}
}
catch
{