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