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