sourcemm/metamod.cpp
author Scott Ehlert <ds@alliedmods.net>
Wed Mar 26 05:06:33 2008 +0000 (2008-03-26)
changeset 521 001607389c25
parent 516 2be030bc9c66
child 523 6f1630519b81
permissions -rw-r--r--
Fixed amb1534 - VDF files with a ".vdf" that wasn't at the very end of the filename were being opened by MM:S. This was due to the use of strstr.
     1 /**
     2  * vim: set ts=4 :
     3  * ======================================================
     4  * Metamod:Source
     5  * Copyright (C) 2004-2007 AlliedModders LLC and authors.
     6  * All rights reserved.
     7  * ======================================================
     8  *
     9  * This software is provided 'as-is', without any express or implied warranty.
    10  * In no event will the authors be held liable for any damages arising from 
    11  * the use of this software.
    12  * 
    13  * Permission is granted to anyone to use this software for any purpose, 
    14  * including commercial applications, and to alter it and redistribute it 
    15  * freely, subject to the following restrictions:
    16  *
    17  * 1. The origin of this software must not be misrepresented; you must not 
    18  * claim that you wrote the original software. If you use this software in a 
    19  * product, an acknowledgment in the product documentation would be 
    20  * appreciated but is not required.
    21  * 2. Altered source versions must be plainly marked as such, and must not be
    22  * misrepresented as being the original software.
    23  * 3. This notice may not be removed or altered from any source distribution.
    24  *
    25  * Version: $Id$
    26  */
    27 
    28 #include "metamod_oslink.h"
    29 #include "metamod.h"
    30 #include <interface.h>
    31 #include <eiface.h>
    32 #include "metamod_provider.h"
    33 #include "metamod_plugins.h"
    34 #include "metamod_util.h"
    35 #include "metamod_console.h"
    36 
    37 using namespace SourceMM;
    38 using namespace SourceHook;
    39 using namespace SourceHook::Impl;
    40 
    41 /**
    42  * @brief Implementation of main SourceMM GameDLL functionality
    43  * @file sourcemm.cpp
    44  */
    45 
    46 SH_DECL_MANUALHOOK4(SGD_DLLInit, 0, 0, 0, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
    47 SH_DECL_MANUALHOOK0(SGD_GameInit, 0, 0, 0, bool);
    48 SH_DECL_MANUALHOOK6(SGD_LevelInit, 0, 0, 0, bool, const char *, const char *, const char *, const char *, bool, bool);
    49 SH_DECL_MANUALHOOK0_void(SGD_LevelShutdown, 0, 0, 0);
    50 SH_DECL_MANUALHOOK0_void(SGD_DLLShutdown, 0, 0, 0);
    51 
    52 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    53 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    54 void Handler_DLLShutdown();
    55 void Handler_LevelShutdown();
    56 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
    57 bool Handler_GameInit();
    58 void InitializeVSP();
    59 void LookForVDFs(const char *dir);
    60 
    61 struct game_dll_t
    62 {
    63 	HINSTANCE lib;
    64 	CreateInterfaceFn factory;
    65 };
    66 
    67 String mod_path;
    68 String metamod_path;
    69 String full_bin_path;
    70 bool parsed_game_info = false;
    71 int vsp_version = 0;
    72 int gamedll_version = 0;
    73 int engine_build = SOURCE_ENGINE_UNKNOWN;
    74 List<game_dll_t *> gamedll_list;
    75 bool is_gamedll_loaded = false;
    76 bool in_first_level = true;
    77 bool is_game_init = false;
    78 bool vsp_load_attempted = false;
    79 bool vsp_load_requested = false;
    80 bool vsp_loaded = false;
    81 game_dll_t gamedll_info;
    82 ConVar *metamod_version = NULL;
    83 ConVar *mm_pluginsfile = NULL;
    84 ConVar *mm_basedir = NULL;
    85 IServerGameDLL *server = NULL;
    86 CreateInterfaceFn engine_factory = NULL;
    87 CreateInterfaceFn physics_factory = NULL;
    88 CreateInterfaceFn filesystem_factory = NULL;
    89 CGlobalVars *gpGlobals = NULL;
    90 CSourceHookImpl g_SourceHook;
    91 CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
    92 ISourceHook *g_SHPtr = &g_SourceHook;
    93 PluginId g_PLID = Pl_Console;
    94 META_RES last_meta_res;
    95 IServerPluginCallbacks *vsp_callbacks = NULL;
    96 bool were_plugins_loaded = false;
    97 
    98 MetamodSource g_Metamod;
    99 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
   100 
   101 void ClearGamedllList();
   102 
   103 /* Helper Macro */
   104 #define	IFACE_MACRO(orig,nam) \
   105 	CPluginManager::CPlugin *pl; \
   106 	SourceHook::List<IMetamodListener *>::iterator event; \
   107 	IMetamodListener *api; \
   108 	int mret = 0; \
   109 	void *val = NULL; \
   110 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   111 		pl = (*iter); \
   112 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   113 			api = (*event); \
   114 			mret = IFACE_FAILED; \
   115 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
   116 				if (ret) *ret = mret; \
   117 				return val; \
   118 			} \
   119 		} \
   120 	} \
   121 	return (orig)(iface, ret);
   122 
   123 #define ITER_EVENT(evn, args) \
   124 	CPluginManager::CPlugin *pl; \
   125 	SourceHook::List<IMetamodListener *>::iterator event; \
   126 	IMetamodListener *api; \
   127 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   128 		pl = (*iter); \
   129 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   130 			api = (*event); \
   131 			api->evn args; \
   132 		} \
   133 	}
   134 
   135 /* Initialize everything here */
   136 void InitializeForLoad()
   137 {
   138 	char full_path[PATH_SIZE] = {0};
   139 	GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
   140 	full_bin_path.assign(full_path);
   141 
   142 	/* Like Metamod, reload plugins at the end of the map.
   143 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   144 	 * if the server is shut down (silly, but rare case).
   145 	 */
   146 	in_first_level = true;
   147 
   148 	SourceHook::MemFuncInfo info;
   149 
   150 	if (!provider->GetHookInfo(ProvidedHook_DLLInit, &info))
   151 	{
   152 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLInit");
   153 	}
   154 	SH_MANUALHOOK_RECONFIGURE(SGD_DLLInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   155 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit, false);
   156 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit_Post, true);
   157 
   158 	if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
   159 	{
   160 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
   161 	}
   162 	SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   163 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
   164 
   165 	if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
   166 	{
   167 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
   168 	}
   169 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   170 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
   171 
   172 	if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
   173 	{
   174 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
   175 	}
   176 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
   177 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
   178 
   179 	if (!provider->GetHookInfo(ProvidedHook_DLLShutdown, &info))
   180 	{
   181 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLShutdown");
   182 	}
   183 	SH_MANUALHOOK_RECONFIGURE(SGD_DLLShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
   184 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLShutdown, server, Handler_DLLShutdown, false);
   185 }
   186 
   187 bool DetectGameInformation()
   188 {
   189 	char mm_path[PATH_SIZE];
   190 	char game_path[PATH_SIZE];
   191 
   192 	/* Get path to SourceMM DLL */
   193 	if (!GetFileOfAddress((void *)InitializeForLoad, mm_path, sizeof(mm_path)))
   194 	{
   195 		return false;
   196 	}
   197 
   198 	metamod_path.assign(mm_path);
   199 
   200 	/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   201 	const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
   202 
   203 	/* Get absolute path */
   204 	abspath(game_path, game_dir);
   205 	mod_path.assign(game_path);
   206 
   207 	engine_build = provider->DetermineSourceEngine(game_dir);;
   208 
   209 	return true;
   210 }
   211 
   212 /* This is where the magic happens */
   213 SMM_API void *CreateInterface(const char *iface, int *ret)
   214 {
   215 	/* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
   216 	if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
   217 	{
   218 		provider->DisplayWarning("Do not try loading Metamod:Source as a plugin.\n");
   219 
   220 		if (ret)
   221 		{
   222 			*ret = IFACE_FAILED;
   223 		}
   224 
   225 		return NULL;
   226 	}
   227 
   228 	if (strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
   229 	{
   230 		vsp_callbacks = provider->GetVSPCallbacks(iface);
   231 
   232 		if (vsp_callbacks != NULL && vsp_version == 0)
   233 		{
   234 			vsp_version = atoi(&iface[22]);
   235 		}
   236 
   237 		if (ret)
   238 		{
   239 			*ret = (vsp_callbacks != NULL) ? IFACE_OK : IFACE_FAILED;
   240 		}
   241 
   242 		return vsp_callbacks;
   243 	}
   244 
   245 	if (provider->IsAlternatelyLoaded())
   246 	{
   247 		IFACE_MACRO(gamedll_info.factory, GameDLL);
   248 	}
   249 
   250 	if (!parsed_game_info)
   251 	{
   252 		parsed_game_info = true;
   253 
   254 		if (!DetectGameInformation())
   255 		{
   256 			provider->DisplayError("GetFileOfAddress() failed! Metamod cannot load.\n");
   257 			return NULL;
   258 		}
   259 
   260 		char temp_path[PATH_SIZE];
   261 
   262 		/* Path to gameinfo.txt */
   263 		g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s", mod_path.c_str(), "gameinfo.txt");
   264 
   265 		FILE *fp = fopen(temp_path, "rt");
   266 
   267 		if (!fp)
   268 		{
   269 			provider->DisplayError("Unable to open gameinfo.txt!  Metamod cannot load.\n");
   270 			return NULL;
   271 		}
   272 
   273 		char buffer[255];
   274 		char key[128], val[128];
   275 		bool search = false;
   276 		bool gamebin = false;
   277 		char *ptr;
   278 		const char *lptr;
   279 		char cur_path[PATH_SIZE];
   280 
   281 		getcwd(cur_path, PATH_SIZE);
   282 
   283 		while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   284 		{
   285 			UTIL_TrimComments(buffer);
   286 			UTIL_TrimLeft(buffer);
   287 			UTIL_TrimRight(buffer);
   288 
   289 			if (stricmp(buffer, "SearchPaths") == 0)
   290 			{
   291 				search = true;
   292 			}
   293 
   294 			if (!search)
   295 			{
   296 				continue;
   297 			}
   298 
   299 			UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   300 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   301 			{
   302 				if (stricmp(key, "Game") == 0)
   303 				{
   304 					gamebin = false;
   305 				}
   306 				else
   307 				{
   308 					gamebin = true;
   309 				}
   310 
   311 				if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
   312 				{
   313 					ptr = &(val[sizeof("|gameinfo_path|") - 1]);
   314 					if (ptr[0] == '.')
   315 					{
   316 						ptr++;
   317 					}
   318 					lptr = mod_path.c_str();
   319 				} else {
   320 					ptr = val;
   321 					lptr = cur_path;
   322 				}
   323 
   324 				size_t ptr_len = strlen(ptr);
   325 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   326 				{
   327 					ptr[--ptr_len] = '\0';
   328 				}
   329 
   330 				/* No need to append "bin" if key is GameBin */
   331 				if (gamebin)
   332 				{
   333 					g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   334 				}
   335 				else if (!ptr[0])
   336 				{
   337 					g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
   338 				}
   339 				else
   340 				{
   341 					g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   342 				}
   343 
   344 				/* If not path to SourceMM... */
   345 				if (!UTIL_PathCmp(metamod_path.c_str(), temp_path))
   346 				{
   347 					FILE *temp_fp = fopen(temp_path, "rb");
   348 					if (!temp_fp)
   349 					{
   350 						continue;
   351 					}
   352 					fclose(temp_fp);
   353 
   354 					/* Search for a matching game dll */
   355 					List<game_dll_t *>::iterator iter;
   356 					game_dll_t *pCheck;
   357 					bool found = false;
   358 					for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
   359 					{
   360 						pCheck = (*iter);
   361 						if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
   362 						{
   363 							if (UTIL_PathCmp(temp_path, buffer))
   364 							{
   365 								found = true;
   366 								break;
   367 							}
   368 						}
   369 					}
   370 
   371 					if (found)
   372 					{
   373 						continue;
   374 					}
   375 					
   376 					HINSTANCE gamedll = dlmount(temp_path);
   377 					if (gamedll == NULL)
   378 					{
   379 						continue;
   380 					}
   381 
   382 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   383 					if (fn == NULL)
   384 					{
   385 						dlclose(gamedll);
   386 						continue;
   387 					}
   388 
   389 					game_dll_t *pInfo = new game_dll_t;
   390 					pInfo->factory = fn;
   391 					pInfo->lib = gamedll;
   392 					gamedll_list.push_back(pInfo);
   393 					break;
   394 				}
   395 			}
   396 		}
   397 		fclose(fp);
   398 	}
   399 
   400 	if (!is_gamedll_loaded)
   401 	{
   402 		if (strncmp(iface, "ServerGameDLL", 13) == 0)
   403 		{
   404 			List<game_dll_t *>::iterator iter;
   405 			game_dll_t *pInfo;
   406 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   407 			{
   408 				pInfo = (*iter);
   409 				if ((server = (IServerGameDLL *)((pInfo->factory)(iface, ret))) != NULL)
   410 				{
   411 					if ((gamedll_version = provider->TryServerGameDLL(iface)) != 0)
   412 					{
   413 						/* We have a match.  Erase us from the list and save our info. */
   414 						gamedll_list.erase(iter);
   415 						gamedll_info = *pInfo;
   416 						delete pInfo;
   417 						is_gamedll_loaded = true;
   418 						break;
   419 					}
   420 					/* :TODO: error otherwise? */
   421 				}
   422 			}
   423 
   424 			if (is_gamedll_loaded)
   425 			{
   426 				ClearGamedllList();
   427 				InitializeForLoad();
   428 			}
   429 			else
   430 			{
   431 				if (ret)
   432 				{
   433 					*ret = IFACE_FAILED;
   434 				}
   435 				return NULL;
   436 			}
   437 		}
   438 		else
   439 		{
   440 			/* wtf do we do... */
   441 			/* :TODO: .. something a bit more intelligent? */
   442 			provider->DisplayError("Engine requested unknown interface before GameDLL was known!\n");
   443 			return NULL;
   444 		}
   445 	}
   446 
   447 	/* If we got here, there's definitely a GameDLL */
   448 	IFACE_MACRO(gamedll_info.factory, GameDLL);
   449 }
   450 
   451 void ClearGamedllList()
   452 {
   453 	List<game_dll_t *>::iterator iter;
   454 
   455 	game_dll_t *pInfo;
   456 	for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
   457 	{
   458 		pInfo = (*iter);
   459 		dlclose(pInfo->lib);
   460 		delete pInfo;
   461 	}
   462 
   463 	gamedll_list.clear();
   464 }
   465 
   466 int LoadPluginsFromFile(const char *_file)
   467 {
   468 	FILE *fp;
   469 	int total = 0, skipped=0;
   470 	PluginId id;
   471 	bool already;
   472 
   473 	fp = fopen(_file, "rt");
   474 	if (!fp)
   475 	{
   476 		LogMessage("[META] Could not open plugins file %s\n", _file);
   477 		return -1;
   478 	}
   479 
   480 	char buffer[255], error[255], full_path[255];
   481 	const char *ptr, *ext, *file;
   482 	size_t length;
   483 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   484 	{
   485 		UTIL_TrimLeft(buffer);
   486 		UTIL_TrimRight(buffer);
   487 
   488 		length = strlen(buffer);
   489 		if (!length)
   490 		{
   491 			continue;
   492 		}
   493 
   494 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   495 		{
   496 			continue;
   497 		}
   498 
   499 		file = buffer;
   500 		if (buffer[0] == '"')
   501 		{
   502 			char *cptr = buffer;
   503 			file = ++cptr;
   504 
   505 			while (*cptr)
   506 			{
   507 				if (*cptr == '"')
   508 				{
   509 					*cptr = '\0';
   510 					break;
   511 				}
   512 				cptr++;
   513 			}
   514 		}
   515 		else
   516 		{
   517 			char *cptr = buffer;
   518 			while (*cptr)
   519 			{
   520 				if (isspace(*cptr))
   521 				{
   522 					char *optr = cptr;
   523 					while (*cptr && isspace(*cptr))
   524 					{
   525 						cptr++;
   526 					}
   527 					*optr = '\0';
   528 					UTIL_TrimRight(cptr);
   529 					if (*cptr && isalpha(*cptr))
   530 					{
   531 						g_PluginMngr.SetAlias(buffer, cptr);
   532 						file = cptr;
   533 					}
   534 					break;
   535 				}
   536 				cptr++;
   537 			}
   538 		}
   539 		if (!file[0])
   540 		{
   541 			continue;
   542 		}
   543 		/* First find if it's an absolute path or not... */
   544 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   545 		{
   546 			/* If we're in an absolute path, ignore our normal heuristics */
   547 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   548 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   549 			{
   550 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   551 			}
   552 			else
   553 			{
   554 				if (already)
   555 				{
   556 					skipped++;
   557 				}
   558 				else
   559 				{
   560 					total++;
   561 				}
   562 			}
   563 		}
   564 		else
   565 		{
   566 			/* Attempt to find a file extension */
   567 			ptr = UTIL_GetExtension(file);
   568 			/* Add an extension if there's none there */
   569 			if (!ptr)
   570 			{
   571 #if defined WIN32 || defined _WIN32
   572 				ext = ".dll";
   573 #else
   574 				ext = "_i486.so";
   575 #endif
   576 			}
   577 			else
   578 			{
   579 				ext = "";
   580 			}
   581 			/* Format the new path */
   582 			g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
   583 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   584 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   585 			{
   586 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   587 			}
   588 			else
   589 			{
   590 				if (already)
   591 				{
   592 					skipped++;
   593 				}
   594 				else
   595 				{
   596 					total++;
   597 				}
   598 			}
   599 		}
   600 	}
   601 	fclose(fp);
   602 
   603 	if (skipped)
   604 	{
   605 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   606 	}
   607 	else
   608 	{
   609 		LogMessage("[META] Loaded %d plugins from file.", total);
   610 	}
   611 	
   612 	return total;
   613 }
   614 
   615 void InitializeVSP()
   616 {
   617 	if (provider->IsAlternatelyLoaded())
   618 	{
   619 		return;
   620 	}
   621 
   622 	size_t len;
   623 	char engine_file[PATH_SIZE];
   624 	char engine_path[PATH_SIZE];
   625 	char rel_path[PATH_SIZE * 2];
   626 
   627 	GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
   628 
   629 	/* Chop off the "engine" file part */
   630 	len = strlen(engine_file);
   631 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   632 	{
   633 		if (engine_file[i] == '/' || engine_file[i] == '\\')
   634 		{
   635 			engine_file[i] = '\0';
   636 			break;
   637 		}
   638 	}
   639 	abspath(engine_path, engine_file);
   640 
   641 	const char *usepath = metamod_path.c_str();
   642 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
   643 	{
   644 		usepath = rel_path;
   645 	}
   646 
   647 	char command[PATH_SIZE * 2];
   648 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   649 	provider->ServerCommand(command);
   650 }
   651 
   652 /* Wrapper function.  This is called when the GameDLL thinks it's using
   653  * the engine's real engineFactory.
   654  */
   655 void *EngineFactory(const char *iface, int *ret)
   656 {
   657 	IFACE_MACRO(engine_factory, Engine);
   658 }
   659 
   660 /* Wrapper function.  This is called when the GameDLL thinks it's using
   661  * the engine's real physicsFactory.
   662  */
   663 void *PhysicsFactory(const char *iface, int *ret)
   664 {
   665 	IFACE_MACRO(physics_factory, Physics);
   666 }
   667 
   668 /* Wrapper function.  This is called when the GameDLL thinks it's using
   669  * the engine's real fileSystemFactory.
   670  */
   671 void *FileSystemFactory(const char *iface, int *ret)
   672 {
   673 	IFACE_MACRO(filesystem_factory, FileSystem);
   674 }
   675 
   676 void LogMessage(const char *msg, ...)
   677 {
   678 	va_list ap;
   679 	static char buffer[2048];
   680 
   681 	va_start(ap, msg);
   682 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   683 	va_end(ap);
   684 
   685 	buffer[len++] = '\n';
   686 	buffer[len] = '\0';
   687 
   688 	if (!provider->LogMessage(buffer))
   689 	{
   690 		fprintf(stdout, "%s", buffer);
   691 	}
   692 }
   693 
   694 void DoInitialPluginLoads()
   695 {
   696 	const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
   697 	const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
   698 	if (!pluginFile) 
   699 	{
   700 		pluginFile = provider->GetConVarString(mm_pluginsfile);
   701 		if (pluginFile == NULL)
   702 		{
   703 			pluginFile = "addons/metamod/metaplugins.ini";
   704 		}
   705 	}
   706 	if (!mmBaseDir)
   707 	{
   708 		mmBaseDir = provider->GetConVarString(mm_basedir);
   709 		if (mmBaseDir == NULL)
   710 		{
   711 			mmBaseDir = "addons/metamod";
   712 		}
   713 	}
   714 
   715 	char full_path[260];
   716 
   717 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
   718 	LoadPluginsFromFile(full_path);
   719 
   720 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
   721 	LookForVDFs(full_path);
   722 }
   723 
   724 void StartupMetamod(bool is_vsp_load)
   725 {
   726 	char buffer[255];
   727 
   728 	UTIL_Format(buffer,
   729 		sizeof(buffer),
   730 		"%s%s",
   731 		SOURCEMM_VERSION,
   732 		is_vsp_load ? "V" : "");
   733 
   734 	metamod_version = provider->CreateConVar("metamod_version", 
   735 		SOURCEMM_VERSION, 
   736 		"Metamod:Source Version",
   737 		ConVarFlag_Notify|ConVarFlag_SpOnly);
   738 
   739 	provider->SetConVarString(metamod_version, buffer);
   740 
   741 	mm_pluginsfile = provider->CreateConVar("mm_pluginsfile", 
   742 #if defined WIN32 || defined _WIN32
   743 		"addons\\metamod\\metaplugins.ini", 
   744 #else
   745 		"addons/metamod/metaplugins.ini",
   746 #endif
   747 		"Metamod:Source Plugins File",
   748 		ConVarFlag_SpOnly);
   749 
   750 	mm_basedir = provider->CreateConVar("mm_basedir",
   751 #if defined __linux__
   752 		"addons/metamod",
   753 #else
   754 		"addons\\metamod",
   755 #endif
   756 		"Metamod:Source Base Folder",
   757 		ConVarFlag_SpOnly);
   758 
   759 	if (!is_vsp_load)
   760 	{
   761 		DoInitialPluginLoads();
   762 		in_first_level = true;
   763 	}
   764 }
   765 
   766 void InitializeGlobals(CreateInterfaceFn engineFactory, 
   767 					   CreateInterfaceFn physicsFactory,
   768 					   CreateInterfaceFn filesystemFactory,
   769 					   CGlobalVars *pGlobals)
   770 {
   771 	engine_factory = engineFactory;
   772 	physics_factory = physicsFactory;
   773 	filesystem_factory = filesystemFactory;
   774 	gpGlobals = pGlobals;
   775 	provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
   776 }
   777 
   778 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   779 {
   780 	InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
   781 	StartupMetamod(false);
   782 
   783 	RETURN_META_VALUE(MRES_IGNORED, true);
   784 }
   785 
   786 bool Handler_GameInit()
   787 {
   788 	if (is_game_init)
   789 	{
   790 		return true;
   791 	}
   792 
   793 	if (vsp_load_requested)
   794 	{
   795 		InitializeVSP();
   796 	}
   797 
   798 	if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
   799 	{
   800 		DoInitialPluginLoads();
   801 		g_PluginMngr.SetAllLoaded();
   802 		were_plugins_loaded = true;
   803 	}
   804 
   805 	is_game_init = true;
   806 
   807 	RETURN_META_VALUE(MRES_IGNORED, true);
   808 }
   809 
   810 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   811 {
   812 	g_PluginMngr.SetAllLoaded();
   813 	RETURN_META_VALUE(MRES_IGNORED, true);
   814 }
   815 
   816 void UnloadMetamod()
   817 {
   818 	/* Unload plugins */
   819 	g_PluginMngr.UnloadAll();
   820 
   821 	provider->Notify_DLLShutdown_Pre();
   822 
   823 	if (is_gamedll_loaded)
   824 	{
   825 		SH_CALL(server, &IServerGameDLL::DLLShutdown)();
   826 	}
   827 
   828 	g_SourceHook.CompleteShutdown();
   829 
   830 	if (is_gamedll_loaded && gamedll_info.lib)
   831 	{
   832 		dlclose(gamedll_info.lib);
   833 		is_gamedll_loaded = false;
   834 	}
   835 }
   836 
   837 void Handler_DLLShutdown()
   838 {
   839 	UnloadMetamod();
   840 	RETURN_META(MRES_SUPERCEDE);
   841 }
   842 
   843 void Handler_LevelShutdown(void)
   844 {
   845 	if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
   846 	{
   847 		g_PluginMngr.SetAllLoaded();
   848 		DoInitialPluginLoads();
   849 		were_plugins_loaded = true;
   850 		in_first_level = true;
   851 	}
   852 
   853 	if (!in_first_level)
   854 	{
   855 		char full_path[255];
   856 
   857 		g_Metamod.PathFormat(full_path, 
   858 			sizeof(full_path), 
   859 			"%s/%s", 
   860 			mod_path.c_str(),
   861 			provider->GetConVarString(mm_pluginsfile));
   862 		LoadPluginsFromFile(full_path);
   863 
   864 		g_Metamod.PathFormat(full_path,
   865 			sizeof(full_path),
   866 			"%s/%s",
   867 			mod_path.c_str(),
   868 			provider->GetConVarString(mm_basedir));
   869 		LookForVDFs(full_path);
   870 	}
   871 	else
   872 	{
   873 		in_first_level = false;
   874 	}
   875 
   876 	ITER_EVENT(OnLevelShutdown, ());
   877 
   878 	RETURN_META(MRES_IGNORED);
   879 }
   880 
   881 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
   882 {
   883 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   884 
   885 	RETURN_META_VALUE(MRES_IGNORED, false);
   886 }
   887 
   888 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
   889 {
   890 	va_list ap;
   891 	char buffer[2048];
   892 	
   893 	va_start(ap, msg);
   894 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
   895 	va_end(ap);
   896 
   897 	LogMessage("[%s] %s", pl->GetLogTag(), buffer);
   898 }
   899 
   900 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
   901 {
   902 	if (syn)
   903 	{
   904 		return EngineFactory;
   905 	}
   906 
   907 	return engine_factory;
   908 }
   909 
   910 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
   911 {
   912 	if (syn)
   913 	{
   914 		return PhysicsFactory;
   915 	}
   916 
   917 	return physics_factory;
   918 }
   919 
   920 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
   921 {
   922 	if (syn)
   923 	{
   924 		return FileSystemFactory;
   925 	}
   926 
   927 	return filesystem_factory;
   928 }
   929 
   930 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
   931 {
   932 	if (syn)
   933 	{
   934 		return CreateInterface;
   935 	}
   936 
   937 	return gamedll_info.factory;
   938 }
   939 
   940 CGlobalVars *MetamodSource::GetCGlobals()
   941 {
   942 	return gpGlobals;
   943 }
   944 
   945 void MetamodSource::SetLastMetaReturn(META_RES res)
   946 {
   947 	last_meta_res = res;
   948 }
   949 
   950 META_RES MetamodSource::GetLastMetaReturn()
   951 {
   952 	return last_meta_res;
   953 }
   954 
   955 void MetamodSource::ConPrint(const char *str)
   956 {
   957 	provider->ConsolePrint(str);
   958 }
   959 
   960 void MetamodSource::ConPrintf(const char *fmt, ...)
   961 {
   962 	va_list ap;
   963 	char buffer[2048];
   964 
   965 	va_start(ap, fmt);
   966 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   967 	va_end(ap);
   968 
   969 	provider->ConsolePrint(buffer);
   970 }
   971 
   972 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   973 {
   974 	major = METAMOD_API_MAJOR;
   975 	minor = METAMOD_API_MINOR;
   976 	plvers = METAMOD_PLAPI_VERSION;
   977 	plmin = PLAPI_MIN_VERSION;
   978 }
   979 
   980 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
   981 {
   982 	shvers = SH_IFACE_VERSION;
   983 	shimpl = SH_IMPL_VERSION;
   984 }
   985 
   986 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
   987 {
   988 	int length = (int)strlen(iface);
   989 	int i;
   990 	int num = 0;
   991 
   992 	for (i = length - 1; i >= 0; i--)
   993 	{
   994 		if (!isdigit(iface[i]))
   995 		{
   996 			if (i != length - 1)
   997 			{
   998 				num = 1;
   999 			}
  1000 			break;
  1001 		}
  1002 	}
  1003 
  1004 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
  1005 	{
  1006 		return -1;
  1007 	}
  1008 
  1009 	if (i != length - 1)
  1010 	{
  1011 		num = atoi(&(iface[++i]));
  1012 	}
  1013 
  1014 	num++;
  1015 
  1016 	snprintf(&(iface[i]), 4, "%03d", num);
  1017 
  1018 	return num;
  1019 }
  1020 
  1021 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
  1022 {
  1023 	char _if[256];	/* assume no interface goes beyond this */
  1024 	size_t len = strlen(iface);
  1025 	int num = 0;
  1026 	void *pf = NULL;
  1027 
  1028 	if (max > 999)
  1029 	{
  1030 		max = 999;
  1031 	}
  1032 
  1033 	if (len + 4 > sizeof(_if))
  1034 	{
  1035 		if (ret)
  1036 		{
  1037 			*ret = IFACE_FAILED;
  1038 		}
  1039 		return NULL;
  1040 	}
  1041 
  1042 	strcpy(_if, iface);
  1043 
  1044 	do
  1045 	{
  1046 		if ((pf = (fn)(_if, ret)) != NULL)
  1047 		{
  1048 			break;
  1049 		}
  1050 		if (num > max)
  1051 		{
  1052 			break;
  1053 		}
  1054 	} while ((num = FormatIface(_if, len+1)));
  1055 
  1056 	return pf;
  1057 }
  1058 
  1059 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
  1060 {
  1061 	char buffer[256];	/* assume no interface will go beyond this */
  1062 	size_t len = strlen(iface);
  1063 	int ret;			/* just in case something doesn't handle NULL properly */
  1064 
  1065 	if (len > sizeof(buffer) - 4)
  1066 	{
  1067 		return NULL;
  1068 	}
  1069 
  1070 	strcpy(buffer, iface);
  1071 
  1072 	if (min != -1)
  1073 	{
  1074 		char *ptr = &buffer[len - 1];
  1075 		int digits = 0;
  1076 		while (isdigit(*ptr) && digits <=3)
  1077 		{
  1078 			*ptr = '\0';
  1079 			digits++;
  1080 			ptr--;
  1081 		}
  1082 		if (digits != 3)
  1083 		{
  1084 			/* for now, assume this is an error */
  1085 			strcpy(buffer, iface);
  1086 		}
  1087 		else
  1088 		{
  1089 			char num[4];
  1090 			min = (min == 0) ? 1 : min;
  1091 			snprintf(num, sizeof(num), "%03d", min);
  1092 			strcat(buffer, num);
  1093 		}
  1094 	}
  1095 
  1096 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
  1097 }
  1098 
  1099 const char *MetamodSource::GetBaseDir()
  1100 {
  1101 	return mod_path.c_str();
  1102 }
  1103 
  1104 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
  1105 {
  1106 	va_list ap;
  1107 	va_start(ap, fmt);
  1108 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
  1109 	va_end(ap);
  1110 
  1111 	for (size_t i = 0; i < mylen; i++)
  1112 	{
  1113 		if (buffer[i] == ALT_SEP_CHAR)
  1114 		{
  1115 			buffer[i] = PATH_SEP_CHAR;
  1116 		}
  1117 	}
  1118 
  1119 	return mylen;
  1120 }
  1121 
  1122 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
  1123 {
  1124 	va_list ap;
  1125 	char buffer[2048];
  1126 
  1127 	va_start(ap, fmt);
  1128 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
  1129 	va_end(ap);
  1130 
  1131 	provider->ClientConsolePrint(client, buffer);
  1132 }
  1133 
  1134 void MetamodSource::EnableVSPListener()
  1135 {
  1136 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
  1137 	{
  1138 		InitializeVSP();
  1139 	}
  1140 
  1141 	vsp_load_requested = true;
  1142 }
  1143 
  1144 int MetamodSource::GetVSPVersion()
  1145 {
  1146 	return vsp_version;
  1147 }
  1148 
  1149 int MetamodSource::GetGameDLLVersion()
  1150 {
  1151 	return gamedll_version;
  1152 }
  1153 
  1154 bool MetamodSource::RemotePrintingAvailable()
  1155 {
  1156 	return provider->IsRemotePrintingAvailable();
  1157 }
  1158 
  1159 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
  1160 {
  1161 	if (id)
  1162 	{
  1163 		*id = 0;
  1164 	}
  1165 
  1166 	if (!iface)
  1167 	{
  1168 		return NULL;
  1169 	}
  1170 
  1171 	/* First check ours... we get first chance! */
  1172 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
  1173 	{
  1174 		if (ret)
  1175 		{
  1176 			*ret = IFACE_OK;
  1177 		}
  1178 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
  1179 	}
  1180 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
  1181 	{
  1182 		if (ret)
  1183 		{
  1184 			*ret = IFACE_OK;
  1185 		}
  1186 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
  1187 	}
  1188 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
  1189 	{
  1190 		if (ret)
  1191 		{
  1192 			*ret = IFACE_OK;
  1193 		}
  1194 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
  1195 	}
  1196 
  1197 	CPluginManager::CPlugin *pl;
  1198 	List<IMetamodListener *>::iterator event;
  1199 	IMetamodListener *api;
  1200 	void *value;
  1201 	
  1202 	int subret = 0;
  1203 	for (PluginIter iter = g_PluginMngr._begin();
  1204 		 iter != g_PluginMngr._end();
  1205 		 iter++)
  1206 	{
  1207 		pl = (*iter);
  1208 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
  1209 		{
  1210 			api = (*event);
  1211 			subret = IFACE_FAILED;
  1212 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
  1213 			{
  1214 				if (ret)
  1215 				{
  1216 					*ret = subret;
  1217 				}
  1218 				if (id)
  1219 				{
  1220 					*id = pl->m_Id;
  1221 				}
  1222 				return value;
  1223 			}
  1224 		}
  1225 	}
  1226 
  1227 	if (ret)
  1228 	{
  1229 		*ret = IFACE_FAILED;
  1230 	}
  1231 
  1232 	return NULL;
  1233 }
  1234 
  1235 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
  1236 {
  1237 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
  1238 
  1239 	pl->m_Events.push_back(pListener);
  1240 }
  1241 
  1242 const char *MetamodSource::GetGameBinaryPath()
  1243 {
  1244 	return full_bin_path.c_str();
  1245 }
  1246 
  1247 const char *MetamodSource::GetPluginsFile()
  1248 {
  1249 	return provider->GetConVarString(mm_pluginsfile);
  1250 }
  1251 
  1252 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
  1253 {
  1254 	return provider->GetConCommandBaseAccessor();
  1255 }
  1256 
  1257 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
  1258 {
  1259 	if (provider->IsConCommandBaseACommand(pCommand))
  1260 	{
  1261 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
  1262 	}
  1263 	else
  1264 	{
  1265 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
  1266 	}
  1267 
  1268 	return provider->RegisterConCommandBase(pCommand);
  1269 }
  1270 
  1271 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
  1272 {
  1273 	if (provider->IsConCommandBaseACommand(pCommand))
  1274 	{
  1275 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
  1276 	}
  1277 	else
  1278 	{
  1279 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
  1280 	}
  1281 
  1282 	CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
  1283 	UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
  1284 }
  1285 
  1286 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
  1287 {
  1288 	PluginIter iter;
  1289 	CPluginManager::CPlugin *pPlugin;
  1290 	List<IMetamodListener *>::iterator event;
  1291 	IMetamodListener *pML;
  1292 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
  1293 	{
  1294 		pPlugin = (*iter);
  1295 		if (pPlugin->m_Status < Pl_Paused)
  1296 		{
  1297 			continue;
  1298 		}
  1299 		/* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
  1300 		if (pPlugin->m_API->GetApiVersion() < 12)
  1301 		{
  1302 			continue;
  1303 		}
  1304 		for (event=pPlugin->m_Events.begin();
  1305 			event!=pPlugin->m_Events.end();
  1306 			event++)
  1307 		{
  1308 			pML = (*event);
  1309 			pML->OnUnlinkConCommandBase(id, pCommand);
  1310 		}
  1311 	}
  1312 
  1313 	return provider->UnregisterConCommandBase(pCommand);
  1314 }
  1315 
  1316 int MetamodSource::GetUserMessageCount()
  1317 {
  1318 	return provider->GetUserMessageCount();
  1319 }
  1320 
  1321 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
  1322 {
  1323 	return provider->FindUserMessage(name, size);
  1324 }
  1325 
  1326 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
  1327 {
  1328 	return provider->GetUserMessage(index, size);
  1329 }
  1330 
  1331 int MetamodSource::GetSourceEngineBuild()
  1332 {
  1333 	return engine_build;
  1334 }
  1335 
  1336 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
  1337 {
  1338 	ITER_EVENT(OnVSPListening, (callbacks));
  1339 }
  1340 
  1341 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
  1342 {
  1343 	if (pVersion)
  1344 	{
  1345 		*pVersion = vsp_version;
  1346 	}
  1347 
  1348 	return vsp_callbacks;
  1349 }
  1350 
  1351 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
  1352 {
  1353 	va_list ap;
  1354 	size_t result;
  1355 
  1356 	va_start(ap, format);
  1357 	result = FormatArgs(buffer, maxlength, format, ap);
  1358 	va_end(ap);
  1359 
  1360 	return result;
  1361 }
  1362 
  1363 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
  1364 {
  1365 	return UTIL_FormatArgs(buffer, maxlength, format, ap);
  1366 }
  1367 
  1368 bool MetamodSource::IsLoadedAsGameDLL()
  1369 {
  1370 	return is_gamedll_loaded;
  1371 }
  1372 
  1373 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
  1374 {
  1375 	gamedll_info.factory = serverFactory;
  1376 	gamedll_version = version;
  1377 }
  1378 
  1379 bool MetamodSource::IsAlternateLoadComplete()
  1380 {
  1381 	return were_plugins_loaded;
  1382 }
  1383 
  1384 void ProcessVDF(const char *path)
  1385 {
  1386 	PluginId id;
  1387 	bool already;
  1388 	char alias[24], file[255], error[255];
  1389 
  1390 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1391 	{
  1392 		return;
  1393 	}
  1394 
  1395 	if (alias[0] != '\0')
  1396 	{
  1397 		g_PluginMngr.SetAlias(alias, file);
  1398 	}
  1399 
  1400 	id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
  1401 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1402 	{
  1403 		LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1404 	}
  1405 }
  1406 
  1407 void LookForVDFs(const char *dir)
  1408 {
  1409 	char path[MAX_PATH];
  1410 
  1411 #if defined _MSC_VER
  1412 	HANDLE hFind;
  1413 	WIN32_FIND_DATA fd;
  1414 	char error[255];
  1415 	int extidx;
  1416 
  1417 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
  1418 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1419 	{
  1420 		DWORD dw = GetLastError();
  1421 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1422 			NULL,
  1423 			dw,
  1424 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1425 			error,
  1426 			sizeof(error),
  1427 			NULL);
  1428 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1429 		return;
  1430 	}
  1431 
  1432 	do
  1433 	{
  1434 		if (strcmp(fd.cFileName, ".") == 0
  1435 			|| strcmp(fd.cFileName, "..") == 0)
  1436 		{
  1437 			continue;
  1438 		}
  1439 		extidx = strlen(fd.cFileName) - 4;
  1440 		if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
  1441 		{
  1442 			continue;
  1443 		}
  1444 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1445 		ProcessVDF(path);
  1446 	} while (FindNextFile(hFind, &fd));
  1447 
  1448 	FindClose(hFind);
  1449 #else
  1450 	DIR *pDir;
  1451 	struct dirent *pEnt;
  1452 
  1453 	if ((pDir = opendir(dir)) == NULL)
  1454 	{
  1455 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1456 		return;
  1457 	}
  1458 
  1459 	while ((pEnt = readdir(pDir)) != NULL)
  1460 	{
  1461 		if (strcmp(pEnt->d_name, ".") == 0
  1462 			|| strcmp(pEnt->d_name, "..") == 0)
  1463 		{
  1464 			continue;
  1465 		}
  1466 		extidx = strlen(fd.cFileName) - 4;
  1467 		if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
  1468 		{
  1469 			continue;
  1470 		}
  1471 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1472 		ProcessVDF(path);
  1473 	}
  1474 
  1475 	closedir(pDir);
  1476 #endif
  1477 }