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"
32 #include "MenuStyle_Valve.h"
33 #include "MenuStyle_Radio.h"
35 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
36 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
37 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
39 SourcePawnEngine g_SourcePawn;
40 SourceModBase g_SourceMod;
42 ILibrary *g_pJIT = NULL;
43 SourceHook::String g_BaseDir;
44 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
45 IVirtualMachine *g_pVM;
46 IdentityToken_t *g_pCoreIdent = NULL;
47 float g_LastTime = 0.0f;
48 float g_LastMenuTime = 0.0f;
49 float g_LastAuthCheck = 0.0f;
50 IForward *g_pOnGameFrame = NULL;
51 IForward *g_pOnMapEnd = NULL;
52 bool g_Loaded = false;
53 int g_StillFrames = 0;
54 float g_StillTime = 0.0f;
56 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
57 typedef unsigned int (*GETEXPORTCOUNT)();
58 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
59 typedef void (*NOTIFYSHUTDOWN)();
63 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
69 g_pJIT->CloseLibrary();
72 SourceModBase::SourceModBase()
74 m_IsMapLoading = false;
75 m_ExecPluginReload = false;
76 m_ExecOnMapEnd = false;
77 m_GotBasePath = false;
80 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
86 if (strcasecmp(key, "BasePath") == 0)
88 if (source == ConfigSource_Console)
90 UTIL_Format(error, maxlength, "Cannot be set at runtime");
91 return ConfigResult_Reject;
96 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
97 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
102 return ConfigResult_Accept;
105 return ConfigResult_Ignore;
108 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
110 const char *gamepath = g_SMAPI->GetBaseDir();
112 /* Store full path to game */
113 g_BaseDir.assign(gamepath);
115 /* Store name of game directory by itself */
116 size_t len = strlen(gamepath);
117 for (size_t i = len - 1; i >= 0; i--)
119 if (gamepath[i] == PLATFORM_SEP_CHAR)
121 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
126 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
127 g_CoreConfig.Initialize();
129 /* This shouldn't happen, but can't hurt to be safe */
130 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
132 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
133 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
134 m_GotBasePath = true;
137 /* Attempt to load the JIT! */
138 char file[PLATFORM_MAX_PATH];
140 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
145 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
148 if (error && maxlength)
150 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
158 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
162 if (error && maxlength)
164 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
169 if ((err=jit_init(g_pSourcePawn)) != 0)
172 if (error && maxlength)
174 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
179 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
180 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
184 if (error && maxlength)
186 snprintf(error, maxlength, "JIT is missing a necessary export!");
191 unsigned int num = jit_getnum();
192 if (!num || ((g_pVM=jit_get(0)) == NULL))
195 if (error && maxlength)
197 snprintf(error, maxlength, "JIT did not export any virtual machines!");
202 unsigned int api = g_pVM->GetAPIVersion();
203 if (api != SOURCEPAWN_VM_API_VERSION)
206 if (error && maxlength)
208 snprintf(error, maxlength, "JIT is not a compatible version");
213 /* Hook this now so we can detect startup without calling StartSourceMod() */
214 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
216 /* Only load if we're not late */
219 StartSourceMod(false);
225 void SourceModBase::StartSourceMod(bool late)
227 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
228 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
230 enginePatch = SH_GET_CALLCLASS(engine);
231 gamedllPatch = SH_GET_CALLCLASS(gamedll);
234 SMGlobalClass *pBase = SMGlobalClass::head;
237 pBase->OnSourceModStartup(false);
238 pBase = pBase->m_pGlobalClassNext;
241 /* Make the global core identity */
242 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
245 pBase = SMGlobalClass::head;
248 pBase->OnSourceModAllInitialized();
249 pBase = pBase->m_pGlobalClassNext;
253 g_ShareSys.AddInterface(NULL, this);
259 static bool g_LevelEndBarrier = false;
260 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
262 /* If we're not loaded... */
265 /* Do all global initialization now */
266 StartSourceMod(true);
269 m_IsMapLoading = true;
270 m_ExecPluginReload = true;
271 m_ExecOnMapEnd = true;
273 g_LastMenuTime = 0.0f;
274 g_LastAuthCheck = 0.0f;
275 g_SimTicks.ticking = true;
276 g_SimTicks.tickcount = 0;
281 SMGlobalClass *pBase = SMGlobalClass::head;
284 pBase->OnSourceModLevelChange(pMapName);
285 pBase = pBase->m_pGlobalClassNext;
288 DoGlobalPluginLoads();
290 m_IsMapLoading = false;
293 pBase = SMGlobalClass::head;
296 pBase->OnSourceModPluginsLoaded();
297 pBase = pBase->m_pGlobalClassNext;
302 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
307 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
310 g_LevelEndBarrier = true;
312 RETURN_META_VALUE(MRES_IGNORED, true);
315 void StartTickSimulation()
317 g_SimTicks.ticking = false;
318 g_SimTicks.tickcount = 0;
319 g_SimTicks.ticktime = gpGlobals->curtime;
322 void StopTickSimulation()
324 g_SimTicks.ticking = true;
325 g_Timers.MapChange();
327 g_LastTime = gpGlobals->curtime;
332 g_SimTicks.tickcount++;
333 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
336 void SourceModBase::GameFrame(bool simulating)
339 * Note: This is all hardcoded rather than delegated to save
340 * precious CPU cycles.
342 float curtime = gpGlobals->curtime;
343 int framecount = gpGlobals->framecount;
345 /* Verify that we're still ticking */
346 if (g_SimTicks.ticking)
348 if (g_StillFrames == 0)
350 g_StillFrames = framecount;
351 g_StillTime = curtime;
353 /* Try to detect when we've stopped ticking.
354 * We do this once 10 frames pass and there have been no ticks.
356 if (g_StillTime == curtime)
358 if (framecount - g_StillFrames >= 5)
360 StartTickSimulation();
364 /* We're definitely ticking we get here,
365 * but update everything as a precaution */
366 g_StillFrames = framecount;
367 g_StillTime = curtime;
371 /* We need to make sure we should still be simulating. */
372 if (g_StillTime != curtime)
374 /* Wow, we're ticking again! It's time to revert. */
375 StopTickSimulation();
378 /* Nope, not ticking. Simulate! */
380 curtime = g_SimTicks.ticktime;
383 if (curtime - g_LastTime >= 0.1f)
386 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
388 g_LastAuthCheck = gpGlobals->curtime;
389 g_Players.RunAuthChecks();
393 g_LastTime = curtime;
396 if (g_SimTicks.tickcount && (curtime - g_LastMenuTime >= 1.0f))
398 g_ValveMenuStyle.ProcessWatchList();
399 g_RadioMenuStyle.ProcessWatchList();
400 g_LastMenuTime = curtime;
403 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
405 g_pOnGameFrame->Execute(NULL);
409 void SourceModBase::LevelShutdown()
411 if (g_LevelEndBarrier)
413 SMGlobalClass *next = SMGlobalClass::head;
416 next->OnSourceModLevelEnd();
417 next = next->m_pGlobalClassNext;
419 g_LevelEndBarrier = false;
422 if (g_pOnMapEnd && m_ExecOnMapEnd)
424 g_pOnMapEnd->Execute(NULL);
425 m_ExecOnMapEnd = false;
428 g_OnMapStarted = false;
430 if (m_ExecPluginReload)
432 g_PluginSys.ReloadOrUnloadPlugins();
433 m_ExecPluginReload = false;
437 bool SourceModBase::IsMapLoading() const
439 return m_IsMapLoading;
442 void SourceModBase::DoGlobalPluginLoads()
444 char config_path[PLATFORM_MAX_PATH];
445 char plugins_path[PLATFORM_MAX_PATH];
447 BuildPath(Path_SM, config_path,
449 "configs/plugin_settings.cfg");
450 BuildPath(Path_SM, plugins_path,
451 sizeof(plugins_path),
454 /* Load any auto extensions */
455 g_Extensions.TryAutoload();
457 /* Run the first pass */
458 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
460 /* Mark any extensions as loaded */
461 g_Extensions.MarkAllLoaded();
463 /* No modules yet, it's safe to call this from here */
464 g_PluginSys.LoadAll_SecondPass();
466 /* Re-mark any extensions as loaded */
467 g_Extensions.MarkAllLoaded();
470 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
472 char _buffer[PLATFORM_MAX_PATH];
475 va_start(ap, format);
476 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
479 const char *base = NULL;
480 if (type == Path_Game)
482 base = GetGamePath();
483 } else if (type == Path_SM) {
484 base = GetSourceModPath();
485 } else if (type == Path_SM_Rel) {
491 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
493 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
497 void SourceModBase::CloseSourceMod()
499 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
505 g_Forwards.ReleaseForward(g_pOnGameFrame);
510 g_Forwards.ReleaseForward(g_pOnMapEnd);
514 SMGlobalClass *pBase = SMGlobalClass::head;
517 pBase->OnSourceModShutdown();
518 pBase = pBase->m_pGlobalClassNext;
521 /* Delete all data packs */
522 CStack<CDataPack *>::iterator iter;
524 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
529 m_freepacks.popall();
532 pBase = SMGlobalClass::head;
535 pBase->OnSourceModAllShutdown();
536 pBase = pBase->m_pGlobalClassNext;
541 SH_RELEASE_CALLCLASS(enginePatch);
547 SH_RELEASE_CALLCLASS(gamedllPatch);
551 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
552 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
559 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
561 IExtensionInterface *pAPI = pExt->GetAPI();
562 const char *tag = pAPI->GetExtensionTag();
566 va_start(ap, format);
567 vsnprintf(buffer, sizeof(buffer), format, ap);
572 g_Logger.LogMessage("[%s] %s", tag, buffer);
574 g_Logger.LogMessage("%s", buffer);
578 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
580 IExtensionInterface *pAPI = pExt->GetAPI();
581 const char *tag = pAPI->GetExtensionTag();
585 va_start(ap, format);
586 vsnprintf(buffer, sizeof(buffer), format, ap);
591 g_Logger.LogError("[%s] %s", tag, buffer);
593 g_Logger.LogError("%s", buffer);
597 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
601 pContext->LocalToString(params[param], &fmt);
603 int lparam = ++param;
605 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
608 const char *SourceModBase::GetSourceModPath() const
613 const char *SourceModBase::GetGamePath() const
615 return g_BaseDir.c_str();
618 void SourceModBase::SetGlobalTarget(unsigned int index)
623 void SourceModBase::SetAuthChecking(bool set)
625 m_CheckingAuth = set;
628 unsigned int SourceModBase::GetGlobalTarget() const
633 IDataPack *SourceModBase::CreateDataPack()
636 if (m_freepacks.empty())
638 pack = new CDataPack;
640 pack = m_freepacks.front();
647 void SourceModBase::FreeDataPack(IDataPack *pack)
649 m_freepacks.push(static_cast<CDataPack *>(pack));
652 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
658 const char *SourceModBase::GetGameFolderName() const
663 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
665 return g_pSourcePawn;
668 IVirtualMachine *SourceModBase::GetScriptingVM()
673 void SourceModBase::AllPluginsLoaded()
675 SMGlobalClass *base = SMGlobalClass::head;
678 base->OnSourceModGameInitialized();
679 base = base->m_pGlobalClassNext;
683 SMGlobalClass *SMGlobalClass::head = NULL;
685 SMGlobalClass::SMGlobalClass()
687 m_pGlobalClassNext = SMGlobalClass::head;
688 SMGlobalClass::head = this;