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