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