extensions can now be built for multiple engines, and will autoload from auto.X.Y folders
3 * =============================================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
32 #include "ConVarManager.h"
33 #include "HalfLife2.h"
34 #include "PluginSys.h"
35 #include "ForwardSys.h"
36 #include "HandleSys.h"
37 #include "sm_srvcmds.h"
38 #include "sm_stringutil.h"
39 #include <sh_vector.h>
41 ConVarManager g_ConVarManager;
43 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
44 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
46 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
47 typedef List<const ConVar *> ConVarList;
49 ConVarManager::ConVarManager() : m_ConVarType(0), m_VSPIface(NULL), m_CanQueryConVars(false)
51 #if PLAPI_VERSION < 12
52 m_IgnoreHandle = false;
55 /* Create a convar lookup trie */
56 m_ConVarCache = sm_trie_create();
59 ConVarManager::~ConVarManager()
61 List<ConVarInfo *>::iterator iter;
63 /* Destroy our convar lookup trie */
64 sm_trie_destroy(m_ConVarCache);
66 /* Destroy all the ConVarInfo structures */
67 for (iter = m_ConVars.begin(); iter != m_ConVars.end(); iter++)
75 void ConVarManager::OnSourceModAllInitialized()
77 /* Only valid with ServerGameDLL006 or greater */
78 if (g_SMAPI->GetGameDLLVersion() >= 6)
80 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
81 m_CanQueryConVars = true;
86 /* Set up access rights for the 'ConVar' handle type */
87 sec.access[HandleAccess_Read] = 0;
88 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
89 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
91 /* Create the 'ConVar' handle type */
92 m_ConVarType = g_HandleSys.CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
94 /* Add the 'convars' option to the 'sm' console command */
95 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
98 void ConVarManager::OnSourceModShutdown()
100 if (m_CanQueryConVars)
102 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, OnQueryCvarValueFinished, gamedll, this, &ConVarManager::OnQueryCvarValueFinished, false);
103 SH_REMOVE_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, m_VSPIface, this, &ConVarManager::OnQueryCvarValueFinished, false);
106 IChangeableForward *fwd;
107 List<ConVarInfo *>::iterator i;
109 /* Iterate list of ConVarInfo structures */
110 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
112 fwd = (*i)->pChangeForward;
114 /* Free any convar-change forwards that still exist */
117 g_Forwards.ReleaseForward(fwd);
121 /* Remove the 'convars' option from the 'sm' console command */
122 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
124 /* Remove the 'ConVar' handle type */
125 g_HandleSys.RemoveType(m_ConVarType, g_pCoreIdent);
128 void ConVarManager::OnSourceModVSPReceived(IServerPluginCallbacks *iface)
130 /* This will be called after OnSourceModAllInitialized(), so...
132 * If we haven't been able to hook the IServerGameDLL version at this point,
133 * then use hook IServerPluginCallbacks version from the engine.
136 /* The Ship currently only supports ServerPluginCallbacks001, but we need 002 */
137 if (g_IsOriginalEngine)
142 if (!m_CanQueryConVars)
146 SH_ADD_HOOK_MEMFUNC(IServerPluginCallbacks, OnQueryCvarValueFinished, iface, this, &ConVarManager::OnQueryCvarValueFinished, false);
147 m_CanQueryConVars = true;
151 #if PLAPI_VERSION >= 12
152 void ConVarManager::OnUnlinkConCommandBase(PluginId id, ConCommandBase *pCommand)
154 /* Only check convars that have not been created by SourceMod's core */
155 if (id != g_PLID && !pCommand->IsCommand())
158 const char *cvarName = pCommand->GetName();
159 HandleSecurity sec(NULL, g_pCoreIdent);
160 bool handleExists = sm_trie_retrieve(m_ConVarCache, cvarName, reinterpret_cast<void **>(&pInfo));
164 g_HandleSys.FreeHandle(pInfo->handle, &sec);
165 sm_trie_delete(m_ConVarCache, cvarName);
166 m_ConVars.remove(pInfo);
173 /* I truly detest this code */
174 void ConVarManager::OnMetamodPluginUnloaded(PluginId id)
177 const char *cvarName;
178 HandleSecurity sec(NULL, g_pCoreIdent);
180 List<ConVarInfo *>::iterator i;
181 for (i = m_ConVars.begin(); i != m_ConVars.end(); i++)
184 cvarName = pInfo->name;
186 if (cvarName && !icvar->FindVar(cvarName))
188 m_IgnoreHandle = true;
189 g_HandleSys.FreeHandle(pInfo->handle, &sec);
191 sm_trie_delete(m_ConVarCache, cvarName);
200 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
202 ConVarList *pConVarList;
204 /* If plugin has a convar list, free its memory */
205 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
211 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
213 #if PLAPI_VERSION < 12
214 /* Lovely workaround for our workaround! */
217 m_IgnoreHandle = false;
223 ConVar *pConVar = static_cast<ConVar *>(object);
225 /* Find convar in lookup trie */
226 sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), reinterpret_cast<void **>(&info));
228 /* If convar was created by SourceMod plugin... */
231 /* Delete string allocations */
232 delete [] pConVar->GetName();
233 delete [] pConVar->GetDefault();
234 delete [] pConVar->GetHelpText();
236 /* Then unlink it from SourceMM */
237 g_SMAPI->UnregisterConCommandBase(g_PLAPI, pConVar);
241 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
243 int argcount = command.ArgC();
246 /* Get plugin index that was passed */
247 int id = atoi(command.Arg(2));
249 /* Get plugin object */
250 CPlugin *plugin = g_PluginSys.GetPluginByOrder(id);
254 g_RootMenu.ConsolePrint("[SM] Plugin index %d not found.", id);
258 /* Get plugin name */
259 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
260 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
262 ConVarList *pConVarList;
263 ConVarList::iterator iter;
265 /* If no convar list... */
266 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
268 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
272 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
273 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
275 /* Iterate convar list and display each one */
276 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
278 const ConVar *pConVar = (*iter);
279 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
285 /* Display usage of subcommand */
286 g_RootMenu.ConsolePrint("[SM] Usage: sm convars <plugin #>");
289 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)
291 ConVar *pConVar = NULL;
292 ConVarInfo *pInfo = NULL;
295 /* Find out if the convar exists already */
296 pConVar = icvar->FindVar(name);
298 /* If the convar already exists... */
301 /* Add convar to plugin's list */
302 AddConVarToPluginList(pContext, pConVar);
304 /* First find out if we already have a handle to it */
305 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
307 return pInfo->handle;
309 /* If we don't, then create a new handle from the convar */
310 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
312 /* Create and initialize ConVarInfo structure */
313 pInfo = new ConVarInfo();
314 pInfo->handle = hndl;
315 pInfo->sourceMod = false;
316 pInfo->pChangeForward = NULL;
317 pInfo->origCallback = pConVar->GetCallback();
318 #if PLAPI_VERSION < 12
319 pInfo->name = sm_strdup(pConVar->GetName());
322 /* Insert struct into caches */
323 m_ConVars.push_back(pInfo);
324 sm_trie_insert(m_ConVarCache, name, pInfo);
330 /* To prevent creating a convar that has the same name as a console command... ugh */
331 ConCommandBase *pBase = icvar->GetCommands();
335 if (pBase->IsCommand() && strcmp(pBase->GetName(), name) == 0)
340 pBase = const_cast<ConCommandBase *>(pBase->GetNext());
343 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
344 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
346 /* Add convar to plugin's list */
347 AddConVarToPluginList(pContext, pConVar);
349 /* Create a handle from the new convar */
350 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
352 /* Create and initialize ConVarInfo structure */
353 pInfo = new ConVarInfo();
354 pInfo->handle = hndl;
355 pInfo->sourceMod = true;
356 pInfo->pChangeForward = NULL;
357 pInfo->origCallback = NULL;
358 #if PLAPI_VERSION < 12
362 /* Insert struct into caches */
363 m_ConVars.push_back(pInfo);
364 sm_trie_insert(m_ConVarCache, name, pInfo);
369 Handle_t ConVarManager::FindConVar(const char *name)
371 ConVar *pConVar = NULL;
375 /* Search for convar */
376 pConVar = icvar->FindVar(name);
378 /* If it doesn't exist, then return an invalid handle */
384 /* At this point, the convar exists. So, find out if we already have a handle */
385 if (sm_trie_retrieve(m_ConVarCache, name, (void **)&pInfo))
387 return pInfo->handle;
390 /* If we don't have a handle, then create a new one */
391 hndl = g_HandleSys.CreateHandle(m_ConVarType, pConVar, NULL, g_pCoreIdent, NULL);
393 /* Create and initialize ConVarInfo structure */
394 pInfo = new ConVarInfo();
395 pInfo->handle = hndl;
396 pInfo->sourceMod = false;
397 pInfo->pChangeForward = NULL;
398 pInfo->origCallback = pConVar->GetCallback();
399 #if PLAPI_VERSION < 12
400 pInfo->name = sm_strdup(pConVar->GetName());
403 /* Insert struct into our caches */
404 m_ConVars.push_back(pInfo);
405 sm_trie_insert(m_ConVarCache, name, pInfo);
410 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
413 IChangeableForward *pForward;
415 /* Find the convar in the lookup trie */
416 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
418 /* Get the forward */
419 pForward = pInfo->pChangeForward;
421 /* If forward does not exist, create it */
424 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
425 pInfo->pChangeForward = pForward;
427 /* Install our own callback */
428 pConVar->InstallChangeCallback(OnConVarChanged);
431 /* Add function to forward's list */
432 pForward->AddFunction(pFunction);
436 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
439 IChangeableForward *pForward;
440 IPluginContext *pContext = pFunction->GetParentContext();
442 /* Find the convar in the lookup trie */
443 if (sm_trie_retrieve(m_ConVarCache, pConVar->GetName(), (void **)&pInfo))
445 /* Get the forward */
446 pForward = pInfo->pChangeForward;
448 /* If the forward doesn't exist, we can't unhook anything */
451 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
455 /* Remove the function from the forward's list */
456 if (!pForward->RemoveFunction(pFunction))
458 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
462 /* If the forward now has 0 functions in it... */
463 if (pForward->GetFunctionCount() == 0)
465 /* Free this forward */
466 g_Forwards.ReleaseForward(pForward);
467 pInfo->pChangeForward = NULL;
469 /* Put back the original convar callback */
470 pConVar->InstallChangeCallback(pInfo->origCallback);
475 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
477 QueryCvarCookie_t cookie;
479 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
482 cookie = engine->StartQueryCvarValue(pPlayer, name);
484 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
487 ConVarQuery query = {cookie, pCallback, hndl};
488 m_ConVarQueries.push_back(query);
493 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
495 ConVarList *pConVarList;
496 ConVarList::iterator iter;
497 bool inserted = false;
498 const char *orig = pConVar->GetName();
500 IPlugin *plugin = g_PluginSys.FindPluginByContext(pContext->GetContext());
502 /* Check plugin for an existing convar list */
503 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
505 pConVarList = new ConVarList();
506 plugin->SetProperty("ConVarList", pConVarList);
507 } else if (pConVarList->find(pConVar) != pConVarList->end()) {
508 /* If convar is already in list, then don't add it */
512 /* Insert convar into list which is sorted alphabetically */
513 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
515 if (strcmp(orig, (*iter)->GetName()) < 0)
517 pConVarList->insert(iter, pConVar);
525 pConVarList->push_back(pConVar);
529 #if defined ORANGEBOX_BUILD
530 void ConVarManager::OnConVarChanged(IConVar *pIConVar, const char *oldValue, float flOldValue)
532 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
535 /* If the values are the same, exit early in order to not trigger callbacks */
536 #if defined ORANGEBOX_BUILD
537 ConVar *pConVar = (ConVar *)pIConVar;
539 if (strcmp(pConVar->GetString(), oldValue) == 0)
544 Trie *pCache = g_ConVarManager.GetConVarCache();
547 /* Find the convar in the lookup trie */
548 sm_trie_retrieve(pCache, pConVar->GetName(), (void **)&pInfo);
550 FnChangeCallback_t origCallback = pInfo->origCallback;
551 IChangeableForward *pForward = pInfo->pChangeForward;
553 /* If there was a change callback installed previously, call it */
556 #if defined ORANGEBOX_BUILD
557 origCallback(pConVar, oldValue, flOldValue);
559 origCallback(pConVar, oldValue);
563 /* Now call forwards in plugins that have hooked this */
564 pForward->PushCell(pInfo->handle);
565 pForward->PushString(oldValue);
566 pForward->PushString(reinterpret_cast<ConVar *>(pConVar)->GetString());
567 pForward->Execute(NULL);
570 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
572 IPluginFunction *pCallback = NULL;
574 List<ConVarQuery>::iterator iter;
576 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
578 ConVarQuery &query = (*iter);
579 if (query.cookie == cookie)
581 pCallback = query.pCallback;
591 pCallback->PushCell(cookie);
592 pCallback->PushCell(engine->IndexOfEdict(pPlayer));
593 pCallback->PushCell(result);
594 pCallback->PushString(cvarName);
596 if (result == eQueryCvarValueStatus_ValueIntact)
598 pCallback->PushString(cvarValue);
600 pCallback->PushString("\0");
603 pCallback->PushCell(value);
604 pCallback->Execute(&ret);
606 m_ConVarQueries.erase(iter);
611 static int s_YamagramState = 0;
613 void _YamagramPrinterTwoPointOhOh(int yamagram)
618 g_RootMenu.ConsolePrint("Answer the following questions correctly and Gaben may not eat you after all.");
619 g_RootMenu.ConsolePrint("You will be given one hint in the form of my patented yamagrams.");
620 g_RootMenu.ConsolePrint("Type sm_nana to see the last question.");
621 g_RootMenu.ConsolePrint("Type sm_nana <answer> to attempt an answer of the question.");
622 g_RootMenu.ConsolePrint("-------------------------------");
623 _YamagramPrinterTwoPointOhOh(1);
626 g_RootMenu.ConsolePrint("Question Ichi (1)");
627 g_RootMenu.ConsolePrint("One can turn into a cow by doing what action?");
628 g_RootMenu.ConsolePrint("Hint: AGE SANS GRIT");
631 g_RootMenu.ConsolePrint("Question Ni (2)");
632 g_RootMenu.ConsolePrint("What kind of hat should you wear when using the Internet?");
633 g_RootMenu.ConsolePrint("Hint: BRR MOOSE");
636 g_RootMenu.ConsolePrint("Question San (3)");
637 g_RootMenu.ConsolePrint("Who is the lead developer of SourceMod?");
638 g_RootMenu.ConsolePrint("Hint: VEAL BANDANA DID RIP SOON");
641 g_RootMenu.ConsolePrint("Question Yon (4)");
642 g_RootMenu.ConsolePrint("A terrible translation of 'SVN Revision' to Japanese romaji might be ...");
643 g_RootMenu.ConsolePrint("Hint: I TAKE IN AN AIR OK");
646 g_RootMenu.ConsolePrint("Question Go (5)");
647 g_RootMenu.ConsolePrint("What is a fundamental concept in the game of Go?");
648 g_RootMenu.ConsolePrint("Hint: AD LADEN THIEF");
651 g_RootMenu.ConsolePrint("Question Roku (6)");
652 g_RootMenu.ConsolePrint("Why am I asking all these strange questions?");
653 g_RootMenu.ConsolePrint("Hint: CHUBBY TITAN EATS EWE WAGE DATA");
656 g_RootMenu.ConsolePrint("Question Nana (7)");
657 g_RootMenu.ConsolePrint("What is my name?");
658 g_RootMenu.ConsolePrint("Hint: AD MODE LAG US");
664 s_YamagramState = yamagram;
667 #if defined ORANGEBOX_BUILD
668 void _IntExt_CallYamagrams(const CCommand &cmd)
671 void _IntExt_CallYamagrams()
675 bool correct = false;
676 const char *arg = cmd.ArgS();
678 if (!arg || arg[0] == '\0')
680 _YamagramPrinterTwoPointOhOh(s_YamagramState);
684 switch (s_YamagramState)
687 correct = !strcasecmp(arg, "eating grass");
690 correct = !strcasecmp(arg, "sombrero");
693 correct = !strcasecmp(arg, "david bailopan anderson");
696 correct = !strcasecmp(arg, "kaitei no kairan");
699 correct = !strcasecmp(arg, "life and death");
702 correct = !strcasecmp(arg, "because gabe wanted it that way");
705 g_RootMenu.ConsolePrint("Congratulations, you have answered 6 of my questions.");
706 g_RootMenu.ConsolePrint("However, I have one final question for you. It wouldn't be nana without it.");
707 g_RootMenu.ConsolePrint("-------------------------------");
708 _YamagramPrinterTwoPointOhOh(7);
713 correct = !strcasecmp(arg, "damaged soul");
716 g_RootMenu.ConsolePrint("You don't know how lucky you are to still be alive!");
717 g_RootMenu.ConsolePrint("Congratulations. You have answered all 7 questions correctly.");
718 g_RootMenu.ConsolePrint("The SourceMod Dev Team will be at your door with anti-Gaben grenades");
719 g_RootMenu.ConsolePrint("within seconds. You will also be provided with a rocket launcher,");
720 g_RootMenu.ConsolePrint("just in case Alfred decides to strike you with a blitzkrieg in retaliation.");
730 if (s_YamagramState > 0)
734 g_RootMenu.ConsolePrint("Correct! You are one step closer to avoiding the deadly jaws of Gaben.");
735 g_RootMenu.ConsolePrint("-------------------------------");
738 g_RootMenu.ConsolePrint("Wrong! You better be more careful. Gaben may be at your door at any minute.");
743 _YamagramPrinterTwoPointOhOh(s_YamagramState);
746 void _IntExt_EnableYamagrams()
748 static ConCommand *pCmd = NULL;
751 pCmd = new ConCommand("sm_nana", _IntExt_CallYamagrams, "Try these yamagrams!", FCVAR_GAMEDLL);
752 g_RootMenu.ConsolePrint("[SM] Warning: Gaben has been alerted of your actions. You may be eaten.");
754 g_RootMenu.ConsolePrint("[SM] Gaben has already been alerted of your actions...");
758 #if defined ORANGEBOX_BUILD
759 void _IntExt_OnHostnameChanged(IConVar *pConVar, const char *oldValue, float flOldValue)
761 void _IntExt_OnHostnameChanged(ConVar *pConVar, char const *oldValue)
764 if (strcmp(oldValue, "Good morning, DS-san.") == 0
765 && strcmp(reinterpret_cast<ConVar *>(pConVar)->GetString(), "Good night, talking desk lamp.") == 0)
767 _IntExt_EnableYamagrams();