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