core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Fri Mar 02 08:34:13 2007 +0000 (2007-03-02)
changeset 558 fc0eec032efb
parent 532 fe6bb91d79b1
child 587 e9f3bbe8ba5d
permissions -rw-r--r--
added state change function
     1 /**
     2  * ===============================================================
     3  * SourceMod (C)2004-2007 AlliedModders LLC.  All rights reserved.
     4  * ===============================================================
     5  *
     6  * This file is not open source and may not be copied without explicit
     7  * written permission of AlliedModders LLC.  This file may not be redistributed 
     8  * in whole or significant part.
     9  * For information, see LICENSE.txt or http://www.sourcemod.net/license.php
    10  *
    11  * Version: $Id$
    12  */
    13 
    14 #include <stdio.h>
    15 #include "sourcemod.h"
    16 #include "sourcemm_api.h"
    17 #include "systems/LibrarySys.h"
    18 #include "vm/sp_vm_engine.h"
    19 #include <sh_string.h>
    20 #include "PluginSys.h"
    21 #include "ShareSys.h"
    22 #include "CLogger.h"
    23 #include "ExtensionSys.h"
    24 #include "AdminCache.h"
    25 #include "sm_stringutil.h"
    26 #include "CPlayerManager.h"
    27 #include "CTranslator.h"
    28 #include "ForwardSys.h"
    29 
    30 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    31 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    32 SH_DECL_HOOK1_void(IServerGameDLL, GameFrame, SH_NOATTRIB, false, bool);
    33 
    34 SourcePawnEngine g_SourcePawn;
    35 SourceModBase g_SourceMod;
    36 
    37 ILibrary *g_pJIT = NULL;
    38 SourceHook::String g_BaseDir;
    39 ISourcePawnEngine *g_pSourcePawn = &g_SourcePawn;
    40 IVirtualMachine *g_pVM;
    41 IdentityToken_t *g_pCoreIdent = NULL;
    42 float g_LastTime = 0.0f;
    43 float g_LastAuthCheck = 0.0f;
    44 IForward *g_pOnGameFrame = NULL;
    45 
    46 typedef int (*GIVEENGINEPOINTER)(ISourcePawnEngine *);
    47 typedef unsigned int (*GETEXPORTCOUNT)();
    48 typedef IVirtualMachine *(*GETEXPORT)(unsigned int);
    49 typedef void (*NOTIFYSHUTDOWN)();
    50 
    51 void ShutdownJIT()
    52 {
    53 	NOTIFYSHUTDOWN notify = (NOTIFYSHUTDOWN)g_pJIT->GetSymbolAddress("NotifyShutdown");
    54 	if (notify)
    55 	{
    56 		notify();
    57 	}
    58 
    59 	g_pJIT->CloseLibrary();
    60 }
    61 
    62 SourceModBase::SourceModBase()
    63 {
    64 	m_IsMapLoading = false;
    65 	m_ExecPluginReload = false;
    66 }
    67 
    68 bool SourceModBase::InitializeSourceMod(char *error, size_t err_max, bool late)
    69 {
    70 	g_BaseDir.assign(g_SMAPI->GetBaseDir());
    71 	g_LibSys.PathFormat(m_SMBaseDir, sizeof(m_SMBaseDir), "%s/addons/sourcemod", g_BaseDir.c_str());
    72 	g_LibSys.PathFormat(m_SMRelDir, sizeof(m_SMRelDir), "addons/sourcemod");
    73 
    74 	/* Attempt to load the JIT! */
    75 	char file[PLATFORM_MAX_PATH];
    76 	char myerror[255];
    77 	g_SMAPI->PathFormat(file, sizeof(file), "%s/bin/sourcepawn.jit.x86.%s",
    78 		GetSourceModPath(),
    79 		PLATFORM_LIB_EXT
    80 		);
    81 
    82 	g_pJIT = g_LibSys.OpenLibrary(file, myerror, sizeof(myerror));
    83 	if (!g_pJIT)
    84 	{
    85 		if (error && err_max)
    86 		{
    87 			snprintf(error, err_max, "%s (failed to load bin/sourcepawn.jit.x86.%s)", 
    88 				myerror,
    89 				PLATFORM_LIB_EXT);
    90 		}
    91 		return false;
    92 	}
    93 
    94 	int err;
    95 	GIVEENGINEPOINTER jit_init = (GIVEENGINEPOINTER)g_pJIT->GetSymbolAddress("GiveEnginePointer");
    96 	if (!jit_init)
    97 	{
    98 		ShutdownJIT();
    99 		if (error && err_max)
   100 		{
   101 			snprintf(error, err_max, "Failed to find GiveEnginePointer in JIT!");
   102 		}
   103 		return false;
   104 	}
   105 
   106 	if ((err=jit_init(g_pSourcePawn)) != 0)
   107 	{
   108 		ShutdownJIT();
   109 		if (error && err_max)
   110 		{
   111 			snprintf(error, err_max, "GiveEnginePointer returned %d in the JIT", err);
   112 		}
   113 		return false;
   114 	}
   115 
   116 	GETEXPORTCOUNT jit_getnum = (GETEXPORTCOUNT)g_pJIT->GetSymbolAddress("GetExportCount");
   117 	GETEXPORT jit_get = (GETEXPORT)g_pJIT->GetSymbolAddress("GetExport");
   118 	if (!jit_get)
   119 	{
   120 		ShutdownJIT();
   121 		if (error && err_max)
   122 		{
   123 			snprintf(error, err_max, "JIT is missing a necessary export!");
   124 		}
   125 		return false;
   126 	}
   127 
   128 	unsigned int num = jit_getnum();
   129 	if (!num || ((g_pVM=jit_get(0)) == NULL))
   130 	{
   131 		ShutdownJIT();
   132 		if (error && err_max)
   133 		{
   134 			snprintf(error, err_max, "JIT did not export any virtual machines!");
   135 		}
   136 		return false;
   137 	}
   138 
   139 	unsigned int api = g_pVM->GetAPIVersion();
   140 	if (api != SOURCEPAWN_VM_API_VERSION)
   141 	{
   142 		ShutdownJIT();
   143 		if (error && err_max)
   144 		{
   145 			snprintf(error, err_max, "JIT is not a compatible version");
   146 		}
   147 		return false;
   148 	}
   149 
   150 	StartSourceMod(late);
   151 
   152 	return true;
   153 }
   154 
   155 void SourceModBase::StartSourceMod(bool late)
   156 {
   157 	/* First initialize the global hooks we need */
   158 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   159 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   160 	SH_ADD_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   161 
   162 	enginePatch = SH_GET_CALLCLASS(engine);
   163 	gamedllPatch = SH_GET_CALLCLASS(gamedll);
   164 
   165 	/* Notify! */
   166 	SMGlobalClass *pBase = SMGlobalClass::head;
   167 	while (pBase)
   168 	{
   169 		pBase->OnSourceModStartup(false);
   170 		pBase = pBase->m_pGlobalClassNext;
   171 	}
   172 
   173 	/* Make the global core identity */
   174 	g_pCoreIdent = g_ShareSys.CreateCoreIdentity();
   175 
   176 	/* Notify! */
   177 	pBase = SMGlobalClass::head;
   178 	while (pBase)
   179 	{
   180 		pBase->OnSourceModAllInitialized();
   181 		pBase = pBase->m_pGlobalClassNext;
   182 	}
   183 
   184 	/* Add us now... */
   185 	g_ShareSys.AddInterface(NULL, this);
   186 }
   187 
   188 bool SourceModBase::LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   189 {
   190 	m_IsMapLoading = true;
   191 	m_ExecPluginReload = true;
   192 	g_LastTime = 0.0f;
   193 	g_LastAuthCheck = 0.0f;
   194 
   195 	g_Logger.MapChange(pMapName);
   196 
   197 	/* Refresh language stuff */
   198 	char path[PLATFORM_MAX_PATH];
   199 	BuildPath(Path_SM, path, sizeof(path), "configs/languages.cfg");
   200 	g_Translator.RebuildLanguageDatabase(path);
   201 
   202 	DoGlobalPluginLoads();
   203 
   204 	m_IsMapLoading = false;
   205 
   206 	g_Admins.DumpAdminCache(AdminCache_Overrides, true);
   207 	g_Admins.DumpAdminCache(AdminCache_Groups, true);
   208 
   209 	if (!g_pOnGameFrame)
   210 	{
   211 		g_pOnGameFrame = g_Forwards.CreateForward("OnGameFrame", ET_Ignore, 0, NULL);
   212 	}
   213 
   214 	RETURN_META_VALUE(MRES_IGNORED, true);
   215 }
   216 
   217 void SourceModBase::GameFrame(bool simulating)
   218 {
   219 	/**
   220 	 * Note: This is all hardcoded rather than delegated to save
   221 	 * precious CPU cycles.
   222 	 */
   223 	float curtime = gpGlobals->curtime;
   224 	if (curtime - g_LastTime > 0.1f)
   225 	{
   226 		if (m_CheckingAuth
   227 			&& (gpGlobals->curtime - g_LastAuthCheck > 0.7f))
   228 		{
   229 			g_LastAuthCheck = gpGlobals->curtime;
   230 			g_Players.RunAuthChecks();
   231 		}
   232 		g_LastTime = curtime;
   233 	}
   234 	
   235 	if (g_pOnGameFrame && g_pOnGameFrame->GetFunctionCount())
   236 	{
   237 		g_pOnGameFrame->Execute(NULL);
   238 	}
   239 }
   240 
   241 void SourceModBase::LevelShutdown()
   242 {
   243 	if (m_ExecPluginReload)
   244 	{
   245 		g_PluginSys.ReloadOrUnloadPlugins();
   246 		m_ExecPluginReload = false;
   247 	}
   248 }
   249 
   250 bool SourceModBase::IsMapLoading() const
   251 {
   252 	return m_IsMapLoading;
   253 }
   254 
   255 void SourceModBase::DoGlobalPluginLoads()
   256 {
   257 	char config_path[PLATFORM_MAX_PATH];
   258 	char plugins_path[PLATFORM_MAX_PATH];
   259 
   260 	BuildPath(Path_SM, config_path, 
   261 		sizeof(config_path),
   262 		"configs/plugin_settings.cfg");
   263 	BuildPath(Path_SM, plugins_path,
   264 		sizeof(plugins_path),
   265 		"plugins");
   266 
   267 	/* Load any auto extensions */
   268 	g_Extensions.TryAutoload();
   269 
   270 	/* Run the first pass */
   271 	g_PluginSys.LoadAll_FirstPass(config_path, plugins_path);
   272 
   273 	/* Mark any extensions as loaded */
   274 	g_Extensions.MarkAllLoaded();
   275 
   276 	/* No modules yet, it's safe to call this from here */
   277 	g_PluginSys.LoadAll_SecondPass();
   278 
   279 	/* Re-mark any extensions as loaded */
   280 	g_Extensions.MarkAllLoaded();
   281 }
   282 
   283 size_t SourceModBase::BuildPath(PathType type, char *buffer, size_t maxlength, char *format, ...)
   284 {
   285 	char _buffer[PLATFORM_MAX_PATH+1];
   286 	va_list ap;
   287 
   288 	va_start(ap, format);
   289 	vsnprintf(_buffer, PLATFORM_MAX_PATH, format, ap);
   290 	va_end(ap);
   291 
   292 	const char *base = NULL;
   293 	if (type == Path_Game)
   294 	{
   295 		base = GetModPath();
   296 	} else if (type == Path_SM) {
   297 		base = GetSourceModPath();
   298 	} else if (type == Path_SM_Rel) {
   299 		base = m_SMRelDir;
   300 	}
   301 
   302 	if (base)
   303 	{
   304 		return g_LibSys.PathFormat(buffer, maxlength, "%s/%s", base, _buffer);
   305 	} else {
   306 		return g_LibSys.PathFormat(buffer, maxlength, "%s", _buffer);
   307 	}
   308 }
   309 
   310 void SourceModBase::CloseSourceMod()
   311 {
   312 	if (g_pOnGameFrame)
   313 	{
   314 		g_Forwards.ReleaseForward(g_pOnGameFrame);
   315 	}
   316 
   317 	/* Notify! */
   318 	SMGlobalClass *pBase = SMGlobalClass::head;
   319 	while (pBase)
   320 	{
   321 		pBase->OnSourceModShutdown();
   322 		pBase = pBase->m_pGlobalClassNext;
   323 	}
   324 
   325 	/* Delete all data packs */
   326 	CStack<CDataPack *>::iterator iter;
   327 	CDataPack *pd;
   328 	for (iter=m_freepacks.begin(); iter!=m_freepacks.end(); iter++)
   329 	{
   330 		pd = (*iter);
   331 		delete pd;
   332 	}
   333 	m_freepacks.popall();
   334 
   335 	/* Notify! */
   336 	pBase = SMGlobalClass::head;
   337 	while (pBase)
   338 	{
   339 		pBase->OnSourceModAllShutdown();
   340 		pBase = pBase->m_pGlobalClassNext;
   341 	}
   342 
   343 	if (enginePatch)
   344 	{
   345 		SH_RELEASE_CALLCLASS(enginePatch);
   346 		enginePatch = NULL;
   347 	}
   348 
   349 	if (gamedllPatch)
   350 	{
   351 		SH_RELEASE_CALLCLASS(gamedllPatch);
   352 		gamedllPatch = NULL;
   353 	}
   354 
   355 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   356 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   357 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   358 
   359 	/* Rest In Peace */
   360 	ShutdownJIT();
   361 }
   362 
   363 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   364 {
   365 	IExtensionInterface *pAPI = pExt->GetAPI();
   366 	const char *tag = pAPI->GetExtensionTag();
   367 	char buffer[2048];
   368 	va_list ap;
   369 
   370 	va_start(ap, format);
   371 	vsnprintf(buffer, sizeof(buffer), format, ap);
   372 	va_end(ap);
   373 
   374 	if (tag)
   375 	{
   376 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   377 	} else {
   378 		g_Logger.LogMessage("%s", buffer);
   379 	}
   380 }
   381 
   382 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   383 {
   384 	IExtensionInterface *pAPI = pExt->GetAPI();
   385 	const char *tag = pAPI->GetExtensionTag();
   386 	char buffer[2048];
   387 	va_list ap;
   388 
   389 	va_start(ap, format);
   390 	vsnprintf(buffer, sizeof(buffer), format, ap);
   391 	va_end(ap);
   392 
   393 	if (tag)
   394 	{
   395 		g_Logger.LogError("[%s] %s", tag, buffer);
   396 	} else {
   397 		g_Logger.LogError("%s", buffer);
   398 	}
   399 }
   400 
   401 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   402 {
   403 	char *fmt;
   404 
   405 	pContext->LocalToString(params[param], &fmt);
   406 
   407 	int lparam = ++param;
   408 
   409 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   410 }
   411 
   412 const char *SourceModBase::GetSourceModPath() const
   413 {
   414 	return m_SMBaseDir;
   415 }
   416 
   417 const char *SourceModBase::GetModPath() const
   418 {
   419 	return g_BaseDir.c_str();
   420 }
   421 
   422 void SourceModBase::SetGlobalTarget(unsigned int index)
   423 {
   424 	m_target = index;
   425 }
   426 
   427 void SourceModBase::SetAuthChecking(bool set)
   428 {
   429 	m_CheckingAuth = set;
   430 }
   431 
   432 unsigned int SourceModBase::GetGlobalTarget() const
   433 {
   434 	return m_target;
   435 }
   436 
   437 IDataPack *SourceModBase::CreateDataPack()
   438 {
   439 	CDataPack *pack;
   440 	if (m_freepacks.empty())
   441 	{
   442 		pack = new CDataPack;
   443 	} else {
   444 		pack = m_freepacks.front();
   445 		m_freepacks.pop();
   446 		pack->Initialize();
   447 	}
   448 	return pack;
   449 }
   450 
   451 void SourceModBase::FreeDataPack(IDataPack *pack)
   452 {
   453 	m_freepacks.push(static_cast<CDataPack *>(pack));
   454 }
   455 
   456 Handle_t SourceModBase::GetDataPackHandleType(bool readonly)
   457 {
   458 	//:TODO:
   459 	return 0;
   460 }
   461 
   462 SMGlobalClass *SMGlobalClass::head = NULL;
   463 
   464 SMGlobalClass::SMGlobalClass()
   465 {
   466 	m_pGlobalClassNext = SMGlobalClass::head;
   467 	SMGlobalClass::head = this;
   468 }