core/sourcemod.cpp
author David Anderson <dvander@alliedmods.net>
Thu Feb 08 01:11:45 2007 +0000 (2007-02-08)
changeset 453 7611078f11cd
parent 448 25984ddd0ce0
child 484 d254e257cac2
permissions -rw-r--r--
added gameevents to the publicly available interfaces
     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()
   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 	/* Notify! */
   300 	pBase = SMGlobalClass::head;
   301 	while (pBase)
   302 	{
   303 		pBase->OnSourceModAllShutdown();
   304 		pBase = pBase->m_pGlobalClassNext;
   305 	}
   306 
   307 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, gamedll, this, &SourceModBase::LevelInit, false);
   308 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelShutdown, gamedll, this, &SourceModBase::LevelShutdown, false);
   309 	SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, GameFrame, gamedll, this, &SourceModBase::GameFrame, false);
   310 
   311 	/* Rest In Peace */
   312 	ShutdownJIT();
   313 }
   314 
   315 void SourceModBase::LogMessage(IExtension *pExt, const char *format, ...)
   316 {
   317 	IExtensionInterface *pAPI = pExt->GetAPI();
   318 	const char *tag = pAPI->GetExtensionTag();
   319 	char buffer[2048];
   320 	va_list ap;
   321 
   322 	va_start(ap, format);
   323 	vsnprintf(buffer, sizeof(buffer), format, ap);
   324 	va_end(ap);
   325 
   326 	if (tag)
   327 	{
   328 		g_Logger.LogMessage("[%s] %s", tag, buffer);
   329 	} else {
   330 		g_Logger.LogMessage("%s", buffer);
   331 	}
   332 }
   333 
   334 void SourceModBase::LogError(IExtension *pExt, const char *format, ...)
   335 {
   336 	IExtensionInterface *pAPI = pExt->GetAPI();
   337 	const char *tag = pAPI->GetExtensionTag();
   338 	char buffer[2048];
   339 	va_list ap;
   340 
   341 	va_start(ap, format);
   342 	vsnprintf(buffer, sizeof(buffer), format, ap);
   343 	va_end(ap);
   344 
   345 	if (tag)
   346 	{
   347 		g_Logger.LogError("[%s] %s", tag, buffer);
   348 	} else {
   349 		g_Logger.LogError("%s", buffer);
   350 	}
   351 }
   352 
   353 size_t SourceModBase::FormatString(char *buffer, size_t maxlength, IPluginContext *pContext, const cell_t *params, unsigned int param)
   354 {
   355 	char *fmt;
   356 
   357 	pContext->LocalToString(params[param], &fmt);
   358 
   359 	int lparam = ++param;
   360 
   361 	return atcprintf(buffer, maxlength, fmt, pContext, params, &lparam);
   362 }
   363 
   364 const char *SourceModBase::GetSourceModPath()
   365 {
   366 	return m_SMBaseDir;
   367 }
   368 
   369 const char *SourceModBase::GetModPath()
   370 {
   371 	return g_BaseDir.c_str();
   372 }
   373 
   374 void SourceModBase::SetGlobalTarget(unsigned int index)
   375 {
   376 	m_target = index;
   377 }
   378 
   379 void SourceModBase::SetAuthChecking(bool set)
   380 {
   381 	m_CheckingAuth = set;
   382 }
   383 
   384 unsigned int SourceModBase::GetGlobalTarget() const
   385 {
   386 	return m_target;
   387 }
   388 
   389 SMGlobalClass *SMGlobalClass::head = NULL;
   390 
   391 SMGlobalClass::SMGlobalClass()
   392 {
   393 	m_pGlobalClassNext = SMGlobalClass::head;
   394 	SMGlobalClass::head = this;
   395 }