3 * ===============================================================
4 * SourceMod (C)2004-2007 AlliedModders LLC. All rights reserved.
5 * ===============================================================
7 * This file is not open source and may not be copied without explicit
8 * written permission of AlliedModders LLC. This file may not be redistributed
9 * in whole or significant part.
10 * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
16 #include "sourcemod.h"
17 #include "sourcemm_api.h"
18 #include "systems/LibrarySys.h"
19 #include "vm/sp_vm_engine.h"
20 #include <sh_string.h>
21 #include "PluginSys.h"
23 #include "CoreConfig.h"
25 #include "ExtensionSys.h"
26 #include "AdminCache.h"
27 #include "sm_stringutil.h"
28 #include "PlayerManager.h"
29 #include "Translator.h"
30 #include "ForwardSys.h"
33 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
34 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
35 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
37 SourcePawnEngine g_SourcePawn;
38 SourceModBase g_SourceMod;
40 ILibrary *g_pJIT = NULL;
41 SourceHook::String g_BaseDir;
42 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
43 IVirtualMachine *g_pVM;
44 IdentityToken_t *g_pCoreIdent = NULL;
45 float g_LastTime = 0.0f;
46 float g_LastAuthCheck = 0.0f;
47 IForward *g_pOnGameFrame = NULL;
48 bool g_Loaded = false;
50 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
51 typedef unsigned int (*GETEXPORTCOUNT)();
52 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
53 typedef void (*NOTIFYSHUTDOWN)();
57 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
63 g_pJIT->CloseLibrary();
66 SourceModBase::SourceModBase()
68 m_IsMapLoading = false;
69 m_ExecPluginReload = false;
70 m_GotBasePath = false;
73 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
79 if (strcasecmp(key, "BasePath") == 0)
81 if (source == ConfigSource_Console)
83 UTIL_Format(error, maxlength, "Cannot be set at runtime");
84 return ConfigResult_Reject;
89 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
90 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
95 return ConfigResult_Accept;
98 return ConfigResult_Ignore;
101 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
103 const char *gamepath = g_SMAPI->GetBaseDir();
105 /* Store full path to game */
106 g_BaseDir.assign(gamepath);
108 /* Store name of game directory by itself */
109 size_t len = strlen(gamepath);
110 for (size_t i = len - 1; i >= 0; i--)
112 if (gamepath[i] == PLATFORM_SEP_CHAR)
114 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
119 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
120 g_CoreConfig.Initialize();
122 /* This shouldn't happen, but can't hurt to be safe */
123 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
125 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
126 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
127 m_GotBasePath = true;
130 /* Attempt to load the JIT! */
131 char file[PLATFORM_MAX_PATH];
133 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
138 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
141 if (error && err_max)
143 snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
151 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
155 if (error && err_max)
157 snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
162 if ((err=jit_init(g_pSourcePawn)) != 0)
165 if (error && err_max)
167 snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
172 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
173 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
177 if (error && err_max)
179 snprintf(error, err_max, "JIT is missing a necessary export!");
184 unsigned int num = jit_getnum();
185 if (!num || ((g_pVM=jit_get(0)) == NULL))
188 if (error && err_max)
190 snprintf(error, err_max, "JIT did not export any virtual machines!");
195 unsigned int api = g_pVM->GetAPIVersion();
196 if (api != SOURCEPAWN_VM_API_VERSION)
199 if (error && err_max)
201 snprintf(error, err_max, "JIT is not a compatible version");
206 /* Hook this now so we can detect startup without calling StartSourceMod() */
207 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
209 /* Only load if we're not late */
212 StartSourceMod(false);
218 void SourceModBase::StartSourceMod(bool late)
220 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
221 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
223 enginePatch = SH_GET_CALLCLASS(engine);
224 gamedllPatch = SH_GET_CALLCLASS(gamedll);
227 SMGlobalClass *pBase = SMGlobalClass::head;
230 pBase->OnSourceModStartup(false);
231 pBase = pBase->m_pGlobalClassNext;
234 /* Make the global core identity */
235 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
238 pBase = SMGlobalClass::head;
241 pBase->OnSourceModAllInitialized();
242 pBase = pBase->m_pGlobalClassNext;
246 g_ShareSys.AddInterface(NULL, this);
252 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
254 /* If we're not loaded... */
257 /* Do all global initialization now */
258 StartSourceMod(true);
261 m_IsMapLoading = true;
262 m_ExecPluginReload = true;
264 g_LastAuthCheck = 0.0f;
267 SMGlobalClass *pBase = SMGlobalClass::head;
270 pBase->OnSourceModLevelChange(pMapName);
271 pBase = pBase->m_pGlobalClassNext;
274 DoGlobalPluginLoads();
276 m_IsMapLoading = false;
279 pBase = SMGlobalClass::head;
282 pBase->OnSourceModPluginsLoaded();
283 pBase = pBase->m_pGlobalClassNext;
288 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
291 RETURN_META_VALUE(MRES_IGNORED, true);
294 void SourceModBase::GameFrame(bool simulating)
297 * Note: This is all hardcoded rather than delegated to save
298 * precious CPU cycles.
300 float curtime = gpGlobals->curtime;
301 if (curtime - g_LastTime >= 0.1f)
304 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
306 g_LastAuthCheck = gpGlobals->curtime;
307 g_Players.RunAuthChecks();
311 g_LastTime = curtime;
314 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
316 g_pOnGameFrame->Execute(NULL);
320 void SourceModBase::LevelShutdown()
322 if (m_ExecPluginReload)
324 g_PluginSys.ReloadOrUnloadPlugins();
325 m_ExecPluginReload = false;
329 bool SourceModBase::IsMapLoading() const
331 return m_IsMapLoading;
334 void SourceModBase::DoGlobalPluginLoads()
336 char config_path[PLATFORM_MAX_PATH];
337 char plugins_path[PLATFORM_MAX_PATH];
339 BuildPath(Path_SM, config_path,
341 "configs/plugin_settings.cfg");
342 BuildPath(Path_SM, plugins_path,
343 sizeof(plugins_path),
346 /* Load any auto extensions */
347 g_Extensions.TryAutoload();
349 /* Run the first pass */
350 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
352 /* Mark any extensions as loaded */
353 g_Extensions.MarkAllLoaded();
355 /* No modules yet, it's safe to call this from here */
356 g_PluginSys.LoadAll_SecondPass();
358 /* Re-mark any extensions as loaded */
359 g_Extensions.MarkAllLoaded();
362 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
364 char _buffer[PLATFORM_MAX_PATH];
367 va_start(ap, format);
368 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
371 const char *base = NULL;
372 if (type == Path_Game)
375 } else if (type == Path_SM) {
376 base = GetSourceModPath();
377 } else if (type == Path_SM_Rel) {
383 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
385 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
389 void SourceModBase::CloseSourceMod()
391 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
397 g_Forwards.ReleaseForward(g_pOnGameFrame);
401 SMGlobalClass *pBase = SMGlobalClass::head;
404 pBase->OnSourceModShutdown();
405 pBase = pBase->m_pGlobalClassNext;
408 /* Delete all data packs */
409 CStack<CDataPack *>::iterator iter;
411 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
416 m_freepacks.popall();
419 pBase = SMGlobalClass::head;
422 pBase->OnSourceModAllShutdown();
423 pBase = pBase->m_pGlobalClassNext;
428 SH_RELEASE_CALLCLASS(enginePatch);
434 SH_RELEASE_CALLCLASS(gamedllPatch);
438 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
439 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
446 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
448 IExtensionInterface *pAPI = pExt->GetAPI();
449 const char *tag = pAPI->GetExtensionTag();
453 va_start(ap, format);
454 vsnprintf(buffer, sizeof(buffer), format, ap);
459 g_Logger.LogMessage("[%s] %s", tag, buffer);
461 g_Logger.LogMessage("%s", buffer);
465 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
467 IExtensionInterface *pAPI = pExt->GetAPI();
468 const char *tag = pAPI->GetExtensionTag();
472 va_start(ap, format);
473 vsnprintf(buffer, sizeof(buffer), format, ap);
478 g_Logger.LogError("[%s] %s", tag, buffer);
480 g_Logger.LogError("%s", buffer);
484 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
488 pContext->LocalToString(params[param], &fmt);
490 int lparam = ++param;
492 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
495 const char *SourceModBase::GetSourceModPath() const
500 const char *SourceModBase::GetModPath() const
502 return g_BaseDir.c_str();
505 void SourceModBase::SetGlobalTarget(unsigned int index)
510 void SourceModBase::SetAuthChecking(bool set)
512 m_CheckingAuth = set;
515 unsigned int SourceModBase::GetGlobalTarget() const
520 IDataPack *SourceModBase::CreateDataPack()
523 if (m_freepacks.empty())
525 pack = new CDataPack;
527 pack = m_freepacks.front();
534 void SourceModBase::FreeDataPack(IDataPack *pack)
536 m_freepacks.push(static_cast<CDataPack *>(pack));
539 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
545 const char *SourceModBase::GetModFolderName() const
550 SMGlobalClass *SMGlobalClass::head = NULL;
552 SMGlobalClass::SMGlobalClass()
554 m_pGlobalClassNext = SMGlobalClass::head;
555 SMGlobalClass::head = this;