core/metamod.cpp
author David Anderson <dvander@alliedmods.net>
Sun Nov 23 23:45:57 2008 -0600 (2008-11-23)
changeset 591 65250cbdb827
parent 589 8e97a1e960a5
child 592 a38d1ebe28d6
permissions -rw-r--r--
Fixed core GameDLL loading not having a VSP listener.
     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 #include "provider/provider_ep2.h"
    38 
    39 using namespace SourceMM;
    40 using namespace SourceHook;
    41 using namespace SourceHook::Impl;
    42 
    43 /**
    44  * @brief Implementation of main SourceMM GameDLL functionality
    45  * @file sourcemm.cpp
    46  */
    47 
    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 
    52 static void
    53 Handler_LevelShutdown();
    54 
    55 static bool
    56 Handler_LevelInit(char const *pMapName,
    57 				  char const *pMapEntities,
    58 				  char const *pOldLevel,
    59 				  char const *pLandmarkName,
    60 				  bool loadGame,
    61 				  bool background);
    62 
    63 static bool
    64 Handler_GameInit();
    65 
    66 static void
    67 InitializeVSP();
    68 
    69 static void
    70 LookForVDFs(const char *dir);
    71 
    72 struct game_dll_t
    73 {
    74 	CreateInterfaceFn factory;
    75 };
    76 
    77 static String mod_path;
    78 static String metamod_path;
    79 static String full_bin_path;
    80 static int vsp_version = 0;
    81 static int gamedll_version = 0;
    82 static int engine_build = SOURCE_ENGINE_UNKNOWN;
    83 static List<game_dll_t *> gamedll_list;
    84 static bool is_gamedll_loaded = false;
    85 static bool in_first_level = true;
    86 static bool is_game_init = false;
    87 static bool vsp_load_requested = false;
    88 static bool vsp_loaded = false;
    89 static game_dll_t gamedll_info;
    90 static ConVar *metamod_version = NULL;
    91 static ConVar *mm_pluginsfile = NULL;
    92 static ConVar *mm_basedir = NULL;
    93 static CreateInterfaceFn engine_factory = NULL;
    94 static CreateInterfaceFn physics_factory = NULL;
    95 static CreateInterfaceFn filesystem_factory = NULL;
    96 static CGlobalVars *gpGlobals = NULL;
    97 static CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
    98 static META_RES last_meta_res;
    99 static IServerPluginCallbacks *vsp_callbacks = NULL;
   100 static bool were_plugins_loaded = false;
   101 static bool g_bIsVspBridged = false;
   102 
   103 MetamodSource g_Metamod;
   104 PluginId g_PLID = Pl_Console;
   105 CSourceHookImpl g_SourceHook;
   106 ISourceHook *g_SHPtr = &g_SourceHook;
   107 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
   108 
   109 /* Helper Macro */
   110 #define	IFACE_MACRO(orig,nam) \
   111 	CPluginManager::CPlugin *pl; \
   112 	SourceHook::List<IMetamodListener *>::iterator event; \
   113 	IMetamodListener *api; \
   114 	int mret = 0; \
   115 	void *val = NULL; \
   116 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   117 		pl = (*iter); \
   118 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   119 			api = (*event); \
   120 			mret = IFACE_FAILED; \
   121 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
   122 				if (ret) *ret = mret; \
   123 				return val; \
   124 			} \
   125 		} \
   126 	} \
   127 	return (orig)(iface, ret);
   128 
   129 #define ITER_EVENT(evn, args) \
   130 	CPluginManager::CPlugin *pl; \
   131 	SourceHook::List<IMetamodListener *>::iterator event; \
   132 	IMetamodListener *api; \
   133 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   134 		pl = (*iter); \
   135 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   136 			api = (*event); \
   137 			api->evn args; \
   138 		} \
   139 	}
   140 
   141 void
   142 mm_SetVspInfo(IServerPluginCallbacks *ispc, unsigned int version)
   143 {
   144 	vsp_version = version;
   145 }
   146 
   147 /* Initialize everything here */
   148 void
   149 mm_InitializeForLoad()
   150 {
   151 	char full_path[PATH_SIZE] = {0};
   152 	GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
   153 	full_bin_path.assign(full_path);
   154 
   155 	/* Like Metamod, reload plugins at the end of the map.
   156 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   157 	 * if the server is shut down (silly, but rare case).
   158 	 */
   159 	in_first_level = true;
   160 
   161 	SourceHook::MemFuncInfo info;
   162 
   163 	if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
   164 	{
   165 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
   166 	}
   167 	SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   168 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
   169 
   170 	if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
   171 	{
   172 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
   173 	}
   174 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
   175 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
   176 
   177 	if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
   178 	{
   179 		provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
   180 	}
   181 	SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
   182 	SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
   183 }
   184 
   185 bool
   186 mm_DetectGameInformation()
   187 {
   188 	char mm_path[PATH_SIZE];
   189 	char game_path[PATH_SIZE];
   190 
   191 	/* Get path to SourceMM DLL */
   192 	if (!GetFileOfAddress((void *)mm_InitializeForLoad, mm_path, sizeof(mm_path)))
   193 	{
   194 		return false;
   195 	}
   196 
   197 	metamod_path.assign(mm_path);
   198 
   199 	/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   200 	const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
   201 
   202 	/* Get absolute path */
   203 	abspath(game_path, game_dir);
   204 	mod_path.assign(game_path);
   205 
   206 	engine_build = provider->DetermineSourceEngine(game_dir);;
   207 
   208 	return true;
   209 }
   210 
   211 void *
   212 ServerFactory(const char *iface, int *ret)
   213 {
   214 	IFACE_MACRO(gamedll_info.factory, GameDLL);
   215 }
   216 
   217 SMM_API void *
   218 CreateInterface(const char *iface, int *ret)
   219 {
   220 	void *ptr = NULL;
   221 
   222 	if (!mm_IsVspBridged() && strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
   223 	{
   224 		if (vsp_callbacks != NULL)
   225 		{
   226 			if (ret != NULL)
   227 				*ret = IFACE_FAILED;
   228 			return NULL;
   229 		}
   230 
   231 		vsp_version = atoi(&iface[22]);
   232 		ptr = provider->GetVSPCallbacks(vsp_version);
   233 
   234 		if (ptr == NULL)
   235 			vsp_version = 0;
   236 
   237 		return ptr;
   238 	}
   239 
   240 	if (ret)
   241 		*ret = (ptr != NULL) ? IFACE_OK : IFACE_FAILED;
   242 
   243 	return ptr;
   244 }
   245 
   246 int
   247 mm_LoadPluginsFromFile(const char *_file)
   248 {
   249 	FILE *fp;
   250 	int total = 0, skipped=0;
   251 	PluginId id;
   252 	bool already;
   253 
   254 	fp = fopen(_file, "rt");
   255 	if (!fp)
   256 	{
   257 		mm_LogMessage("[META] Could not open plugins file %s\n", _file);
   258 		return -1;
   259 	}
   260 
   261 	char buffer[255], error[255], full_path[255];
   262 	const char *ptr, *ext, *file;
   263 	size_t length;
   264 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   265 	{
   266 		UTIL_TrimLeft(buffer);
   267 		UTIL_TrimRight(buffer);
   268 
   269 		length = strlen(buffer);
   270 		if (!length)
   271 		{
   272 			continue;
   273 		}
   274 
   275 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   276 		{
   277 			continue;
   278 		}
   279 
   280 		file = buffer;
   281 		if (buffer[0] == '"')
   282 		{
   283 			char *cptr = buffer;
   284 			file = ++cptr;
   285 
   286 			while (*cptr)
   287 			{
   288 				if (*cptr == '"')
   289 				{
   290 					*cptr = '\0';
   291 					break;
   292 				}
   293 				cptr++;
   294 			}
   295 		}
   296 		else
   297 		{
   298 			char *cptr = buffer;
   299 			while (*cptr)
   300 			{
   301 				if (isspace(*cptr))
   302 				{
   303 					char *optr = cptr;
   304 					while (*cptr && isspace(*cptr))
   305 					{
   306 						cptr++;
   307 					}
   308 					*optr = '\0';
   309 					UTIL_TrimRight(cptr);
   310 					if (*cptr && isalpha(*cptr))
   311 					{
   312 						g_PluginMngr.SetAlias(buffer, cptr);
   313 						file = cptr;
   314 					}
   315 					break;
   316 				}
   317 				cptr++;
   318 			}
   319 		}
   320 		if (!file[0])
   321 		{
   322 			continue;
   323 		}
   324 		/* First find if it's an absolute path or not... */
   325 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   326 		{
   327 			/* If we're in an absolute path, ignore our normal heuristics */
   328 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   329 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   330 			{
   331 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   332 			}
   333 			else
   334 			{
   335 				if (already)
   336 					skipped++;
   337 				else
   338 					total++;
   339 			}
   340 		}
   341 		else
   342 		{
   343 			/* Attempt to find a file extension */
   344 			ptr = UTIL_GetExtension(file);
   345 			/* Add an extension if there's none there */
   346 			if (!ptr)
   347 			{
   348 #if defined WIN32 || defined _WIN32
   349 				ext = ".dll";
   350 #else
   351 				ext = "_i486.so";
   352 #endif
   353 			}
   354 			else
   355 			{
   356 				ext = "";
   357 			}
   358 			/* Format the new path */
   359 			g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
   360 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   361 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   362 			{
   363 				mm_LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   364 			}
   365 			else
   366 			{
   367 				if (already)
   368 					skipped++;
   369 				else
   370 					total++;
   371 			}
   372 		}
   373 	}
   374 	fclose(fp);
   375 
   376 	if (skipped)
   377 		mm_LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   378 	else
   379 		mm_LogMessage("[META] Loaded %d plugins from file.", total);
   380 	
   381 	return total;
   382 }
   383 
   384 void InitializeVSP()
   385 {
   386 	if (g_bIsVspBridged)
   387 		return;
   388 
   389 	size_t len;
   390 	char engine_file[PATH_SIZE];
   391 	char engine_path[PATH_SIZE];
   392 	char rel_path[PATH_SIZE * 2];
   393 
   394 	GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
   395 
   396 	/* Chop off the "engine" file part */
   397 	len = strlen(engine_file);
   398 	for (size_t i = len - 1; i >= 0 && i < len; i--)
   399 	{
   400 		if (engine_file[i] == '/' || engine_file[i] == '\\')
   401 		{
   402 			engine_file[i] = '\0';
   403 			break;
   404 		}
   405 	}
   406 	abspath(engine_path, engine_file);
   407 
   408 	const char *usepath = metamod_path.c_str();
   409 	if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
   410 	{
   411 		usepath = rel_path;
   412 	}
   413 
   414 	char command[PATH_SIZE * 2];
   415 	UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
   416 	provider->ServerCommand(command);
   417 }
   418 
   419 /* Wrapper function.  This is called when the GameDLL thinks it's using
   420  * the engine's real engineFactory.
   421  */
   422 static void *
   423 EngineFactory(const char *iface, int *ret)
   424 {
   425 	IFACE_MACRO(engine_factory, Engine);
   426 }
   427 
   428 /* Wrapper function.  This is called when the GameDLL thinks it's using
   429  * the engine's real physicsFactory.
   430  */
   431 static void *
   432 PhysicsFactory(const char *iface, int *ret)
   433 {
   434 	IFACE_MACRO(physics_factory, Physics);
   435 }
   436 
   437 /* Wrapper function.  This is called when the GameDLL thinks it's using
   438  * the engine's real fileSystemFactory.
   439  */
   440 static void *
   441 FileSystemFactory(const char *iface, int *ret)
   442 {
   443 	IFACE_MACRO(filesystem_factory, FileSystem);
   444 }
   445 
   446 void
   447 mm_LogMessage(const char *msg, ...)
   448 {
   449 	va_list ap;
   450 	static char buffer[2048];
   451 
   452 	va_start(ap, msg);
   453 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   454 	va_end(ap);
   455 
   456 	buffer[len++] = '\n';
   457 	buffer[len] = '\0';
   458 
   459 	if (!provider->LogMessage(buffer))
   460 	{
   461 		fprintf(stdout, "%s", buffer);
   462 	}
   463 }
   464 
   465 static void
   466 DoInitialPluginLoads()
   467 {
   468 	const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
   469 	const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
   470 	if (!pluginFile) 
   471 	{
   472 		pluginFile = provider->GetConVarString(mm_pluginsfile);
   473 		if (pluginFile == NULL)
   474 		{
   475 			pluginFile = "addons/metamod/metaplugins.ini";
   476 		}
   477 	}
   478 	if (!mmBaseDir)
   479 	{
   480 		mmBaseDir = provider->GetConVarString(mm_basedir);
   481 		if (mmBaseDir == NULL)
   482 		{
   483 			mmBaseDir = "addons/metamod";
   484 		}
   485 	}
   486 
   487 	char full_path[260];
   488 
   489 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
   490 	mm_LoadPluginsFromFile(full_path);
   491 
   492 	g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
   493 	LookForVDFs(full_path);
   494 }
   495 
   496 void
   497 mm_StartupMetamod(bool is_vsp_load)
   498 {
   499 	char buffer[255];
   500 
   501 	UTIL_Format(buffer,
   502 		sizeof(buffer),
   503 		"%s%s",
   504 		SVN_FULL_VERSION,
   505 		is_vsp_load ? "V" : "");
   506 
   507 	metamod_version = provider->CreateConVar("metamod_version", 
   508 		SVN_FULL_VERSION, 
   509 		"Metamod:Source Version",
   510 		ConVarFlag_Notify|ConVarFlag_SpOnly);
   511 
   512 	provider->SetConVarString(metamod_version, buffer);
   513 
   514 	mm_pluginsfile = provider->CreateConVar("mm_pluginsfile", 
   515 #if defined WIN32 || defined _WIN32
   516 		"addons\\metamod\\metaplugins.ini", 
   517 #else
   518 		"addons/metamod/metaplugins.ini",
   519 #endif
   520 		"Metamod:Source Plugins File",
   521 		ConVarFlag_SpOnly);
   522 
   523 	mm_basedir = provider->CreateConVar("mm_basedir",
   524 #if defined __linux__
   525 		"addons/metamod",
   526 #else
   527 		"addons\\metamod",
   528 #endif
   529 		"Metamod:Source Base Folder",
   530 		ConVarFlag_SpOnly);
   531 	
   532 	g_bIsVspBridged = is_vsp_load;
   533 
   534 	if (!is_vsp_load)
   535 	{
   536 		DoInitialPluginLoads();
   537 		in_first_level = true;
   538 	}
   539 }
   540 
   541 void
   542 mm_InitializeGlobals(CreateInterfaceFn engineFactory, 
   543 					 CreateInterfaceFn physicsFactory,
   544 					 CreateInterfaceFn filesystemFactory,
   545 					 CGlobalVars *pGlobals)
   546 {
   547 	engine_factory = engineFactory;
   548 	physics_factory = physicsFactory;
   549 	filesystem_factory = filesystemFactory;
   550 	gpGlobals = pGlobals;
   551 	provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
   552 }
   553 
   554 static bool
   555 Handler_GameInit()
   556 {
   557 	if (is_game_init)
   558 		return true;
   559 
   560 	if (vsp_load_requested)
   561 		InitializeVSP();
   562 
   563 	if (g_bIsVspBridged && !were_plugins_loaded)
   564 	{
   565 		DoInitialPluginLoads();
   566 		g_PluginMngr.SetAllLoaded();
   567 		were_plugins_loaded = true;
   568 	}
   569 
   570 	is_game_init = true;
   571 
   572 	RETURN_META_VALUE(MRES_IGNORED, true);
   573 }
   574 
   575 void
   576 mm_UnloadMetamod()
   577 {
   578 	/* Unload plugins */
   579 	g_PluginMngr.UnloadAll();
   580 
   581 	provider->Notify_DLLShutdown_Pre();
   582 
   583 	g_SourceHook.CompleteShutdown();
   584 }
   585 
   586 static void
   587 Handler_LevelShutdown(void)
   588 {
   589 	if (g_bIsVspBridged && !were_plugins_loaded)
   590 	{
   591 		g_PluginMngr.SetAllLoaded();
   592 		DoInitialPluginLoads();
   593 		were_plugins_loaded = true;
   594 		in_first_level = true;
   595 	}
   596 
   597 	if (!in_first_level)
   598 	{
   599 		char full_path[255];
   600 
   601 		g_Metamod.PathFormat(full_path, 
   602 			sizeof(full_path), 
   603 			"%s/%s", 
   604 			mod_path.c_str(),
   605 			provider->GetConVarString(mm_pluginsfile));
   606 		mm_LoadPluginsFromFile(full_path);
   607 
   608 		g_Metamod.PathFormat(full_path,
   609 			sizeof(full_path),
   610 			"%s/%s",
   611 			mod_path.c_str(),
   612 			provider->GetConVarString(mm_basedir));
   613 		LookForVDFs(full_path);
   614 	}
   615 	else
   616 	{
   617 		in_first_level = false;
   618 	}
   619 
   620 	ITER_EVENT(OnLevelShutdown, ());
   621 
   622 	RETURN_META(MRES_IGNORED);
   623 }
   624 
   625 static bool
   626 Handler_LevelInit(char const *pMapName,
   627 				  char const *pMapEntities,
   628 				  char const *pOldLevel,
   629 				  char const *pLandmarkName,
   630 				  bool loadGame,
   631 				  bool background)
   632 {
   633 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
   634 
   635 	RETURN_META_VALUE(MRES_IGNORED, false);
   636 }
   637 
   638 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
   639 {
   640 	va_list ap;
   641 	char buffer[2048];
   642 	
   643 	va_start(ap, msg);
   644 	UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
   645 	va_end(ap);
   646 
   647 	mm_LogMessage("[%s] %s", pl->GetLogTag(), buffer);
   648 }
   649 
   650 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
   651 {
   652 	if (syn)
   653 		return EngineFactory;
   654 	return engine_factory;
   655 }
   656 
   657 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
   658 {
   659 	if (syn)
   660 		return PhysicsFactory;
   661 	return physics_factory;
   662 }
   663 
   664 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
   665 {
   666 	if (syn)
   667 		return FileSystemFactory;
   668 	return filesystem_factory;
   669 }
   670 
   671 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
   672 {
   673 	if (syn)
   674 		return ServerFactory;
   675 	return gamedll_info.factory;
   676 }
   677 
   678 CGlobalVars *MetamodSource::GetCGlobals()
   679 {
   680 	return gpGlobals;
   681 }
   682 
   683 void MetamodSource::SetLastMetaReturn(META_RES res)
   684 {
   685 	last_meta_res = res;
   686 }
   687 
   688 META_RES MetamodSource::GetLastMetaReturn()
   689 {
   690 	return last_meta_res;
   691 }
   692 
   693 void MetamodSource::ConPrint(const char *str)
   694 {
   695 	provider->ConsolePrint(str);
   696 }
   697 
   698 void MetamodSource::ConPrintf(const char *fmt, ...)
   699 {
   700 	va_list ap;
   701 	char buffer[2048];
   702 
   703 	va_start(ap, fmt);
   704 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   705 	va_end(ap);
   706 
   707 	provider->ConsolePrint(buffer);
   708 }
   709 
   710 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
   711 {
   712 	major = METAMOD_API_MAJOR;
   713 	minor = METAMOD_API_MINOR;
   714 	plvers = METAMOD_PLAPI_VERSION;
   715 	plmin = PLAPI_MIN_VERSION;
   716 }
   717 
   718 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
   719 {
   720 	shvers = SH_IFACE_VERSION;
   721 	shimpl = SH_IMPL_VERSION;
   722 }
   723 
   724 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
   725 {
   726 	int length = (int)strlen(iface);
   727 	int i;
   728 	int num = 0;
   729 
   730 	for (i = length - 1; i >= 0; i--)
   731 	{
   732 		if (!isdigit(iface[i]))
   733 		{
   734 			if (i != length - 1)
   735 			{
   736 				num = 1;
   737 			}
   738 			break;
   739 		}
   740 	}
   741 
   742 	if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
   743 	{
   744 		return -1;
   745 	}
   746 
   747 	if (i != length - 1)
   748 	{
   749 		num = atoi(&(iface[++i]));
   750 	}
   751 
   752 	num++;
   753 
   754 	snprintf(&(iface[i]), 4, "%03d", num);
   755 
   756 	return num;
   757 }
   758 
   759 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
   760 {
   761 	char _if[256];	/* assume no interface goes beyond this */
   762 	size_t len = strlen(iface);
   763 	int num = 0;
   764 	void *pf = NULL;
   765 
   766 	if (max > 999)
   767 	{
   768 		max = 999;
   769 	}
   770 
   771 	if (len + 4 > sizeof(_if))
   772 	{
   773 		if (ret)
   774 		{
   775 			*ret = IFACE_FAILED;
   776 		}
   777 		return NULL;
   778 	}
   779 
   780 	strcpy(_if, iface);
   781 
   782 	do
   783 	{
   784 		if ((pf = (fn)(_if, ret)) != NULL)
   785 		{
   786 			break;
   787 		}
   788 		if (num > max)
   789 		{
   790 			break;
   791 		}
   792 	} while ((num = FormatIface(_if, len+1)));
   793 
   794 	return pf;
   795 }
   796 
   797 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
   798 {
   799 	char buffer[256];	/* assume no interface will go beyond this */
   800 	size_t len = strlen(iface);
   801 	int ret;			/* just in case something doesn't handle NULL properly */
   802 
   803 	if (len > sizeof(buffer) - 4)
   804 	{
   805 		return NULL;
   806 	}
   807 
   808 	strcpy(buffer, iface);
   809 
   810 	if (min != -1)
   811 	{
   812 		char *ptr = &buffer[len - 1];
   813 		int digits = 0;
   814 		while (isdigit(*ptr) && digits <=3)
   815 		{
   816 			*ptr = '\0';
   817 			digits++;
   818 			ptr--;
   819 		}
   820 		if (digits != 3)
   821 		{
   822 			/* for now, assume this is an error */
   823 			strcpy(buffer, iface);
   824 		}
   825 		else
   826 		{
   827 			char num[4];
   828 			min = (min == 0) ? 1 : min;
   829 			snprintf(num, sizeof(num), "%03d", min);
   830 			strcat(buffer, num);
   831 		}
   832 	}
   833 
   834 	return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
   835 }
   836 
   837 const char *MetamodSource::GetBaseDir()
   838 {
   839 	return mod_path.c_str();
   840 }
   841 
   842 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
   843 {
   844 	va_list ap;
   845 	va_start(ap, fmt);
   846 	size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
   847 	va_end(ap);
   848 
   849 	for (size_t i = 0; i < mylen; i++)
   850 	{
   851 		if (buffer[i] == ALT_SEP_CHAR)
   852 		{
   853 			buffer[i] = PATH_SEP_CHAR;
   854 		}
   855 	}
   856 
   857 	return mylen;
   858 }
   859 
   860 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
   861 {
   862 	va_list ap;
   863 	char buffer[2048];
   864 
   865 	va_start(ap, fmt);
   866 	UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
   867 	va_end(ap);
   868 
   869 	provider->ClientConsolePrint(client, buffer);
   870 }
   871 
   872 void MetamodSource::EnableVSPListener()
   873 {
   874 	if (is_game_init && !vsp_load_requested && !vsp_loaded)
   875 		InitializeVSP();
   876 
   877 	vsp_load_requested = true;
   878 }
   879 
   880 int MetamodSource::GetVSPVersion()
   881 {
   882 	return vsp_version;
   883 }
   884 
   885 int MetamodSource::GetGameDLLVersion()
   886 {
   887 	return gamedll_version;
   888 }
   889 
   890 bool MetamodSource::RemotePrintingAvailable()
   891 {
   892 	return provider->IsRemotePrintingAvailable();
   893 }
   894 
   895 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
   896 {
   897 	if (id)
   898 	{
   899 		*id = 0;
   900 	}
   901 
   902 	if (!iface)
   903 	{
   904 		return NULL;
   905 	}
   906 
   907 	/* First check ours... we get first chance! */
   908 	if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
   909 	{
   910 		if (ret)
   911 		{
   912 			*ret = IFACE_OK;
   913 		}
   914 		return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
   915 	}
   916 	else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
   917 	{
   918 		if (ret)
   919 		{
   920 			*ret = IFACE_OK;
   921 		}
   922 		return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
   923 	}
   924 	else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
   925 	{
   926 		if (ret)
   927 		{
   928 			*ret = IFACE_OK;
   929 		}
   930 		return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
   931 	}
   932 
   933 	CPluginManager::CPlugin *pl;
   934 	List<IMetamodListener *>::iterator event;
   935 	IMetamodListener *api;
   936 	void *value;
   937 	
   938 	int subret = 0;
   939 	for (PluginIter iter = g_PluginMngr._begin();
   940 		 iter != g_PluginMngr._end();
   941 		 iter++)
   942 	{
   943 		pl = (*iter);
   944 		for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
   945 		{
   946 			api = (*event);
   947 			subret = IFACE_FAILED;
   948 			if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
   949 			{
   950 				if (ret)
   951 				{
   952 					*ret = subret;
   953 				}
   954 				if (id)
   955 				{
   956 					*id = pl->m_Id;
   957 				}
   958 				return value;
   959 			}
   960 		}
   961 	}
   962 
   963 	if (ret)
   964 	{
   965 		*ret = IFACE_FAILED;
   966 	}
   967 
   968 	return NULL;
   969 }
   970 
   971 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
   972 {
   973 	CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
   974 
   975 	pl->m_Events.push_back(pListener);
   976 }
   977 
   978 const char *MetamodSource::GetGameBinaryPath()
   979 {
   980 	return full_bin_path.c_str();
   981 }
   982 
   983 const char *MetamodSource::GetPluginsFile()
   984 {
   985 	return provider->GetConVarString(mm_pluginsfile);
   986 }
   987 
   988 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
   989 {
   990 	return provider->GetConCommandBaseAccessor();
   991 }
   992 
   993 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
   994 {
   995 	if (provider->IsConCommandBaseACommand(pCommand))
   996 	{
   997 		g_PluginMngr.AddPluginCmd(plugin, pCommand);
   998 	}
   999 	else
  1000 	{
  1001 		g_PluginMngr.AddPluginCvar(plugin, pCommand);
  1002 	}
  1003 
  1004 	return provider->RegisterConCommandBase(pCommand);
  1005 }
  1006 
  1007 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
  1008 {
  1009 	if (provider->IsConCommandBaseACommand(pCommand))
  1010 	{
  1011 		g_PluginMngr.RemovePluginCmd(plugin, pCommand);
  1012 	}
  1013 	else
  1014 	{
  1015 		g_PluginMngr.RemovePluginCvar(plugin, pCommand);
  1016 	}
  1017 
  1018 	CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
  1019 	UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
  1020 }
  1021 
  1022 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
  1023 {
  1024 	PluginIter iter;
  1025 	CPluginManager::CPlugin *pPlugin;
  1026 	List<IMetamodListener *>::iterator event;
  1027 	IMetamodListener *pML;
  1028 	for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
  1029 	{
  1030 		pPlugin = (*iter);
  1031 		if (pPlugin->m_Status < Pl_Paused)
  1032 		{
  1033 			continue;
  1034 		}
  1035 		/* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
  1036 		if (pPlugin->m_API->GetApiVersion() < 12)
  1037 		{
  1038 			continue;
  1039 		}
  1040 		for (event=pPlugin->m_Events.begin();
  1041 			event!=pPlugin->m_Events.end();
  1042 			event++)
  1043 		{
  1044 			pML = (*event);
  1045 			pML->OnUnlinkConCommandBase(id, pCommand);
  1046 		}
  1047 	}
  1048 
  1049 	return provider->UnregisterConCommandBase(pCommand);
  1050 }
  1051 
  1052 int MetamodSource::GetUserMessageCount()
  1053 {
  1054 	return provider->GetUserMessageCount();
  1055 }
  1056 
  1057 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
  1058 {
  1059 	return provider->FindUserMessage(name, size);
  1060 }
  1061 
  1062 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
  1063 {
  1064 	return provider->GetUserMessage(index, size);
  1065 }
  1066 
  1067 int MetamodSource::GetSourceEngineBuild()
  1068 {
  1069 	return engine_build;
  1070 }
  1071 
  1072 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
  1073 {
  1074 	vsp_callbacks = callbacks;
  1075 	ITER_EVENT(OnVSPListening, (callbacks));
  1076 }
  1077 
  1078 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
  1079 {
  1080 	if (pVersion)
  1081 	{
  1082 		*pVersion = vsp_version;
  1083 	}
  1084 
  1085 	return vsp_callbacks;
  1086 }
  1087 
  1088 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
  1089 {
  1090 	va_list ap;
  1091 	size_t result;
  1092 
  1093 	va_start(ap, format);
  1094 	result = FormatArgs(buffer, maxlength, format, ap);
  1095 	va_end(ap);
  1096 
  1097 	return result;
  1098 }
  1099 
  1100 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
  1101 {
  1102 	return UTIL_FormatArgs(buffer, maxlength, format, ap);
  1103 }
  1104 
  1105 bool MetamodSource::IsLoadedAsGameDLL()
  1106 {
  1107 	return is_gamedll_loaded;
  1108 }
  1109 
  1110 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version, bool loaded)
  1111 {
  1112 	gamedll_info.factory = serverFactory;
  1113 	gamedll_version = version;
  1114 	is_gamedll_loaded = loaded;
  1115 }
  1116 
  1117 static void
  1118 ProcessVDF(const char *path)
  1119 {
  1120 	PluginId id;
  1121 	bool already;
  1122 	char alias[24], file[255], error[255];
  1123 
  1124 	if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
  1125 		return;
  1126 
  1127 	if (alias[0] != '\0')
  1128 		g_PluginMngr.SetAlias(alias, file);
  1129 
  1130 	id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
  1131 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
  1132 		mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
  1133 }
  1134 
  1135 static void
  1136 LookForVDFs(const char *dir)
  1137 {
  1138 	char path[MAX_PATH];
  1139 	char relpath[MAX_PATH * 2];
  1140 
  1141 #if defined _MSC_VER
  1142 	HANDLE hFind;
  1143 	WIN32_FIND_DATA fd;
  1144 	char error[255];
  1145 
  1146 	g_Metamod.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
  1147 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
  1148 	{
  1149 		DWORD dw = GetLastError();
  1150 		if (dw == ERROR_FILE_NOT_FOUND)
  1151 			return;
  1152 
  1153 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
  1154 			NULL,
  1155 			dw,
  1156 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  1157 			error,
  1158 			sizeof(error),
  1159 			NULL);
  1160 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
  1161 		return;
  1162 	}
  1163 
  1164 	do
  1165 	{
  1166 		g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
  1167 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1168 		ProcessVDF(relpath);
  1169 	} while (FindNextFile(hFind, &fd));
  1170 
  1171 	FindClose(hFind);
  1172 #else
  1173 	DIR *pDir;
  1174 	struct dirent *pEnt;
  1175 	int extidx;
  1176 
  1177 	if ((pDir = opendir(dir)) == NULL)
  1178 	{
  1179 		mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
  1180 		return;
  1181 	}
  1182 
  1183 	while ((pEnt = readdir(pDir)) != NULL)
  1184 	{
  1185 		if (strcmp(pEnt->d_name, ".") == 0
  1186 			|| strcmp(pEnt->d_name, "..") == 0)
  1187 		{
  1188 			continue;
  1189 		}
  1190 		extidx = strlen(pEnt->d_name) - 4;
  1191 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
  1192 		{
  1193 			continue;
  1194 		}
  1195 		g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
  1196 		UTIL_Relatize(relpath, sizeof(relpath), mod_path.c_str(), path);
  1197 		ProcessVDF(relpath);
  1198 	}
  1199 
  1200 	closedir(pDir);
  1201 #endif
  1202 }
  1203 
  1204 bool
  1205 mm_IsVspBridged()
  1206 {
  1207 	return g_bIsVspBridged;
  1208 }
  1209 
  1210 bool
  1211 mm_IsVspLoadComplete()
  1212 {
  1213 	return were_plugins_loaded;
  1214 }
  1215