3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
15 #include "ConVarManager.h"
16 #include "HalfLife2.h"
17 #include "PluginSys.h"
18 #include "ForwardSys.h"
19 #include "HandleSys.h"
20 #include "sm_srvcmds.h"
21 #include "sm_stringutil.h"
22 #include <sh_vector.h>
24 ConVarManager g_ConVarManager;
26 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
27 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
29 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
30 typedef List<const ConVar *> ConVarList;
32 ConVarManager::ConVarManager() : m_ConVarType(0), m_VSPIface(NULL), m_CanQueryConVars(false)
34 #if PLAPI_VERSION < 12
35 m_IgnoreHandle = false;
38 /* Create a convar lookup trie */
39 m_ConVarCache = sm_trie_create();
42 ConVarManager::~ConVarManager()
44 List<ConVarInfo *>::iterator iter;
46 /* Destroy our convar lookup trie */
47 sm_trie_destroy(m_ConVarCache);
49 /* Destroy all the ConVarInfo structures */
50 for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
58 void ConVarManager::OnSourceModAllInitialized()
60 /* Only valid with ServerGameDLL006 or greater */
61 if (g_SMAPI->GetGameDLLVersion() >= 6)
63 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
64 m_CanQueryConVars = true;
69 /* Set up access rights for the 'ConVar' handle type */
70 sec.access[HandleAccess_Read] = 0;
71 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
72 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
74 /* Create the 'ConVar' handle type */
75 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
77 /* Add the 'convars' option to the 'sm' console command */
78 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
81 void ConVarManager::OnSourceModShutdown()
83 if (m_CanQueryConVars)
85 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
86 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, m_VSPIface, this, &ConVarManager::OnQueryCvarValueFinished, false);
89 IChangeableForward *fwd;
90 List<ConVarInfo *>::iterator i;
92 /* Iterate list of ConVarInfo structures */
93 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
95 fwd = (*i)->pChangeForward;
97 /* Free any convar-change forwards that still exist */
100 g_Forwards.ReleaseForward(fwd);
104 /* Remove the 'convars' option from the 'sm' console command */
105 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
107 /* Remove the 'ConVar' handle type */
108 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
111 void ConVarManager::OnSourceModVSPReceived(IServerPluginCallbacks *iface)
113 /* This will be called after OnSourceModAllInitialized(), so...
115 * If we haven't been able to hook the IServerGameDLL version at this point,
116 * then use hook IServerPluginCallbacks version from the engine.
119 /* The Ship currently only supports ServerPluginCallbacks001, but we need 002 */
120 if (g_IsOriginalEngine)
125 if (!m_CanQueryConVars)
129 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, iface, this, &ConVarManager::OnQueryCvarValueFinished, false);
130 m_CanQueryConVars = true;
134 #if PLAPI_VERSION >= 12
135 void ConVarManager::OnUnlinkConCommandBase(PluginId id, ConCommandBase *pCommand)
137 /* Only check convars that have not been created by SourceMod's core */
138 if (id != g_PLID && !pCommand->IsCommand())
141 const char *cvarName = pCommand->GetName();
142 HandleSecurity sec(NULL, g_pCoreIdent);
143 bool handleExists = sm_trie_retrieve(m_ConVarCache, cvarName, reinterpret_cast<void **>(&pInfo));
147 g_HandleSys.FreeHandle(pInfo->handle, &sec);
148 sm_trie_delete(m_ConVarCache, cvarName);
149 m_ConVars.remove(pInfo);
156 /* I truly detest this code */
157 void ConVarManager::OnMetamodPluginUnloaded(PluginId id)
160 const char *cvarName;
161 HandleSecurity sec(NULL, g_pCoreIdent);
163 List<ConVarInfo *>::iterator i;
164 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
167 cvarName = pInfo->name;
169 if (cvarName && !icvar->FindVar(cvarName))
171 m_IgnoreHandle = true;
172 g_HandleSys.FreeHandle(pInfo->handle, &sec);
174 sm_trie_delete(m_ConVarCache, cvarName);
183 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
185 ConVarList *pConVarList;
187 /* If plugin has a convar list, free its memory */
188 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
194 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
196 #if PLAPI_VERSION < 12
197 /* Lovely workaround for our workaround! */
200 m_IgnoreHandle = false;
206 ConVar *pConVar = static_cast<ConVar *>(object);
208 /* Find convar in lookup trie */
209 sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
211 /* If convar was created by SourceMod plugin... */
214 /* Delete string allocations */
215 delete [] pConVar->GetName();
216 delete [] pConVar->GetDefault();
217 delete [] pConVar->GetHelpText();
219 /* Then unlink it from SourceMM */
220 g_SMAPI->UnregisterConCmdBase(g_PLAPI, pConVar);
224 void ConVarManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
228 /* Get plugin index that was passed */
229 int id = atoi(g_RootMenu.GetArgument(2));
231 /* Get plugin object */
232 CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
236 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
240 /* Get plugin name */
241 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
242 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
244 ConVarList *pConVarList;
245 ConVarList::iterator iter;
247 /* If no convar list... */
248 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
250 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
254 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
255 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
257 /* Iterate convar list and display each one */
258 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
260 const ConVar *pConVar = (*iter);
261 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
267 /* Display usage of subcommand */
268 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
271 Handle_t ConVarManager::CreateConVar(IPluginContext *pContext, const char *name, const char *defaultVal, const char *description, int flags, bool hasMin, float min, bool hasMax, float max)
273 ConVar *pConVar = NULL;
274 ConVarInfo *pInfo = NULL;
277 /* Find out if the convar exists already */
278 pConVar = icvar->FindVar(name);
280 /* If the convar already exists... */
283 /* Add convar to plugin's list */
284 AddConVarToPluginList(pContext, pConVar);
286 /* First find out if we already have a handle to it */
287 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
289 return pInfo->handle;
291 /* If we don't, then create a new handle from the convar */
292 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
294 /* Create and initialize ConVarInfo structure */
295 pInfo = new ConVarInfo();
296 pInfo->handle = hndl;
297 pInfo->sourceMod = false;
298 pInfo->pChangeForward = NULL;
299 pInfo->origCallback = pConVar->GetCallback();
300 #if PLAPI_VERSION < 12
301 pInfo->name = sm_strdup(pConVar->GetName());
304 /* Insert struct into caches */
305 m_ConVars.push_back(pInfo);
306 sm_trie_insert(m_ConVarCache, name, pInfo);
312 /* To prevent creating a convar that has the same name as a console command... ugh */
313 ConCommandBase *pBase = icvar->GetCommands();
317 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
322 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
325 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
326 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
328 /* Add convar to plugin's list */
329 AddConVarToPluginList(pContext, pConVar);
331 /* Create a handle from the new convar */
332 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
334 /* Create and initialize ConVarInfo structure */
335 pInfo = new ConVarInfo();
336 pInfo->handle = hndl;
337 pInfo->sourceMod = true;
338 pInfo->pChangeForward = NULL;
339 pInfo->origCallback = NULL;
340 #if PLAPI_VERSION < 12
344 /* Insert struct into caches */
345 m_ConVars.push_back(pInfo);
346 sm_trie_insert(m_ConVarCache, name, pInfo);
351 Handle_t ConVarManager::FindConVar(const char *name)
353 ConVar *pConVar = NULL;
357 /* Search for convar */
358 pConVar = icvar->FindVar(name);
360 /* If it doesn't exist, then return an invalid handle */
366 /* At this point, the convar exists. So, find out if we already have a handle */
367 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
369 return pInfo->handle;
372 /* If we don't have a handle, then create a new one */
373 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
375 /* Create and initialize ConVarInfo structure */
376 pInfo = new ConVarInfo();
377 pInfo->handle = hndl;
378 pInfo->sourceMod = false;
379 pInfo->pChangeForward = NULL;
380 pInfo->origCallback = pConVar->GetCallback();
381 #if PLAPI_VERSION < 12
382 pInfo->name = sm_strdup(pConVar->GetName());
385 /* Insert struct into our caches */
386 m_ConVars.push_back(pInfo);
387 sm_trie_insert(m_ConVarCache, name, pInfo);
392 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
395 IChangeableForward *pForward;
397 /* Find the convar in the lookup trie */
398 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
400 /* Get the forward */
401 pForward = pInfo->pChangeForward;
403 /* If forward does not exist, create it */
406 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
407 pInfo->pChangeForward = pForward;
409 /* Install our own callback */
410 pConVar->InstallChangeCallback(OnConVarChanged);
413 /* Add function to forward's list */
414 pForward->AddFunction(pFunction);
418 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
421 IChangeableForward *pForward;
422 IPluginContext *pContext = pFunction->GetParentContext();
424 /* Find the convar in the lookup trie */
425 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
427 /* Get the forward */
428 pForward = pInfo->pChangeForward;
430 /* If the forward doesn't exist, we can't unhook anything */
433 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
437 /* Remove the function from the forward's list */
438 if (!pForward->RemoveFunction(pFunction))
440 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
444 /* If the forward now has 0 functions in it... */
445 if (pForward->GetFunctionCount() == 0)
447 /* Free this forward */
448 g_Forwards.ReleaseForward(pForward);
449 pInfo->pChangeForward = NULL;
451 /* Put back the original convar callback */
452 pConVar->InstallChangeCallback(pInfo->origCallback);
457 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
459 QueryCvarCookie_t cookie;
461 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
464 cookie = engine->StartQueryCvarValue(pPlayer, name);
466 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
469 ConVarQuery query = {cookie, pCallback, hndl};
470 m_ConVarQueries.push_back(query);
475 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
477 ConVarList *pConVarList;
478 ConVarList::iterator iter;
479 bool inserted = false;
480 const char *orig = pConVar->GetName();
482 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
484 /* Check plugin for an existing convar list */
485 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
487 pConVarList = new ConVarList();
488 plugin->SetProperty("ConVarList", pConVarList);
489 } else if (pConVarList->find(pConVar) != pConVarList->end()) {
490 /* If convar is already in list, then don't add it */
494 /* Insert convar into list which is sorted alphabetically */
495 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
497 if (strcmp(orig, (*iter)->GetName()) < 0)
499 pConVarList->insert(iter, pConVar);
507 pConVarList->push_back(pConVar);
511 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
513 /* If the values are the same, exit early in order to not trigger callbacks */
514 if (strcmp(pConVar->GetString(), oldValue) == 0)
519 Trie *pCache = g_ConVarManager.GetConVarCache();
522 /* Find the convar in the lookup trie */
523 sm_trie_retrieve(pCache, pConVar->GetName(), (void **)&pInfo);
525 FnChangeCallback origCallback = pInfo->origCallback;
526 IChangeableForward *pForward = pInfo->pChangeForward;
528 /* If there was a change callback installed previously, call it */
531 origCallback(pConVar, oldValue);
534 /* Now call forwards in plugins that have hooked this */
535 pForward->PushCell(pInfo->handle);
536 pForward->PushString(oldValue);
537 pForward->PushString(pConVar->GetString());
538 pForward->Execute(NULL);
541 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
543 IPluginFunction *pCallback = NULL;
545 List<ConVarQuery>::iterator iter;
547 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
549 ConVarQuery &query = (*iter);
551 if (query.cookie == cookie)
553 pCallback = query.pCallback;
564 pCallback->PushCell(cookie);
565 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
566 pCallback->PushCell(result);
567 pCallback->PushString(cvarName);
569 if (result == eQueryCvarValueStatus_ValueIntact)
571 pCallback->PushString(cvarValue);
573 pCallback->PushString("\0");
576 pCallback->PushCell(value);
577 pCallback->Execute(&ret);
579 m_ConVarQueries.erase(iter);
584 static int s_YamagramState = 0;
586 void _YamagramPrinterTwoPointOhOh(int yamagram)
591 g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
592 g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
593 g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
594 g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
595 g_RootMenu.ConsolePrint("-------------------------------");
596 _YamagramPrinterTwoPointOhOh(1);
599 g_RootMenu.ConsolePrint("Question Ichi (1)");
600 g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
601 g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
604 g_RootMenu.ConsolePrint("Question Ni (2)");
605 g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
606 g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
609 g_RootMenu.ConsolePrint("Question San (3)");
610 g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
611 g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
614 g_RootMenu.ConsolePrint("Question Yon (4)");
615 g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
616 g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
619 g_RootMenu.ConsolePrint("Question Go (5)");
620 g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
621 g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
624 g_RootMenu.ConsolePrint("Question Roku (6)");
625 g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
626 g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
629 g_RootMenu.ConsolePrint("Question Nana (7)");
630 g_RootMenu.ConsolePrint("What is my name?");
631 g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
637 s_YamagramState = yamagram;
640 void _IntExt_CallYamagrams()
642 bool correct = false;
643 const char *arg = engine->Cmd_Args();
645 if (!arg || arg[0] == '\0')
647 _YamagramPrinterTwoPointOhOh(s_YamagramState);
651 switch (s_YamagramState)
654 correct = !strcasecmp(arg, "eating grass");
657 correct = !strcasecmp(arg, "sombrero");
660 correct = !strcasecmp(arg, "david bailopan anderson");
663 correct = !strcasecmp(arg, "kaitei no kairan");
666 correct = !strcasecmp(arg, "life and death");
669 correct = !strcasecmp(arg, "because gabe wanted it that way");
672 g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
673 g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
674 g_RootMenu.ConsolePrint("-------------------------------");
675 _YamagramPrinterTwoPointOhOh(7);
680 correct = !strcasecmp(arg, "damaged soul");
683 g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
684 g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
685 g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
686 g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
687 g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
697 if (s_YamagramState > 0)
701 g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
702 g_RootMenu.ConsolePrint("-------------------------------");
705 g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
710 _YamagramPrinterTwoPointOhOh(s_YamagramState);
713 void _IntExt_EnableYamagrams()
715 static ConCommand *pCmd = NULL;
718 pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
719 g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
721 g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
725 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
727 if (strcmp(oldValue, "Good morning, DS-san.") == 0
728 && strcmp(pConVar->GetString(), "Good night, talking desk lamp.") == 0)
730 _IntExt_EnableYamagrams();