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