core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Wed May 02 17:49:23 2007 +0000 (2007-05-02)
changeset 718 8a5d1da7dd18
parent 696 d5cc8d0fa899
child 727 fade10824d88
permissions -rw-r--r--
added request amb234 (OnMapEnd)
     1 /**
     2  * vim: set ts=4 :
     3  * ===============================================================
     4  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     5  * ===============================================================
     6  *
     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
    11  *
    12  * Version: $Id$
    13  */
    14 
    15 #include <stdio.h>
    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"
    22 #include "ShareSys.h"
    23 #include "CoreConfig.h"
    24 #include "Logger.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"
    31 #include "TimerSys.h"
    32 
    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);
    36 
    37 SourcePawnEngine g_SourcePawn;
    38 SourceModBase g_SourceMod;
    39 
    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 
    51 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
    52 typedef unsigned int (*GETEXPORTCOUNT)();
    53 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
    54 typedef void (*NOTIFYSHUTDOWN)();
    55 
    56 void ShutdownJIT()
    57 {
    58 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    59 	if (notify)
    60 	{
    61 		notify();
    62 	}
    63 
    64 	g_pJIT->CloseLibrary();
    65 }
    66 
    67 SourceModBase::SourceModBase()
    68 {
    69 	m_IsMapLoading = false;
    70 	m_ExecPluginReload = false;
    71 	m_GotBasePath = false;
    72 }
    73 
    74 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key, 
    75 									  const char *value, 
    76 									  ConfigSource source, 
    77 									  char *error, 
    78 									  size_t maxlength)
    79 {
    80 	if (strcasecmp(key, "BasePath") == 0)
    81 	{
    82 		if (source == ConfigSource_Console)
    83 		{
    84 			UTIL_Format(error, maxlength, "Cannot be set at runtime");
    85 			return ConfigResult_Reject;
    86 		}
    87 
    88 		if (!m_GotBasePath)
    89 		{
    90 			g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
    91 			g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
    92 
    93 			m_GotBasePath = true;
    94 		}
    95 
    96 		return ConfigResult_Accept;
    97 	}
    98 
    99 	return ConfigResult_Ignore;
   100 }
   101 
   102 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
   103 {
   104 	const char *gamepath = g_SMAPI->GetBaseDir();
   105 
   106 	/* Store full path to game */
   107 	g_BaseDir.assign(gamepath);
   108 
   109 	/* Store name of game directory by itself */
   110 	size_t len = strlen(gamepath);
   111 	for (size_t i = len - 1; i >= 0; i--)
   112 	{
   113 		if (gamepath[i] == PLATFORM_SEP_CHAR)
   114 		{
   115 			strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
   116 			break;
   117 		}
   118 	}
   119 
   120 	/* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
   121 	g_CoreConfig.Initialize();
   122 
   123 	/* This shouldn't happen, but can't hurt to be safe */
   124 	if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
   125 	{
   126 		g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
   127 		g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
   128 		m_GotBasePath = true;
   129 	}
   130 
   131 	/* Attempt to load the JIT! */
   132 	char file[PLATFORM_MAX_PATH];
   133 	char myerror[255];
   134 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
   135 		GetSourceModPath(),
   136 		PLATFORM_LIB_EXT
   137 		);
   138 
   139 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
   140 	if (!g_pJIT)
   141 	{
   142 		if (error && err_max)
   143 		{
   144 			snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
   145 				myerror,
   146 				PLATFORM_LIB_EXT);
   147 		}
   148 		return false;
   149 	}
   150 
   151 	int err;
   152 	GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
   153 	if (!jit_init)
   154 	{
   155 		ShutdownJIT();
   156 		if (error && err_max)
   157 		{
   158 			snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
   159 		}
   160 		return false;
   161 	}
   162 
   163 	if ((err=jit_init(g_pSourcePawn)) != 0)
   164 	{
   165 		ShutdownJIT();
   166 		if (error && err_max)
   167 		{
   168 			snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
   169 		}
   170 		return false;
   171 	}
   172 
   173 	GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
   174 	GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
   175 	if (!jit_get)
   176 	{
   177 		ShutdownJIT();
   178 		if (error && err_max)
   179 		{
   180 			snprintf(error, err_max, "JIT is missing a necessary export!");
   181 		}
   182 		return false;
   183 	}
   184 
   185 	unsigned int num = jit_getnum();
   186 	if (!num || ((g_pVM=jit_get(0)) == NULL))
   187 	{
   188 		ShutdownJIT();
   189 		if (error && err_max)
   190 		{
   191 			snprintf(error, err_max, "JIT did not export any virtual machines!");
   192 		}
   193 		return false;
   194 	}
   195 
   196 	unsigned int api = g_pVM->GetAPIVersion();
   197 	if (api != SOURCEPAWN_VM_API_VERSION)
   198 	{
   199 		ShutdownJIT();
   200 		if (error && err_max)
   201 		{
   202 			snprintf(error, err_max, "JIT is not a compatible version");
   203 		}
   204 		return false;
   205 	}
   206 
   207 	/* Hook this now so we can detect startup without calling StartSourceMod() */
   208 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   209 
   210 	/* Only load if we're not late */
   211 	if (!late)
   212 	{
   213 		StartSourceMod(false);
   214 	}
   215 
   216 	return true;
   217 }
   218 
   219 void SourceModBase::StartSourceMod(bool late)
   220 {
   221 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   222 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   223 
   224 	enginePatch = SH_GET_CALLCLASS(engine);
   225 	gamedllPatch = SH_GET_CALLCLASS(gamedll);
   226 
   227 	/* Notify! */
   228 	SMGlobalClass *pBase = SMGlobalClass::head;
   229 	while (pBase)
   230 	{
   231 		pBase->OnSourceModStartup(false);
   232 		pBase = pBase->m_pGlobalClassNext;
   233 	}
   234 
   235 	/* Make the global core identity */
   236 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   237 
   238 	/* Notify! */
   239 	pBase = SMGlobalClass::head;
   240 	while (pBase)
   241 	{
   242 		pBase->OnSourceModAllInitialized();
   243 		pBase = pBase->m_pGlobalClassNext;
   244 	}
   245 
   246 	/* Add us now... */
   247 	g_ShareSys.AddInterface(NULL, this);
   248 
   249 	/* We're loaded! */
   250 	g_Loaded = true;
   251 }
   252 
   253 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   254 {
   255 	/* If we're not loaded... */
   256 	if (!g_Loaded)
   257 	{
   258 		/* Do all global initialization now */
   259 		StartSourceMod(true);
   260 	}
   261 
   262 	m_IsMapLoading = true;
   263 	m_ExecPluginReload = true;
   264 	g_LastTime = 0.0f;
   265 	g_LastAuthCheck = 0.0f;
   266 
   267 	/* Notify! */
   268 	SMGlobalClass *pBase = SMGlobalClass::head;
   269 	while (pBase)
   270 	{
   271 		pBase->OnSourceModLevelChange(pMapName);
   272 		pBase = pBase->m_pGlobalClassNext;
   273 	}
   274 
   275 	DoGlobalPluginLoads();
   276 
   277 	m_IsMapLoading = false;
   278 
   279 	/* Notify! */
   280 	pBase = SMGlobalClass::head;
   281 	while (pBase)
   282 	{
   283 		pBase->OnSourceModPluginsLoaded();
   284 		pBase = pBase->m_pGlobalClassNext;
   285 	}
   286 
   287 	if (!g_pOnGameFrame)
   288 	{
   289 		g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
   290 	}
   291 
   292 	if (!g_pOnMapEnd)
   293 	{
   294 		g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
   295 	}
   296 
   297 	RETURN_META_VALUE(MRES_IGNORED, true);
   298 }
   299 
   300 void SourceModBase::GameFrame(bool simulating)
   301 {
   302 	/**
   303 	 * Note: This is all hardcoded rather than delegated to save
   304 	 * precious CPU cycles.
   305 	 */
   306 	float curtime = gpGlobals->curtime;
   307 	if (curtime - g_LastTime >= 0.1f)
   308 	{
   309 		if (m_CheckingAuth
   310 			&& (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
   311 		{
   312 			g_LastAuthCheck = gpGlobals->curtime;
   313 			g_Players.RunAuthChecks();
   314 		}
   315 
   316 		g_Timers.RunFrame();
   317 		g_LastTime = curtime;
   318 	}
   319 
   320 	if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
   321 	{
   322 		g_pOnGameFrame->Execute(NULL);
   323 	}
   324 }
   325 
   326 void SourceModBase::LevelShutdown()
   327 {
   328 	if (g_pOnMapEnd)
   329 	{
   330 		g_pOnMapEnd->Execute(NULL);
   331 	}
   332 
   333 	if (m_ExecPluginReload)
   334 	{
   335 		g_PluginSys.ReloadOrUnloadPlugins();
   336 		m_ExecPluginReload = false;
   337 	}
   338 }
   339 
   340 bool SourceModBase::IsMapLoading() const
   341 {
   342 	return m_IsMapLoading;
   343 }
   344 
   345 void SourceModBase::DoGlobalPluginLoads()
   346 {
   347 	char config_path[PLATFORM_MAX_PATH];
   348 	char plugins_path[PLATFORM_MAX_PATH];
   349 
   350 	BuildPath(Path_SM, config_path, 
   351 		sizeof(config_path),
   352 		"configs/plugin_settings.cfg");
   353 	BuildPath(Path_SM, plugins_path,
   354 		sizeof(plugins_path),
   355 		"plugins");
   356 
   357 	/* Load any auto extensions */
   358 	g_Extensions.TryAutoload();
   359 
   360 	/* Run the first pass */
   361 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   362 
   363 	/* Mark any extensions as loaded */
   364 	g_Extensions.MarkAllLoaded();
   365 
   366 	/* No modules yet, it's safe to call this from here */
   367 	g_PluginSys.LoadAll_SecondPass();
   368 
   369 	/* Re-mark any extensions as loaded */
   370 	g_Extensions.MarkAllLoaded();
   371 }
   372 
   373 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
   374 {
   375 	char _buffer[PLATFORM_MAX_PATH];
   376 	va_list ap;
   377 
   378 	va_start(ap, format);
   379 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   380 	va_end(ap);
   381 
   382 	const char *base = NULL;
   383 	if (type == Path_Game)
   384 	{
   385 		base = GetModPath();
   386 	} else if (type == Path_SM) {
   387 		base = GetSourceModPath();
   388 	} else if (type == Path_SM_Rel) {
   389 		base = m_SMRelDir;
   390 	}
   391 
   392 	if (base)
   393 	{
   394 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   395 	} else {
   396 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   397 	}
   398 }
   399 
   400 void SourceModBase::CloseSourceMod()
   401 {
   402 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   403 
   404 	if (g_Loaded)
   405 	{
   406 		if (g_pOnGameFrame)
   407 		{
   408 			g_Forwards.ReleaseForward(g_pOnGameFrame);
   409 		}
   410 
   411 		if (g_pOnMapEnd)
   412 		{
   413 			g_Forwards.ReleaseForward(g_pOnMapEnd);
   414 		}
   415 	
   416 		/* Notify! */
   417 		SMGlobalClass *pBase = SMGlobalClass::head;
   418 		while (pBase)
   419 		{
   420 			pBase->OnSourceModShutdown();
   421 			pBase = pBase->m_pGlobalClassNext;
   422 		}
   423 	
   424 		/* Delete all data packs */
   425 		CStack<CDataPack *>::iterator iter;
   426 		CDataPack *pd;
   427 		for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   428 		{
   429 			pd = (*iter);
   430 			delete pd;
   431 		}
   432 		m_freepacks.popall();
   433 	
   434 		/* Notify! */
   435 		pBase = SMGlobalClass::head;
   436 		while (pBase)
   437 		{
   438 			pBase->OnSourceModAllShutdown();
   439 			pBase = pBase->m_pGlobalClassNext;
   440 		}
   441 	
   442 		if (enginePatch)
   443 		{
   444 			SH_RELEASE_CALLCLASS(enginePatch);
   445 			enginePatch = NULL;
   446 		}
   447 	
   448 		if (gamedllPatch)
   449 		{
   450 			SH_RELEASE_CALLCLASS(gamedllPatch);
   451 			gamedllPatch = NULL;
   452 		}
   453 
   454 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   455 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   456 	}
   457 
   458 	/* Rest In Peace */
   459 	ShutdownJIT();
   460 }
   461 
   462 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   463 {
   464 	IExtensionInterface *pAPI = pExt->GetAPI();
   465 	const char *tag = pAPI->GetExtensionTag();
   466 	char buffer[2048];
   467 	va_list ap;
   468 
   469 	va_start(ap, format);
   470 	vsnprintf(buffer, sizeof(buffer), format, ap);
   471 	va_end(ap);
   472 
   473 	if (tag)
   474 	{
   475 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   476 	} else {
   477 		g_Logger.LogMessage("%s", buffer);
   478 	}
   479 }
   480 
   481 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   482 {
   483 	IExtensionInterface *pAPI = pExt->GetAPI();
   484 	const char *tag = pAPI->GetExtensionTag();
   485 	char buffer[2048];
   486 	va_list ap;
   487 
   488 	va_start(ap, format);
   489 	vsnprintf(buffer, sizeof(buffer), format, ap);
   490 	va_end(ap);
   491 
   492 	if (tag)
   493 	{
   494 		g_Logger.LogError("[%s] %s", tag, buffer);
   495 	} else {
   496 		g_Logger.LogError("%s", buffer);
   497 	}
   498 }
   499 
   500 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   501 {
   502 	char *fmt;
   503 
   504 	pContext->LocalToString(params[param], &fmt);
   505 
   506 	int lparam = ++param;
   507 
   508 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   509 }
   510 
   511 const char *SourceModBase::GetSourceModPath() const
   512 {
   513 	return m_SMBaseDir;
   514 }
   515 
   516 const char *SourceModBase::GetModPath() const
   517 {
   518 	return g_BaseDir.c_str();
   519 }
   520 
   521 void SourceModBase::SetGlobalTarget(unsigned int index)
   522 {
   523 	m_target = index;
   524 }
   525 
   526 void SourceModBase::SetAuthChecking(bool set)
   527 {
   528 	m_CheckingAuth = set;
   529 }
   530 
   531 unsigned int SourceModBase::GetGlobalTarget() const
   532 {
   533 	return m_target;
   534 }
   535 
   536 IDataPack *SourceModBase::CreateDataPack()
   537 {
   538 	CDataPack *pack;
   539 	if (m_freepacks.empty())
   540 	{
   541 		pack = new CDataPack;
   542 	} else {
   543 		pack = m_freepacks.front();
   544 		m_freepacks.pop();
   545 		pack->Initialize();
   546 	}
   547 	return pack;
   548 }
   549 
   550 void SourceModBase::FreeDataPack(IDataPack *pack)
   551 {
   552 	m_freepacks.push(static_cast<CDataPack *>(pack));
   553 }
   554 
   555 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   556 {
   557 	//:TODO:
   558 	return 0;
   559 }
   560 
   561 const char *SourceModBase::GetModFolderName() const
   562 {
   563 	return m_ModDir;
   564 }
   565 
   566 SMGlobalClass *SMGlobalClass::head = NULL;
   567 
   568 SMGlobalClass::SMGlobalClass()
   569 {
   570 	m_pGlobalClassNext = SMGlobalClass::head;
   571 	SMGlobalClass::head = this;
   572 }