2 * vim: set ts=4 sw=4 tw=99 noet:
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 "CoreConfig.h"
39 #include "AdminCache.h"
40 #include "sm_stringutil.h"
41 #include "PlayerManager.h"
42 #include "ForwardSys.h"
44 #include <IGameConfigs.h>
45 #include "frame_hooks.h"
46 #include "logic_bridge.h"
48 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
49 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
50 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
51 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
53 SourceModBase g_SourceMod;
55 ILibrary *g_pJIT = NULL;
56 SourceHook::String g_BaseDir;
57 ISourcePawnEngine *g_pSourcePawn = NULL;
58 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
59 IdentityToken_t *g_pCoreIdent = NULL;
60 IForward *g_pOnMapEnd = NULL;
61 IGameConfig *g_pGameConf = NULL;
62 bool g_Loaded = false;
63 bool sm_show_debug_spew = false;
65 typedef ISourcePawnEngine *(*GET_SP_V1)();
66 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
67 typedef void (*NOTIFYSHUTDOWN)();
69 #ifdef PLATFORM_WINDOWS
70 ConVar sm_basepath("sm_basepath", "addons\\sourcemod", 0, "SourceMod base path (set via command line)");
71 #elif defined PLATFORM_LINUX || defined PLATFORM_APPLE
72 ConVar sm_basepath("sm_basepath", "addons/sourcemod", 0, "SourceMod base path (set via command line)");
77 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
83 if (g_pSourcePawn2 != NULL)
85 g_pSourcePawn2->Shutdown();
88 g_pJIT->CloseLibrary();
91 SourceModBase::SourceModBase()
93 m_IsMapLoading = false;
94 m_ExecPluginReload = false;
95 m_GotBasePath = false;
98 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
104 if (strcasecmp(key, "BasePath") == 0)
106 if (source == ConfigSource_Console)
108 UTIL_Format(error, maxlength, "Cannot be set at runtime");
109 return ConfigResult_Reject;
114 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
115 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
117 m_GotBasePath = true;
120 return ConfigResult_Accept;
122 else if (strcasecmp(key, "DebugSpew") == 0)
124 sm_show_debug_spew = (strcasecmp(value, "yes") == 0) ? true : false;
126 return ConfigResult_Accept;
129 return ConfigResult_Ignore;
132 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
134 const char *gamepath = g_SMAPI->GetBaseDir();
136 /* Store full path to game */
137 g_BaseDir.assign(gamepath);
139 /* Store name of game directory by itself */
140 size_t len = strlen(gamepath);
141 for (size_t i = len - 1; i < len; i--)
143 if (gamepath[i] == PLATFORM_SEP_CHAR)
145 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
150 const char *basepath = icvar->GetCommandLineValue("sm_basepath");
151 /* Set a custom base path if there is one. */
152 if (basepath != NULL && basepath[0] != '\0')
154 m_GotBasePath = true;
156 /* Otherwise, use a default and keep the m_GotBasePath unlocked. */
159 basepath = sm_basepath.GetDefault();
162 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), basepath);
163 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "%s", basepath);
165 if (!StartLogicBridge(error, maxlength))
170 /* Initialize CoreConfig to get the SourceMod base path properly - this parses core.cfg */
171 g_CoreConfig.Initialize();
173 /* There will always be a path by this point, since it was force-set above. */
174 m_GotBasePath = true;
176 /* Attempt to load the JIT! */
177 char file[PLATFORM_MAX_PATH];
179 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
184 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
187 if (error && maxlength)
189 UTIL_Format(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
196 GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
197 GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
201 if (error && maxlength)
203 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
208 else if (getv2 == NULL)
210 if (error && maxlength)
212 snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
218 g_pSourcePawn = getv1();
219 g_pSourcePawn2 = getv2();
221 if (g_pSourcePawn2->GetAPIVersion() < 3)
223 g_pSourcePawn2 = NULL;
224 if (error && maxlength)
226 snprintf(error, maxlength, "JIT version is out of date");
231 if (!g_pSourcePawn2->Initialize())
233 g_pSourcePawn2 = NULL;
234 if (error && maxlength)
236 snprintf(error, maxlength, "JIT could not be initialized");
241 g_pSourcePawn2->SetDebugListener(logicore.debugger);
243 /* Hook this now so we can detect startup without calling StartSourceMod() */
244 SH_ADD_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(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(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false);
258 SH_ADD_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false);
260 enginePatch = SH_GET_CALLCLASS(engine);
261 gamedllPatch = SH_GET_CALLCLASS(gamedll);
266 SMGlobalClass *pBase = SMGlobalClass::head;
269 pBase->OnSourceModStartup(false);
270 pBase = pBase->m_pGlobalClassNext;
272 g_pGameConf = logicore.GetCoreGameConfig();
275 pBase = SMGlobalClass::head;
278 pBase->OnSourceModAllInitialized();
279 pBase = pBase->m_pGlobalClassNext;
283 pBase = SMGlobalClass::head;
286 pBase->OnSourceModAllInitialized_Post();
287 pBase = pBase->m_pGlobalClassNext;
291 sharesys->AddInterface(NULL, this);
296 /* Initialize VSP stuff */
297 if (vsp_interface != NULL)
299 g_SourceMod_Core.OnVSPListening(vsp_interface);
304 /* We missed doing anythin gin this if we late-loaded. Sneak it in now. */
308 /* If we want to autoload, do that now */
309 const char *disabled = GetCoreConfigValue("DisableAutoUpdate");
310 if (disabled == NULL || strcasecmp(disabled, "yes") != 0)
312 extsys->LoadAutoExtension("updater.ext." PLATFORM_LIB_EXT);
315 const char *timeout = GetCoreConfigValue("SlowScriptTimeout");
320 if (atoi(timeout) != 0)
322 g_pSourcePawn2->InstallWatchdogTimer(atoi(timeout) * 1000);
326 static bool g_LevelEndBarrier = false;
327 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
329 /* If we're not loaded... */
332 /* Do all global initialization now */
333 StartSourceMod(true);
336 m_IsMapLoading = true;
337 m_ExecPluginReload = true;
340 SMGlobalClass *pBase = SMGlobalClass::head;
343 pBase->OnSourceModLevelChange(pMapName);
344 pBase = pBase->m_pGlobalClassNext;
347 DoGlobalPluginLoads();
349 m_IsMapLoading = false;
352 pBase = SMGlobalClass::head;
355 pBase->OnSourceModPluginsLoaded();
356 pBase = pBase->m_pGlobalClassNext;
361 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
364 g_LevelEndBarrier = true;
366 RETURN_META_VALUE(MRES_IGNORED, true);
369 void SourceModBase::LevelShutdown()
371 if (g_LevelEndBarrier)
373 SMGlobalClass *next = SMGlobalClass::head;
376 next->OnSourceModLevelEnd();
377 next = next->m_pGlobalClassNext;
380 if (g_pOnMapEnd != NULL)
382 g_pOnMapEnd->Execute(NULL);
385 g_Timers.RemoveMapChangeTimers();
387 g_LevelEndBarrier = false;
390 g_OnMapStarted = false;
392 if (m_ExecPluginReload)
394 scripts->RefreshAll();
395 m_ExecPluginReload = false;
399 bool SourceModBase::IsMapLoading() const
401 return m_IsMapLoading;
404 void SourceModBase::DoGlobalPluginLoads()
406 char config_path[PLATFORM_MAX_PATH];
407 char plugins_path[PLATFORM_MAX_PATH];
409 BuildPath(Path_SM, config_path,
411 "configs/plugin_settings.cfg");
412 BuildPath(Path_SM, plugins_path,
413 sizeof(plugins_path),
416 /* Load any auto extensions */
417 extsys->TryAutoload();
419 /* Fire the extensions ready message */
420 g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);
422 /* Load any game extension */
423 const char *game_ext;
424 if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
426 char path[PLATFORM_MAX_PATH];
427 UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
428 extsys->LoadAutoExtension(path);
431 scripts->LoadAll(config_path, plugins_path);
434 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
436 char _buffer[PLATFORM_MAX_PATH];
439 va_start(ap, format);
440 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
443 /* If we get a "file://" notation, strip off the file:// part so we're left
444 * with an absolute path. Note that the absolute path gets returned, so
445 * usage with relative paths here is completely invalid.
447 if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
449 return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
452 const char *base = NULL;
453 if (type == Path_Game)
455 base = GetGamePath();
457 else if (type == Path_SM)
459 base = GetSourceModPath();
461 else if (type == Path_SM_Rel)
468 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
472 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
476 void SourceModBase::CloseSourceMod()
478 /* Force a level end */
484 /* Unload extensions */
487 SH_REMOVE_HOOK(IServerGameDLL, LevelInit, gamedll, SH_MEMBER(this, &SourceModBase::LevelInit), false);
493 g_Forwards.ReleaseForward(g_pOnMapEnd);
497 SMGlobalClass *pBase = SMGlobalClass::head;
500 pBase->OnSourceModShutdown();
501 pBase = pBase->m_pGlobalClassNext;
504 /* Delete all data packs */
505 CStack<CDataPack *>::iterator iter;
507 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
512 m_freepacks.popall();
515 pBase = SMGlobalClass::head;
518 pBase->OnSourceModAllShutdown();
519 pBase = pBase->m_pGlobalClassNext;
524 SH_RELEASE_CALLCLASS(enginePatch);
530 SH_RELEASE_CALLCLASS(gamedllPatch);
534 SH_REMOVE_HOOK(IServerGameDLL, LevelShutdown, gamedll, SH_MEMBER(this, &SourceModBase::LevelShutdown), false);
535 SH_REMOVE_HOOK(IServerGameDLL, GameFrame, gamedll, SH_MEMBER(&g_Timers, &TimerSystem::GameFrame), false);
539 ShutdownLogicBridge();
543 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
545 IExtensionInterface *pAPI = pExt->GetAPI();
546 const char *tag = pAPI->GetExtensionTag();
550 va_start(ap, format);
551 vsnprintf(buffer, sizeof(buffer), format, ap);
556 g_Logger.LogMessage("[%s] %s", tag, buffer);
558 g_Logger.LogMessage("%s", buffer);
562 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
564 IExtensionInterface *pAPI = pExt->GetAPI();
565 const char *tag = pAPI->GetExtensionTag();
569 va_start(ap, format);
570 vsnprintf(buffer, sizeof(buffer), format, ap);
575 g_Logger.LogError("[%s] %s", tag, buffer);
577 g_Logger.LogError("%s", buffer);
581 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
585 pContext->LocalToString(params[param], &fmt);
587 int lparam = ++param;
589 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
592 const char *SourceModBase::GetSourceModPath() const
597 const char *SourceModBase::GetGamePath() const
599 return g_BaseDir.c_str();
602 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
604 unsigned int old = m_target;
609 unsigned int SourceModBase::GetGlobalTarget() const
614 IDataPack *SourceModBase::CreateDataPack()
617 if (m_freepacks.empty())
619 pack = new CDataPack;
621 pack = m_freepacks.front();
628 void SourceModBase::FreeDataPack(IDataPack *pack)
630 m_freepacks.push(static_cast<CDataPack *>(pack));
633 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
639 const char *SourceModBase::GetGameFolderName() const
644 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
646 return g_pSourcePawn;
649 IVirtualMachine *SourceModBase::GetScriptingVM()
654 void SourceModBase::AllPluginsLoaded()
661 SMGlobalClass *base = SMGlobalClass::head;
664 base->OnSourceModGameInitialized();
665 base = base->m_pGlobalClassNext;
669 time_t SourceModBase::GetAdjustedTime()
671 return ::GetAdjustedTime();
674 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
676 m_frame_hooks.push_back(hook);
679 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
681 for (size_t i = 0; i < m_frame_hooks.size(); i++)
683 if (m_frame_hooks[i] == hook)
685 m_frame_hooks.erase(m_frame_hooks.iterAt(i));
691 void SourceModBase::ProcessGameFrameHooks(bool simulating)
693 if (m_frame_hooks.size() == 0)
698 for (size_t i = 0; i < m_frame_hooks.size(); i++)
700 m_frame_hooks[i](simulating);
704 size_t SourceModBase::Format(char *buffer, size_t maxlength, const char *fmt, ...)
710 len = FormatArgs(buffer, maxlength, fmt, ap);
716 size_t SourceModBase::FormatArgs(char *buffer,
721 return UTIL_FormatArgs(buffer, maxlength, fmt, ap);
724 void SourceModBase::AddFrameAction(FRAMEACTION fn, void *data)
726 ::AddFrameAction(FrameAction(fn, data));
729 const char *SourceModBase::GetCoreConfigValue(const char *key)
731 return g_CoreConfig.GetCoreConfigValue(key);
734 int SourceModBase::GetPluginId()
739 int SourceModBase::GetShApiVersion()
742 g_SMAPI->GetShVersions(api, impl);
747 bool SourceModBase::IsMapRunning()
749 return g_OnMapStarted;
752 SMGlobalClass *SMGlobalClass::head = NULL;