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