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