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