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