core-legacy/sourcemm.cpp
author Scott Ehlert <ds@alliedmods.net>
Sat May 15 18:31:36 2010 -0500 (2010-05-15)
changeset 711 f76a4eb5ee58
parent 689 4065ba5e9155
child 714 966f819588a2
permissions -rw-r--r--
Fixed buildbot upload for OS X with horrible workaround (r=dvander).
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2009 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 "iplayerinfo.h"
    22 #include <filesystem.h>
    23 
    24 using namespace SourceMM;
    25 
    26 /**
    27  * @brief Implementation of main SourceMM GameDLL functionality
    28  * @file sourcemm.cpp
    29  */
    30 
    31 #undef CommandLine
    32 DLL_IMPORT ICommandLine *CommandLine();
    33 
    34 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    35 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    36 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    37 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
    38 
    39 void LevelShutdown_handler();
    40 bool LevelInit_handler(char const *pMapName,
    41 					   char const *pMapEntities,
    42 					   char const *pOldLevel,
    43 					   char const *pLandmarkName,
    44 					   bool loadGame,
    45 					   bool background);
    46 bool GameInit_handler();
    47 int LoadPlugins(const char *filepath, const char *vdfpath);
    48 int LoadVDFPluginsFromDir(const char *dir, int &skipped);
    49 bool KVLoadFromFile(KeyValues *kv,
    50 					IBaseFileSystem *filesystem,
    51 					const char *resourceName,
    52 					const char *pathID = NULL);
    53 
    54 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
    55 EngineInfo g_Engine;
    56 SourceHook::CSourceHookImpl g_SourceHook;
    57 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
    58 SourceHook::String g_ModPath;
    59 SourceHook::String g_MetamodPath;
    60 PluginId g_PLID = Pl_Console;			/* Technically, SourceMM is the "Console" plugin... :p */
    61 static bool bInFirstLevel = true;
    62 bool g_bGameInit = false;
    63 int g_GameDllVersion = 0;
    64 static const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
    65 static const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
    66 static const char GAMEINFO_PATH[] = "|gameinfo_path|";
    67 IFileSystem *baseFs = NULL;
    68 bool g_bLevelChanged = false;
    69 IServerPluginCallbacks *g_pRealVspCallbacks = NULL;
    70 unsigned int g_vsp_version = 0;
    71 
    72 #define ITER_EVENT(evn, args) \
    73 	CPluginManager::CPlugin *pl; \
    74 	SourceHook::List<CPluginEventHandler>::iterator event; \
    75 	IMetamodListener *api; \
    76 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    77 		pl = (*iter); \
    78 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    79 			api = (*event).event; \
    80 			api->evn args; \
    81 		} \
    82 	}
    83 
    84 ///////////////////////////////////
    85 // Main code for HL2 Interaction //
    86 ///////////////////////////////////
    87 
    88 /* Initialize everything here */
    89 void InitMainStates()
    90 {
    91 	/* Like Metamod, reload plugins at the end of the map.
    92 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
    93 	 * if the server is shut down (silly, but rare case).
    94 	 */
    95 	bInFirstLevel = true;
    96 
    97 	char smm_path[PATH_SIZE];
    98 	const char *game_dir = CommandLine()->ParmValue("-game", "hl2");
    99 	abspath(smm_path, game_dir);
   100 	g_ModPath.assign(smm_path);
   101 
   102 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
   103 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
   104 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
   105 }
   106 
   107 void DoInitialPluginLoads()
   108 {
   109 	const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
   110 	const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
   111 
   112 	if (!pluginFile) 
   113 	{
   114 		pluginFile = GetPluginsFile();
   115 	}
   116 	if (!mmBaseDir)
   117 	{
   118 		mmBaseDir = GetMetamodBaseDir();
   119 	}
   120 
   121 	char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   122 
   123 	g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), pluginFile);
   124 	g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), mmBaseDir);
   125 	LoadPlugins(filepath, vdfpath);
   126 }
   127 
   128 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
   129 {
   130 	g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   131 
   132 	if (!g_Engine.engine)
   133 	{
   134 		Error("Could not find IVEngineServer! Metamod cannot load.");
   135 		return false;
   136 	}
   137 	g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
   138 	if (!g_Engine.icvar)
   139 	{
   140 		Error("Could not find ICvar! Metamod cannot load.");
   141 		return false;
   142 	}
   143 
   144 	g_Engine.loaded = true;
   145 
   146 	/* The Ship is the only game known at this time that uses the pre-Episode One engine */
   147 	g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
   148 
   149 	ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   150 
   151 	if (g_GameDll.pGameClients)
   152 	{
   153 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
   154 	}
   155 	else
   156 	{
   157 		/* If IServerGameClients isn't found, this really isn't a fatal error so... */
   158 		LogMessage("[META] Warning: Could not find IServerGameClients!");
   159 		LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
   160 	}
   161 
   162 	if (!g_SmmAPI.CacheCmds())
   163 	{
   164 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   165 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   166 	}
   167 
   168 	g_SmmAPI.CacheUserMessages();
   169 
   170 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   171 	if (baseFs == NULL)
   172 	{
   173 		LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
   174 	}
   175 
   176 	if (!g_SMConVarAccessor.InitConCommandBaseList())
   177 	{
   178 		/* This is very unlikely considering it's old engine */
   179 		LogMessage("[META] Warning: Failed to find ConCommandBase list!");
   180 		LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
   181 	}
   182 
   183 	if (!bWaitForGameInit)
   184 	{
   185 		DoInitialPluginLoads();
   186 		bInFirstLevel = true;
   187 	}
   188 
   189 	return true;
   190 }
   191 
   192 void LoadAsGameDLL(const gamedll_bridge_info *info)
   193 {
   194 	g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
   195 	g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
   196 	g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
   197 	g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
   198 	g_GameDll.loaded = true;
   199 	g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
   200 	g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
   201 	g_GameDllVersion = info->dllVersion;
   202 	g_MetamodPath.assign(info->vsp_listener_path);
   203 
   204 	InitMainStates();
   205 
   206 	StartupMetamod(g_Engine.engineFactory, false);
   207 }
   208 
   209 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
   210 {
   211 	g_Engine.engineFactory = ifaceFactory;
   212 	g_Engine.fileSystemFactory = ifaceFactory;
   213 	g_Engine.physicsFactory = ifaceFactory;
   214 
   215 	IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
   216 	if (playerInfoManager == NULL)
   217 	{
   218 		Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
   219 		return false;
   220 	}
   221 
   222 	g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
   223 
   224 	/* Now find the server */
   225 	g_GameDll.factory = serverFactory;
   226 
   227 	char gamedll_iface[] = "ServerGameDLL000";
   228 	for (unsigned int i = 3; i <= 50; i++)
   229 	{
   230 		gamedll_iface[15] = '0' + i;
   231 		g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
   232 		if (g_GameDll.pGameDLL != NULL)
   233 		{
   234 			g_GameDllVersion = i;
   235 			break;
   236 		}
   237 	}
   238 
   239 	if (g_GameDll.pGameDLL == NULL)
   240 	{
   241 		Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
   242 		return false;
   243 	}
   244 
   245 	char gameclients_iface[] = "ServerGameClients000";
   246 	for (unsigned int i = 3; i <= 4; i++)
   247 	{
   248 		gameclients_iface[19] = '0' + i;
   249 		g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
   250 		if (g_GameDll.pGameClients != NULL)
   251 		{
   252 			break;
   253 		}
   254 	}
   255 
   256 	InitMainStates();
   257 
   258 	if (!StartupMetamod(ifaceFactory, true))
   259 	{
   260 		return false;
   261 	}
   262 
   263 	return true;
   264 }
   265 
   266 bool GameInit_handler()
   267 {
   268 	if (g_bGameInit)
   269 		RETURN_META_VALUE(MRES_IGNORED, true);
   270 
   271 	if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
   272 		g_SmmAPI.LoadAsVSP();
   273 
   274 	if (g_bIsBridgedAsVsp)
   275 	{
   276 		DoInitialPluginLoads();
   277 		g_PluginMngr.SetAllLoaded();
   278 	}
   279 
   280 	g_bGameInit = true;
   281 
   282 	RETURN_META_VALUE(MRES_IGNORED, true);
   283 }
   284 
   285 void UnloadMetamod(bool shutting_down)
   286 {
   287 	/* Unload plugins */
   288 	g_PluginMngr.UnloadAll();
   289 
   290 	if (shutting_down)
   291 	{
   292 		/* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
   293 		g_SMConVarAccessor.MarkCommandsAsGameDLL();
   294 		g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
   295 	}
   296 
   297 	g_SourceHook.CompleteShutdown();
   298 }
   299 
   300 bool LoadFromVDF(const char *file, bool &skipped)
   301 {
   302 	PluginId id;
   303 	bool already, kvfileLoaded;
   304 	KeyValues *pValues;
   305 	const char *plugin_file, *alias;
   306 	char full_path[256], error[256];
   307 	
   308 	pValues = new KeyValues("Metamod Plugin");
   309 
   310 	if (g_Engine.original)
   311 	{
   312 		/* The Ship must use a special version of this function */
   313 		kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
   314 	}
   315 	else
   316 	{
   317 		kvfileLoaded = pValues->LoadFromFile(baseFs, file);
   318 	}
   319 
   320 	if (!kvfileLoaded)
   321 	{
   322 		pValues->deleteThis();
   323 		skipped = false;
   324 		return false;
   325 	}
   326 
   327 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   328 	{
   329 		pValues->deleteThis();
   330 		skipped = false;
   331 		return false;
   332 	}
   333 
   334 	if ((alias = pValues->GetString("alias", NULL)) != NULL)
   335 	{
   336 		g_PluginMngr.SetAlias(alias, plugin_file);
   337 	}
   338 
   339 	/* Attempt to find a file extension */
   340 	if (UTIL_GetExtension(plugin_file) == NULL)
   341 	{
   342 		g_SmmAPI.PathFormat(full_path, 
   343 			sizeof(full_path), 
   344 			"%s/%s%s", 
   345 			g_ModPath.c_str(), 
   346 			plugin_file, 
   347 #if defined WIN32 || defined _WIN32
   348 			".dll"
   349 #else
   350 			"_i486.so"
   351 #endif
   352 			);
   353 	}
   354 	else
   355 	{
   356 		g_SmmAPI.PathFormat(full_path,
   357 			sizeof(full_path),
   358 			"%s/%s", 
   359 			g_ModPath.c_str(),
   360 			plugin_file);
   361 	}
   362 
   363 	id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   364 	skipped = already;
   365 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   366 	{
   367 		LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
   368 		return false;
   369 	}
   370 
   371 	pValues->deleteThis();
   372 	return true;
   373 }
   374 
   375 int LoadVDFPluginsFromDir(const char *dir, int &skipped)
   376 {
   377 	bool success, skip;
   378 	int total = 0;
   379 	char path[MAX_PATH];
   380 
   381 	skipped = 0;
   382 
   383 #if defined _MSC_VER
   384 	HANDLE hFind;
   385 	WIN32_FIND_DATA fd;
   386 	char error[255];
   387 
   388 	g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
   389 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
   390 	{
   391 		DWORD dw = GetLastError();
   392 		if (dw == ERROR_FILE_NOT_FOUND)
   393 			return 0;
   394 
   395 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   396 			NULL,
   397 			dw,
   398 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   399 			error,
   400 			sizeof(error),
   401 			NULL);
   402 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
   403 		return 0;
   404 	}
   405 
   406 	do
   407 	{
   408 		g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
   409 		success = LoadFromVDF(path, skip);
   410 		if (skip)
   411 			skipped++;
   412 		else if (success)
   413 			total++;
   414 	} while (FindNextFile(hFind, &fd));
   415 
   416 	FindClose(hFind);
   417 #else
   418 	DIR *pDir;
   419 	struct dirent *pEnt;
   420 	int extidx;
   421 
   422 	if ((pDir = opendir(dir)) == NULL)
   423 	{
   424 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
   425 		return 0;
   426 	}
   427 
   428 	while ((pEnt = readdir(pDir)) != NULL)
   429 	{
   430 		if (strcmp(pEnt->d_name, ".") == 0
   431 			|| strcmp(pEnt->d_name, "..") == 0)
   432 		{
   433 			continue;
   434 		}
   435 		extidx = strlen(pEnt->d_name) - 4;
   436 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
   437 		{
   438 			continue;
   439 		}
   440 		g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
   441 		success = LoadFromVDF(path, skip);
   442 		if (skip)
   443 			skipped++;
   444 		else if (success)
   445 			total++;
   446 	}
   447 
   448 	closedir(pDir);
   449 #endif
   450 
   451 	return total;
   452 }
   453 
   454 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
   455 {
   456 	Assert(filesystem);
   457 #ifdef _MSC_VER
   458 	Assert(_heapchk() == _HEAPOK);
   459 #endif
   460 
   461 	FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
   462 	if (!f)
   463 		return false;
   464 
   465 	// load file into a null-terminated buffer
   466 	int fileSize = filesystem->Size(f);
   467 	char *buffer = (char *)MemAllocScratch(fileSize + 1);
   468 	
   469 	Assert(buffer);
   470 	
   471 	filesystem->Read(buffer, fileSize, f); // read into local buffer
   472 
   473 	buffer[fileSize] = 0; // null terminate file as EOF
   474 
   475 	filesystem->Close( f );	// close file after reading
   476 
   477 	bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
   478 
   479 	MemFreeScratch();
   480 
   481 	return retOK;
   482 }
   483 
   484 int LoadPluginsFromFile(const char *filepath, int &skipped)
   485 {
   486 	FILE *fp;
   487 	int total = 0;
   488 	PluginId id;
   489 	bool already;
   490 
   491 	skipped = 0;
   492 
   493 	fp = fopen(filepath, "rt");
   494 	if (!fp)
   495 	{
   496 		return 0;
   497 	}
   498 
   499 	char buffer[255], error[255], full_path[PATH_SIZE];
   500 	const char *ptr, *ext, *file;
   501 	size_t length;
   502 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   503 	{
   504 		UTIL_TrimLeft(buffer);
   505 		UTIL_TrimRight(buffer);
   506 
   507 		length = strlen(buffer);
   508 		if (!length)
   509 		{
   510 			continue;
   511 		}
   512 
   513 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   514 		{
   515 			continue;
   516 		}
   517 
   518 		file = buffer;
   519 		if (buffer[0] == '"')
   520 		{
   521 			char *cptr = buffer;
   522 			file = ++cptr;
   523 
   524 			while (*cptr)
   525 			{
   526 				if (*cptr == '"')
   527 				{
   528 					*cptr = '\0';
   529 					break;
   530 				}
   531 				cptr++;
   532 			}
   533 		}
   534 		else
   535 		{
   536 			char *cptr = buffer;
   537 			while (*cptr)
   538 			{
   539 				if (isspace(*cptr))
   540 				{
   541 					char *optr = cptr;
   542 					while (*cptr && isspace(*cptr))
   543 					{
   544 						cptr++;
   545 					}
   546 					*optr = '\0';
   547 					UTIL_TrimRight(cptr);
   548 					if (*cptr && isalpha(*cptr))
   549 					{
   550 						g_PluginMngr.SetAlias(buffer, cptr);
   551 						file = cptr;
   552 					}
   553 					break;
   554 				}
   555 				cptr++;
   556 			}
   557 		}
   558 		if (!file[0])
   559 		{
   560 			continue;
   561 		}
   562 		/* First find if it's an absolute path or not... */
   563 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   564 		{
   565 			/* If we're in an absolute path, ignore our normal heuristics */
   566 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   567 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   568 			{
   569 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   570 			}
   571 			else
   572 			{
   573 				if (already)
   574 				{
   575 					skipped++;
   576 				}
   577 				else
   578 				{
   579 					total++;
   580 				}
   581 			}
   582 		}
   583 		else
   584 		{
   585 			/* Attempt to find a file extension */
   586 			ptr = UTIL_GetExtension(file);
   587 			/* Add an extension if there's none there */
   588 			if (!ptr)
   589 			{
   590 #if defined WIN32 || defined _WIN32
   591 				ext = ".dll";
   592 #else
   593 				ext = "_i486.so";
   594 #endif
   595 			}
   596 			else
   597 			{
   598 				ext = "";
   599 			}
   600 			/* Format the new path */
   601 			g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
   602 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   603 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   604 			{
   605 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   606 			}
   607 			else
   608 			{
   609 				if (already)
   610 				{
   611 					skipped++;
   612 				}
   613 				else
   614 				{
   615 					total++;
   616 				}
   617 			}
   618 		}
   619 	}
   620 	fclose(fp);
   621 
   622 	return total;
   623 }
   624 
   625 int LoadPlugins(const char *filepath, const char *vdfpath)
   626 {
   627 	int total, skipped, fskipped, vskipped;
   628 	const char *s = "";
   629 
   630 	total = LoadPluginsFromFile(filepath, fskipped);
   631 	total += LoadVDFPluginsFromDir(vdfpath, vskipped);
   632 	skipped = fskipped + vskipped;
   633 
   634 	if (total == 0 || total > 1)
   635 		s = "s";
   636 
   637 	if (skipped)
   638 		LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
   639 	else
   640 		LogMessage("[META] Loaded %d plugin%s.", total, s);
   641 
   642 	return total;
   643 }
   644 
   645 void LogMessage(const char *msg, ...)
   646 {
   647 	va_list ap;
   648 	static char buffer[2048];
   649 
   650 	va_start(ap, msg);
   651 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   652 	va_end(ap);
   653 
   654 	buffer[len++] = '\n';
   655 	buffer[len] = '\0';
   656 
   657 	if (!g_Engine.engine)
   658 	{
   659 		fprintf(stdout, "%s", buffer);
   660 	} else {
   661 		g_Engine.engine->LogPrint(buffer);
   662 	}
   663 }
   664 
   665 void LevelShutdown_handler(void)
   666 {
   667 	if (!bInFirstLevel)
   668 	{
   669 		char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
   670 
   671 		g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
   672 		g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
   673 		LoadPlugins(filepath, vdfpath);
   674 	}
   675 	else
   676 	{
   677 		bInFirstLevel = false;
   678 	}
   679 
   680 	g_bLevelChanged = true;
   681 
   682 	ITER_EVENT(OnLevelShutdown, ());
   683 
   684 	RETURN_META(MRES_IGNORED);
   685 }
   686 
   687 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   688 {
   689 	if (!g_SmmAPI.CmdCacheSuccessful())
   690 	{
   691 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   692 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   693 	}
   694 
   695 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   696 
   697 	RETURN_META_VALUE(MRES_IGNORED, false);
   698 }
   699 
   700 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
   701 void * operator new(size_t size) {
   702 	return(calloc(1, size)); 
   703 }
   704 
   705 void * operator new[](size_t size) {
   706 	return(calloc(1, size)); 
   707 }
   708 
   709 void operator delete(void * ptr) {
   710 	if(ptr)
   711 		free(ptr);
   712 }
   713 
   714 void operator delete[](void * ptr) {
   715 	if(ptr)
   716 		free(ptr);
   717 }
   718 #endif