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