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"
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 bool g_Loaded = false;
66 bool sm_show_debug_spew = false;
68 typedef ISourcePawnEngine *(*GET_SP_V1)();
69 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
70 typedef void (*NOTIFYSHUTDOWN)();
74 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
80 if (g_pSourcePawn2 != NULL)
82 g_pSourcePawn2->Shutdown();
85 g_pJIT->CloseLibrary();
88 SourceModBase::SourceModBase()
90 m_IsMapLoading = false;
91 m_ExecPluginReload = false;
92 m_GotBasePath = false;
95 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
101 if (strcasecmp(key, "BasePath") == 0)
103 if (source == ConfigSource_Console)
105 UTIL_Format(error, maxlength, "Cannot be set at runtime");
106 return ConfigResult_Reject;
111 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
112 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
114 m_GotBasePath = true;
117 return ConfigResult_Accept;
119 else if (strcasecmp(key, "DebugSpew") == 0)
121 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
123 return ConfigResult_Accept;
126 return ConfigResult_Ignore;
129 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
131 const char *gamepath = g_SMAPI->GetBaseDir();
133 /* Store full path to game */
134 g_BaseDir.assign(gamepath);
136 /* Store name of game directory by itself */
137 size_t len = strlen(gamepath);
138 for (size_t i = len - 1; i >= 0; i--)
140 if (gamepath[i] == PLATFORM_SEP_CHAR)
142 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
147 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
148 g_CoreConfig.Initialize();
150 /* This shouldn't happen, but can't hurt to be safe */
151 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
153 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
154 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
155 m_GotBasePath = true;
158 /* Attempt to load the JIT! */
159 char file[PLATFORM_MAX_PATH];
161 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
166 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
169 if (error && maxlength)
171 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
178 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
179 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
183 if (error && maxlength)
185 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
190 else if (getv2 == NULL)
192 if (error && maxlength)
194 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
200 g_pSourcePawn = getv1();
201 g_pSourcePawn2 = getv2();
203 if (g_pSourcePawn2->GetAPIVersion() < 2)
205 g_pSourcePawn2 = NULL;
206 if (error && maxlength)
208 snprintf(error, maxlength, "JIT version is out of date");
213 if (!g_pSourcePawn2->Initialize())
215 g_pSourcePawn2 = NULL;
216 if (error && maxlength)
218 snprintf(error, maxlength, "JIT could not be initialized");
223 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
224 g_pSourcePawn2->SetProfiler(&g_Profiler);
226 /* Hook this now so we can detect startup without calling StartSourceMod() */
227 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
229 /* Only load if we're not late */
232 StartSourceMod(false);
238 void SourceModBase::StartSourceMod(bool late)
240 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
241 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
243 enginePatch = SH_GET_CALLCLASS(engine);
244 gamedllPatch = SH_GET_CALLCLASS(gamedll);
246 g_ShareSys.Initialize();
248 /* Make the global core identity */
249 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
252 SMGlobalClass *pBase = SMGlobalClass::head;
255 pBase->OnSourceModStartup(false);
256 pBase = pBase->m_pGlobalClassNext;
260 pBase = SMGlobalClass::head;
263 pBase->OnSourceModAllInitialized();
264 pBase = pBase->m_pGlobalClassNext;
268 pBase = SMGlobalClass::head;
271 pBase->OnSourceModAllInitialized_Post();
272 pBase = pBase->m_pGlobalClassNext;
276 g_ShareSys.AddInterface(NULL, this);
281 /* Initialize VSP stuff */
282 if (vsp_interface != NULL)
284 g_SourceMod_Core.OnVSPListening(vsp_interface);
288 static bool g_LevelEndBarrier = false;
289 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
291 /* If we're not loaded... */
294 /* Do all global initialization now */
295 StartSourceMod(true);
298 m_IsMapLoading = true;
299 m_ExecPluginReload = true;
302 SMGlobalClass *pBase = SMGlobalClass::head;
305 pBase->OnSourceModLevelChange(pMapName);
306 pBase = pBase->m_pGlobalClassNext;
309 DoGlobalPluginLoads();
311 m_IsMapLoading = false;
314 pBase = SMGlobalClass::head;
317 pBase->OnSourceModPluginsLoaded();
318 pBase = pBase->m_pGlobalClassNext;
323 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
326 g_LevelEndBarrier = true;
328 RETURN_META_VALUE(MRES_IGNORED, true);
331 void SourceModBase::LevelShutdown()
333 if (g_LevelEndBarrier)
335 SMGlobalClass *next = SMGlobalClass::head;
338 next->OnSourceModLevelEnd();
339 next = next->m_pGlobalClassNext;
342 if (g_pOnMapEnd != NULL)
344 g_pOnMapEnd->Execute(NULL);
347 g_Timers.RemoveMapChangeTimers();
349 g_LevelEndBarrier = false;
352 g_OnMapStarted = false;
354 if (m_ExecPluginReload)
356 g_PluginSys.ReloadOrUnloadPlugins();
357 m_ExecPluginReload = false;
361 bool SourceModBase::IsMapLoading() const
363 return m_IsMapLoading;
366 void SourceModBase::DoGlobalPluginLoads()
368 char config_path[PLATFORM_MAX_PATH];
369 char plugins_path[PLATFORM_MAX_PATH];
371 BuildPath(Path_SM, config_path,
373 "configs/plugin_settings.cfg");
374 BuildPath(Path_SM, plugins_path,
375 sizeof(plugins_path),
378 /* Load any auto extensions */
379 g_Extensions.TryAutoload();
381 /* Fire the extensions ready message */
382 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
384 /* Load any game extension */
385 const char *game_ext;
386 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
388 char path[PLATFORM_MAX_PATH];
389 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
390 g_Extensions.LoadAutoExtension(path);
393 /* Run the first pass */
394 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
396 /* Mark any extensions as loaded */
397 g_Extensions.MarkAllLoaded();
399 /* No modules yet, it's safe to call this from here */
400 g_PluginSys.LoadAll_SecondPass();
402 /* Re-mark any extensions as loaded */
403 g_Extensions.MarkAllLoaded();
405 /* Call OnAllPluginsLoaded */
406 g_PluginSys.AllPluginsLoaded();
409 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
411 char _buffer[PLATFORM_MAX_PATH];
414 va_start(ap, format);
415 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
418 /* If we get a "file://" notation, strip off the file:// part so we're left
419 * with an absolute path. Note that the absolute path gets returned, so
420 * usage with relative paths here is completely invalid.
422 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
424 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
427 const char *base = NULL;
428 if (type == Path_Game)
430 base = GetGamePath();
432 else if (type == Path_SM)
434 base = GetSourceModPath();
436 else if (type == Path_SM_Rel)
443 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
447 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
451 void SourceModBase::CloseSourceMod()
453 /* Force a level end */
457 g_PluginSys.Shutdown();
459 /* Unload extensions */
460 g_Extensions.Shutdown();
462 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
468 g_Forwards.ReleaseForward(g_pOnMapEnd);
472 SMGlobalClass *pBase = SMGlobalClass::head;
475 pBase->OnSourceModShutdown();
476 pBase = pBase->m_pGlobalClassNext;
479 /* Delete all data packs */
480 CStack<CDataPack *>::iterator iter;
482 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
487 m_freepacks.popall();
490 pBase = SMGlobalClass::head;
493 pBase->OnSourceModAllShutdown();
494 pBase = pBase->m_pGlobalClassNext;
499 SH_RELEASE_CALLCLASS(enginePatch);
505 SH_RELEASE_CALLCLASS(gamedllPatch);
509 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
510 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
517 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
519 IExtensionInterface *pAPI = pExt->GetAPI();
520 const char *tag = pAPI->GetExtensionTag();
524 va_start(ap, format);
525 vsnprintf(buffer, sizeof(buffer), format, ap);
530 g_Logger.LogMessage("[%s] %s", tag, buffer);
532 g_Logger.LogMessage("%s", buffer);
536 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
538 IExtensionInterface *pAPI = pExt->GetAPI();
539 const char *tag = pAPI->GetExtensionTag();
543 va_start(ap, format);
544 vsnprintf(buffer, sizeof(buffer), format, ap);
549 g_Logger.LogError("[%s] %s", tag, buffer);
551 g_Logger.LogError("%s", buffer);
555 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
559 pContext->LocalToString(params[param], &fmt);
561 int lparam = ++param;
563 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
566 const char *SourceModBase::GetSourceModPath() const
571 const char *SourceModBase::GetGamePath() const
573 return g_BaseDir.c_str();
576 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
578 unsigned int old = m_target;
583 unsigned int SourceModBase::GetGlobalTarget() const
588 IDataPack *SourceModBase::CreateDataPack()
591 if (m_freepacks.empty())
593 pack = new CDataPack;
595 pack = m_freepacks.front();
602 void SourceModBase::FreeDataPack(IDataPack *pack)
604 m_freepacks.push(static_cast<CDataPack *>(pack));
607 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
613 const char *SourceModBase::GetGameFolderName() const
618 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
620 return g_pSourcePawn;
623 IVirtualMachine *SourceModBase::GetScriptingVM()
628 void SourceModBase::AllPluginsLoaded()
630 SMGlobalClass *base = SMGlobalClass::head;
633 base->OnSourceModGameInitialized();
634 base = base->m_pGlobalClassNext;
638 time_t SourceModBase::GetAdjustedTime()
640 return ::GetAdjustedTime();
643 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
645 m_frame_hooks.push_back(hook);
648 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
650 for (size_t i = 0; i < m_frame_hooks.size(); i++)
652 if (m_frame_hooks[i] == hook)
654 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
660 void SourceModBase::ProcessGameFrameHooks(bool simulating)
662 if (m_frame_hooks.size() == 0)
667 for (size_t i = 0; i < m_frame_hooks.size(); i++)
669 m_frame_hooks[i](simulating);
673 SMGlobalClass *SMGlobalClass::head = NULL;
675 SMGlobalClass::SMGlobalClass()
677 m_pGlobalClassNext = SMGlobalClass::head;
678 SMGlobalClass::head = this;