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