core/sourcemod.cpp
author Matt Woodrow <pred@alliedmods.net>
Fri Aug 08 00:17:37 2008 +0000 (2008-08-08)
changeset 2224 676c3b826f13
parent 2193 db7c6362f3f2
child 2226 d10b38524be3
permissions -rw-r--r--
Initial Import of beta structs extension.
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <stdio.h>
    33 #include "sourcemod.h"
    34 #include "sourcemm_api.h"
    35 #include "systems/LibrarySys.h"
    36 #include <sh_string.h>
    37 #include "PluginSys.h"
    38 #include "ShareSys.h"
    39 #include "CoreConfig.h"
    40 #include "Logger.h"
    41 #include "ExtensionSys.h"
    42 #include "AdminCache.h"
    43 #include "sm_stringutil.h"
    44 #include "PlayerManager.h"
    45 #include "Translator.h"
    46 #include "ForwardSys.h"
    47 #include "TimerSys.h"
    48 #include "GameConfigs.h"
    49 #include "DebugReporter.h"
    50 #include "Profiler.h"
    51 
    52 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    53 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    54 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
    55 SH_DECL_HOOK1_void(IVEngineServer, ServerCommand, SH_NOATTRIB, false, const char *);
    56 
    57 SourceModBase g_SourceMod;
    58 
    59 ILibrary *g_pJIT = NULL;
    60 SourceHook::String g_BaseDir;
    61 ISourcePawnEngine *g_pSourcePawn = NULL;
    62 ISourcePawnEngine2 *g_pSourcePawn2 = NULL;
    63 IdentityToken_t *g_pCoreIdent = NULL;
    64 IForward *g_pOnMapEnd = NULL;
    65 bool g_Loaded = false;
    66 
    67 typedef ISourcePawnEngine *(*GET_SP_V1)();
    68 typedef ISourcePawnEngine2 *(*GET_SP_V2)();
    69 typedef void (*NOTIFYSHUTDOWN)();
    70 
    71 void ShutdownJIT()
    72 {
    73 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    74 	if (notify)
    75 	{
    76 		notify();
    77 	}
    78 
    79 	g_pJIT->CloseLibrary();
    80 }
    81 
    82 SourceModBase::SourceModBase()
    83 {
    84 	m_IsMapLoading = false;
    85 	m_ExecPluginReload = false;
    86 	m_GotBasePath = false;
    87 }
    88 
    89 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key, 
    90 									  const char *value, 
    91 									  ConfigSource source, 
    92 									  char *error, 
    93 									  size_t maxlength)
    94 {
    95 	if (strcasecmp(key, "BasePath") == 0)
    96 	{
    97 		if (source == ConfigSource_Console)
    98 		{
    99 			UTIL_Format(error, maxlength, "Cannot be set at runtime");
   100 			return ConfigResult_Reject;
   101 		}
   102 
   103 		if (!m_GotBasePath)
   104 		{
   105 			g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
   106 			g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
   107 
   108 			m_GotBasePath = true;
   109 		}
   110 
   111 		return ConfigResult_Accept;
   112 	}
   113 
   114 	return ConfigResult_Ignore;
   115 }
   116 
   117 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
   118 {
   119 	const char *gamepath = g_SMAPI->GetBaseDir();
   120 
   121 	/* Store full path to game */
   122 	g_BaseDir.assign(gamepath);
   123 
   124 	/* Store name of game directory by itself */
   125 	size_t len = strlen(gamepath);
   126 	for (size_t i = len - 1; i >= 0; i--)
   127 	{
   128 		if (gamepath[i] == PLATFORM_SEP_CHAR)
   129 		{
   130 			strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
   131 			break;
   132 		}
   133 	}
   134 
   135 	/* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
   136 	g_CoreConfig.Initialize();
   137 
   138 	/* This shouldn't happen, but can't hurt to be safe */
   139 	if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
   140 	{
   141 		g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
   142 		g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
   143 		m_GotBasePath = true;
   144 	}
   145 
   146 	/* Attempt to load the JIT! */
   147 	char file[PLATFORM_MAX_PATH];
   148 	char myerror[255];
   149 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
   150 		GetSourceModPath(),
   151 		PLATFORM_LIB_EXT
   152 		);
   153 
   154 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
   155 	if (!g_pJIT)
   156 	{
   157 		if (error && maxlength)
   158 		{
   159 			snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
   160 				myerror,
   161 				PLATFORM_LIB_EXT);
   162 		}
   163 		return false;
   164 	}
   165 
   166 	GET_SP_V1 getv1 = (GET_SP_V1)g_pJIT->GetSymbolAddress("GetSourcePawnEngine1");
   167 	GET_SP_V2 getv2 = (GET_SP_V2)g_pJIT->GetSymbolAddress("GetSourcePawnEngine2");
   168 
   169 	if (getv1 == NULL)
   170 	{
   171 		if (error && maxlength)
   172 		{
   173 			snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
   174 		}
   175 		ShutdownJIT();
   176 		return false;
   177 	}
   178 	else if (getv2 == NULL)
   179 	{
   180 		if (error && maxlength)
   181 		{
   182 			snprintf(error, maxlength, "JIT is too old; upgrade SourceMod");
   183 		}
   184 		ShutdownJIT();
   185 		return false;
   186 	}
   187 
   188 	g_pSourcePawn = getv1();
   189 	g_pSourcePawn2 = getv2();
   190 
   191 	g_pSourcePawn2->SetDebugListener(&g_DbgReporter);
   192 	g_pSourcePawn2->SetProfiler(&g_Profiler);
   193 
   194 	/* Hook this now so we can detect startup without calling StartSourceMod() */
   195 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   196 
   197 	/* Only load if we're not late */
   198 	if (!late)
   199 	{
   200 		StartSourceMod(false);
   201 	}
   202 
   203 	return true;
   204 }
   205 
   206 void SourceModBase::StartSourceMod(bool late)
   207 {
   208 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   209 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
   210 
   211 	enginePatch = SH_GET_CALLCLASS(engine);
   212 	gamedllPatch = SH_GET_CALLCLASS(gamedll);
   213 
   214 	g_ShareSys.Initialize();
   215 
   216 	/* Make the global core identity */
   217 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   218 
   219 	/* Notify! */
   220 	SMGlobalClass *pBase = SMGlobalClass::head;
   221 	while (pBase)
   222 	{
   223 		pBase->OnSourceModStartup(false);
   224 		pBase = pBase->m_pGlobalClassNext;
   225 	}
   226 
   227 	/* Notify! */
   228 	pBase = SMGlobalClass::head;
   229 	while (pBase)
   230 	{
   231 		pBase->OnSourceModAllInitialized();
   232 		pBase = pBase->m_pGlobalClassNext;
   233 	}
   234 
   235 	/* Notify! */
   236 	pBase = SMGlobalClass::head;
   237 	while (pBase)
   238 	{
   239 		pBase->OnSourceModAllInitialized_Post();
   240 		pBase = pBase->m_pGlobalClassNext;
   241 	}
   242 
   243 	/* Add us now... */
   244 	g_ShareSys.AddInterface(NULL, this);
   245 
   246 	/* We're loaded! */
   247 	g_Loaded = true;
   248 
   249 	/* Initialize VSP stuff */
   250 	if (vsp_interface != NULL)
   251 	{
   252 		g_SourceMod_Core.OnVSPListening(vsp_interface);
   253 	}
   254 }
   255 
   256 static bool g_LevelEndBarrier = false;
   257 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   258 {
   259 	/* If we're not loaded... */
   260 	if (!g_Loaded)
   261 	{
   262 		/* Do all global initialization now */
   263 		StartSourceMod(true);
   264 	}
   265 
   266 	m_IsMapLoading = true;
   267 	m_ExecPluginReload = true;
   268 
   269 	/* Notify! */
   270 	SMGlobalClass *pBase = SMGlobalClass::head;
   271 	while (pBase)
   272 	{
   273 		pBase->OnSourceModLevelChange(pMapName);
   274 		pBase = pBase->m_pGlobalClassNext;
   275 	}
   276 
   277 	DoGlobalPluginLoads();
   278 
   279 	m_IsMapLoading = false;
   280 
   281 	/* Notify! */
   282 	pBase = SMGlobalClass::head;
   283 	while (pBase)
   284 	{
   285 		pBase->OnSourceModPluginsLoaded();
   286 		pBase = pBase->m_pGlobalClassNext;
   287 	}
   288 
   289 	if (!g_pOnMapEnd)
   290 	{
   291 		g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
   292 	}
   293 
   294 	g_LevelEndBarrier = true;
   295 
   296 	RETURN_META_VALUE(MRES_IGNORED, true);
   297 }
   298 
   299 void SourceModBase::LevelShutdown()
   300 {
   301 	if (g_LevelEndBarrier)
   302 	{
   303 		SMGlobalClass *next = SMGlobalClass::head;
   304 		while (next)
   305 		{
   306 			next->OnSourceModLevelEnd();
   307 			next = next->m_pGlobalClassNext;
   308 		}
   309 		
   310 		if (g_pOnMapEnd != NULL)
   311 		{
   312 			g_pOnMapEnd->Execute(NULL);
   313 		}
   314 
   315 		g_Timers.RemoveMapChangeTimers();
   316 
   317 		g_LevelEndBarrier = false;
   318 	}
   319 
   320 	g_OnMapStarted = false;
   321 
   322 	if (m_ExecPluginReload)
   323 	{
   324 		g_PluginSys.ReloadOrUnloadPlugins();
   325 		m_ExecPluginReload = false;
   326 	}
   327 }
   328 
   329 bool SourceModBase::IsMapLoading() const
   330 {
   331 	return m_IsMapLoading;
   332 }
   333 
   334 void SourceModBase::DoGlobalPluginLoads()
   335 {
   336 	char config_path[PLATFORM_MAX_PATH];
   337 	char plugins_path[PLATFORM_MAX_PATH];
   338 
   339 	BuildPath(Path_SM, config_path, 
   340 		sizeof(config_path),
   341 		"configs/plugin_settings.cfg");
   342 	BuildPath(Path_SM, plugins_path,
   343 		sizeof(plugins_path),
   344 		"plugins");
   345 
   346 	/* Load any auto extensions */
   347 	g_Extensions.TryAutoload();
   348 
   349 	/* Fire the extensions ready message */
   350 	g_SMAPI->MetaFactory(SOURCEMOD_NOTICE_EXTENSIONS, NULL, NULL);	
   351 
   352 	/* Load any game extension */
   353 	const char *game_ext;
   354 	if ((game_ext = g_pGameConf->GetKeyValue("GameExtension")) != NULL)
   355 	{
   356 		char path[PLATFORM_MAX_PATH];
   357 		UTIL_Format(path, sizeof(path), "%s.ext." PLATFORM_LIB_EXT, game_ext);
   358 		g_Extensions.LoadAutoExtension(path);
   359 	}
   360 
   361 	/* Run the first pass */
   362 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   363 
   364 	/* Mark any extensions as loaded */
   365 	g_Extensions.MarkAllLoaded();
   366 
   367 	/* No modules yet, it's safe to call this from here */
   368 	g_PluginSys.LoadAll_SecondPass();
   369 
   370 	/* Re-mark any extensions as loaded */
   371 	g_Extensions.MarkAllLoaded();
   372 
   373 	/* Call OnAllPluginsLoaded */
   374 	g_PluginSys.AllPluginsLoaded();
   375 }
   376 
   377 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, const char *format, ...)
   378 {
   379 	char _buffer[PLATFORM_MAX_PATH];
   380 	va_list ap;
   381 
   382 	va_start(ap, format);
   383 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   384 	va_end(ap);
   385 
   386 	/* If we get a "file://" notation, strip off the file:// part so we're left 
   387 	 * with an absolute path.  Note that the absolute path gets returned, so 
   388 	 * usage with relative paths here is completely invalid.
   389 	 */
   390 	if (type != Path_SM_Rel && strncmp(_buffer, "file://", 7) == 0)
   391 	{
   392 		return g_LibSys.PathFormat(buffer, maxlength, "%s", &_buffer[7]);
   393 	}
   394 
   395 	const char *base = NULL;
   396 	if (type == Path_Game)
   397 	{
   398 		base = GetGamePath();
   399 	}
   400 	else if (type == Path_SM)
   401 	{
   402 		base = GetSourceModPath();
   403 	}
   404 	else if (type == Path_SM_Rel)
   405 	{
   406 		base = m_SMRelDir;
   407 	}
   408 
   409 	if (base)
   410 	{
   411 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   412 	}
   413 	else
   414 	{
   415 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   416 	}
   417 }
   418 
   419 void SourceModBase::CloseSourceMod()
   420 {
   421 	/* Force a level end */
   422 	LevelShutdown();
   423 
   424 	/* Unload plugins */
   425 	g_PluginSys.Shutdown();
   426 
   427 	/* Unload extensions */
   428 	g_Extensions.Shutdown();
   429 
   430 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   431 
   432 	if (g_Loaded)
   433 	{
   434 		if (g_pOnMapEnd)
   435 		{
   436 			g_Forwards.ReleaseForward(g_pOnMapEnd);
   437 		}
   438 	
   439 		/* Notify! */
   440 		SMGlobalClass *pBase = SMGlobalClass::head;
   441 		while (pBase)
   442 		{
   443 			pBase->OnSourceModShutdown();
   444 			pBase = pBase->m_pGlobalClassNext;
   445 		}
   446 	
   447 		/* Delete all data packs */
   448 		CStack<CDataPack *>::iterator iter;
   449 		CDataPack *pd;
   450 		for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   451 		{
   452 			pd = (*iter);
   453 			delete pd;
   454 		}
   455 		m_freepacks.popall();
   456 	
   457 		/* Notify! */
   458 		pBase = SMGlobalClass::head;
   459 		while (pBase)
   460 		{
   461 			pBase->OnSourceModAllShutdown();
   462 			pBase = pBase->m_pGlobalClassNext;
   463 		}
   464 	
   465 		if (enginePatch)
   466 		{
   467 			SH_RELEASE_CALLCLASS(enginePatch);
   468 			enginePatch = NULL;
   469 		}
   470 	
   471 		if (gamedllPatch)
   472 		{
   473 			SH_RELEASE_CALLCLASS(gamedllPatch);
   474 			gamedllPatch = NULL;
   475 		}
   476 
   477 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   478 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, &g_Timers, &TimerSystem::GameFrame, false);
   479 	}
   480 
   481 	/* Rest In Peace */
   482 	ShutdownJIT();
   483 }
   484 
   485 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   486 {
   487 	IExtensionInterface *pAPI = pExt->GetAPI();
   488 	const char *tag = pAPI->GetExtensionTag();
   489 	char buffer[2048];
   490 	va_list ap;
   491 
   492 	va_start(ap, format);
   493 	vsnprintf(buffer, sizeof(buffer), format, ap);
   494 	va_end(ap);
   495 
   496 	if (tag)
   497 	{
   498 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   499 	} else {
   500 		g_Logger.LogMessage("%s", buffer);
   501 	}
   502 }
   503 
   504 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   505 {
   506 	IExtensionInterface *pAPI = pExt->GetAPI();
   507 	const char *tag = pAPI->GetExtensionTag();
   508 	char buffer[2048];
   509 	va_list ap;
   510 
   511 	va_start(ap, format);
   512 	vsnprintf(buffer, sizeof(buffer), format, ap);
   513 	va_end(ap);
   514 
   515 	if (tag)
   516 	{
   517 		g_Logger.LogError("[%s] %s", tag, buffer);
   518 	} else {
   519 		g_Logger.LogError("%s", buffer);
   520 	}
   521 }
   522 
   523 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   524 {
   525 	char *fmt;
   526 
   527 	pContext->LocalToString(params[param], &fmt);
   528 
   529 	int lparam = ++param;
   530 
   531 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   532 }
   533 
   534 const char *SourceModBase::GetSourceModPath() const
   535 {
   536 	return m_SMBaseDir;
   537 }
   538 
   539 const char *SourceModBase::GetGamePath() const
   540 {
   541 	return g_BaseDir.c_str();
   542 }
   543 
   544 unsigned int SourceModBase::SetGlobalTarget(unsigned int index)
   545 {
   546 	unsigned int old = m_target;
   547 	m_target = index;
   548 	return old;
   549 }
   550 
   551 unsigned int SourceModBase::GetGlobalTarget() const
   552 {
   553 	return m_target;
   554 }
   555 
   556 IDataPack *SourceModBase::CreateDataPack()
   557 {
   558 	CDataPack *pack;
   559 	if (m_freepacks.empty())
   560 	{
   561 		pack = new CDataPack;
   562 	} else {
   563 		pack = m_freepacks.front();
   564 		m_freepacks.pop();
   565 		pack->Initialize();
   566 	}
   567 	return pack;
   568 }
   569 
   570 void SourceModBase::FreeDataPack(IDataPack *pack)
   571 {
   572 	m_freepacks.push(static_cast<CDataPack *>(pack));
   573 }
   574 
   575 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   576 {
   577 	//:TODO:
   578 	return 0;
   579 }
   580 
   581 const char *SourceModBase::GetGameFolderName() const
   582 {
   583 	return m_ModDir;
   584 }
   585 
   586 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
   587 {
   588 	return g_pSourcePawn;
   589 }
   590 
   591 IVirtualMachine *SourceModBase::GetScriptingVM()
   592 {
   593 	return NULL;
   594 }
   595 
   596 void SourceModBase::AllPluginsLoaded()
   597 {
   598 	SMGlobalClass *base = SMGlobalClass::head;
   599 	while (base)
   600 	{
   601 		base->OnSourceModGameInitialized();
   602 		base = base->m_pGlobalClassNext;
   603 	}
   604 }
   605 
   606 time_t SourceModBase::GetAdjustedTime()
   607 {
   608 	return ::GetAdjustedTime();
   609 }
   610 
   611 void SourceModBase::AddGameFrameHook(GAME_FRAME_HOOK hook)
   612 {
   613 	m_frame_hooks.push_back(hook);
   614 }
   615 
   616 void SourceModBase::RemoveGameFrameHook(GAME_FRAME_HOOK hook)
   617 {
   618 	for (size_t i = 0; i < m_frame_hooks.size(); i++)
   619 	{
   620 		if (m_frame_hooks[i] == hook)
   621 		{
   622 			m_frame_hooks.erase(m_frame_hooks.iterAt(i));
   623 			return;
   624 		}
   625 	}
   626 }
   627 
   628 void SourceModBase::ProcessGameFrameHooks(bool simulating)
   629 {
   630 	if (m_frame_hooks.size() == 0)
   631 	{
   632 		return;
   633 	}
   634 
   635 	for (size_t i = 0; i < m_frame_hooks.size(); i++)
   636 	{
   637 		m_frame_hooks[i](simulating);
   638 	}
   639 }
   640 
   641 SMGlobalClass *SMGlobalClass::head = NULL;
   642 
   643 SMGlobalClass::SMGlobalClass()
   644 {
   645 	m_pGlobalClassNext = SMGlobalClass::head;
   646 	SMGlobalClass::head = this;
   647 }