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