3 * =============================================================================
5 * Copyright (C) 2004-2007 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 "systems/LibrarySys.h"
36 #include "vm/sp_vm_engine.h"
37 #include <sh_string.h>
38 #include "PluginSys.h"
40 #include "CoreConfig.h"
42 #include "ExtensionSys.h"
43 #include "AdminCache.h"
44 #include "sm_stringutil.h"
45 #include "PlayerManager.h"
46 #include "Translator.h"
47 #include "ForwardSys.h"
49 #include "MenuStyle_Valve.h"
50 #include "MenuStyle_Radio.h"
52 #include "HalfLife2.h"
54 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
55 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
56 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
57 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
59 SourcePawnEngine g_SourcePawn;
60 SourceModBase g_SourceMod;
62 ILibrary *g_pJIT = NULL;
63 SourceHook::String g_BaseDir;
64 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
65 IVirtualMachine *g_pVM;
66 IdentityToken_t *g_pCoreIdent = NULL;
67 float g_LastTime = 0.0f;
68 float g_LastMenuTime = 0.0f;
69 float g_LastAuthCheck = 0.0f;
70 IForward *g_pOnGameFrame = NULL;
71 IForward *g_pOnMapEnd = NULL;
72 bool g_Loaded = false;
73 int g_StillFrames = 0;
74 float g_StillTime = 0.0f;
76 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
77 typedef int (*GIVEENGINEPOINTER2)(ISourcePawnEngine *, unsigned int api_version);
78 typedef unsigned int (*GETEXPORTCOUNT)();
79 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
80 typedef void (*NOTIFYSHUTDOWN)();
84 NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
90 g_pJIT->CloseLibrary();
93 SourceModBase::SourceModBase()
95 m_IsMapLoading = false;
96 m_ExecPluginReload = false;
97 m_ExecOnMapEnd = false;
98 m_GotBasePath = false;
101 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key,
107 if (strcasecmp(key, "BasePath") == 0)
109 if (source == ConfigSource_Console)
111 UTIL_Format(error, maxlength, "Cannot be set at runtime");
112 return ConfigResult_Reject;
117 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
118 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
120 m_GotBasePath = true;
123 return ConfigResult_Accept;
126 return ConfigResult_Ignore;
129 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
131 const char *gamepath = g_SMAPI->GetBaseDir();
133 /* Store full path to game */
134 g_BaseDir.assign(gamepath);
136 /* Store name of game directory by itself */
137 size_t len = strlen(gamepath);
138 for (size_t i = len - 1; i >= 0; i--)
140 if (gamepath[i] == PLATFORM_SEP_CHAR)
142 strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
147 /* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
148 g_CoreConfig.Initialize();
150 /* This shouldn't happen, but can't hurt to be safe */
151 if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
153 g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
154 g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
155 m_GotBasePath = true;
158 /* Attempt to load the JIT! */
159 char file[PLATFORM_MAX_PATH];
161 g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
166 g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
169 if (error && maxlength)
171 snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)",
180 GIVEENGINEPOINTER2 jit_init2 = (GIVEENGINEPOINTER2)g_pJIT->GetSymbolAddress("GiveEnginePointer2");
183 GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
187 if (error && maxlength)
189 snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
194 if ((err=jit_init(g_pSourcePawn)) != 0)
197 if (error && maxlength)
199 snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
204 /* On version bumps, we should check for older versions as well, if the new version fails.
205 * We can then check the exports to see if any VM versions will be sufficient.
207 if ((err=jit_init2(g_pSourcePawn, SOURCEPAWN_ENGINE_API_VERSION)) != SP_ERROR_NONE)
210 if (error && maxlength)
212 snprintf(error, maxlength, "JIT incompatible with SourceMod version");
218 GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
219 GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
223 if (error && maxlength)
225 snprintf(error, maxlength, "JIT is missing a necessary export!");
230 unsigned int num = jit_getnum();
234 if (error && maxlength)
236 snprintf(error, maxlength, "JIT did not export any virtual machines!");
241 unsigned int api_version;
242 for (unsigned int i=0; i<num; i++)
244 if ((g_pVM=jit_get(i)) == NULL)
246 if (error && maxlength)
248 snprintf(error, maxlength, "JIT did not export any virtual machines!");
252 /* Refuse any API that we might not be able to deal with.
253 * Also refuse anything < 3 because we need fake natives.
255 api_version = g_pVM->GetAPIVersion();
256 if (api_version < 3 || api_version > SOURCEPAWN_VM_API_VERSION)
258 if (error && maxlength)
260 snprintf(error, maxlength, "JIT is not a compatible version");
274 /* Hook this now so we can detect startup without calling StartSourceMod() */
275 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
277 /* Only load if we're not late */
280 StartSourceMod(false);
286 void SourceModBase::StartSourceMod(bool late)
288 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
289 SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
291 enginePatch = SH_GET_CALLCLASS(engine);
292 gamedllPatch = SH_GET_CALLCLASS(gamedll);
295 SMGlobalClass *pBase = SMGlobalClass::head;
298 pBase->OnSourceModStartup(false);
299 pBase = pBase->m_pGlobalClassNext;
302 /* Make the global core identity */
303 g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
306 pBase = SMGlobalClass::head;
309 pBase->OnSourceModAllInitialized();
310 pBase = pBase->m_pGlobalClassNext;
314 g_ShareSys.AddInterface(NULL, this);
320 static bool g_LevelEndBarrier = false;
321 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
323 /* If we're not loaded... */
326 /* Do all global initialization now */
327 StartSourceMod(true);
330 m_IsMapLoading = true;
331 m_ExecPluginReload = true;
332 m_ExecOnMapEnd = true;
334 g_LastMenuTime = 0.0f;
335 g_LastAuthCheck = 0.0f;
336 g_SimTicks.ticking = true;
337 g_SimTicks.tickcount = 0;
342 SMGlobalClass *pBase = SMGlobalClass::head;
345 pBase->OnSourceModLevelChange(pMapName);
346 pBase = pBase->m_pGlobalClassNext;
349 DoGlobalPluginLoads();
351 m_IsMapLoading = false;
354 pBase = SMGlobalClass::head;
357 pBase->OnSourceModPluginsLoaded();
358 pBase = pBase->m_pGlobalClassNext;
363 g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
368 g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
371 g_LevelEndBarrier = true;
373 RETURN_META_VALUE(MRES_IGNORED, true);
376 void StartTickSimulation()
378 g_SimTicks.ticking = false;
379 g_SimTicks.tickcount = 0;
380 g_SimTicks.ticktime = gpGlobals->curtime;
383 void StopTickSimulation()
385 g_SimTicks.ticking = true;
386 g_Timers.MapChange(false);
388 g_LastTime = gpGlobals->curtime;
393 g_SimTicks.tickcount++;
394 g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
397 void SourceModBase::GameFrame(bool simulating)
400 g_HL2.ProcessFakeCliCmdQueue();
403 * Note: This is all hardcoded rather than delegated to save
404 * precious CPU cycles.
406 float curtime = gpGlobals->curtime;
407 int framecount = gpGlobals->framecount;
409 /* Verify that we're still ticking */
410 if (g_SimTicks.ticking)
412 if (g_StillFrames == 0)
414 g_StillFrames = framecount;
415 g_StillTime = curtime;
417 /* Try to detect when we've stopped ticking.
418 * We do this once 10 frames pass and there have been no ticks.
420 if (g_StillTime == curtime)
422 if (framecount - g_StillFrames >= 5)
424 StartTickSimulation();
428 /* We're definitely ticking we get here,
429 * but update everything as a precaution */
430 g_StillFrames = framecount;
431 g_StillTime = curtime;
435 /* We need to make sure we should still be simulating. */
436 if (g_StillTime != curtime)
438 /* Wow, we're ticking again! It's time to revert. */
439 StopTickSimulation();
442 /* Nope, not ticking. Simulate! */
444 curtime = g_SimTicks.ticktime;
447 if (curtime - g_LastTime >= 0.1f)
450 && (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
452 g_LastAuthCheck = gpGlobals->curtime;
453 g_Players.RunAuthChecks();
457 g_LastTime = curtime;
460 if (g_SimTicks.ticking && curtime - g_LastMenuTime >= 1.0f)
462 g_ValveMenuStyle.ProcessWatchList();
463 g_RadioMenuStyle.ProcessWatchList();
464 g_LastMenuTime = curtime;
467 if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
469 g_pOnGameFrame->Execute(NULL);
473 void SourceModBase::LevelShutdown()
475 if (g_LevelEndBarrier)
477 SMGlobalClass *next = SMGlobalClass::head;
480 next->OnSourceModLevelEnd();
481 next = next->m_pGlobalClassNext;
483 g_LevelEndBarrier = false;
486 if (g_pOnMapEnd && m_ExecOnMapEnd)
488 g_pOnMapEnd->Execute(NULL);
489 m_ExecOnMapEnd = false;
492 g_OnMapStarted = false;
494 if (m_ExecPluginReload)
496 g_PluginSys.ReloadOrUnloadPlugins();
497 m_ExecPluginReload = false;
501 bool SourceModBase::IsMapLoading() const
503 return m_IsMapLoading;
506 void SourceModBase::DoGlobalPluginLoads()
508 char config_path[PLATFORM_MAX_PATH];
509 char plugins_path[PLATFORM_MAX_PATH];
511 BuildPath(Path_SM, config_path,
513 "configs/plugin_settings.cfg");
514 BuildPath(Path_SM, plugins_path,
515 sizeof(plugins_path),
518 /* Load any auto extensions */
519 g_Extensions.TryAutoload();
521 /* Run the first pass */
522 g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
524 /* Mark any extensions as loaded */
525 g_Extensions.MarkAllLoaded();
527 /* No modules yet, it's safe to call this from here */
528 g_PluginSys.LoadAll_SecondPass();
530 /* Re-mark any extensions as loaded */
531 g_Extensions.MarkAllLoaded();
533 /* Call OnAllPluginsLoaded */
534 g_PluginSys.AllPluginsLoaded();
537 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
539 char _buffer[PLATFORM_MAX_PATH];
542 va_start(ap, format);
543 vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
546 const char *base = NULL;
547 if (type == Path_Game)
549 base = GetGamePath();
550 } else if (type == Path_SM) {
551 base = GetSourceModPath();
552 } else if (type == Path_SM_Rel) {
558 return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
560 return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
564 void SourceModBase::CloseSourceMod()
566 /* Force a level end */
570 g_PluginSys.Shutdown();
572 /* Unload extensions */
573 g_Extensions.Shutdown();
575 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
581 g_Forwards.ReleaseForward(g_pOnGameFrame);
586 g_Forwards.ReleaseForward(g_pOnMapEnd);
590 SMGlobalClass *pBase = SMGlobalClass::head;
593 pBase->OnSourceModShutdown();
594 pBase = pBase->m_pGlobalClassNext;
597 /* Delete all data packs */
598 CStack<CDataPack *>::iterator iter;
600 for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
605 m_freepacks.popall();
608 pBase = SMGlobalClass::head;
611 pBase->OnSourceModAllShutdown();
612 pBase = pBase->m_pGlobalClassNext;
617 SH_RELEASE_CALLCLASS(enginePatch);
623 SH_RELEASE_CALLCLASS(gamedllPatch);
627 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
628 SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
635 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
637 IExtensionInterface *pAPI = pExt->GetAPI();
638 const char *tag = pAPI->GetExtensionTag();
642 va_start(ap, format);
643 vsnprintf(buffer, sizeof(buffer), format, ap);
648 g_Logger.LogMessage("[%s] %s", tag, buffer);
650 g_Logger.LogMessage("%s", buffer);
654 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
656 IExtensionInterface *pAPI = pExt->GetAPI();
657 const char *tag = pAPI->GetExtensionTag();
661 va_start(ap, format);
662 vsnprintf(buffer, sizeof(buffer), format, ap);
667 g_Logger.LogError("[%s] %s", tag, buffer);
669 g_Logger.LogError("%s", buffer);
673 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
677 pContext->LocalToString(params[param], &fmt);
679 int lparam = ++param;
681 return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
684 const char *SourceModBase::GetSourceModPath() const
689 const char *SourceModBase::GetGamePath() const
691 return g_BaseDir.c_str();
694 void SourceModBase::SetGlobalTarget(unsigned int index)
699 void SourceModBase::SetAuthChecking(bool set)
701 m_CheckingAuth = set;
704 unsigned int SourceModBase::GetGlobalTarget() const
709 IDataPack *SourceModBase::CreateDataPack()
712 if (m_freepacks.empty())
714 pack = new CDataPack;
716 pack = m_freepacks.front();
723 void SourceModBase::FreeDataPack(IDataPack *pack)
725 m_freepacks.push(static_cast<CDataPack *>(pack));
728 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
734 const char *SourceModBase::GetGameFolderName() const
739 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
741 return g_pSourcePawn;
744 IVirtualMachine *SourceModBase::GetScriptingVM()
749 void SourceModBase::AllPluginsLoaded()
751 SMGlobalClass *base = SMGlobalClass::head;
754 base->OnSourceModGameInitialized();
755 base = base->m_pGlobalClassNext;
759 SMGlobalClass *SMGlobalClass::head = NULL;
761 SMGlobalClass::SMGlobalClass()
763 m_pGlobalClassNext = SMGlobalClass::head;
764 SMGlobalClass::head = this;