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