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 IForward *g_pOnMapEnd = NULL;
49 bool g_Loaded = false;
50 int g_StillFrames = 0;
51 float g_StillTime = 0.0f;
53 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
54 typedef unsigned int (*GETEXPORTCOUNT)();
55 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
56 typedef void (*NOTIFYSHUTDOWN)();
60 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
66 g_pJIT->CloseLibrary();
69 SourceModBase::SourceModBase()
71 m_IsMapLoading = false;
72 m_ExecPluginReload = false;
73 m_GotBasePath = false;
76 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
82 if (strcasecmp(key, "BasePath") == 0)
84 if (source == ConfigSource_Console)
86 UTIL_Format(error, maxlength, "Cannot be set at runtime");
87 return ConfigResult_Reject;
92 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
93 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
98 return ConfigResult_Accept;
101 return ConfigResult_Ignore;
104 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
106 const char *gamepath = g_SMAPI->GetBaseDir();
108 /* Store full path to game */
109 g_BaseDir.assign(gamepath);
111 /* Store name of game directory by itself */
112 size_t len = strlen(gamepath);
113 for (size_t i = len - 1; i >= 0; i--)
115 if (gamepath[i] == PLATFORM_SEP_CHAR)
117 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
122 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
123 g_CoreConfig.Initialize();
125 /* This shouldn't happen, but can't hurt to be safe */
126 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
128 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
129 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
130 m_GotBasePath = true;
133 /* Attempt to load the JIT! */
134 char file[PLATFORM_MAX_PATH];
136 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
141 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
144 if (error && err_max)
146 snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
154 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
158 if (error && err_max)
160 snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
165 if ((err=jit_init(g_pSourcePawn)) != 0)
168 if (error && err_max)
170 snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
175 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
176 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
180 if (error && err_max)
182 snprintf(error, err_max, "JIT is missing a necessary export!");
187 unsigned int num = jit_getnum();
188 if (!num || ((g_pVM=jit_get(0)) == NULL))
191 if (error && err_max)
193 snprintf(error, err_max, "JIT did not export any virtual machines!");
198 unsigned int api = g_pVM->GetAPIVersion();
199 if (api != SOURCEPAWN_VM_API_VERSION)
202 if (error && err_max)
204 snprintf(error, err_max, "JIT is not a compatible version");
209 /* Hook this now so we can detect startup without calling StartSourceMod() */
210 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
212 /* Only load if we're not late */
215 StartSourceMod(false);
221 void SourceModBase::StartSourceMod(bool late)
223 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
224 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
226 enginePatch = SH_GET_CALLCLASS(engine);
227 gamedllPatch = SH_GET_CALLCLASS(gamedll);
230 SMGlobalClass *pBase = SMGlobalClass::head;
233 pBase->OnSourceModStartup(false);
234 pBase = pBase->m_pGlobalClassNext;
237 /* Make the global core identity */
238 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
241 pBase = SMGlobalClass::head;
244 pBase->OnSourceModAllInitialized();
245 pBase = pBase->m_pGlobalClassNext;
249 g_ShareSys.AddInterface(NULL, this);
255 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
257 /* If we're not loaded... */
260 /* Do all global initialization now */
261 StartSourceMod(true);
264 m_IsMapLoading = true;
265 m_ExecPluginReload = true;
267 g_LastAuthCheck = 0.0f;
268 g_SimTicks.ticking = true;
269 g_SimTicks.tickcount = 0;
274 SMGlobalClass *pBase = SMGlobalClass::head;
277 pBase->OnSourceModLevelChange(pMapName);
278 pBase = pBase->m_pGlobalClassNext;
281 DoGlobalPluginLoads();
283 m_IsMapLoading = false;
286 pBase = SMGlobalClass::head;
289 pBase->OnSourceModPluginsLoaded();
290 pBase = pBase->m_pGlobalClassNext;
295 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
300 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
303 RETURN_META_VALUE(MRES_IGNORED, true);
306 void StartTickSimulation()
308 g_SimTicks.ticking = false;
309 g_SimTicks.tickcount = 0;
310 g_SimTicks.ticktime = gpGlobals->curtime;
313 void StopTickSimulation()
315 g_SimTicks.ticking = true;
316 g_Timers.MapChange();
318 g_LastTime = gpGlobals->curtime;
323 g_SimTicks.tickcount++;
324 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
327 void SourceModBase::GameFrame(bool simulating)
330 * Note: This is all hardcoded rather than delegated to save
331 * precious CPU cycles.
333 float curtime = gpGlobals->curtime;
334 int framecount = gpGlobals->framecount;
336 /* Verify that we're still ticking */
337 if (g_SimTicks.ticking)
339 if (g_StillFrames == 0)
341 g_StillFrames = framecount;
342 g_StillTime = curtime;
344 /* Try to detect when we've stopped ticking.
345 * We do this once 10 frames pass and there have been no ticks.
347 if (g_StillTime == curtime)
349 if (framecount - g_StillFrames >= 5)
351 StartTickSimulation();
355 /* We're definitely ticking we get here,
356 * but update everything as a precaution */
357 g_StillFrames = framecount;
358 g_StillTime = curtime;
362 /* We need to make sure we should still be simulating. */
363 if (g_StillTime != curtime)
365 /* Wow, we're ticking again! It's time to revert. */
366 StopTickSimulation();
369 /* Nope, not ticking. Simulate! */
371 curtime = g_SimTicks.ticktime;
374 if (curtime - g_LastTime >= 0.1f)
377 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
379 g_LastAuthCheck = gpGlobals->curtime;
380 g_Players.RunAuthChecks();
384 g_LastTime = curtime;
387 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
389 g_pOnGameFrame->Execute(NULL);
393 void SourceModBase::LevelShutdown()
397 g_pOnMapEnd->Execute(NULL);
400 if (m_ExecPluginReload)
402 g_PluginSys.ReloadOrUnloadPlugins();
403 m_ExecPluginReload = false;
407 bool SourceModBase::IsMapLoading() const
409 return m_IsMapLoading;
412 void SourceModBase::DoGlobalPluginLoads()
414 char config_path[PLATFORM_MAX_PATH];
415 char plugins_path[PLATFORM_MAX_PATH];
417 BuildPath(Path_SM, config_path,
419 "configs/plugin_settings.cfg");
420 BuildPath(Path_SM, plugins_path,
421 sizeof(plugins_path),
424 /* Load any auto extensions */
425 g_Extensions.TryAutoload();
427 /* Run the first pass */
428 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
430 /* Mark any extensions as loaded */
431 g_Extensions.MarkAllLoaded();
433 /* No modules yet, it's safe to call this from here */
434 g_PluginSys.LoadAll_SecondPass();
436 /* Re-mark any extensions as loaded */
437 g_Extensions.MarkAllLoaded();
440 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
442 char _buffer[PLATFORM_MAX_PATH];
445 va_start(ap, format);
446 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
449 const char *base = NULL;
450 if (type == Path_Game)
452 base = GetGamePath();
453 } else if (type == Path_SM) {
454 base = GetSourceModPath();
455 } else if (type == Path_SM_Rel) {
461 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
463 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
467 void SourceModBase::CloseSourceMod()
469 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
475 g_Forwards.ReleaseForward(g_pOnGameFrame);
480 g_Forwards.ReleaseForward(g_pOnMapEnd);
484 SMGlobalClass *pBase = SMGlobalClass::head;
487 pBase->OnSourceModShutdown();
488 pBase = pBase->m_pGlobalClassNext;
491 /* Delete all data packs */
492 CStack<CDataPack *>::iterator iter;
494 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
499 m_freepacks.popall();
502 pBase = SMGlobalClass::head;
505 pBase->OnSourceModAllShutdown();
506 pBase = pBase->m_pGlobalClassNext;
511 SH_RELEASE_CALLCLASS(enginePatch);
517 SH_RELEASE_CALLCLASS(gamedllPatch);
521 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
522 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
529 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
531 IExtensionInterface *pAPI = pExt->GetAPI();
532 const char *tag = pAPI->GetExtensionTag();
536 va_start(ap, format);
537 vsnprintf(buffer, sizeof(buffer), format, ap);
542 g_Logger.LogMessage("[%s] %s", tag, buffer);
544 g_Logger.LogMessage("%s", buffer);
548 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
550 IExtensionInterface *pAPI = pExt->GetAPI();
551 const char *tag = pAPI->GetExtensionTag();
555 va_start(ap, format);
556 vsnprintf(buffer, sizeof(buffer), format, ap);
561 g_Logger.LogError("[%s] %s", tag, buffer);
563 g_Logger.LogError("%s", buffer);
567 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
571 pContext->LocalToString(params[param], &fmt);
573 int lparam = ++param;
575 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
578 const char *SourceModBase::GetSourceModPath() const
583 const char *SourceModBase::GetGamePath() const
585 return g_BaseDir.c_str();
588 void SourceModBase::SetGlobalTarget(unsigned int index)
593 void SourceModBase::SetAuthChecking(bool set)
595 m_CheckingAuth = set;
598 unsigned int SourceModBase::GetGlobalTarget() const
603 IDataPack *SourceModBase::CreateDataPack()
606 if (m_freepacks.empty())
608 pack = new CDataPack;
610 pack = m_freepacks.front();
617 void SourceModBase::FreeDataPack(IDataPack *pack)
619 m_freepacks.push(static_cast<CDataPack *>(pack));
622 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
628 const char *SourceModBase::GetGameFolderName() const
633 SMGlobalClass *SMGlobalClass::head = NULL;
635 SMGlobalClass::SMGlobalClass()
637 m_pGlobalClassNext = SMGlobalClass::head;
638 SMGlobalClass::head = this;