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