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>.
33 #include "sourcemod.h"
34 #include "sourcemm_api.h"
35 #include "LibrarySys.h"
36 #include <sh_string.h>
37 #include "PluginSys.h"
39 #include "CoreConfig.h"
41 #include "ExtensionSys.h"
42 #include "AdminCache.h"
43 #include "sm_stringutil.h"
44 #include "PlayerManager.h"
45 #include "Translator.h"
46 #include "ForwardSys.h"
48 #include "GameConfigs.h"
49 #include "DebugReporter.h"
51 #include "frame_hooks.h"
52 #include "logic_bridge.h"
54 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
55 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
56 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
57 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
59 SourceModBase g_SourceMod;
61 ILibrary *g_pJIT = NULL;
62 SourceHook::String g_BaseDir;
63 ISourcePawnEngine *g_pSourcePawn = NULL;
64 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
65 IdentityToken_t *g_pCoreIdent = NULL;
66 IForward *g_pOnMapEnd = NULL;
67 bool g_Loaded = false;
68 bool sm_show_debug_spew = false;
70 typedef ISourcePawnEngine *(*GET_SP_V1)();
71 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
72 typedef void (*NOTIFYSHUTDOWN)();
74 #ifdef PLATFORM_WINDOWS
75 ConVar sm_basepath("sm_basepath", "addons\\sourcemod", 0, "SourceMod base path (set via command line)");
76 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
77 ConVar sm_basepath("sm_basepath", "addons/sourcemod", 0, "SourceMod base path (set via command line)");
82 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
88 if (g_pSourcePawn2 != NULL)
90 g_pSourcePawn2->Shutdown();
93 g_pJIT->CloseLibrary();
96 SourceModBase::SourceModBase()
98 m_IsMapLoading = false;
99 m_ExecPluginReload = false;
100 m_GotBasePath = false;
103 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
109 if (strcasecmp(key, "BasePath") == 0)
111 if (source == ConfigSource_Console)
113 UTIL_Format(error, maxlength, "Cannot be set at runtime");
114 return ConfigResult_Reject;
119 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
120 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
122 m_GotBasePath = true;
125 return ConfigResult_Accept;
127 else if (strcasecmp(key, "DebugSpew") == 0)
129 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
131 return ConfigResult_Accept;
134 return ConfigResult_Ignore;
137 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
139 const char *gamepath = g_SMAPI->GetBaseDir();
141 /* Store full path to game */
142 g_BaseDir.assign(gamepath);
144 /* Store name of game directory by itself */
145 size_t len = strlen(gamepath);
146 for (size_t i = len - 1; i >= 0; i--)
148 if (gamepath[i] == PLATFORM_SEP_CHAR)
150 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
155 const char *basepath = icvar->GetCommandLineValue("sm_basepath");
156 /* Set a custom base path if there is one. */
157 if (basepath != NULL && basepath[0] != '\0')
159 m_GotBasePath = true;
161 /* Otherwise, use a default and keep the m_GotBasePath unlocked. */
164 basepath = sm_basepath.GetDefault();
167 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), basepath);
168 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "%s", basepath);
170 if (!StartLogicBridge(error, maxlength))
175 /* Initialize CoreConfig to get the SourceMod base path properly - this parses core.cfg */
176 g_CoreConfig.Initialize();
178 /* There will always be a path by this point, since it was force-set above. */
179 m_GotBasePath = true;
181 /* Attempt to load the JIT! */
182 char file[PLATFORM_MAX_PATH];
184 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
189 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
192 if (error && maxlength)
194 UTIL_Format(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
201 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
202 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
206 if (error && maxlength)
208 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
213 else if (getv2 == NULL)
215 if (error && maxlength)
217 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
223 g_pSourcePawn = getv1();
224 g_pSourcePawn2 = getv2();
226 if (g_pSourcePawn2->GetAPIVersion() < 3)
228 g_pSourcePawn2 = NULL;
229 if (error && maxlength)
231 snprintf(error, maxlength, "JIT version is out of date");
236 if (!g_pSourcePawn2->Initialize())
238 g_pSourcePawn2 = NULL;
239 if (error && maxlength)
241 snprintf(error, maxlength, "JIT could not be initialized");
246 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
247 g_pSourcePawn2->SetProfiler(&g_Profiler);
249 /* Hook this now so we can detect startup without calling StartSourceMod() */
250 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
252 /* Only load if we're not late */
255 StartSourceMod(false);
261 void SourceModBase::StartSourceMod(bool late)
263 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
264 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
266 enginePatch = SH_GET_CALLCLASS(engine);
267 gamedllPatch = SH_GET_CALLCLASS(gamedll);
269 g_ShareSys.Initialize();
271 /* Make the global core identity */
272 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
277 SMGlobalClass *pBase = SMGlobalClass::head;
280 pBase->OnSourceModStartup(false);
281 pBase = pBase->m_pGlobalClassNext;
285 pBase = SMGlobalClass::head;
288 pBase->OnSourceModAllInitialized();
289 pBase = pBase->m_pGlobalClassNext;
293 pBase = SMGlobalClass::head;
296 pBase->OnSourceModAllInitialized_Post();
297 pBase = pBase->m_pGlobalClassNext;
301 g_ShareSys.AddInterface(NULL, this);
306 /* Initialize VSP stuff */
307 if (vsp_interface != NULL)
309 g_SourceMod_Core.OnVSPListening(vsp_interface);
312 /* If we want to autoload, do that now */
313 const char *disabled = GetCoreConfigValue("DisableAutoUpdate");
314 if (disabled == NULL || strcasecmp(disabled, "yes") != 0)
316 g_Extensions.LoadAutoExtension("updater.ext." PLATFORM_LIB_EXT);
320 static bool g_LevelEndBarrier = false;
321 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
323 /* If we're not loaded... */
326 /* Do all global initialization now */
327 StartSourceMod(true);
330 m_IsMapLoading = true;
331 m_ExecPluginReload = true;
334 SMGlobalClass *pBase = SMGlobalClass::head;
337 pBase->OnSourceModLevelChange(pMapName);
338 pBase = pBase->m_pGlobalClassNext;
341 DoGlobalPluginLoads();
343 m_IsMapLoading = false;
346 pBase = SMGlobalClass::head;
349 pBase->OnSourceModPluginsLoaded();
350 pBase = pBase->m_pGlobalClassNext;
355 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
358 g_LevelEndBarrier = true;
360 RETURN_META_VALUE(MRES_IGNORED, true);
363 void SourceModBase::LevelShutdown()
365 if (g_LevelEndBarrier)
367 SMGlobalClass *next = SMGlobalClass::head;
370 next->OnSourceModLevelEnd();
371 next = next->m_pGlobalClassNext;
374 if (g_pOnMapEnd != NULL)
376 g_pOnMapEnd->Execute(NULL);
379 g_Timers.RemoveMapChangeTimers();
381 g_LevelEndBarrier = false;
384 g_OnMapStarted = false;
386 if (m_ExecPluginReload)
388 g_PluginSys.ReloadOrUnloadPlugins();
389 m_ExecPluginReload = false;
393 bool SourceModBase::IsMapLoading() const
395 return m_IsMapLoading;
398 void SourceModBase::DoGlobalPluginLoads()
400 char config_path[PLATFORM_MAX_PATH];
401 char plugins_path[PLATFORM_MAX_PATH];
403 BuildPath(Path_SM, config_path,
405 "configs/plugin_settings.cfg");
406 BuildPath(Path_SM, plugins_path,
407 sizeof(plugins_path),
410 /* Load any auto extensions */
411 g_Extensions.TryAutoload();
413 /* Fire the extensions ready message */
414 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
416 /* Load any game extension */
417 const char *game_ext;
418 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
420 char path[PLATFORM_MAX_PATH];
421 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
422 g_Extensions.LoadAutoExtension(path);
425 /* Run the first pass */
426 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
428 /* Mark any extensions as loaded */
429 g_Extensions.MarkAllLoaded();
431 /* No modules yet, it's safe to call this from here */
432 g_PluginSys.LoadAll_SecondPass();
434 /* Re-mark any extensions as loaded */
435 g_Extensions.MarkAllLoaded();
437 /* Call OnAllPluginsLoaded */
438 g_PluginSys.AllPluginsLoaded();
441 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
443 char _buffer[PLATFORM_MAX_PATH];
446 va_start(ap, format);
447 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
450 /* If we get a "file://" notation, strip off the file:// part so we're left
451 * with an absolute path. Note that the absolute path gets returned, so
452 * usage with relative paths here is completely invalid.
454 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
456 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
459 const char *base = NULL;
460 if (type == Path_Game)
462 base = GetGamePath();
464 else if (type == Path_SM)
466 base = GetSourceModPath();
468 else if (type == Path_SM_Rel)
475 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
479 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
483 void SourceModBase::CloseSourceMod()
485 /* Force a level end */
489 g_PluginSys.Shutdown();
491 /* Unload extensions */
492 g_Extensions.Shutdown();
494 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
500 g_Forwards.ReleaseForward(g_pOnMapEnd);
504 SMGlobalClass *pBase = SMGlobalClass::head;
507 pBase->OnSourceModShutdown();
508 pBase = pBase->m_pGlobalClassNext;
511 /* Delete all data packs */
512 CStack<CDataPack *>::iterator iter;
514 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
519 m_freepacks.popall();
522 pBase = SMGlobalClass::head;
525 pBase->OnSourceModAllShutdown();
526 pBase = pBase->m_pGlobalClassNext;
531 SH_RELEASE_CALLCLASS(enginePatch);
537 SH_RELEASE_CALLCLASS(gamedllPatch);
541 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
542 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
546 ShutdownLogicBridge();
550 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
552 IExtensionInterface *pAPI = pExt->GetAPI();
553 const char *tag = pAPI->GetExtensionTag();
557 va_start(ap, format);
558 vsnprintf(buffer, sizeof(buffer), format, ap);
563 g_Logger.LogMessage("[%s] %s", tag, buffer);
565 g_Logger.LogMessage("%s", buffer);
569 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
571 IExtensionInterface *pAPI = pExt->GetAPI();
572 const char *tag = pAPI->GetExtensionTag();
576 va_start(ap, format);
577 vsnprintf(buffer, sizeof(buffer), format, ap);
582 g_Logger.LogError("[%s] %s", tag, buffer);
584 g_Logger.LogError("%s", buffer);
588 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
592 pContext->LocalToString(params[param], &fmt);
594 int lparam = ++param;
596 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
599 const char *SourceModBase::GetSourceModPath() const
604 const char *SourceModBase::GetGamePath() const
606 return g_BaseDir.c_str();
609 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
611 unsigned int old = m_target;
616 unsigned int SourceModBase::GetGlobalTarget() const
621 IDataPack *SourceModBase::CreateDataPack()
624 if (m_freepacks.empty())
626 pack = new CDataPack;
628 pack = m_freepacks.front();
635 void SourceModBase::FreeDataPack(IDataPack *pack)
637 m_freepacks.push(static_cast<CDataPack *>(pack));
640 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
646 const char *SourceModBase::GetGameFolderName() const
651 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
653 return g_pSourcePawn;
656 IVirtualMachine *SourceModBase::GetScriptingVM()
661 void SourceModBase::AllPluginsLoaded()
663 SMGlobalClass *base = SMGlobalClass::head;
666 base->OnSourceModGameInitialized();
667 base = base->m_pGlobalClassNext;
671 time_t SourceModBase::GetAdjustedTime()
673 return ::GetAdjustedTime();
676 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
678 m_frame_hooks.push_back(hook);
681 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
683 for (size_t i = 0; i < m_frame_hooks.size(); i++)
685 if (m_frame_hooks[i] == hook)
687 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
693 void SourceModBase::ProcessGameFrameHooks(bool simulating)
695 if (m_frame_hooks.size() == 0)
700 for (size_t i = 0; i < m_frame_hooks.size(); i++)
702 m_frame_hooks[i](simulating);
706 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
712 len = FormatArgs(buffer, maxlength, fmt, ap);
718 size_t SourceModBase::FormatArgs(char *buffer,
723 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
726 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
728 ::AddFrameAction(FrameAction(fn, data));
731 const char *SourceModBase::GetCoreConfigValue(const char *key)
733 return g_CoreConfig.GetCoreConfigValue(key);
736 int SourceModBase::GetPluginId()
741 SMGlobalClass *SMGlobalClass::head = NULL;