-
Notifications
You must be signed in to change notification settings - Fork 12
/
cwx.sp
584 lines (486 loc) · 17.9 KB
/
cwx.sp
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
/**
* [TF2] Custom Weapons X
*/
#pragma semicolon 1
#include <sourcemod>
#pragma newdecls required
#include <tf_econ_data>
#include <stocksoup/convars>
#include <stocksoup/math>
#include <stocksoup/tf/econ>
#include <stocksoup/tf/entity_prop_stocks>
#include <stocksoup/tf/weapon>
#include <tf2attributes>
#include <tf_custom_attributes>
#include <tf2utils>
#include <clientprefs>
#include <dhooks>
#tryinclude <autoversioning/version>
#if defined __ninjabuild_auto_version_included
#define VERSION_SUFFIX "-" ... GIT_COMMIT_SHORT_HASH
#else
#define VERSION_SUFFIX ""
#endif
public Plugin myinfo = {
name = "[TF2] Custom Weapons X",
author = "nosoop",
description = "Allows server operators to design their own weapons.",
version = "X.0.7" ... VERSION_SUFFIX,
url = "https://github.com/nosoop/SM-TFCustomWeaponsX"
}
// this is the maximum expected length of our UID
#define MAX_ITEM_IDENTIFIER_LENGTH 64
// this is the maximum length of the item name displayed to players
#define MAX_ITEM_NAME_LENGTH 128
// this is the number of slots allocated to our thing
#define NUM_ITEMS 7
// okay, so we can't use TFClassType even view_as'd
// otherwise it'll warn on array-based enumstruct
#define NUM_PLAYER_CLASSES 10
bool g_bRetrievedLoadout[MAXPLAYERS + 1];
char g_CurrentLoadout[MAXPLAYERS + 1][NUM_PLAYER_CLASSES][NUM_ITEMS][MAX_ITEM_IDENTIFIER_LENGTH];
// loadout entity, for persistence
// note for the future: we do *not* restore this on late load since the schema may have changed
int g_CurrentLoadoutEntity[MAXPLAYERS + 1][NUM_PLAYER_CLASSES][NUM_ITEMS];
Cookie g_ItemPersistCookies[NUM_PLAYER_CLASSES][NUM_ITEMS];
bool g_bForceReequipItems[MAXPLAYERS + 1];
ConVar sm_cwx_enable_loadout;
ConVar mp_stalemate_meleeonly;
#include "cwx/item_config.sp"
#include "cwx/item_entity.sp"
#include "cwx/item_export.sp"
#include "cwx/loadout_radio_menu.sp"
int g_attrdef_AllowedInMedievalMode;
public void OnPluginStart() {
LoadTranslations("cwx.phrases");
LoadTranslations("common.phrases");
LoadTranslations("core.phrases");
Handle hGameConf = LoadGameConfigFile("tf2.custom_weapons_x");
if (!hGameConf) {
SetFailState("Failed to load gamedata (tf2.custom_weapons_x).");
}
Handle dtGetLoadoutItem = DHookCreateFromConf(hGameConf, "CTFPlayer::GetLoadoutItem()");
DHookEnableDetour(dtGetLoadoutItem, true, OnGetLoadoutItemPost);
delete hGameConf;
HookEvent("player_spawn", OnPlayerSpawnPost);
HookUserMessage(GetUserMessageId("PlayerLoadoutUpdated"), OnPlayerLoadoutUpdated,
.post = OnPlayerLoadoutUpdatedPost);
CreateVersionConVar("cwx_version", "Custom Weapons X version.");
sm_cwx_enable_loadout = CreateConVar("sm_cwx_enable_loadout", "1",
"Allows players to receive custom items they have selected.");
RegAdminCmd("sm_cwx_equip", EquipItemCmd, ADMFLAG_ROOT);
RegAdminCmd("sm_cwx_equip_target", EquipItemCmdTarget, ADMFLAG_ROOT);
RegAdminCmd("sm_cwx_export", ExportActiveWeapon, ADMFLAG_ROOT);
// player commands
RegAdminCmd("sm_cwx", DisplayItems, 0);
AddCommandListener(DisplayItemsCompat, "sm_c");
AddCommandListener(DisplayItemsCompat, "sm_cus");
AddCommandListener(DisplayItemsCompat, "sm_custom");
mp_stalemate_meleeonly = FindConVar("mp_stalemate_meleeonly");
// TODO: I'd like to use a separate, independent database for this
// but leveraging the cookie system is easier for now
char cookieName[64], cookieDesc[128];
for (int c; c < NUM_PLAYER_CLASSES; c++) {
for (int i; i < NUM_ITEMS; i++) {
FormatEx(cookieName, sizeof(cookieName), "cwx_loadout_%d_%d", c, i);
FormatEx(cookieDesc, sizeof(cookieDesc),
"CWX loadout entry for class %d in slot %d", c, i);
g_ItemPersistCookies[c][i] = new Cookie(cookieName, cookieDesc,
CookieAccess_Private);
}
}
for (int i = 1; i <= MaxClients; i++) {
if (!IsClientConnected(i)) {
continue;
}
OnClientConnected(i);
if (IsClientAuthorized(i)) {
FetchLoadoutItems(i);
}
}
}
public void OnAllPluginsLoaded() {
BuildLoadoutSlotMenu();
g_attrdef_AllowedInMedievalMode =
TF2Econ_TranslateAttributeNameToDefinitionIndex("allowed in medieval mode");
}
public void OnMapStart() {
LoadCustomItemConfig();
PrecacheMenuResources();
}
/**
* Clear out per-client inventory from previous player.
*/
public void OnClientConnected(int client) {
g_bRetrievedLoadout[client] = false;
for (int c; c < NUM_PLAYER_CLASSES; c++) {
for (int i; i < NUM_ITEMS; i++) {
g_CurrentLoadout[client][c][i] = "";
g_CurrentLoadoutEntity[client][c][i] = INVALID_ENT_REFERENCE;
}
}
}
public void OnClientAuthorized(int client, const char[] auth) {
FetchLoadoutItems(client);
}
/**
* Called when we know our client is valid. Retrieve our loadout from our storage backend.
*
* `g_bRetrievedLoadout[client]` should be set once our loadout is retrieved, which may happen
* asynchronously.
*/
void FetchLoadoutItems(int client) {
if (AreClientCookiesCached(client)) {
OnClientCookiesCached(client);
}
}
public void OnClientCookiesCached(int client) {
for (int c; c < NUM_PLAYER_CLASSES; c++) {
for (int i; i < NUM_ITEMS; i++) {
g_ItemPersistCookies[c][i].Get(client, g_CurrentLoadout[client][c][i],
sizeof(g_CurrentLoadout[][][]));
}
}
g_bRetrievedLoadout[client] = true;
}
/**
* Testing command to equip the given item uid on the player.
*/
Action EquipItemCmd(int client, int argc) {
if (!client) {
return Plugin_Continue;
}
char itemuid[MAX_ITEM_IDENTIFIER_LENGTH];
GetCmdArgString(itemuid, sizeof(itemuid));
StripQuotes(itemuid);
TrimString(itemuid);
CustomItemDefinition item;
if (!GetCustomItemDefinition(itemuid, item)) {
ReplyToCommand(client, "Unknown custom item uid %s", itemuid);
} else if (!IsValidEntity(EquipCustomItem(client, item))) {
ReplyToCommand(client, "Failed to equip custom item uid %s", itemuid);
}
return Plugin_Handled;
}
/**
* Testing command to equip the given item uid on the specified target.
*/
Action EquipItemCmdTarget(int client, int argc) {
if (!client) {
return Plugin_Continue;
}
char targetString[64];
GetCmdArg(1, targetString, sizeof(targetString));
char itemuid[MAX_ITEM_IDENTIFIER_LENGTH];
GetCmdArg(2, itemuid, sizeof(itemuid));
StripQuotes(itemuid);
TrimString(itemuid);
CustomItemDefinition item;
if (!GetCustomItemDefinition(itemuid, item)) {
ReplyToCommand(client, "Unknown custom item uid %s", itemuid);
return Plugin_Handled;
}
bool multilang;
char targetName[MAX_NAME_LENGTH];
int targets[MAXPLAYERS], nTargetsOrFailureReason;
nTargetsOrFailureReason = ProcessTargetString(targetString, client,
targets, sizeof(targets), COMMAND_FILTER_NO_IMMUNITY,
targetName, sizeof(targetName), multilang);
if (nTargetsOrFailureReason <= 0) {
ReplyToTargetError(client, nTargetsOrFailureReason);
return Plugin_Handled;
}
for (int i; i < nTargetsOrFailureReason; i++) {
int target = targets[i];
if (!IsValidEntity(EquipCustomItem(target, item))) {
ReplyToCommand(client, "Failed to equip custom item uid %s on %N", itemuid, target);
}
}
return Plugin_Handled;
}
int s_LastUpdatedClient;
/**
* Called once the game has updated the player's loadout with all the weapons it wanted, but
* before the post_inventory_application event is fired.
*
* As other plugins may perform actions in response to our equip events, we have to wait until
* after the usermessage is sent before we can run our own logic.
*/
Action OnPlayerLoadoutUpdated(UserMsg msg_id, BfRead msg, const int[] players,
int playersNum, bool reliable, bool init) {
int client = msg.ReadByte();
s_LastUpdatedClient = GetClientSerial(client);
}
/**
* Called once the game has updated the player's loadout with all the weapons it wanted, but
* before the post_inventory_application event is fired.
*
* This is the point where we check our custom loadout settings, then create our items if
* necessary (because persistence is implemented, the player may already have our custom items,
* and we keep track of them so we don't unnecessarily reequip them).
*/
void OnPlayerLoadoutUpdatedPost(UserMsg msg_id, bool sent) {
if (!sm_cwx_enable_loadout.BoolValue) {
return;
}
int client = GetClientFromSerial(s_LastUpdatedClient);
int playerClass = view_as<int>(TF2_GetPlayerClass(client));
for (int i; i < NUM_ITEMS; i++) {
if (!g_CurrentLoadout[client][playerClass][i][0]) {
// no item specified, use default
continue;
}
// equip our item if it isn't already equipped, or if it's being killed
// the latter applies to items that are normally invalid for the class
int currentLoadoutItem = g_CurrentLoadoutEntity[client][playerClass][i];
if (g_bForceReequipItems[client] || !IsValidEntity(currentLoadoutItem)
|| GetEntityFlags(currentLoadoutItem) & FL_KILLME) {
// TODO validate that the player can access this item
CustomItemDefinition item;
if (!GetCustomItemDefinition(g_CurrentLoadout[client][playerClass][i], item)) {
continue;
}
if (!IsCustomItemAllowed(client, item)) {
continue;
}
g_CurrentLoadoutEntity[client][playerClass][i] =
EntIndexToEntRef(EquipCustomItem(client, item));
}
}
// TODO: switch to the correct slot if we're not holding anything
// as is the case again, this happens on non-valid-for-class items
}
void OnPlayerSpawnPost(Event event, const char[] name, bool dontBroadcast) {
int client = GetClientOfUserId(event.GetInt("userid"));
g_bForceReequipItems[client] = false;
}
/**
* Item persistence - we return our item's CEconItemView instance when the game looks up our
* inventory item. This prevents our custom item from being invalidated when touch resupply.
*
* The game expects there to be a valid CEconItemView pointer in certain areas of the code, so
* avoid returning a nullptr.
*/
MRESReturn OnGetLoadoutItemPost(int client, Handle hReturn, Handle hParams) {
if (!sm_cwx_enable_loadout.BoolValue) {
return MRES_Ignored;
}
// TODO: work around invalid class items being invalidated
int playerClass = DHookGetParam(hParams, 1);
int loadoutSlot = DHookGetParam(hParams, 2);
if (loadoutSlot < 0 || loadoutSlot >= NUM_ITEMS) {
return MRES_Ignored;
}
int storedItem = g_CurrentLoadoutEntity[client][playerClass][loadoutSlot];
if (!IsValidEntity(storedItem) || !HasEntProp(storedItem, Prop_Send, "m_Item")) {
// the loadout entity we keep track of isn't valid, so we may need to make one
// we expect to have to equip something new at this point
if (!g_CurrentLoadout[client][playerClass][loadoutSlot][0]) {
// we don't have a custom item; let the game process it
return MRES_Ignored;
}
/**
* we have a custom item we'd like to spawn in, don't return a loadout item, otherwise
* we may equip / unequip a weapon that has side effects (e.g. Gunslinger)
*
* we'll initialize our custom item later in `OnPlayerLoadoutUpdated`
*/
static int s_DefaultItem = INVALID_ENT_REFERENCE;
if (!IsValidEntity(s_DefaultItem)) {
s_DefaultItem = EntIndexToEntRef(TF2_SpawnWearable());
RemoveEntity(s_DefaultItem);
}
storedItem = s_DefaultItem;
}
Address pStoredItemView = GetEntityAddress(storedItem)
+ view_as<Address>(GetEntSendPropOffs(storedItem, "m_Item", true));
DHookSetReturn(hReturn, pStoredItemView);
return MRES_Supercede;
}
/**
* Handles a special case where the player is refunding all of their upgrades, which may stomp
* on any existing runtime attributes applied to our weapon.
*/
public Action OnClientCommandKeyValues(int client, KeyValues kv) {
char cmd[64];
kv.GetSectionName(cmd, sizeof(cmd));
/**
* Mark the player to always invalidate our items so they get reequipped during respawn --
* this is fine since TF2 manages to reapply upgrades to plugin-granted items.
*
* The player gets their loadout changed multiple times during respec so we can't just
* invalidate the reference in g_CurrentLoadoutEntity (since it'll be valid after the first
* change).
*
* Hopefully nobody's blocking "MVM_Respec", because that would leave this flag set.
* Otherwise we should be able to hook CUpgrades::GrantOrRemoveAllUpgrades() directly,
* though that incurs a gamedata burden.
*/
if (StrEqual(cmd, "MVM_Respec")) {
g_bForceReequipItems[client] = true;
}
}
public void OnClientCommandKeyValues_Post(int client, KeyValues kv) {
char cmd[64];
kv.GetSectionName(cmd, sizeof(cmd));
if (StrEqual(cmd, "MVM_Respec")) {
g_bForceReequipItems[client] = false;
}
}
/**
* Saves the current item into the loadout for the specified class.
*/
bool SetClientCustomLoadoutItem(int client, int playerClass, const char[] itemuid) {
CustomItemDefinition item;
if (!GetCustomItemDefinition(itemuid, item)) {
return false;
}
int itemSlot = item.loadoutPosition[playerClass];
if (0 <= itemSlot < NUM_ITEMS) {
strcopy(g_CurrentLoadout[client][playerClass][itemSlot],
sizeof(g_CurrentLoadout[][][]), itemuid);
g_ItemPersistCookies[playerClass][itemSlot].Set(client, itemuid);
g_CurrentLoadoutEntity[client][playerClass][itemSlot] = INVALID_ENT_REFERENCE;
} else {
return false;
}
OnClientCustomLoadoutItemModified(client, playerClass);
return true;
}
/**
* Unsets any existing item in the given loadout slot for the specified class.
*/
void UnsetClientCustomLoadoutItem(int client, int playerClass, int itemSlot) {
strcopy(g_CurrentLoadout[client][playerClass][itemSlot],
sizeof(g_CurrentLoadout[][][]), "");
g_ItemPersistCookies[playerClass][itemSlot].Set(client, "");
g_CurrentLoadoutEntity[client][playerClass][itemSlot] = INVALID_ENT_REFERENCE;
OnClientCustomLoadoutItemModified(client, playerClass);
}
/**
* Called when a player's custom inventory has changed. Decide if we should act on it.
*/
void OnClientCustomLoadoutItemModified(int client, int modifiedClass) {
if (view_as<int>(TF2_GetPlayerClass(client)) != modifiedClass) {
// do nothing if the loadout for the current class wasn't modified
return;
}
if (!sm_cwx_enable_loadout.BoolValue) {
// do nothing if user selections are disabled
return;
}
if (IsPlayerAllowedToRespawnOnLoadoutChange(client)) {
// see if the player is into being respawned on loadout changes
QueryClientConVar(client, "tf_respawn_on_loadoutchanges", OnLoadoutRespawnPreference);
} else {
PrintToChat(client, "%t", "LoadoutChangesUpdate");
}
}
/**
* Called after inventory change and we have the client's tf_respawn_on_loadoutchanges convar
* value. Respawn them if desired.
*/
void OnLoadoutRespawnPreference(QueryCookie cookie, int client, ConVarQueryResult result,
const char[] cvarName, const char[] cvarValue) {
if (result != ConVarQuery_Okay) {
return;
} else if (!StringToInt(cvarValue) || !IsPlayerAllowedToRespawnOnLoadoutChange(client)) {
// the second check for respawn room is in case we're somehow not in one between
// the query and the callback
PrintToChat(client, "%t", "LoadoutChangesUpdate");
return;
}
TF2_RespawnPlayer(client);
}
/**
* Returns whether or not the player can actually equip this item normally.
* (This does not prevent admins from forcibly applying the item to the player.)
*/
bool CanPlayerEquipItem(int client, const CustomItemDefinition item) {
TFClassType playerClass = TF2_GetPlayerClass(client);
if (item.loadoutPosition[playerClass] == -1) {
return false;
} else if (item.access[0] && !CheckCommandAccess(client, item.access, 0, true)) {
// this item requires access
return false;
}
return true;
}
/**
* Returns whether or not the player is in a respawn room that their team owns, for the purpose
* of repsawning on loadout change.
*/
static bool IsPlayerInRespawnRoom(int client) {
float vecMins[3], vecMaxs[3], vecCenter[3], vecOrigin[3];
GetClientMins(client, vecMins);
GetClientMaxs(client, vecMaxs);
GetClientAbsOrigin(client, vecOrigin);
GetCenterFromPoints(vecMins, vecMaxs, vecCenter);
AddVectors(vecOrigin, vecCenter, vecCenter);
return TF2Util_IsPointInRespawnRoom(vecCenter, client, true);
}
/**
* Returns whether or not the player is allowed to respawn on loadout changes.
*/
static bool IsPlayerAllowedToRespawnOnLoadoutChange(int client) {
if (!IsClientInGame(client) || !IsPlayerInRespawnRoom(client) || !IsPlayerAlive(client)) {
return false;
}
// prevent respawns on sudden death
// ideally we'd base this off of CTFGameRules::CanChangeClassInStalemate(), but that
// requires either gamedata or keeping track of the stalemate time ourselves
if (GameRules_GetRoundState() == RoundState_Stalemate) {
return false;
}
return true;
}
/**
* Returns whether or not the custom item is currently allowed. This is specifically for
* instances where the item may be temporarily restricted (Medieval, melee-only Sudden Death).
*/
static bool IsCustomItemAllowed(int client, const CustomItemDefinition item) {
if (!IsClientInGame(client)) {
return false;
}
TFClassType playerClass = TF2_GetPlayerClass(client);
int slot = item.loadoutPosition[playerClass];
// TODO work out other restrictions?
if (GameRules_GetRoundState() == RoundState_Stalemate && mp_stalemate_meleeonly.BoolValue) {
bool bMelee = slot == 2 || (playerClass == TFClass_Spy && (slot == 5 || slot == 6));
if (!bMelee) {
return false;
}
}
if (GameRules_GetProp("m_bPlayingMedieval")) {
bool bMedievalAllowed;
if (slot == 2) {
bMedievalAllowed = true;
}
if (!bMedievalAllowed) {
// non-melee item; time to check the schema...
bool bMedievalAllowedInSchema;
bool bNativeAttributeOverride;
if (item.nativeAttributes) {
char configValue[8];
item.nativeAttributes.GetString("allowed in medieval mode",
configValue, sizeof(configValue));
if (configValue[0]) {
// don't fallback to static attributes if override in config
bNativeAttributeOverride = true;
bMedievalAllowedInSchema = !!StringToInt(configValue);
}
}
if (!bNativeAttributeOverride && item.bKeepStaticAttributes) {
// TODO we should cache this...
ArrayList attribList = TF2Econ_GetItemStaticAttributes(item.defindex);
bMedievalAllowedInSchema =
attribList.FindValue(g_attrdef_AllowedInMedievalMode) != -1;
delete attribList;
}
if (!bMedievalAllowedInSchema) {
return false;
}
}
}
return true;
}