core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Sat May 12 23:45:52 2007 +0000 (2007-05-12)
changeset 769 d7dc79f1f93e
parent 755 66c9fde7f632
child 780 570fa34723bf
permissions -rw-r--r--
behold with your eyes and view upon what are MENUS
     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 #include "MenuStyle_Valve.h"
    33 
    34 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    35 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    36 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
    37 
    38 SourcePawnEngine g_SourcePawn;
    39 SourceModBase g_SourceMod;
    40 
    41 ILibrary *g_pJIT = NULL;
    42 SourceHook::String g_BaseDir;
    43 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
    44 IVirtualMachine *g_pVM;
    45 IdentityToken_t *g_pCoreIdent = NULL;
    46 float g_LastTime = 0.0f;
    47 float g_LastMenuTime = 0.0f;
    48 float g_LastAuthCheck = 0.0f;
    49 IForward *g_pOnGameFrame = NULL;
    50 IForward *g_pOnMapEnd = NULL;
    51 bool g_Loaded = false;
    52 int g_StillFrames = 0;
    53 float g_StillTime = 0.0f;
    54 
    55 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
    56 typedef unsigned int (*GETEXPORTCOUNT)();
    57 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
    58 typedef void (*NOTIFYSHUTDOWN)();
    59 
    60 void ShutdownJIT()
    61 {
    62 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    63 	if (notify)
    64 	{
    65 		notify();
    66 	}
    67 
    68 	g_pJIT->CloseLibrary();
    69 }
    70 
    71 SourceModBase::SourceModBase()
    72 {
    73 	m_IsMapLoading = false;
    74 	m_ExecPluginReload = false;
    75 	m_GotBasePath = false;
    76 }
    77 
    78 ConfigResult SourceModBase::OnSourceModConfigChanged(const char *key, 
    79 									  const char *value, 
    80 									  ConfigSource source, 
    81 									  char *error, 
    82 									  size_t maxlength)
    83 {
    84 	if (strcasecmp(key, "BasePath") == 0)
    85 	{
    86 		if (source == ConfigSource_Console)
    87 		{
    88 			UTIL_Format(error, maxlength, "Cannot be set at runtime");
    89 			return ConfigResult_Reject;
    90 		}
    91 
    92 		if (!m_GotBasePath)
    93 		{
    94 			g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/%s", g_BaseDir.c_str(), value);
    95 			g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), value);
    96 
    97 			m_GotBasePath = true;
    98 		}
    99 
   100 		return ConfigResult_Accept;
   101 	}
   102 
   103 	return ConfigResult_Ignore;
   104 }
   105 
   106 bool SourceModBase::InitializeSourceMod(char *error, size_t maxlength, bool late)
   107 {
   108 	const char *gamepath = g_SMAPI->GetBaseDir();
   109 
   110 	/* Store full path to game */
   111 	g_BaseDir.assign(gamepath);
   112 
   113 	/* Store name of game directory by itself */
   114 	size_t len = strlen(gamepath);
   115 	for (size_t i = len - 1; i >= 0; i--)
   116 	{
   117 		if (gamepath[i] == PLATFORM_SEP_CHAR)
   118 		{
   119 			strncopy(m_ModDir, &gamepath[++i], sizeof(m_ModDir));
   120 			break;
   121 		}
   122 	}
   123 
   124 	/* Initialize CoreConfig so we can get SourceMod base path properly - this basically parses core.cfg */
   125 	g_CoreConfig.Initialize();
   126 
   127 	/* This shouldn't happen, but can't hurt to be safe */
   128 	if (!g_LibSys.PathExists(m_SMBaseDir) || !m_GotBasePath)
   129 	{
   130 		g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
   131 		g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
   132 		m_GotBasePath = true;
   133 	}
   134 
   135 	/* Attempt to load the JIT! */
   136 	char file[PLATFORM_MAX_PATH];
   137 	char myerror[255];
   138 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
   139 		GetSourceModPath(),
   140 		PLATFORM_LIB_EXT
   141 		);
   142 
   143 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
   144 	if (!g_pJIT)
   145 	{
   146 		if (error && maxlength)
   147 		{
   148 			snprintf(error, maxlength, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
   149 				myerror,
   150 				PLATFORM_LIB_EXT);
   151 		}
   152 		return false;
   153 	}
   154 
   155 	int err;
   156 	GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
   157 	if (!jit_init)
   158 	{
   159 		ShutdownJIT();
   160 		if (error && maxlength)
   161 		{
   162 			snprintf(error, maxlength, "Failed to find GiveEnginePointer in JIT!");
   163 		}
   164 		return false;
   165 	}
   166 
   167 	if ((err=jit_init(g_pSourcePawn)) != 0)
   168 	{
   169 		ShutdownJIT();
   170 		if (error && maxlength)
   171 		{
   172 			snprintf(error, maxlength, "GiveEnginePointer returned %d in the JIT", err);
   173 		}
   174 		return false;
   175 	}
   176 
   177 	GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
   178 	GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
   179 	if (!jit_get)
   180 	{
   181 		ShutdownJIT();
   182 		if (error && maxlength)
   183 		{
   184 			snprintf(error, maxlength, "JIT is missing a necessary export!");
   185 		}
   186 		return false;
   187 	}
   188 
   189 	unsigned int num = jit_getnum();
   190 	if (!num || ((g_pVM=jit_get(0)) == NULL))
   191 	{
   192 		ShutdownJIT();
   193 		if (error && maxlength)
   194 		{
   195 			snprintf(error, maxlength, "JIT did not export any virtual machines!");
   196 		}
   197 		return false;
   198 	}
   199 
   200 	unsigned int api = g_pVM->GetAPIVersion();
   201 	if (api != SOURCEPAWN_VM_API_VERSION)
   202 	{
   203 		ShutdownJIT();
   204 		if (error && maxlength)
   205 		{
   206 			snprintf(error, maxlength, "JIT is not a compatible version");
   207 		}
   208 		return false;
   209 	}
   210 
   211 	/* Hook this now so we can detect startup without calling StartSourceMod() */
   212 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   213 
   214 	/* Only load if we're not late */
   215 	if (!late)
   216 	{
   217 		StartSourceMod(false);
   218 	}
   219 
   220 	return true;
   221 }
   222 
   223 void SourceModBase::StartSourceMod(bool late)
   224 {
   225 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   226 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   227 
   228 	enginePatch = SH_GET_CALLCLASS(engine);
   229 	gamedllPatch = SH_GET_CALLCLASS(gamedll);
   230 
   231 	/* Notify! */
   232 	SMGlobalClass *pBase = SMGlobalClass::head;
   233 	while (pBase)
   234 	{
   235 		pBase->OnSourceModStartup(false);
   236 		pBase = pBase->m_pGlobalClassNext;
   237 	}
   238 
   239 	/* Make the global core identity */
   240 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   241 
   242 	/* Notify! */
   243 	pBase = SMGlobalClass::head;
   244 	while (pBase)
   245 	{
   246 		pBase->OnSourceModAllInitialized();
   247 		pBase = pBase->m_pGlobalClassNext;
   248 	}
   249 
   250 	/* Add us now... */
   251 	g_ShareSys.AddInterface(NULL, this);
   252 
   253 	/* We're loaded! */
   254 	g_Loaded = true;
   255 }
   256 
   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 	g_LastTime = 0.0f;
   269 	g_LastMenuTime = 0.0f;
   270 	g_LastAuthCheck = 0.0f;
   271 	g_SimTicks.ticking = true;
   272 	g_SimTicks.tickcount = 0;
   273 	g_StillTime = 0.0f;
   274 	g_StillFrames = 0;
   275 
   276 	/* Notify! */
   277 	SMGlobalClass *pBase = SMGlobalClass::head;
   278 	while (pBase)
   279 	{
   280 		pBase->OnSourceModLevelChange(pMapName);
   281 		pBase = pBase->m_pGlobalClassNext;
   282 	}
   283 
   284 	DoGlobalPluginLoads();
   285 
   286 	m_IsMapLoading = false;
   287 
   288 	/* Notify! */
   289 	pBase = SMGlobalClass::head;
   290 	while (pBase)
   291 	{
   292 		pBase->OnSourceModPluginsLoaded();
   293 		pBase = pBase->m_pGlobalClassNext;
   294 	}
   295 
   296 	if (!g_pOnGameFrame)
   297 	{
   298 		g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
   299 	}
   300 
   301 	if (!g_pOnMapEnd)
   302 	{
   303 		g_pOnMapEnd = g_Forwards.CreateForward("OnMapEnd", ET_Ignore, 0, NULL);
   304 	}
   305 
   306 	RETURN_META_VALUE(MRES_IGNORED, true);
   307 }
   308 
   309 void StartTickSimulation()
   310 {
   311 	g_SimTicks.ticking = false;
   312 	g_SimTicks.tickcount = 0;
   313 	g_SimTicks.ticktime = gpGlobals->curtime;
   314 }
   315 
   316 void StopTickSimulation()
   317 {
   318 	g_SimTicks.ticking = true;
   319 	g_Timers.MapChange();
   320 	g_StillFrames = 0;
   321 	g_LastTime = gpGlobals->curtime;
   322 }
   323 
   324 void SimulateTick()
   325 {
   326 	g_SimTicks.tickcount++;
   327 	g_SimTicks.ticktime = g_StillTime + (g_SimTicks.tickcount * gpGlobals->interval_per_tick);
   328 }
   329 
   330 void SourceModBase::GameFrame(bool simulating)
   331 {
   332 	/**
   333 	 * Note: This is all hardcoded rather than delegated to save
   334 	 * precious CPU cycles.
   335 	 */
   336 	float curtime = gpGlobals->curtime;
   337 	int framecount = gpGlobals->framecount;
   338 
   339 	/* Verify that we're still ticking */
   340 	if (g_SimTicks.ticking)
   341 	{
   342 		if (g_StillFrames == 0)
   343 		{
   344 			g_StillFrames = framecount;
   345 			g_StillTime = curtime;
   346 		} else {
   347 			/* Try to detect when we've stopped ticking.
   348 			 * We do this once 10 frames pass and there have been no ticks.
   349 			 */
   350 			if (g_StillTime == curtime)
   351 			{
   352 				if (framecount - g_StillFrames >= 5)
   353 				{
   354 					StartTickSimulation();
   355 					return;
   356 				}
   357 			} else {
   358 				/* We're definitely ticking we get here, 
   359 				 * but update everything as a precaution */
   360 				g_StillFrames = framecount;
   361 				g_StillTime = curtime;
   362 			}
   363 		}
   364 	} else {
   365 		/* We need to make sure we should still be simulating. */
   366 		if (g_StillTime != curtime)
   367 		{
   368 			/* Wow, we're ticking again! It's time to revert. */
   369 			StopTickSimulation();
   370 			return;
   371 		}
   372 		/* Nope, not ticking.  Simulate! */
   373 		SimulateTick();
   374 		curtime = g_SimTicks.ticktime;
   375 	}
   376 
   377 	if (curtime - g_LastTime >= 0.1f)
   378 	{
   379 		if (m_CheckingAuth
   380 			&& (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
   381 		{
   382 			g_LastAuthCheck = gpGlobals->curtime;
   383 			g_Players.RunAuthChecks();
   384 		}
   385 
   386 		g_Timers.RunFrame();
   387 		g_LastTime = curtime;
   388 	}
   389 
   390 	if (g_SimTicks.tickcount && (curtime - g_LastMenuTime >= 1.0f))
   391 	{
   392 		g_ValveMenuStyle.ProcessWatchList();
   393 		g_LastMenuTime = curtime;
   394 	}
   395 
   396 	if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
   397 	{
   398 		g_pOnGameFrame->Execute(NULL);
   399 	}
   400 }
   401 
   402 void SourceModBase::LevelShutdown()
   403 {
   404 	if (g_pOnMapEnd)
   405 	{
   406 		g_pOnMapEnd->Execute(NULL);
   407 	}
   408 
   409 	if (m_ExecPluginReload)
   410 	{
   411 		g_PluginSys.ReloadOrUnloadPlugins();
   412 		m_ExecPluginReload = false;
   413 	}
   414 }
   415 
   416 bool SourceModBase::IsMapLoading() const
   417 {
   418 	return m_IsMapLoading;
   419 }
   420 
   421 void SourceModBase::DoGlobalPluginLoads()
   422 {
   423 	char config_path[PLATFORM_MAX_PATH];
   424 	char plugins_path[PLATFORM_MAX_PATH];
   425 
   426 	BuildPath(Path_SM, config_path, 
   427 		sizeof(config_path),
   428 		"configs/plugin_settings.cfg");
   429 	BuildPath(Path_SM, plugins_path,
   430 		sizeof(plugins_path),
   431 		"plugins");
   432 
   433 	/* Load any auto extensions */
   434 	g_Extensions.TryAutoload();
   435 
   436 	/* Run the first pass */
   437 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   438 
   439 	/* Mark any extensions as loaded */
   440 	g_Extensions.MarkAllLoaded();
   441 
   442 	/* No modules yet, it's safe to call this from here */
   443 	g_PluginSys.LoadAll_SecondPass();
   444 
   445 	/* Re-mark any extensions as loaded */
   446 	g_Extensions.MarkAllLoaded();
   447 }
   448 
   449 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
   450 {
   451 	char _buffer[PLATFORM_MAX_PATH];
   452 	va_list ap;
   453 
   454 	va_start(ap, format);
   455 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   456 	va_end(ap);
   457 
   458 	const char *base = NULL;
   459 	if (type == Path_Game)
   460 	{
   461 		base = GetGamePath();
   462 	} else if (type == Path_SM) {
   463 		base = GetSourceModPath();
   464 	} else if (type == Path_SM_Rel) {
   465 		base = m_SMRelDir;
   466 	}
   467 
   468 	if (base)
   469 	{
   470 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   471 	} else {
   472 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   473 	}
   474 }
   475 
   476 void SourceModBase::CloseSourceMod()
   477 {
   478 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   479 
   480 	if (g_Loaded)
   481 	{
   482 		if (g_pOnGameFrame)
   483 		{
   484 			g_Forwards.ReleaseForward(g_pOnGameFrame);
   485 		}
   486 
   487 		if (g_pOnMapEnd)
   488 		{
   489 			g_Forwards.ReleaseForward(g_pOnMapEnd);
   490 		}
   491 	
   492 		/* Notify! */
   493 		SMGlobalClass *pBase = SMGlobalClass::head;
   494 		while (pBase)
   495 		{
   496 			pBase->OnSourceModShutdown();
   497 			pBase = pBase->m_pGlobalClassNext;
   498 		}
   499 	
   500 		/* Delete all data packs */
   501 		CStack<CDataPack *>::iterator iter;
   502 		CDataPack *pd;
   503 		for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   504 		{
   505 			pd = (*iter);
   506 			delete pd;
   507 		}
   508 		m_freepacks.popall();
   509 	
   510 		/* Notify! */
   511 		pBase = SMGlobalClass::head;
   512 		while (pBase)
   513 		{
   514 			pBase->OnSourceModAllShutdown();
   515 			pBase = pBase->m_pGlobalClassNext;
   516 		}
   517 	
   518 		if (enginePatch)
   519 		{
   520 			SH_RELEASE_CALLCLASS(enginePatch);
   521 			enginePatch = NULL;
   522 		}
   523 	
   524 		if (gamedllPatch)
   525 		{
   526 			SH_RELEASE_CALLCLASS(gamedllPatch);
   527 			gamedllPatch = NULL;
   528 		}
   529 
   530 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   531 		SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   532 	}
   533 
   534 	/* Rest In Peace */
   535 	ShutdownJIT();
   536 }
   537 
   538 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   539 {
   540 	IExtensionInterface *pAPI = pExt->GetAPI();
   541 	const char *tag = pAPI->GetExtensionTag();
   542 	char buffer[2048];
   543 	va_list ap;
   544 
   545 	va_start(ap, format);
   546 	vsnprintf(buffer, sizeof(buffer), format, ap);
   547 	va_end(ap);
   548 
   549 	if (tag)
   550 	{
   551 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   552 	} else {
   553 		g_Logger.LogMessage("%s", buffer);
   554 	}
   555 }
   556 
   557 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   558 {
   559 	IExtensionInterface *pAPI = pExt->GetAPI();
   560 	const char *tag = pAPI->GetExtensionTag();
   561 	char buffer[2048];
   562 	va_list ap;
   563 
   564 	va_start(ap, format);
   565 	vsnprintf(buffer, sizeof(buffer), format, ap);
   566 	va_end(ap);
   567 
   568 	if (tag)
   569 	{
   570 		g_Logger.LogError("[%s] %s", tag, buffer);
   571 	} else {
   572 		g_Logger.LogError("%s", buffer);
   573 	}
   574 }
   575 
   576 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   577 {
   578 	char *fmt;
   579 
   580 	pContext->LocalToString(params[param], &fmt);
   581 
   582 	int lparam = ++param;
   583 
   584 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   585 }
   586 
   587 const char *SourceModBase::GetSourceModPath() const
   588 {
   589 	return m_SMBaseDir;
   590 }
   591 
   592 const char *SourceModBase::GetGamePath() const
   593 {
   594 	return g_BaseDir.c_str();
   595 }
   596 
   597 void SourceModBase::SetGlobalTarget(unsigned int index)
   598 {
   599 	m_target = index;
   600 }
   601 
   602 void SourceModBase::SetAuthChecking(bool set)
   603 {
   604 	m_CheckingAuth = set;
   605 }
   606 
   607 unsigned int SourceModBase::GetGlobalTarget() const
   608 {
   609 	return m_target;
   610 }
   611 
   612 IDataPack *SourceModBase::CreateDataPack()
   613 {
   614 	CDataPack *pack;
   615 	if (m_freepacks.empty())
   616 	{
   617 		pack = new CDataPack;
   618 	} else {
   619 		pack = m_freepacks.front();
   620 		m_freepacks.pop();
   621 		pack->Initialize();
   622 	}
   623 	return pack;
   624 }
   625 
   626 void SourceModBase::FreeDataPack(IDataPack *pack)
   627 {
   628 	m_freepacks.push(static_cast<CDataPack *>(pack));
   629 }
   630 
   631 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   632 {
   633 	//:TODO:
   634 	return 0;
   635 }
   636 
   637 const char *SourceModBase::GetGameFolderName() const
   638 {
   639 	return m_ModDir;
   640 }
   641 
   642 ISourcePawnEngine *SourceModBase::GetScriptingEngine()
   643 {
   644 	return g_pSourcePawn;
   645 }
   646 
   647 IVirtualMachine *SourceModBase::GetScriptingVM()
   648 {
   649 	return g_pVM;
   650 }
   651 
   652 SMGlobalClass *SMGlobalClass::head = NULL;
   653 
   654 SMGlobalClass::SMGlobalClass()
   655 {
   656 	m_pGlobalClassNext = SMGlobalClass::head;
   657 	SMGlobalClass::head = this;
   658 }