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