sourcemm/sourcemm.cpp
author Scott Ehlert <ds@alliedmods.net>
Thu Jul 13 06:08:08 2006 +0000 (2006-07-13)
changeset 216 baece18f381f
parent 215 e3b5d251a9dd
child 224 401c3ea7f8b5
permissions -rw-r--r--
Added some extra information to the "meta game" command: Description and Interface
(This is BAILOPAN's excellent idea!)
     1 /* ======== SourceMM ========
     2 * Copyright (C) 2004-2006 Metamod:Source Development Team
     3 * No warranties of any kind
     4 *
     5 * License: zlib/libpng
     6 *
     7 * Author(s): David "BAILOPAN" Anderson
     8 * Contributor(s): Scott "Damaged Soul" Ehlert
     9 *				: Pavol "PM OnoTo" Marko
    10 * ============================
    11 */
    12 
    13 #include <interface.h>
    14 #include <eiface.h>
    15 #include "sourcemm.h"
    16 #include "concommands.h"
    17 #include "CSmmAPI.h"
    18 #include "CPlugin.h"
    19 #include "util.h"
    20 
    21 using namespace SourceMM;
    22 
    23 /**
    24  * @brief Implementation of main SourceMM GameDLL functionality
    25  * @file sourcemm.cpp
    26  */
    27 
    28 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
    29 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
    30 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    31 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    32 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    33 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    34 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    35 void DLLShutdown_handler();
    36 void LevelShutdown_handler();
    37 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
    38 
    39 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
    40 EngineInfo g_Engine;
    41 SourceHook::CSourceHookImpl g_SourceHook;
    42 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
    43 SourceHook::String g_ModPath;
    44 SourceHook::String g_BinPath;
    45 PluginId g_PLID = Pl_Console;		//Technically, SourceMM is the "Console" plugin... :p
    46 bool bInFirstLevel = true;
    47 bool gParsedGameInfo = false;
    48 SourceHook::List<GameDllInfo *> gamedll_list;
    49 SourceHook::CallClass<IServerGameDLL> *dllExec;
    50 int g_GameDllVersion = 0;
    51 
    52 void ClearGamedllList();
    53 
    54 //helper macro
    55 #define	IFACE_MACRO(orig,nam) \
    56 	CPluginManager::CPlugin *pl; \
    57 	SourceHook::List<IMetamodListener *>::iterator event; \
    58 	IMetamodListener *api; \
    59 	int mret = 0; \
    60 	void *val = NULL; \
    61 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    62 		pl = (*iter); \
    63 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    64 			api = (*event); \
    65 			mret = IFACE_FAILED; \
    66 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
    67 				if (ret) *ret = mret; \
    68 				return val; \
    69 			} \
    70 		} \
    71 	} \
    72 	return (orig)(iface, ret);
    73 
    74 #define ITER_EVENT(evn, args) \
    75 	CPluginManager::CPlugin *pl; \
    76 	SourceHook::List<IMetamodListener *>::iterator event; \
    77 	IMetamodListener *api; \
    78 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    79 		pl = (*iter); \
    80 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    81 			api = (*event); \
    82 			api->evn args; \
    83 		} \
    84 	}
    85 
    86 ///////////////////////////////////
    87 // Main code for HL2 Interaction //
    88 ///////////////////////////////////
    89 
    90 //Initialize everything here
    91 void InitMainStates()
    92 {
    93 	char full_path[260] = {0};
    94 	GetFileOfAddress(g_GameDll.factory, full_path, sizeof(full_path)-1);
    95 	g_BinPath.assign(full_path);
    96 
    97 	//Like metamod, reload plugins at the end of the map.
    98 	//This is so plugins can hook everything on load, BUT, new plugins will be reloaded
    99 	// if the server is shut down (silly, but rare case).
   100 	bInFirstLevel = true;
   101 
   102 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
   103 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
   104 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
   105 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
   106 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
   107 
   108 	if (g_GameDll.pGameClients)
   109 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
   110 	else
   111 	{
   112 		// If IServerGameClients isn't found, this really isn't a fatal error so...
   113 		LogMessage("[META] Warning: Could not find IServerGameClients!");
   114 		LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
   115 	}
   116 }
   117 
   118 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   119 {
   120 	g_Engine.engineFactory = engineFactory;
   121 	g_Engine.fileSystemFactory = filesystemFactory;
   122 	g_Engine.physicsFactory = physicsFactory;
   123 	g_Engine.pGlobals = pGlobals;
   124 
   125 	g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   126 	if (!g_Engine.engine)
   127 	{
   128 		Error("Could not find IVEngineServer! Metamod cannot load.");
   129 		return false;
   130 	}
   131 	g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
   132 	if (!g_Engine.icvar)
   133 	{
   134 		Error("Could not find ICvar! Metamod cannot load.");
   135 		return false;
   136 	}
   137 
   138 	g_Engine.loaded = true;
   139 
   140 	//Initialize our console hooks
   141 	ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   142 
   143 	if (!g_SmmAPI.CacheCmds())
   144 	{
   145 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   146 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   147 	}
   148 
   149 
   150 	const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
   151 	if (!pluginFile) 
   152 		pluginFile = GetPluginsFile();
   153 
   154 	char full_path[260];
   155 	g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s", g_ModPath.c_str(), pluginFile);
   156 
   157 	LoadPluginsFromFile(full_path);
   158 
   159 	bInFirstLevel = true;
   160 
   161 	dllExec = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
   162 
   163 	RETURN_META_VALUE(MRES_IGNORED, true);
   164 }
   165 
   166 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   167 {
   168 	g_PluginMngr.SetAllLoaded();
   169 	RETURN_META_VALUE(MRES_IGNORED, true);
   170 }
   171 
   172 //This is where the magic happens
   173 SMM_API void *CreateInterface(const char *iface, int *ret)
   174 {
   175 	if (!gParsedGameInfo)
   176 	{
   177 		gParsedGameInfo = true;
   178 		char curpath[260] = {0};
   179 		char dllpath[260] = {0};
   180 		getcwd(curpath, sizeof(curpath)-1);
   181 		if (!GetFileOfAddress((void *)CreateInterface, dllpath, sizeof(dllpath)-1))
   182 		{
   183 			Error("GetFileOfAddress() failed! Metamod cannot load.");
   184 			return NULL;
   185 		}
   186 		SourceHook::String s_dllpath(dllpath);
   187 		//begin the heuristics for searching for the mod path (these are quite ugly).
   188 		//for OS compatibility purposes, we're going to do case insensitivity on windows.
   189 		size_t path_len = strlen(curpath);
   190 		size_t dll_len = strlen(dllpath);
   191 
   192 		//strip the dll path off
   193 		//:TODO: with path stuff - in Linux, \ can exist in a file path as a non-seperator!
   194 		for (size_t i=dll_len-1; i>0; i--)
   195 		{
   196 			if (dllpath[i] == '\\' || dllpath[i] == '/')
   197 			{
   198 				if (i == dll_len-1)
   199 					break;
   200 				//save path by stripping off file name and ending terminator
   201 				dllpath[i] = '\0';
   202 				dll_len = i;
   203 				break;
   204 			}
   205 		}
   206 
   207 		//strip absolute path terminators if any!
   208 		if (curpath[path_len-1] == '/' || curpath[path_len-1] == '\\')
   209 			curpath[--path_len] = '\0';
   210 
   211 		//if the base path doesn't fit into the module path, something is wrong!
   212 		// ex: c:\games\srcds
   213 		//     c:\gaben.dll
   214 		if (path_len > dll_len)
   215 		{
   216 			Error("Could not detect GameDLL path! Metamod cannot load[1].");
   217 			return NULL;
   218 		}
   219 
   220 		//we are now in such a position that the two dir names SHOULD MATCH!
   221 		typedef int (*STRNCMP)(const char *str1, const char *str2, size_t n);
   222 		STRNCMP cmp = 
   223 #ifdef WIN32
   224 			strnicmp;
   225 #else
   226 			strncmp;
   227 #endif
   228 		//are they equal?
   229 		if ( ((cmp)(curpath, dllpath, path_len)) != 0 )
   230 		{
   231 			//:TODO: In this case, we should read /proc/self/maps and find srcds!
   232 			Error("Could not detect GameDLL path! Metamod cannot load[2].");
   233 			return NULL;
   234 		}
   235 		//this will skip past the dir and its separator char
   236 		char *ptr = &(dllpath[path_len+1]);
   237 		path_len = strlen(ptr);
   238 		for (size_t i=0; i<path_len; i++)
   239 		{
   240 			if (ptr[i] == '/' || ptr[i] == '\\')
   241 			{
   242 				if (i == 0)
   243 				{
   244 					Error("Could not detect GameDLL path! Metamod cannot load[3].");
   245 					return NULL;
   246 				} else {
   247 					ptr[i] = '\0';
   248 					path_len = i+1;
   249 					break;
   250 				}
   251 			}
   252 		}
   253 		//WE NOW HAVE A GUESS AT THE MOD DIR.  OH MY GOD.
   254 		char temp_path[260];
   255 		snprintf(temp_path, sizeof(temp_path)-1, 
   256 			"%s%s%s", 
   257 			curpath, 
   258 			PATH_SEP_STR, 
   259 			ptr);
   260 
   261 		g_ModPath.assign(temp_path);
   262 
   263 		snprintf(temp_path, sizeof(temp_path)-1, 
   264 			"%s%s%s", 
   265 			g_ModPath.c_str(),
   266 			PATH_SEP_STR,
   267 			"gameinfo.txt");
   268 
   269 		FILE *fp = fopen(temp_path, "rt");
   270 		if (!fp)
   271 		{
   272 			Error("Unable to open gameinfo.txt!  Metamod cannot load.");
   273 			return NULL;
   274 		}
   275 		char buffer[255];
   276 		char key[128], val[128];
   277 		size_t len = 0;
   278 		const char *gameinfo = "|gameinfo_path|";
   279 		size_t gameinfo_len = strlen(gameinfo);
   280 		bool search = false;
   281 		bool gamebin = false;
   282 		const char *lptr;
   283 		while (!feof(fp))
   284 		{
   285 			buffer[0] = '\0';
   286 			fgets(buffer, sizeof(buffer)-1, fp);
   287 			len = strlen(buffer);
   288 			if (buffer[len-1] == '\n')
   289 				buffer[--len] = '\0';
   290 			UTIL_TrimComments(buffer);
   291 			UTIL_TrimLeft(buffer);
   292 			UTIL_TrimRight(buffer);
   293 			if (stricmp(buffer, "SearchPaths") == 0)
   294 				search = true;
   295 			if (!search)
   296 				continue;
   297 			UTIL_KeySplit(buffer, key, sizeof(key)-1, val, sizeof(val)-1);
   298 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   299 			{
   300 				if (stricmp(key, "Game") == 0)
   301 					gamebin = false;
   302 				else
   303 					gamebin = true;
   304 
   305 				if (strncmp(val, gameinfo, gameinfo_len) == 0)
   306 				{
   307 					ptr = &(val[gameinfo_len]);
   308 					if (ptr[0] == '.')
   309 						ptr++;
   310 					lptr = g_ModPath.c_str();
   311 				} else {
   312 					lptr = curpath;
   313 					ptr = val;
   314 				}
   315 				size_t ptr_len = strlen(ptr);
   316 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   317 					ptr[--ptr_len] = '\0';
   318 
   319 				//no need to append "bin"
   320 				if (gamebin)
   321 				{
   322 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   323 				} else if (ptr[0] == NULL) {
   324 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s", lptr, "bin", SERVER_DLL);
   325 				} else {
   326 					g_SmmAPI.PathFormat(temp_path, sizeof(temp_path)-1, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   327 				}
   328 				if (!UTIL_PathCmp(s_dllpath.c_str(), temp_path))
   329 				{
   330 					FILE *fp = fopen(temp_path, "rb");
   331 					if (!fp)
   332 						continue;
   333 					//:TODO: Optimize this a bit!
   334 					SourceHook::List<GameDllInfo *>::iterator iter;
   335 					GameDllInfo *pCheck;
   336 					bool found = false;
   337 					for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   338 					{
   339 						pCheck = (*iter);
   340 						if (GetFileOfAddress(pCheck->factory, buffer, sizeof(buffer)-1))
   341 						{
   342 							if (UTIL_PathCmp(temp_path, buffer))
   343 							{
   344 								found = true;
   345 								break;
   346 							}
   347 						}
   348 					}
   349 					if (found)
   350 						continue;
   351 					fclose(fp);
   352 					HINSTANCE gamedll = dlmount(temp_path);
   353 					if (gamedll == NULL)
   354 						continue;
   355 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   356 					if (fn == NULL)
   357 					{
   358 						dlclose(gamedll);
   359 						continue;
   360 					}
   361 					GameDllInfo *pInfo = new GameDllInfo;
   362 					pInfo->factory = fn;
   363 					pInfo->lib = gamedll;
   364 					pInfo->loaded = true;
   365 					pInfo->pGameDLL = NULL;
   366 					pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
   367 					gamedll_list.push_back(pInfo);
   368 					break;
   369 				}
   370 			}
   371 		}
   372 		fclose(fp);
   373 	}
   374 
   375 	if (!g_GameDll.loaded)
   376 	{
   377 		const char *str = "ServerGameDLL";
   378 		size_t len = strlen(str);
   379 
   380 		if (strncmp(iface, str, len) == 0)
   381 		{
   382 			//This is the interface we want!  Right now we support versions 3 through 5.
   383 			g_GameDllVersion = atoi(&(iface[len]));
   384 			int sizeTooBig = 0;	//rename this to sizeWrong in the future!
   385 			if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
   386 			{
   387 				//maybe this will get used in the future
   388 				sizeTooBig = g_GameDllVersion;
   389 				if (ret)
   390 					*ret = IFACE_FAILED;
   391 			}
   392 			SourceHook::List<GameDllInfo *>::iterator iter;
   393 			GameDllInfo *pInfo = NULL;
   394 			void *ptr;
   395 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   396 			{
   397 				pInfo = (*iter);
   398 				ptr = (pInfo->factory)(iface, ret);
   399 				if (ptr)
   400 				{
   401 					//this is our gamedll.  unload the others.
   402 					gamedll_list.erase(iter);
   403 					ClearGamedllList();
   404 					pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
   405 					g_GameDll = *pInfo;
   406 					delete pInfo;
   407 					break;
   408 				}
   409 			}
   410 			if (g_GameDll.loaded)
   411 			{
   412 				if (sizeTooBig)
   413 				{
   414 					Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!", sizeTooBig);
   415 					if (ret)
   416 						*ret = IFACE_FAILED;
   417 					return NULL;
   418 				} else {
   419 					InitMainStates();
   420 				}
   421 			} else {
   422 				sizeTooBig = 0;
   423 				if (ret)
   424 					*ret = IFACE_FAILED;
   425 				return NULL;
   426 			}
   427 		} else {
   428 			//wtf do we do...
   429 			//:TODO: .. something a bit more intelligent?
   430 			Error("Engine requested unknown interface before GameDLL was known!");
   431 			return NULL;
   432 		}
   433 	}
   434 
   435 	//if we got here, there's definitely a gamedll.
   436 	IFACE_MACRO(g_GameDll.factory, GameDLL);
   437 }
   438 
   439 void ClearGamedllList()
   440 {
   441 	SourceHook::List<GameDllInfo *>::iterator iter;
   442 
   443 	GameDllInfo *pInfo;
   444 	for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   445 	{
   446 		pInfo = (*iter);
   447 		dlclose(pInfo->lib);
   448 		delete pInfo;
   449 	}
   450 
   451 	gamedll_list.clear();
   452 }
   453 
   454 void DLLShutdown_handler()
   455 {
   456 	//Unload plugins
   457 	g_PluginMngr.UnloadAll();
   458 
   459 	// Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly
   460 	g_SMConVarAccessor.MarkCommandsAsGameDLL();
   461 	g_SMConVarAccessor.UnregisterGameDLLCommands();
   462 
   463 	SH_CALL(dllExec, &IServerGameDLL::DLLShutdown)();
   464 
   465 	SH_RELEASE_CALLCLASS(dllExec);
   466 	dllExec = NULL;
   467 
   468 	g_SourceHook.CompleteShutdown();
   469 
   470 	if (g_GameDll.lib && g_GameDll.loaded)
   471 		dlclose(g_GameDll.lib);
   472 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   473 
   474 	RETURN_META(MRES_SUPERCEDE);
   475 }
   476 
   477 int LoadPluginsFromFile(const char *_file)
   478 {
   479 	FILE *fp;
   480 	int total = 0, skipped=0;
   481 	PluginId id;
   482 	bool already;
   483 
   484 	fp = fopen(_file, "rt");
   485 	if (!fp)
   486 	{
   487 		LogMessage("[META] Could not open plugins file %s\n", _file);
   488 		return -1;
   489 	}
   490 
   491 	char buffer[255], error[255], full_path[128];
   492 	const char *ptr, *ext, *file;
   493 	size_t length;
   494 	while (!feof(fp))
   495 	{
   496 		buffer[0] = '\0';
   497 		fgets(buffer, sizeof(buffer)-1, fp);
   498 		length = strlen(buffer);
   499 		if (!length)
   500 			continue;
   501 		if (buffer[length-1] == '\n')
   502 			buffer[--length] = '\0';
   503 
   504 		UTIL_TrimLeft(buffer);
   505 		UTIL_TrimRight(buffer);
   506 
   507 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   508 			continue;
   509 		file = buffer;
   510 		if (buffer[0] == '"')
   511 		{
   512 			char *cptr = buffer;
   513 			file = ++cptr;
   514 
   515 			while (*cptr)
   516 			{
   517 				if (*cptr == '"')
   518 				{
   519 					*cptr = '\0';
   520 					break;
   521 				}
   522 				cptr++;
   523 			}
   524 		} else {
   525 			char *cptr = buffer;
   526 			while (*cptr)
   527 			{
   528 				if (isspace(*cptr))
   529 				{
   530 					char *optr = cptr;
   531 					while (*cptr && isspace(*cptr))
   532 						cptr++;
   533 					*optr = '\0';
   534 					UTIL_TrimRight(cptr);
   535 					if (*cptr && isalpha(*cptr))
   536 					{
   537 						g_PluginMngr.SetAlias(buffer, cptr);
   538 						file = cptr;
   539 					}
   540 					break;
   541 				}
   542 				cptr++;
   543 			}
   544 		}
   545 		if (!file[0])
   546 		{
   547 			continue;
   548 		}
   549 		//First find if it's an absolute path or not...
   550 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   551 		{
   552 			//If we're in an absolute path, ignore our normal heuristics
   553 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error)-1);
   554 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   555 			{
   556 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   557 			} else {
   558 				if (already)
   559 					skipped++;
   560 				else
   561 					total++;
   562 			}
   563 		} else {
   564 			//Attempt to find a file extension
   565 			ptr = UTIL_GetExtension(file);
   566 			//Add an extension if there's none there
   567 			if (!ptr)
   568 			{
   569 #if defined WIN32 || defined _WIN32
   570 				ext = ".dll";
   571 #else
   572 				ext = "_i486.so";
   573 #endif
   574 			} else {
   575 				ext = "";
   576 			}
   577 			//Format the new path
   578 			g_SmmAPI.PathFormat(full_path, sizeof(full_path)-1, "%s/%s%s", g_ModPath.c_str(), file, ext);
   579 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error)-1);
   580 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   581 			{
   582 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   583 			} else {
   584 				if (already)
   585 					skipped++;
   586 				else
   587 					total++;
   588 			}
   589 		}
   590 	}
   591 	fclose(fp);
   592 
   593 	if (skipped)
   594 	{
   595 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   596 	} else {
   597 		LogMessage("[META] Loaded %d plugins from file.", total);
   598 	}
   599 	
   600 	return total;
   601 }
   602 
   603 //Wrapper function.  This is called when the GameDLL thinks it's using
   604 // the engine's real engineFactory.
   605 void *EngineFactory(const char *iface, int *ret)
   606 {
   607 	IFACE_MACRO(g_Engine.engineFactory, Engine);
   608 }
   609 
   610 //Wrapper function.  This is called when the GameDLL thinks it's using
   611 // the engine's real physicsFactory.
   612 void *PhysicsFactory(const char *iface, int *ret)
   613 {
   614 	IFACE_MACRO(g_Engine.physicsFactory, Physics);
   615 }
   616 
   617 //Wrapper function.  This is called when the GameDLL thinks it's using
   618 // the engine's real fileSystemFactory.
   619 void *FileSystemFactory(const char *iface, int *ret)
   620 {
   621 	IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
   622 }
   623 
   624 void LogMessage(const char *msg, ...)
   625 {
   626 	va_list ap;
   627 	static char buffer[2048];
   628 
   629 	buffer[0] = '\0';
   630 
   631 	va_start(ap, msg);
   632 	vsnprintf(buffer, sizeof(buffer)-5, msg, ap);
   633 	strcat(buffer, "\n");
   634 	va_end(ap);
   635 
   636 	if (!g_Engine.engine)
   637 	{
   638 		fprintf(stdout, "%s", buffer);
   639 	} else {
   640 		g_Engine.engine->LogPrint(buffer);
   641 	}
   642 }
   643 
   644 void LevelShutdown_handler(void)
   645 {
   646 	if (!bInFirstLevel)
   647 	{
   648 		char full_path[255];
   649 		g_SmmAPI.PathFormat(full_path, sizeof(full_path) - 1, "%s/%s", g_ModPath.c_str(), GetPluginsFile());
   650 
   651 		LoadPluginsFromFile(full_path);
   652 	} else {
   653 		bInFirstLevel = false;
   654 	}
   655 
   656 	ITER_EVENT(OnLevelShutdown, ());
   657 
   658 	RETURN_META(MRES_IGNORED);
   659 }
   660 
   661 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   662 {
   663 	if (!g_SmmAPI.CacheSuccessful())
   664 	{
   665 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   666 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   667 	}
   668 
   669 #if (defined _DEBUG || defined DEBUG) && (defined OS_WIN32)
   670     SetUnhandledExceptionFilter(NULL);
   671 #endif
   672 
   673 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   674 
   675 	RETURN_META_VALUE(MRES_IGNORED, false);
   676 }
   677 
   678 #if defined __GNUC__ && (__GNUC__ == 3)
   679 void * ::operator new(size_t size) {
   680 	return(calloc(1, size)); 
   681 }
   682 
   683 void * ::operator new[](size_t size) {
   684 	return(calloc(1, size)); 
   685 }
   686 
   687 void ::operator delete(void * ptr) {
   688 	if(ptr)
   689 		free(ptr);
   690 }
   691 
   692 void ::operator delete[](void * ptr) {
   693 	if(ptr)
   694 		free(ptr);
   695 }
   696 #endif