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 /* Create a convar lookup trie */
35 m_ConVarCache = sm_trie_create();
38 ConVarManager::~ConVarManager()
40 List<ConVarInfo *>::iterator iter;
42 /* Destroy our convar lookup trie */
43 sm_trie_destroy(m_ConVarCache);
45 /* Destroy all the ConVarInfo structures */
46 for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
54 void ConVarManager::OnSourceModAllInitialized()
56 /* Only valid with ServerGameDLL006 or greater */
57 if (g_SMAPI->GetGameDLLVersion() >= 6)
59 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
60 m_CanQueryConVars = true;
65 /* Set up access rights for the 'ConVar' handle type */
66 sec.access[HandleAccess_Read] = 0;
67 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
68 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
70 /* Create the 'ConVar' handle type */
71 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
73 /* Add the 'convars' option to the 'sm' console command */
74 g_RootMenu.AddRootConsoleCommand("convars", "View convars created by a plugin", this);
77 void ConVarManager::OnSourceModShutdown()
79 if (m_CanQueryConVars)
81 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
82 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, m_VSPIface, this, &ConVarManager::OnQueryCvarValueFinished, false);
85 IChangeableForward *fwd;
86 List<ConVarInfo *>::iterator i;
88 /* Iterate list of ConVarInfo structures */
89 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
91 fwd = (*i)->pChangeForward;
93 /* Free any convar-change forwards that still exist */
96 g_Forwards.ReleaseForward(fwd);
100 /* Remove the 'convars' option from the 'sm' console command */
101 g_RootMenu.RemoveRootConsoleCommand("convars", this);
103 /* Remove the 'ConVar' handle type */
104 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
107 void ConVarManager::OnSourceModVSPReceived(IServerPluginCallbacks *iface)
109 /* This will be called after OnSourceModAllInitialized(), so...
111 * If we haven't been able to hook the IServerGameDLL version at this point,
112 * then use hook IServerPluginCallbacks version from the engine.
115 /* The Ship currently only supports ServerPluginCallbacks001, but we need 002 */
116 if (g_IsOriginalEngine)
121 if (!m_CanQueryConVars)
125 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, iface, this, &ConVarManager::OnQueryCvarValueFinished, false);
126 m_CanQueryConVars = true;
130 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
132 ConVarList *pConVarList;
134 /* If plugin has a convar list, free its memory */
135 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
141 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
144 ConVar *pConVar = static_cast<ConVar *>(object);
146 /* Find convar in lookup trie */
147 sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
149 /* If convar was created by SourceMod plugin... */
152 /* Delete string allocations */
153 delete [] pConVar->GetName();
154 delete [] pConVar->GetDefault();
155 delete [] pConVar->GetHelpText();
157 /* Then unlink it from SourceMM */
158 g_SMAPI->UnregisterConCmdBase(g_PLAPI, pConVar);
162 void ConVarManager::OnRootConsoleCommand(const char *command, unsigned int argcount)
166 /* Get plugin index that was passed */
167 int id = atoi(g_RootMenu.GetArgument(2));
169 /* Get plugin object */
170 CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
174 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
178 /* Get plugin name */
179 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
180 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
182 ConVarList *pConVarList;
183 ConVarList::iterator iter;
185 /* If no convar list... */
186 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
188 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
192 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
193 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
195 /* Iterate convar list and display each one */
196 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
198 const ConVar *pConVar = (*iter);
199 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
205 /* Display usage of subcommand */
206 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
209 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)
211 ConVar *pConVar = NULL;
212 ConVarInfo *pInfo = NULL;
215 /* Find out if the convar exists already */
216 pConVar = icvar->FindVar(name);
218 /* If the convar already exists... */
221 /* First find out if we already have a handle to it */
222 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
224 return pInfo->handle;
226 /* If we don't, then create a new handle from the convar */
227 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
229 /* Create and initialize ConVarInfo structure */
230 pInfo = new ConVarInfo();
231 pInfo->handle = hndl;
232 pInfo->sourceMod = false;
233 pInfo->pChangeForward = NULL;
234 pInfo->origCallback = pConVar->GetCallback();
236 /* Insert struct into caches */
237 m_ConVars.push_back(pInfo);
238 sm_trie_insert(m_ConVarCache, name, pInfo);
244 /* To prevent creating a convar that has the same name as a console command... ugh */
245 ConCommandBase *pBase = icvar->GetCommands();
249 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
254 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
257 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
258 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
260 /* Add convar to plugin's list */
261 AddConVarToPluginList(pContext, pConVar);
263 /* Create a handle from the new convar */
264 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
266 /* Create and initialize ConVarInfo structure */
267 pInfo = new ConVarInfo();
268 pInfo->handle = hndl;
269 pInfo->sourceMod = true;
270 pInfo->pChangeForward = NULL;
271 pInfo->origCallback = NULL;
273 /* Insert struct into caches */
274 m_ConVars.push_back(pInfo);
275 sm_trie_insert(m_ConVarCache, name, pInfo);
280 Handle_t ConVarManager::FindConVar(const char *name)
282 ConVar *pConVar = NULL;
286 /* Search for convar */
287 pConVar = icvar->FindVar(name);
289 /* If it doesn't exist, then return an invalid handle */
295 /* At this point, the convar exists. So, find out if we already have a handle */
296 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
298 return pInfo->handle;
301 /* If we don't have a handle, then create a new one */
302 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
304 /* Create and initilize ConVarInfo structure */
305 pInfo = new ConVarInfo();
306 pInfo->handle = hndl;
307 pInfo->sourceMod = false;
308 pInfo->pChangeForward = NULL;
309 pInfo->origCallback = pConVar->GetCallback();
311 /* Insert struct into our caches */
312 m_ConVars.push_back(pInfo);
313 sm_trie_insert(m_ConVarCache, name, pInfo);
318 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
321 IChangeableForward *pForward;
323 /* Find the convar in the lookup trie */
324 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
326 /* Get the forward */
327 pForward = pInfo->pChangeForward;
329 /* If forward does not exist, create it */
332 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
333 pInfo->pChangeForward = pForward;
335 /* Install our own callback */
336 pConVar->InstallChangeCallback(OnConVarChanged);
339 /* Add function to forward's list */
340 pForward->AddFunction(pFunction);
344 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
347 IChangeableForward *pForward;
348 IPluginContext *pContext = pFunction->GetParentContext();
350 /* Find the convar in the lookup trie */
351 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
353 /* Get the forward */
354 pForward = pInfo->pChangeForward;
356 /* If the forward doesn't exist, we can't unhook anything */
359 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
363 /* Remove the function from the forward's list */
364 if (!pForward->RemoveFunction(pFunction))
366 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
370 /* If the forward now has 0 functions in it... */
371 if (pForward->GetFunctionCount() == 0)
373 /* Free this forward */
374 g_Forwards.ReleaseForward(pForward);
375 pInfo->pChangeForward = NULL;
377 /* Put back the original convar callback */
378 pConVar->InstallChangeCallback(pInfo->origCallback);
383 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
385 QueryCvarCookie_t cookie;
387 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
390 cookie = engine->StartQueryCvarValue(pPlayer, name);
392 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
395 ConVarQuery query = {cookie, pCallback, hndl};
396 m_ConVarQueries.push_back(query);
401 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
403 ConVarList *pConVarList;
404 ConVarList::iterator iter;
405 bool inserted = false;
406 const char *orig = pConVar->GetName();
408 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
410 /* Check plugin for an existing convar list */
411 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
413 pConVarList = new ConVarList();
414 plugin->SetProperty("ConVarList", pConVarList);
417 /* Insert convar into list which is sorted alphabetically */
418 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
420 if (strcmp(orig, (*iter)->GetName()) < 0)
422 pConVarList->insert(iter, pConVar);
430 pConVarList->push_back(pConVar);
434 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
436 /* If the values are the same, exit early in order to not trigger callbacks */
437 if (strcmp(pConVar->GetString(), oldValue) == 0)
442 Trie *pCache = g_ConVarManager.GetConVarCache();
445 /* Find the convar in the lookup trie */
446 sm_trie_retrieve(pCache, pConVar->GetName(), (void **)&pInfo);
448 FnChangeCallback origCallback = pInfo->origCallback;
449 IChangeableForward *pForward = pInfo->pChangeForward;
451 /* If there was a change callback installed previously, call it */
454 origCallback(pConVar, oldValue);
457 /* Now call forwards in plugins that have hooked this */
458 pForward->PushCell(pInfo->handle);
459 pForward->PushString(oldValue);
460 pForward->PushString(pConVar->GetString());
461 pForward->Execute(NULL);
464 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
466 IPluginFunction *pCallback = NULL;
468 List<ConVarQuery>::iterator iter;
470 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
472 ConVarQuery &query = (*iter);
474 if (query.cookie == cookie)
476 pCallback = query.pCallback;
487 pCallback->PushCell(cookie);
488 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
489 pCallback->PushCell(result);
490 pCallback->PushString(cvarName);
492 if (result == eQueryCvarValueStatus_ValueIntact)
494 pCallback->PushString(cvarValue);
496 pCallback->PushString("\0");
499 pCallback->PushCell(value);
500 pCallback->Execute(&ret);
502 m_ConVarQueries.erase(iter);
507 static int s_YamagramState = 0;
509 void _YamagramPrinterTwoPointOhOh(int yamagram)
514 g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
515 g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
516 g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
517 g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
518 g_RootMenu.ConsolePrint("-------------------------------");
519 _YamagramPrinterTwoPointOhOh(1);
522 g_RootMenu.ConsolePrint("Question Ichi (1)");
523 g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
524 g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
527 g_RootMenu.ConsolePrint("Question Ni (2)");
528 g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
529 g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
532 g_RootMenu.ConsolePrint("Question San (3)");
533 g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
534 g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
537 g_RootMenu.ConsolePrint("Question Yon (4)");
538 g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
539 g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
542 g_RootMenu.ConsolePrint("Question Go (5)");
543 g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
544 g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
547 g_RootMenu.ConsolePrint("Question Roku (6)");
548 g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
549 g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
552 g_RootMenu.ConsolePrint("Question Nana (7)");
553 g_RootMenu.ConsolePrint("What is my name?");
554 g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
560 s_YamagramState = yamagram;
563 void _IntExt_CallYamagrams()
565 bool correct = false;
566 const char *arg = engine->Cmd_Args();
568 if (!arg || arg[0] == '\0')
570 _YamagramPrinterTwoPointOhOh(s_YamagramState);
574 switch (s_YamagramState)
577 correct = !strcasecmp(arg, "eating grass");
580 correct = !strcasecmp(arg, "sombrero");
583 correct = !strcasecmp(arg, "david bailopan anderson");
586 correct = !strcasecmp(arg, "kaitei no kairan");
589 correct = !strcasecmp(arg, "life and death");
592 correct = !strcasecmp(arg, "because gabe wanted it that way");
595 g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
596 g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
597 g_RootMenu.ConsolePrint("-------------------------------");
598 _YamagramPrinterTwoPointOhOh(7);
603 correct = !strcasecmp(arg, "damaged soul");
606 g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
607 g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
608 g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
609 g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
610 g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
620 if (s_YamagramState > 0)
624 g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
625 g_RootMenu.ConsolePrint("-------------------------------");
628 g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
633 _YamagramPrinterTwoPointOhOh(s_YamagramState);
636 void _IntExt_EnableYamagrams()
638 static ConCommand *pCmd = NULL;
641 pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
642 g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
644 g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
648 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
650 if (strcmp(oldValue, "Good morning, DS-san.") == 0
651 && strcmp(pConVar->GetString(), "Good night, talking desk lamp.") == 0)
653 _IntExt_EnableYamagrams();