core/metamod.cpp
author Scott Ehlert <ds@alliedmods.net>
Wed Feb 18 01:38:23 2009 -0600 (2009-02-18)
changeset 637 b66489d8aedc
parent 635 61c2224c8d68
child 639 5b691c4b0849
permissions -rw-r--r--
Added support for Dark Messiah engine and game. (no bug, r=me).

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