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