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