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