3 * =============================================================================
5 * Copyright (C) 2004-2008 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"
53 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
54 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
55 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
56 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
58 SourceModBase g_SourceMod;
60 ILibrary *g_pJIT = NULL;
61 SourceHook::String g_BaseDir;
62 ISourcePawnEngine *g_pSourcePawn = NULL;
63 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
64 IdentityToken_t *g_pCoreIdent = NULL;
65 IForward *g_pOnMapEnd = 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 >= 0; 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 /* Initialize CoreConfig to get the SourceMod base path properly - this parses core.cfg */
170 g_CoreConfig.Initialize();
172 /* There will always be a path by this point, since it was force-set above. */
173 m_GotBasePath = true;
175 /* Attempt to load the JIT! */
176 char file[PLATFORM_MAX_PATH];
178 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
183 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
186 if (error && maxlength)
188 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
195 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
196 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
200 if (error && maxlength)
202 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
207 else if (getv2 == NULL)
209 if (error && maxlength)
211 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
217 g_pSourcePawn = getv1();
218 g_pSourcePawn2 = getv2();
220 if (g_pSourcePawn2->GetAPIVersion() < 3)
222 g_pSourcePawn2 = NULL;
223 if (error && maxlength)
225 snprintf(error, maxlength, "JIT version is out of date");
230 if (!g_pSourcePawn2->Initialize())
232 g_pSourcePawn2 = NULL;
233 if (error && maxlength)
235 snprintf(error, maxlength, "JIT could not be initialized");
240 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
241 g_pSourcePawn2->SetProfiler(&g_Profiler);
243 /* Hook this now so we can detect startup without calling StartSourceMod() */
244 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
246 /* Only load if we're not late */
249 StartSourceMod(false);
255 void SourceModBase::StartSourceMod(bool late)
257 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
258 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
260 enginePatch = SH_GET_CALLCLASS(engine);
261 gamedllPatch = SH_GET_CALLCLASS(gamedll);
263 g_ShareSys.Initialize();
265 /* Make the global core identity */
266 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
269 SMGlobalClass *pBase = SMGlobalClass::head;
272 pBase->OnSourceModStartup(false);
273 pBase = pBase->m_pGlobalClassNext;
277 pBase = SMGlobalClass::head;
280 pBase->OnSourceModAllInitialized();
281 pBase = pBase->m_pGlobalClassNext;
285 pBase = SMGlobalClass::head;
288 pBase->OnSourceModAllInitialized_Post();
289 pBase = pBase->m_pGlobalClassNext;
293 g_ShareSys.AddInterface(NULL, this);
298 /* Initialize VSP stuff */
299 if (vsp_interface != NULL)
301 g_SourceMod_Core.OnVSPListening(vsp_interface);
305 static bool g_LevelEndBarrier = false;
306 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
308 /* If we're not loaded... */
311 /* Do all global initialization now */
312 StartSourceMod(true);
315 m_IsMapLoading = true;
316 m_ExecPluginReload = true;
319 SMGlobalClass *pBase = SMGlobalClass::head;
322 pBase->OnSourceModLevelChange(pMapName);
323 pBase = pBase->m_pGlobalClassNext;
326 DoGlobalPluginLoads();
328 m_IsMapLoading = false;
331 pBase = SMGlobalClass::head;
334 pBase->OnSourceModPluginsLoaded();
335 pBase = pBase->m_pGlobalClassNext;
340 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
343 g_LevelEndBarrier = true;
345 RETURN_META_VALUE(MRES_IGNORED, true);
348 void SourceModBase::LevelShutdown()
350 if (g_LevelEndBarrier)
352 SMGlobalClass *next = SMGlobalClass::head;
355 next->OnSourceModLevelEnd();
356 next = next->m_pGlobalClassNext;
359 if (g_pOnMapEnd != NULL)
361 g_pOnMapEnd->Execute(NULL);
364 g_Timers.RemoveMapChangeTimers();
366 g_LevelEndBarrier = false;
369 g_OnMapStarted = false;
371 if (m_ExecPluginReload)
373 g_PluginSys.ReloadOrUnloadPlugins();
374 m_ExecPluginReload = false;
378 bool SourceModBase::IsMapLoading() const
380 return m_IsMapLoading;
383 void SourceModBase::DoGlobalPluginLoads()
385 char config_path[PLATFORM_MAX_PATH];
386 char plugins_path[PLATFORM_MAX_PATH];
388 BuildPath(Path_SM, config_path,
390 "configs/plugin_settings.cfg");
391 BuildPath(Path_SM, plugins_path,
392 sizeof(plugins_path),
395 /* Load any auto extensions */
396 g_Extensions.TryAutoload();
398 /* Fire the extensions ready message */
399 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
401 /* Load any game extension */
402 const char *game_ext;
403 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
405 char path[PLATFORM_MAX_PATH];
406 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
407 g_Extensions.LoadAutoExtension(path);
410 /* Run the first pass */
411 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
413 /* Mark any extensions as loaded */
414 g_Extensions.MarkAllLoaded();
416 /* No modules yet, it's safe to call this from here */
417 g_PluginSys.LoadAll_SecondPass();
419 /* Re-mark any extensions as loaded */
420 g_Extensions.MarkAllLoaded();
422 /* Call OnAllPluginsLoaded */
423 g_PluginSys.AllPluginsLoaded();
426 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
428 char _buffer[PLATFORM_MAX_PATH];
431 va_start(ap, format);
432 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
435 /* If we get a "file://" notation, strip off the file:// part so we're left
436 * with an absolute path. Note that the absolute path gets returned, so
437 * usage with relative paths here is completely invalid.
439 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
441 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
444 const char *base = NULL;
445 if (type == Path_Game)
447 base = GetGamePath();
449 else if (type == Path_SM)
451 base = GetSourceModPath();
453 else if (type == Path_SM_Rel)
460 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
464 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
468 void SourceModBase::CloseSourceMod()
470 /* Force a level end */
474 g_PluginSys.Shutdown();
476 /* Unload extensions */
477 g_Extensions.Shutdown();
479 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
485 g_Forwards.ReleaseForward(g_pOnMapEnd);
489 SMGlobalClass *pBase = SMGlobalClass::head;
492 pBase->OnSourceModShutdown();
493 pBase = pBase->m_pGlobalClassNext;
496 /* Delete all data packs */
497 CStack<CDataPack *>::iterator iter;
499 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
504 m_freepacks.popall();
507 pBase = SMGlobalClass::head;
510 pBase->OnSourceModAllShutdown();
511 pBase = pBase->m_pGlobalClassNext;
516 SH_RELEASE_CALLCLASS(enginePatch);
522 SH_RELEASE_CALLCLASS(gamedllPatch);
526 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
527 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
534 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
536 IExtensionInterface *pAPI = pExt->GetAPI();
537 const char *tag = pAPI->GetExtensionTag();
541 va_start(ap, format);
542 vsnprintf(buffer, sizeof(buffer), format, ap);
547 g_Logger.LogMessage("[%s] %s", tag, buffer);
549 g_Logger.LogMessage("%s", buffer);
553 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
555 IExtensionInterface *pAPI = pExt->GetAPI();
556 const char *tag = pAPI->GetExtensionTag();
560 va_start(ap, format);
561 vsnprintf(buffer, sizeof(buffer), format, ap);
566 g_Logger.LogError("[%s] %s", tag, buffer);
568 g_Logger.LogError("%s", buffer);
572 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
576 pContext->LocalToString(params[param], &fmt);
578 int lparam = ++param;
580 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
583 const char *SourceModBase::GetSourceModPath() const
588 const char *SourceModBase::GetGamePath() const
590 return g_BaseDir.c_str();
593 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
595 unsigned int old = m_target;
600 unsigned int SourceModBase::GetGlobalTarget() const
605 IDataPack *SourceModBase::CreateDataPack()
608 if (m_freepacks.empty())
610 pack = new CDataPack;
612 pack = m_freepacks.front();
619 void SourceModBase::FreeDataPack(IDataPack *pack)
621 m_freepacks.push(static_cast<CDataPack *>(pack));
624 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
630 const char *SourceModBase::GetGameFolderName() const
635 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
637 return g_pSourcePawn;
640 IVirtualMachine *SourceModBase::GetScriptingVM()
645 void SourceModBase::AllPluginsLoaded()
647 SMGlobalClass *base = SMGlobalClass::head;
650 base->OnSourceModGameInitialized();
651 base = base->m_pGlobalClassNext;
655 time_t SourceModBase::GetAdjustedTime()
657 return ::GetAdjustedTime();
660 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
662 m_frame_hooks.push_back(hook);
665 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
667 for (size_t i = 0; i < m_frame_hooks.size(); i++)
669 if (m_frame_hooks[i] == hook)
671 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
677 void SourceModBase::ProcessGameFrameHooks(bool simulating)
679 if (m_frame_hooks.size() == 0)
684 for (size_t i = 0; i < m_frame_hooks.size(); i++)
686 m_frame_hooks[i](simulating);
690 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
696 len = FormatArgs(buffer, maxlength, fmt, ap);
702 size_t SourceModBase::FormatArgs(char *buffer,
707 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
710 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
712 ::AddFrameAction(FrameAction(fn, data));
715 SMGlobalClass *SMGlobalClass::head = NULL;
717 SMGlobalClass::SMGlobalClass()
719 m_pGlobalClassNext = SMGlobalClass::head;
720 SMGlobalClass::head = this;