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)();
75 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
81 if (g_pSourcePawn2 != NULL)
83 g_pSourcePawn2->Shutdown();
86 g_pJIT->CloseLibrary();
89 SourceModBase::SourceModBase()
91 m_IsMapLoading = false;
92 m_ExecPluginReload = false;
93 m_GotBasePath = false;
96 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
102 if (strcasecmp(key, "BasePath") == 0)
104 if (source == ConfigSource_Console)
106 UTIL_Format(error, maxlength, "Cannot be set at runtime");
107 return ConfigResult_Reject;
112 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
113 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
115 m_GotBasePath = true;
118 return ConfigResult_Accept;
120 else if (strcasecmp(key, "DebugSpew") == 0)
122 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
124 return ConfigResult_Accept;
127 return ConfigResult_Ignore;
130 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
132 const char *gamepath = g_SMAPI->GetBaseDir();
134 /* Store full path to game */
135 g_BaseDir.assign(gamepath);
137 /* Store name of game directory by itself */
138 size_t len = strlen(gamepath);
139 for (size_t i = len - 1; i >= 0; i--)
141 if (gamepath[i] == PLATFORM_SEP_CHAR)
143 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
148 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
149 g_CoreConfig.Initialize();
151 /* This shouldn't happen, but can't hurt to be safe */
152 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
154 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
155 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
156 m_GotBasePath = true;
159 /* Attempt to load the JIT! */
160 char file[PLATFORM_MAX_PATH];
162 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
167 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
170 if (error && maxlength)
172 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
179 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
180 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
184 if (error && maxlength)
186 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
191 else if (getv2 == NULL)
193 if (error && maxlength)
195 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
201 g_pSourcePawn = getv1();
202 g_pSourcePawn2 = getv2();
204 if (g_pSourcePawn2->GetAPIVersion() < 3)
206 g_pSourcePawn2 = NULL;
207 if (error && maxlength)
209 snprintf(error, maxlength, "JIT version is out of date");
214 if (!g_pSourcePawn2->Initialize())
216 g_pSourcePawn2 = NULL;
217 if (error && maxlength)
219 snprintf(error, maxlength, "JIT could not be initialized");
224 g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
225 g_pSourcePawn2->SetProfiler(&g_Profiler);
227 /* Hook this now so we can detect startup without calling StartSourceMod() */
228 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
230 /* Only load if we're not late */
233 StartSourceMod(false);
239 void SourceModBase::StartSourceMod(bool late)
241 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
242 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
244 enginePatch = SH_GET_CALLCLASS(engine);
245 gamedllPatch = SH_GET_CALLCLASS(gamedll);
247 g_ShareSys.Initialize();
249 /* Make the global core identity */
250 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
253 SMGlobalClass *pBase = SMGlobalClass::head;
256 pBase->OnSourceModStartup(false);
257 pBase = pBase->m_pGlobalClassNext;
261 pBase = SMGlobalClass::head;
264 pBase->OnSourceModAllInitialized();
265 pBase = pBase->m_pGlobalClassNext;
269 pBase = SMGlobalClass::head;
272 pBase->OnSourceModAllInitialized_Post();
273 pBase = pBase->m_pGlobalClassNext;
277 g_ShareSys.AddInterface(NULL, this);
282 /* Initialize VSP stuff */
283 if (vsp_interface != NULL)
285 g_SourceMod_Core.OnVSPListening(vsp_interface);
289 static bool g_LevelEndBarrier = false;
290 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
292 /* If we're not loaded... */
295 /* Do all global initialization now */
296 StartSourceMod(true);
299 m_IsMapLoading = true;
300 m_ExecPluginReload = true;
303 SMGlobalClass *pBase = SMGlobalClass::head;
306 pBase->OnSourceModLevelChange(pMapName);
307 pBase = pBase->m_pGlobalClassNext;
310 DoGlobalPluginLoads();
312 m_IsMapLoading = false;
315 pBase = SMGlobalClass::head;
318 pBase->OnSourceModPluginsLoaded();
319 pBase = pBase->m_pGlobalClassNext;
324 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
327 g_LevelEndBarrier = true;
329 RETURN_META_VALUE(MRES_IGNORED, true);
332 void SourceModBase::LevelShutdown()
334 if (g_LevelEndBarrier)
336 SMGlobalClass *next = SMGlobalClass::head;
339 next->OnSourceModLevelEnd();
340 next = next->m_pGlobalClassNext;
343 if (g_pOnMapEnd != NULL)
345 g_pOnMapEnd->Execute(NULL);
348 g_Timers.RemoveMapChangeTimers();
350 g_LevelEndBarrier = false;
353 g_OnMapStarted = false;
355 if (m_ExecPluginReload)
357 g_PluginSys.ReloadOrUnloadPlugins();
358 m_ExecPluginReload = false;
362 bool SourceModBase::IsMapLoading() const
364 return m_IsMapLoading;
367 void SourceModBase::DoGlobalPluginLoads()
369 char config_path[PLATFORM_MAX_PATH];
370 char plugins_path[PLATFORM_MAX_PATH];
372 BuildPath(Path_SM, config_path,
374 "configs/plugin_settings.cfg");
375 BuildPath(Path_SM, plugins_path,
376 sizeof(plugins_path),
379 /* Load any auto extensions */
380 g_Extensions.TryAutoload();
382 /* Fire the extensions ready message */
383 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
385 /* Load any game extension */
386 const char *game_ext;
387 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
389 char path[PLATFORM_MAX_PATH];
390 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
391 g_Extensions.LoadAutoExtension(path);
394 /* Run the first pass */
395 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
397 /* Mark any extensions as loaded */
398 g_Extensions.MarkAllLoaded();
400 /* No modules yet, it's safe to call this from here */
401 g_PluginSys.LoadAll_SecondPass();
403 /* Re-mark any extensions as loaded */
404 g_Extensions.MarkAllLoaded();
406 /* Call OnAllPluginsLoaded */
407 g_PluginSys.AllPluginsLoaded();
410 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
412 char _buffer[PLATFORM_MAX_PATH];
415 va_start(ap, format);
416 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
419 /* If we get a "file://" notation, strip off the file:// part so we're left
420 * with an absolute path. Note that the absolute path gets returned, so
421 * usage with relative paths here is completely invalid.
423 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
425 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
428 const char *base = NULL;
429 if (type == Path_Game)
431 base = GetGamePath();
433 else if (type == Path_SM)
435 base = GetSourceModPath();
437 else if (type == Path_SM_Rel)
444 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
448 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
452 void SourceModBase::CloseSourceMod()
454 /* Force a level end */
458 g_PluginSys.Shutdown();
460 /* Unload extensions */
461 g_Extensions.Shutdown();
463 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
469 g_Forwards.ReleaseForward(g_pOnMapEnd);
473 SMGlobalClass *pBase = SMGlobalClass::head;
476 pBase->OnSourceModShutdown();
477 pBase = pBase->m_pGlobalClassNext;
480 /* Delete all data packs */
481 CStack<CDataPack *>::iterator iter;
483 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
488 m_freepacks.popall();
491 pBase = SMGlobalClass::head;
494 pBase->OnSourceModAllShutdown();
495 pBase = pBase->m_pGlobalClassNext;
500 SH_RELEASE_CALLCLASS(enginePatch);
506 SH_RELEASE_CALLCLASS(gamedllPatch);
510 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
511 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
518 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
520 IExtensionInterface *pAPI = pExt->GetAPI();
521 const char *tag = pAPI->GetExtensionTag();
525 va_start(ap, format);
526 vsnprintf(buffer, sizeof(buffer), format, ap);
531 g_Logger.LogMessage("[%s] %s", tag, buffer);
533 g_Logger.LogMessage("%s", buffer);
537 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
539 IExtensionInterface *pAPI = pExt->GetAPI();
540 const char *tag = pAPI->GetExtensionTag();
544 va_start(ap, format);
545 vsnprintf(buffer, sizeof(buffer), format, ap);
550 g_Logger.LogError("[%s] %s", tag, buffer);
552 g_Logger.LogError("%s", buffer);
556 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
560 pContext->LocalToString(params[param], &fmt);
562 int lparam = ++param;
564 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
567 const char *SourceModBase::GetSourceModPath() const
572 const char *SourceModBase::GetGamePath() const
574 return g_BaseDir.c_str();
577 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
579 unsigned int old = m_target;
584 unsigned int SourceModBase::GetGlobalTarget() const
589 IDataPack *SourceModBase::CreateDataPack()
592 if (m_freepacks.empty())
594 pack = new CDataPack;
596 pack = m_freepacks.front();
603 void SourceModBase::FreeDataPack(IDataPack *pack)
605 m_freepacks.push(static_cast<CDataPack *>(pack));
608 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
614 const char *SourceModBase::GetGameFolderName() const
619 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
621 return g_pSourcePawn;
624 IVirtualMachine *SourceModBase::GetScriptingVM()
629 void SourceModBase::AllPluginsLoaded()
631 SMGlobalClass *base = SMGlobalClass::head;
634 base->OnSourceModGameInitialized();
635 base = base->m_pGlobalClassNext;
639 time_t SourceModBase::GetAdjustedTime()
641 return ::GetAdjustedTime();
644 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
646 m_frame_hooks.push_back(hook);
649 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
651 for (size_t i = 0; i < m_frame_hooks.size(); i++)
653 if (m_frame_hooks[i] == hook)
655 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
661 void SourceModBase::ProcessGameFrameHooks(bool simulating)
663 if (m_frame_hooks.size() == 0)
668 for (size_t i = 0; i < m_frame_hooks.size(); i++)
670 m_frame_hooks[i](simulating);
674 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
680 len = FormatArgs(buffer, maxlength, fmt, ap);
686 size_t SourceModBase::FormatArgs(char *buffer,
691 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
694 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
696 ::AddFrameAction(FrameAction(fn, data));
699 SMGlobalClass *SMGlobalClass::head = NULL;
701 SMGlobalClass::SMGlobalClass()
703 m_pGlobalClassNext = SMGlobalClass::head;
704 SMGlobalClass::head = this;