Updated for latest hl2sdk-dota changes.
2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2009 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>.
30 #include "ConVarManager.h"
31 #include "HalfLife2.h"
32 #include "ForwardSys.h"
33 #include "sm_srvcmds.h"
34 #include "sm_stringutil.h"
35 #include <sh_vector.h>
36 #include <sm_trie_tpl.h>
37 #include "logic_bridge.h"
39 ConVarManager g_ConVarManager;
41 #if SOURCE_ENGINE >= SE_ORANGEBOX
42 SH_DECL_HOOK3_void(ICvar, CallGlobalChangeCallbacks, SH_NOATTRIB, false, ConVar *, const char *, float);
44 SH_DECL_HOOK2_void(ICvar, CallGlobalChangeCallback, SH_NOATTRIB, false, ConVar *, const char *);
47 #if SOURCE_ENGINE == SE_DOTA
48 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, CEntityIndex, EQueryCvarValueStatus, const char *, const char *);
49 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, CEntityIndex, EQueryCvarValueStatus, const char *, const char *);
50 #elif SOURCE_ENGINE != SE_DARKMESSIAH
51 SH_DECL_HOOK5_void(IServerGameDLL, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
52 SH_DECL_HOOK5_void(IServerPluginCallbacks, OnQueryCvarValueFinished, SH_NOATTRIB, 0, QueryCvarCookie_t, edict_t *, EQueryCvarValueStatus, const char *, const char *);
55 const ParamType CONVARCHANGE_PARAMS[] = {Param_Cell, Param_String, Param_String};
56 typedef List<const ConVar *> ConVarList;
57 KTrie<ConVarInfo *> convar_cache;
59 class ConVarReentrancyGuard
62 ConVarReentrancyGuard *up;
64 static ConVarReentrancyGuard *chain;
66 ConVarReentrancyGuard(ConVar *cvar)
67 : cvar(cvar), up(chain)
72 ~ConVarReentrancyGuard()
74 assert(chain == this);
78 static bool IsCvarInChain(ConVar *cvar)
80 ConVarReentrancyGuard *guard = chain;
83 if (guard->cvar == cvar)
91 ConVarReentrancyGuard *ConVarReentrancyGuard::chain = NULL;
93 ConVarManager::ConVarManager() : m_ConVarType(0), m_bIsDLLQueryHooked(false), m_bIsVSPQueryHooked(false)
97 ConVarManager::~ConVarManager()
101 void ConVarManager::OnSourceModStartup(bool late)
105 /* Set up access rights for the 'ConVar' handle type */
106 sec.access[HandleAccess_Read] = 0;
107 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
108 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
110 /* Create the 'ConVar' handle type */
111 m_ConVarType = handlesys->CreateType("ConVar", this, 0, NULL, &sec, g_pCoreIdent, NULL);
114 void ConVarManager::OnSourceModAllInitialized()
117 * Episode 2 has this function by default, but the older versions do not.
119 #if SOURCE_ENGINE == SE_EPISODEONE
120 if (g_SMAPI->GetGameDLLVersion() >= 6)
122 SH_ADD_HOOK(IServerGameDLL, OnQueryCvarValueFinished, gamedll, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
123 m_bIsDLLQueryHooked = true;
127 #if SOURCE_ENGINE >= SE_ORANGEBOX
128 SH_ADD_HOOK(ICvar, CallGlobalChangeCallbacks, icvar, SH_STATIC(OnConVarChanged), false);
130 SH_ADD_HOOK(ICvar, CallGlobalChangeCallback, icvar, SH_STATIC(OnConVarChanged), false);
133 scripts->AddPluginsListener(this);
135 /* Add the 'convars' option to the 'sm' console command */
136 g_RootMenu.AddRootConsoleCommand("cvars", "View convars created by a plugin", this);
139 void ConVarManager::OnSourceModShutdown()
141 List<ConVarInfo *>::iterator iter = m_ConVars.begin();
142 HandleSecurity sec(NULL, g_pCoreIdent);
144 /* Iterate list of ConVarInfo structures, remove every one of them */
145 while (iter != m_ConVars.end())
147 ConVarInfo *pInfo = (*iter);
149 iter = m_ConVars.erase(iter);
151 handlesys->FreeHandle(pInfo->handle, &sec);
152 if (pInfo->pChangeForward != NULL)
154 g_Forwards.ReleaseForward(pInfo->pChangeForward);
156 if (pInfo->sourceMod)
158 /* If we created it, we won't be tracking it, therefore it is
159 * safe to remove everything in one go.
161 META_UNREGCVAR(pInfo->pVar);
162 delete [] pInfo->pVar->GetName();
163 delete [] pInfo->pVar->GetHelpText();
164 delete [] pInfo->pVar->GetDefault();
169 /* If we didn't create it, we might be tracking it. Also,
170 * it could be unreadable.
172 UntrackConCommandBase(pInfo->pVar, this);
175 /* It's not safe to read the name here, so we simply delete the
176 * the info struct and clear the lookup cache at the end.
180 convar_cache.clear();
182 #if SOURCE_ENGINE != SE_DARKMESSIAH
184 if (m_bIsDLLQueryHooked)
186 SH_REMOVE_HOOK(IServerGameDLL, OnQueryCvarValueFinished, gamedll, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
187 m_bIsDLLQueryHooked = false;
189 else if (m_bIsVSPQueryHooked)
191 #if SOURCE_ENGINE != SE_DOTA
192 SH_REMOVE_HOOK(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
194 m_bIsVSPQueryHooked = false;
198 #if SOURCE_ENGINE >= SE_ORANGEBOX
199 SH_REMOVE_HOOK(ICvar, CallGlobalChangeCallbacks, icvar, SH_STATIC(OnConVarChanged), false);
201 SH_REMOVE_HOOK(ICvar, CallGlobalChangeCallback, icvar, SH_STATIC(OnConVarChanged), false);
204 /* Remove the 'convars' option from the 'sm' console command */
205 g_RootMenu.RemoveRootConsoleCommand("cvars", this);
207 scripts->RemovePluginsListener(this);
209 /* Remove the 'ConVar' handle type */
210 handlesys->RemoveType(m_ConVarType, g_pCoreIdent);
214 * Orange Box will never use this.
216 void ConVarManager::OnSourceModVSPReceived()
219 * Don't bother if the DLL is already hooked.
221 if (m_bIsDLLQueryHooked)
226 /* For later MM:S versions, use the updated API, since it's cleaner. */
227 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
228 int engine = g_SMAPI->GetSourceEngineBuild();
229 if (engine == SOURCE_ENGINE_ORIGINAL || vsp_version < 2)
234 if (g_HL2.IsOriginalEngine() || vsp_version < 2)
240 #if SOURCE_ENGINE != SE_DARKMESSIAH && SOURCE_ENGINE != SE_DOTA
241 SH_ADD_HOOK(IServerPluginCallbacks, OnQueryCvarValueFinished, vsp_interface, SH_MEMBER(this, &ConVarManager::OnQueryCvarValueFinished), false);
242 m_bIsVSPQueryHooked = true;
246 bool convar_cache_lookup(const char *name, ConVarInfo **pVar)
248 ConVarInfo **pLookup = convar_cache.retrieve(name);
260 void ConVarManager::OnUnlinkConCommandBase(ConCommandBase *pBase, const char *name, bool is_read_safe)
262 /* Only check convars that have not been created by SourceMod's core */
264 if (!convar_cache_lookup(name, &pInfo))
269 HandleSecurity sec(NULL, g_pCoreIdent);
271 /* Remove it from our cache */
272 m_ConVars.remove(pInfo);
273 convar_cache.remove(name);
275 /* Now make sure no plugins are referring to this pointer */
276 IPluginIterator *pl_iter = scripts->GetPluginIterator();
277 while (pl_iter->MorePlugins())
279 IPlugin *pl = pl_iter->GetPlugin();
281 ConVarList *pConVarList;
282 if (pl->GetProperty("ConVarList", (void **)&pConVarList, true)
283 && pConVarList != NULL)
285 pConVarList->remove(pInfo->pVar);
288 pl_iter->NextPlugin();
292 handlesys->FreeHandle(pInfo->handle, &sec);
296 void ConVarManager::OnPluginUnloaded(IPlugin *plugin)
298 ConVarList *pConVarList;
299 List<ConVarQuery>::iterator iter;
301 /* If plugin has a convar list, free its memory */
302 if (plugin->GetProperty("ConVarList", (void **)&pConVarList, true))
307 /* Remove convar queries for this plugin that haven't returned results yet */
308 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
310 ConVarQuery &query = (*iter);
311 if (query.pCallback->GetParentRuntime() == plugin->GetRuntime())
313 m_ConVarQueries.erase(iter);
318 void ConVarManager::OnHandleDestroy(HandleType_t type, void *object)
322 bool ConVarManager::GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
324 *pSize = sizeof(ConVar) + sizeof(ConVarInfo);
328 void ConVarManager::OnRootConsoleCommand(const char *cmdname, const CCommand &command)
330 int argcount = command.ArgC();
333 bool wantReset = false;
335 /* Get plugin index that was passed */
336 const char *arg = command.Arg(2);
337 if (argcount >= 4 && strcmp(arg, "reset") == 0)
340 arg = command.Arg(3);
343 /* Get plugin object */
344 IPlugin *plugin = scripts->FindPluginByConsoleArg(arg);
348 g_RootMenu.ConsolePrint("[SM] Plugin \"%s\" was not found.", arg);
352 /* Get plugin name */
353 const sm_plugininfo_t *plinfo = plugin->GetPublicInfo();
354 const char *plname = IS_STR_FILLED(plinfo->name) ? plinfo->name : plugin->GetFilename();
356 ConVarList *pConVarList;
357 ConVarList::iterator iter;
359 /* If no convar list... */
360 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
362 g_RootMenu.ConsolePrint("[SM] No convars found for: %s", plname);
368 g_RootMenu.ConsolePrint("[SM] Listing %d convars for: %s", pConVarList->size(), plname);
369 g_RootMenu.ConsolePrint(" %-32.31s %s", "[Name]", "[Value]");
372 /* Iterate convar list and display/reset each one */
373 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
375 /*const */ConVar *pConVar = const_cast<ConVar *>(*iter);
378 g_RootMenu.ConsolePrint(" %-32.31s %s", pConVar->GetName(), pConVar->GetString());
386 g_RootMenu.ConsolePrint("[SM] Reset %d convars for: %s", pConVarList->size(), plname);
392 /* Display usage of subcommand */
393 g_RootMenu.ConsolePrint("[SM] Usage: sm cvars [reset] <plugin #>");
396 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)
398 ConVar *pConVar = NULL;
399 ConVarInfo *pInfo = NULL;
402 /* Find out if the convar exists already */
403 pConVar = icvar->FindVar(name);
405 /* If the convar already exists... */
408 /* Add convar to plugin's list */
409 AddConVarToPluginList(pContext, pConVar);
411 /* First find out if we already have a handle to it */
412 if (convar_cache_lookup(name, &pInfo))
414 return pInfo->handle;
418 /* Create and initialize ConVarInfo structure */
419 pInfo = new ConVarInfo();
420 pInfo->sourceMod = false;
421 pInfo->pChangeForward = NULL;
422 pInfo->pVar = pConVar;
424 /* If we don't, then create a new handle from the convar */
425 hndl = handlesys->CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
426 if (hndl == BAD_HANDLE)
432 pInfo->handle = hndl;
434 /* Insert struct into caches */
435 m_ConVars.push_back(pInfo);
436 convar_cache.insert(name, pInfo);
437 TrackConCommandBase(pConVar, this);
443 /* Prevent creating a convar that has the same name as a console command */
444 if (FindCommand(name))
449 /* Create and initialize ConVarInfo structure */
450 pInfo = new ConVarInfo();
451 pInfo->handle = hndl;
452 pInfo->sourceMod = true;
453 pInfo->pChangeForward = NULL;
455 /* Create a handle from the new convar */
456 hndl = handlesys->CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
457 if (hndl == BAD_HANDLE)
463 pInfo->handle = hndl;
465 /* Since an existing convar (or concmd with the same name) was not found , now we can finally create it */
466 pConVar = new ConVar(sm_strdup(name), sm_strdup(defaultVal), flags, sm_strdup(description), hasMin, min, hasMax, max);
467 pInfo->pVar = pConVar;
469 /* Add convar to plugin's list */
470 AddConVarToPluginList(pContext, pConVar);
472 /* Insert struct into caches */
473 m_ConVars.push_back(pInfo);
474 convar_cache.insert(name, pInfo);
479 Handle_t ConVarManager::FindConVar(const char *name)
481 ConVar *pConVar = NULL;
485 /* Search for convar */
486 pConVar = icvar->FindVar(name);
488 /* If it doesn't exist, then return an invalid handle */
494 /* At this point, the convar exists. So, find out if we already have a handle */
495 if (convar_cache_lookup(name, &pInfo))
497 return pInfo->handle;
500 /* Create and initialize ConVarInfo structure */
501 pInfo = new ConVarInfo();
502 pInfo->sourceMod = false;
503 pInfo->pChangeForward = NULL;
504 pInfo->pVar = pConVar;
506 /* If we don't have a handle, then create a new one */
507 hndl = handlesys->CreateHandle(m_ConVarType, pInfo, NULL, g_pCoreIdent, NULL);
508 if (hndl == BAD_HANDLE)
514 pInfo->handle = hndl;
516 /* Insert struct into our caches */
517 m_ConVars.push_back(pInfo);
518 convar_cache.insert(name, pInfo);
519 TrackConCommandBase(pConVar, this);
524 void ConVarManager::AddConVarChangeListener(const char *name, IConVarChangeListener *pListener)
528 if (FindConVar(name) == BAD_HANDLE)
533 /* Find the convar in the lookup trie */
534 if (convar_cache_lookup(name, &pInfo))
536 pInfo->changeListeners.push_back(pListener);
540 void ConVarManager::RemoveConVarChangeListener(const char *name, IConVarChangeListener *pListener)
544 /* Find the convar in the lookup trie */
545 if (convar_cache_lookup(name, &pInfo))
547 pInfo->changeListeners.remove(pListener);
551 void ConVarManager::HookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
554 IChangeableForward *pForward;
556 /* Find the convar in the lookup trie */
557 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
559 /* Get the forward */
560 pForward = pInfo->pChangeForward;
562 /* If forward does not exist, create it */
565 pForward = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, CONVARCHANGE_PARAMS);
566 pInfo->pChangeForward = pForward;
569 /* Add function to forward's list */
570 pForward->AddFunction(pFunction);
574 void ConVarManager::UnhookConVarChange(ConVar *pConVar, IPluginFunction *pFunction)
577 IChangeableForward *pForward;
578 IPluginContext *pContext = pFunction->GetParentContext();
580 /* Find the convar in the lookup trie */
581 if (convar_cache_lookup(pConVar->GetName(), &pInfo))
583 /* Get the forward */
584 pForward = pInfo->pChangeForward;
586 /* If the forward doesn't exist, we can't unhook anything */
589 pContext->ThrowNativeError("Convar \"%s\" has no active hook", pConVar->GetName());
593 /* Remove the function from the forward's list */
594 if (!pForward->RemoveFunction(pFunction))
596 pContext->ThrowNativeError("Invalid hook callback specified for convar \"%s\"", pConVar->GetName());
600 /* If the forward now has 0 functions in it... */
601 if (pForward->GetFunctionCount() == 0 &&
602 !ConVarReentrancyGuard::IsCvarInChain(pConVar))
604 /* Free this forward */
605 g_Forwards.ReleaseForward(pForward);
606 pInfo->pChangeForward = NULL;
611 QueryCvarCookie_t ConVarManager::QueryClientConVar(edict_t *pPlayer, const char *name, IPluginFunction *pCallback, Handle_t hndl)
613 QueryCvarCookie_t cookie = 0;
615 #if SOURCE_ENGINE != SE_DARKMESSIAH
616 /* Call StartQueryCvarValue() in either the IVEngineServer or IServerPluginHelpers depending on situation */
617 if (m_bIsDLLQueryHooked)
619 #if SOURCE_ENGINE == SE_DOTA
620 cookie = engine->StartQueryCvarValue(CEntityIndex(IndexOfEdict(pPlayer)), name);
622 cookie = engine->StartQueryCvarValue(pPlayer, name);
625 #if SOURCE_ENGINE != SE_DOTA
626 else if (m_bIsVSPQueryHooked)
628 cookie = serverpluginhelpers->StartQueryCvarValue(pPlayer, name);
633 return InvalidQueryCvarCookie;
636 ConVarQuery query = {cookie, pCallback, hndl};
637 m_ConVarQueries.push_back(query);
643 void ConVarManager::AddConVarToPluginList(IPluginContext *pContext, const ConVar *pConVar)
645 ConVarList *pConVarList;
646 ConVarList::iterator iter;
647 bool inserted = false;
648 const char *orig = pConVar->GetName();
650 IPlugin *plugin = scripts->FindPluginByContext(pContext->GetContext());
652 /* Check plugin for an existing convar list */
653 if (!plugin->GetProperty("ConVarList", (void **)&pConVarList))
655 pConVarList = new ConVarList();
656 plugin->SetProperty("ConVarList", pConVarList);
658 else if (pConVarList->find(pConVar) != pConVarList->end())
660 /* If convar is already in list, then don't add it */
664 /* Insert convar into list which is sorted alphabetically */
665 for (iter = pConVarList->begin(); iter != pConVarList->end(); iter++)
667 if (strcmp(orig, (*iter)->GetName()) < 0)
669 pConVarList->insert(iter, pConVar);
677 pConVarList->push_back(pConVar);
681 #if SOURCE_ENGINE >= SE_ORANGEBOX
682 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue, float flOldValue)
684 void ConVarManager::OnConVarChanged(ConVar *pConVar, const char *oldValue)
687 /* If the values are the same, exit early in order to not trigger callbacks */
688 if (strcmp(pConVar->GetString(), oldValue) == 0)
695 /* Find the convar in the lookup trie */
696 if (!convar_cache_lookup(pConVar->GetName(), &pInfo))
701 IChangeableForward *pForward = pInfo->pChangeForward;
703 if (pInfo->changeListeners.size() != 0)
705 for (List<IConVarChangeListener *>::iterator i = pInfo->changeListeners.begin();
706 i != pInfo->changeListeners.end();
709 #if SOURCE_ENGINE >= SE_ORANGEBOX
710 (*i)->OnConVarChanged(pConVar, oldValue, flOldValue);
712 (*i)->OnConVarChanged(pConVar, oldValue, atof(oldValue));
717 if (pForward != NULL)
719 ConVarReentrancyGuard guard(pConVar);
721 /* Now call forwards in plugins that have hooked this */
722 pForward->PushCell(pInfo->handle);
723 pForward->PushString(oldValue);
724 pForward->PushString(pConVar->GetString());
725 pForward->Execute(NULL);
729 bool ConVarManager::IsQueryingSupported()
731 return (m_bIsDLLQueryHooked || m_bIsVSPQueryHooked);
734 #if SOURCE_ENGINE != SE_DARKMESSIAH
735 #if SOURCE_ENGINE == SE_DOTA
736 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, CEntityIndex player, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
738 void ConVarManager::OnQueryCvarValueFinished(QueryCvarCookie_t cookie, edict_t *pPlayer, EQueryCvarValueStatus result, const char *cvarName, const char *cvarValue)
741 IPluginFunction *pCallback = NULL;
743 List<ConVarQuery>::iterator iter;
745 for (iter = m_ConVarQueries.begin(); iter != m_ConVarQueries.end(); iter++)
747 ConVarQuery &query = (*iter);
748 if (query.cookie == cookie)
750 pCallback = query.pCallback;
760 pCallback->PushCell(cookie);
761 #if SOURCE_ENGINE == SE_DOTA
762 pCallback->PushCell(player.Get());
764 pCallback->PushCell(IndexOfEdict(pPlayer));
766 pCallback->PushCell(result);
767 pCallback->PushString(cvarName);
769 if (result == eQueryCvarValueStatus_ValueIntact)
771 pCallback->PushString(cvarValue);
775 pCallback->PushString("\0");
778 pCallback->PushCell(value);
779 pCallback->Execute(&ret);
781 m_ConVarQueries.erase(iter);
786 HandleError ConVarManager::ReadConVarHandle(Handle_t hndl, ConVar **pVar)
791 if ((error = handlesys->ReadHandle(hndl, m_ConVarType, NULL, (void **)&pInfo)) != HandleError_None)