3 * =============================================================================
5 * Copyright (C) 2004-2010 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 "ForwardSys.h"
47 #include <IGameConfigs.h>
48 #include "DebugReporter.h"
49 #include "frame_hooks.h"
50 #include "logic_bridge.h"
52 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
53 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
54 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
55 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
57 SourceModBase g_SourceMod;
59 ILibrary *g_pJIT = NULL;
60 SourceHook::String g_BaseDir;
61 ISourcePawnEngine *g_pSourcePawn = NULL;
62 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
63 IdentityToken_t *g_pCoreIdent = NULL;
64 IForward *g_pOnMapEnd = NULL;
65 IGameConfig *g_pGameConf = NULL;
66 bool g_Loaded = false;
67 bool sm_show_debug_spew = false;
69 typedef ISourcePawnEngine *(*GET_SP_V1)();
70 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
71 typedef void (*NOTIFYSHUTDOWN)();
73 #ifdef PLATFORM_WINDOWS
74 ConVar sm_basepath("sm_basepath", "addons\\sourcemod", 0, "SourceMod base path (set via command line)");
75 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
76 ConVar sm_basepath("sm_basepath", "addons/sourcemod", 0, "SourceMod base path (set via command line)");
81 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
87 if (g_pSourcePawn2 != NULL)
89 g_pSourcePawn2->Shutdown();
92 g_pJIT->CloseLibrary();
95 SourceModBase::SourceModBase()
97 m_IsMapLoading = false;
98 m_ExecPluginReload = false;
99 m_GotBasePath = false;
102 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
108 if (strcasecmp(key, "BasePath") == 0)
110 if (source == ConfigSource_Console)
112 UTIL_Format(error, maxlength, "Cannot be set at runtime");
113 return ConfigResult_Reject;
118 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
119 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
121 m_GotBasePath = true;
124 return ConfigResult_Accept;
126 else if (strcasecmp(key, "DebugSpew") == 0)
128 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
130 return ConfigResult_Accept;
133 return ConfigResult_Ignore;
136 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
138 const char *gamepath = g_SMAPI->GetBaseDir();
140 /* Store full path to game */
141 g_BaseDir.assign(gamepath);
143 /* Store name of game directory by itself */
144 size_t len = strlen(gamepath);
145 for (size_t i = len - 1; i < len; i--)
147 if (gamepath[i] == PLATFORM_SEP_CHAR)
149 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
154 const char *basepath = icvar->GetCommandLineValue("sm_basepath");
155 /* Set a custom base path if there is one. */
156 if (basepath != NULL && basepath[0] != '\0')
158 m_GotBasePath = true;
160 /* Otherwise, use a default and keep the m_GotBasePath unlocked. */
163 basepath = sm_basepath.GetDefault();
166 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), basepath);
167 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "%s", basepath);
169 if (!StartLogicBridge(error, maxlength))
174 /* Initialize CoreConfig to get the SourceMod base path properly - this parses core.cfg */
175 g_CoreConfig.Initialize();
177 /* There will always be a path by this point, since it was force-set above. */
178 m_GotBasePath = true;
180 /* Attempt to load the JIT! */
181 char file[PLATFORM_MAX_PATH];
183 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
188 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
191 if (error && maxlength)
193 UTIL_Format(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
200 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
201 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
205 if (error && maxlength)
207 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
212 else if (getv2 == NULL)
214 if (error && maxlength)
216 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
222 g_pSourcePawn = getv1();
223 g_pSourcePawn2 = getv2();
225 if (g_pSourcePawn2->GetAPIVersion() < 3)
227 g_pSourcePawn2 = NULL;
228 if (error && maxlength)
230 snprintf(error, maxlength, "JIT version is out of date");
235 if (!g_pSourcePawn2->Initialize())
237 g_pSourcePawn2 = NULL;
238 if (error && maxlength)
240 snprintf(error, maxlength, "JIT could not be initialized");
245 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
247 /* Hook this now so we can detect startup without calling StartSourceMod() */
248 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
250 /* Only load if we're not late */
253 StartSourceMod(false);
259 void SourceModBase::StartSourceMod(bool late)
261 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
262 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
264 enginePatch = SH_GET_CALLCLASS(engine);
265 gamedllPatch = SH_GET_CALLCLASS(gamedll);
267 g_ShareSys.Initialize();
269 /* Make the global core identity */
270 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
275 SMGlobalClass *pBase = SMGlobalClass::head;
278 pBase->OnSourceModStartup(false);
279 pBase = pBase->m_pGlobalClassNext;
281 g_pGameConf = logicore.GetCoreGameConfig();
284 pBase = SMGlobalClass::head;
287 pBase->OnSourceModAllInitialized();
288 pBase = pBase->m_pGlobalClassNext;
292 pBase = SMGlobalClass::head;
295 pBase->OnSourceModAllInitialized_Post();
296 pBase = pBase->m_pGlobalClassNext;
300 g_ShareSys.AddInterface(NULL, this);
305 /* Initialize VSP stuff */
306 if (vsp_interface != NULL)
308 g_SourceMod_Core.OnVSPListening(vsp_interface);
311 /* If we want to autoload, do that now */
312 const char *disabled = GetCoreConfigValue("DisableAutoUpdate");
313 if (disabled == NULL || strcasecmp(disabled, "yes") != 0)
315 g_Extensions.LoadAutoExtension("updater.ext." PLATFORM_LIB_EXT);
319 static bool g_LevelEndBarrier = false;
320 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
322 /* If we're not loaded... */
325 /* Do all global initialization now */
326 StartSourceMod(true);
329 m_IsMapLoading = true;
330 m_ExecPluginReload = true;
333 SMGlobalClass *pBase = SMGlobalClass::head;
336 pBase->OnSourceModLevelChange(pMapName);
337 pBase = pBase->m_pGlobalClassNext;
340 DoGlobalPluginLoads();
342 m_IsMapLoading = false;
345 pBase = SMGlobalClass::head;
348 pBase->OnSourceModPluginsLoaded();
349 pBase = pBase->m_pGlobalClassNext;
354 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
357 g_LevelEndBarrier = true;
359 RETURN_META_VALUE(MRES_IGNORED, true);
362 void SourceModBase::LevelShutdown()
364 if (g_LevelEndBarrier)
366 SMGlobalClass *next = SMGlobalClass::head;
369 next->OnSourceModLevelEnd();
370 next = next->m_pGlobalClassNext;
373 if (g_pOnMapEnd != NULL)
375 g_pOnMapEnd->Execute(NULL);
378 g_Timers.RemoveMapChangeTimers();
380 g_LevelEndBarrier = false;
383 g_OnMapStarted = false;
385 if (m_ExecPluginReload)
387 g_PluginSys.ReloadOrUnloadPlugins();
388 m_ExecPluginReload = false;
392 bool SourceModBase::IsMapLoading() const
394 return m_IsMapLoading;
397 void SourceModBase::DoGlobalPluginLoads()
399 char config_path[PLATFORM_MAX_PATH];
400 char plugins_path[PLATFORM_MAX_PATH];
402 BuildPath(Path_SM, config_path,
404 "configs/plugin_settings.cfg");
405 BuildPath(Path_SM, plugins_path,
406 sizeof(plugins_path),
409 /* Load any auto extensions */
410 g_Extensions.TryAutoload();
412 /* Fire the extensions ready message */
413 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
415 /* Load any game extension */
416 const char *game_ext;
417 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
419 char path[PLATFORM_MAX_PATH];
420 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
421 g_Extensions.LoadAutoExtension(path);
424 /* Run the first pass */
425 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
427 /* Mark any extensions as loaded */
428 g_Extensions.MarkAllLoaded();
430 /* No modules yet, it's safe to call this from here */
431 g_PluginSys.LoadAll_SecondPass();
433 /* Re-mark any extensions as loaded */
434 g_Extensions.MarkAllLoaded();
436 /* Call OnAllPluginsLoaded */
437 g_PluginSys.AllPluginsLoaded();
440 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
442 char _buffer[PLATFORM_MAX_PATH];
445 va_start(ap, format);
446 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
449 /* If we get a "file://" notation, strip off the file:// part so we're left
450 * with an absolute path. Note that the absolute path gets returned, so
451 * usage with relative paths here is completely invalid.
453 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
455 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
458 const char *base = NULL;
459 if (type == Path_Game)
461 base = GetGamePath();
463 else if (type == Path_SM)
465 base = GetSourceModPath();
467 else if (type == Path_SM_Rel)
474 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
478 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
482 void SourceModBase::CloseSourceMod()
484 /* Force a level end */
488 g_PluginSys.Shutdown();
490 /* Unload extensions */
491 g_Extensions.Shutdown();
493 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
499 g_Forwards.ReleaseForward(g_pOnMapEnd);
503 SMGlobalClass *pBase = SMGlobalClass::head;
506 pBase->OnSourceModShutdown();
507 pBase = pBase->m_pGlobalClassNext;
510 /* Delete all data packs */
511 CStack<CDataPack *>::iterator iter;
513 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
518 m_freepacks.popall();
521 pBase = SMGlobalClass::head;
524 pBase->OnSourceModAllShutdown();
525 pBase = pBase->m_pGlobalClassNext;
530 SH_RELEASE_CALLCLASS(enginePatch);
536 SH_RELEASE_CALLCLASS(gamedllPatch);
540 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
541 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
545 ShutdownLogicBridge();
549 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
551 IExtensionInterface *pAPI = pExt->GetAPI();
552 const char *tag = pAPI->GetExtensionTag();
556 va_start(ap, format);
557 vsnprintf(buffer, sizeof(buffer), format, ap);
562 g_Logger.LogMessage("[%s] %s", tag, buffer);
564 g_Logger.LogMessage("%s", buffer);
568 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
570 IExtensionInterface *pAPI = pExt->GetAPI();
571 const char *tag = pAPI->GetExtensionTag();
575 va_start(ap, format);
576 vsnprintf(buffer, sizeof(buffer), format, ap);
581 g_Logger.LogError("[%s] %s", tag, buffer);
583 g_Logger.LogError("%s", buffer);
587 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
591 pContext->LocalToString(params[param], &fmt);
593 int lparam = ++param;
595 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
598 const char *SourceModBase::GetSourceModPath() const
603 const char *SourceModBase::GetGamePath() const
605 return g_BaseDir.c_str();
608 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
610 unsigned int old = m_target;
615 unsigned int SourceModBase::GetGlobalTarget() const
620 IDataPack *SourceModBase::CreateDataPack()
623 if (m_freepacks.empty())
625 pack = new CDataPack;
627 pack = m_freepacks.front();
634 void SourceModBase::FreeDataPack(IDataPack *pack)
636 m_freepacks.push(static_cast<CDataPack *>(pack));
639 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
645 const char *SourceModBase::GetGameFolderName() const
650 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
652 return g_pSourcePawn;
655 IVirtualMachine *SourceModBase::GetScriptingVM()
660 void SourceModBase::AllPluginsLoaded()
662 SMGlobalClass *base = SMGlobalClass::head;
665 base->OnSourceModGameInitialized();
666 base = base->m_pGlobalClassNext;
670 time_t SourceModBase::GetAdjustedTime()
672 return ::GetAdjustedTime();
675 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
677 m_frame_hooks.push_back(hook);
680 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
682 for (size_t i = 0; i < m_frame_hooks.size(); i++)
684 if (m_frame_hooks[i] == hook)
686 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
692 void SourceModBase::ProcessGameFrameHooks(bool simulating)
694 if (m_frame_hooks.size() == 0)
699 for (size_t i = 0; i < m_frame_hooks.size(); i++)
701 m_frame_hooks[i](simulating);
705 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
711 len = FormatArgs(buffer, maxlength, fmt, ap);
717 size_t SourceModBase::FormatArgs(char *buffer,
722 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
725 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
727 ::AddFrameAction(FrameAction(fn, data));
730 const char *SourceModBase::GetCoreConfigValue(const char *key)
732 return g_CoreConfig.GetCoreConfigValue(key);
735 int SourceModBase::GetPluginId()
740 int SourceModBase::GetShApiVersion()
743 g_SMAPI->GetShVersions(api, impl);
748 SMGlobalClass *SMGlobalClass::head = NULL;