core-legacy/sourcemm.cpp
author David Anderson <dvander@alliedmods.net>
Fri Nov 14 05:02:00 2008 -0600 (2008-11-14)
changeset 545 07e5df11f9fc
parent 541 core-1.4/sourcemm.cpp@35a8cda28485
child 548 dd85920ecaaf
permissions -rw-r--r--
Renamed core-1.4 to core-legacy.
     1 /* ======== SourceMM ========
     2  * Copyright (C) 2004-2008 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 #include <interface.h>
    14 #include <eiface.h>
    15 #include <tier0/icommandline.h>
    16 #include "sourcemm.h"
    17 #include "concommands.h"
    18 #include "CSmmAPI.h"
    19 #include "CPlugin.h"
    20 #include "util.h"
    21 #include "vsp_listener.h"
    22 #include "iplayerinfo.h"
    23 #include <filesystem.h>
    24 
    25 using namespace SourceMM;
    26 
    27 /**
    28  * @brief Implementation of main SourceMM GameDLL functionality
    29  * @file sourcemm.cpp
    30  */
    31 
    32 #undef CommandLine
    33 DLL_IMPORT ICommandLine *CommandLine();
    34 
    35 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
    36 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
    37 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
    38 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
    39 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
    40 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
    41 
    42 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    43 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
    44 void DLLShutdown_handler();
    45 void LevelShutdown_handler();
    46 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
    47 bool GameInit_handler();
    48 void LookForVDFs(const char *dir);
    49 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID = NULL);
    50 
    51 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
    52 EngineInfo g_Engine;
    53 SourceHook::CSourceHookImpl g_SourceHook;
    54 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
    55 SourceHook::String g_ModPath;
    56 SourceHook::String g_BinPath;
    57 SourceHook::String g_SmmPath;
    58 PluginId g_PLID = Pl_Console;			/* Technically, SourceMM is the "Console" plugin... :p */
    59 bool bInFirstLevel = true;
    60 bool gParsedGameInfo = false;
    61 bool bGameInit = false;
    62 SourceHook::List<GameDllInfo *> gamedll_list;
    63 SourceHook::CallClass<IServerGameDLL> *g_GameDllPatch;
    64 SourceHook::CallClass<ICvar> *g_CvarPatch;
    65 int g_GameDllVersion = 0;
    66 const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
    67 const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
    68 const char GAMEINFO_PATH[] = "|gameinfo_path|";
    69 IFileSystem *baseFs = NULL;
    70 bool g_bLevelChanged = false;
    71 
    72 
    73 void ClearGamedllList();
    74 
    75 /* Helper Macro */
    76 #define	IFACE_MACRO(orig,nam) \
    77 	CPluginManager::CPlugin *pl; \
    78 	SourceHook::List<CPluginEventHandler>::iterator event; \
    79 	IMetamodListener *api; \
    80 	int mret = 0; \
    81 	void *val = NULL; \
    82 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
    83 		pl = (*iter); \
    84 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
    85 			api = (*event).event; \
    86 			mret = IFACE_FAILED; \
    87 			if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
    88 				if (ret) *ret = mret; \
    89 				return val; \
    90 			} \
    91 		} \
    92 	} \
    93 	return (orig)(iface, ret);
    94 
    95 #define ITER_EVENT(evn, args) \
    96 	CPluginManager::CPlugin *pl; \
    97 	SourceHook::List<CPluginEventHandler>::iterator event; \
    98 	IMetamodListener *api; \
    99 	for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
   100 		pl = (*iter); \
   101 		for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
   102 			api = (*event).event; \
   103 			api->evn args; \
   104 		} \
   105 	}
   106 
   107 ///////////////////////////////////
   108 // Main code for HL2 Interaction //
   109 ///////////////////////////////////
   110 
   111 /* Initialize everything here */
   112 void InitMainStates()
   113 {
   114 	char full_path[PATH_SIZE] = {0};
   115 	GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path));
   116 	g_BinPath.assign(full_path);
   117 
   118 	/* Like Metamod, reload plugins at the end of the map.
   119 	 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
   120 	 * if the server is shut down (silly, but rare case).
   121 	 */
   122 	bInFirstLevel = true;
   123 
   124 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
   125 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
   126 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
   127 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
   128 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
   129 	SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
   130 }
   131 
   132 void DoInitialPluginLoads()
   133 {
   134 	const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
   135 	const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
   136 
   137 	if (!pluginFile) 
   138 	{
   139 		pluginFile = GetPluginsFile();
   140 	}
   141 	if (!mmBaseDir)
   142 	{
   143 		mmBaseDir = GetMetamodBaseDir();
   144 	}
   145 
   146 	char full_path[260];
   147 
   148 	g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), pluginFile);
   149 	LoadPluginsFromFile(full_path);
   150 	g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), mmBaseDir);
   151 	LookForVDFs(full_path);
   152 }
   153 
   154 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
   155 {
   156 	g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
   157 
   158 	if (!g_Engine.engine)
   159 	{
   160 		Error("Could not find IVEngineServer! Metamod cannot load.");
   161 		return false;
   162 	}
   163 	g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
   164 	if (!g_Engine.icvar)
   165 	{
   166 		Error("Could not find ICvar! Metamod cannot load.");
   167 		return false;
   168 	}
   169 
   170 	g_Engine.loaded = true;
   171 
   172 	/* The Ship is the only game known at this time that uses the pre-Episode One engine */
   173 	g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
   174 
   175 	ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
   176 
   177 	g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
   178 	g_CvarPatch = SH_GET_CALLCLASS(g_Engine.icvar);
   179 
   180 	if (g_GameDll.pGameClients)
   181 	{
   182 		SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
   183 	}
   184 	else
   185 	{
   186 		/* If IServerGameClients isn't found, this really isn't a fatal error so... */
   187 		LogMessage("[META] Warning: Could not find IServerGameClients!");
   188 		LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
   189 	}
   190 
   191 	if (!g_SmmAPI.CacheCmds())
   192 	{
   193 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
   194 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
   195 	}
   196 
   197 	if (!g_SmmAPI.CacheUserMessages())
   198 	{
   199 		/* Don't know of a mod that has stripped out user messages completely, 
   200 		 * but perhaps should do something different here?
   201 		 */
   202 		LogMessage("[META] Warning: Failed to get list of user messages.");
   203 		LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
   204 	}
   205 
   206 	baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
   207 	if (baseFs == NULL)
   208 	{
   209 		LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
   210 	}
   211 
   212 	if (!g_SMConVarAccessor.InitConCommandBaseList())
   213 	{
   214 		/* This is very unlikely considering it's old engine */
   215 		LogMessage("[META] Warning: Failed to find ConCommandBase list!");
   216 		LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
   217 	}
   218 
   219 	if (!bWaitForGameInit)
   220 	{
   221 		DoInitialPluginLoads();
   222 		bInFirstLevel = true;
   223 	}
   224 
   225 	return true;
   226 }
   227 
   228 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   229 {
   230 	g_Engine.engineFactory = engineFactory;
   231 	g_Engine.fileSystemFactory = filesystemFactory;
   232 	g_Engine.physicsFactory = physicsFactory;
   233 	g_Engine.pGlobals = pGlobals;
   234 
   235 	StartupMetamod(engineFactory, false);
   236 
   237 	RETURN_META_VALUE(MRES_IGNORED, true);
   238 }
   239 
   240 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
   241 {
   242 	g_Engine.engineFactory = ifaceFactory;
   243 	g_Engine.fileSystemFactory = ifaceFactory;
   244 	g_Engine.physicsFactory = ifaceFactory;
   245 
   246 	IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
   247 	if (playerInfoManager == NULL)
   248 	{
   249 		Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
   250 		return false;
   251 	}
   252 
   253 	g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
   254 
   255 	/* Now find the server */
   256 	g_GameDll.factory = serverFactory;
   257 	g_GameDll.lib = NULL;
   258 
   259 	char gamedll_iface[] = "ServerGameDLL000";
   260 	for (unsigned int i = 3; i <= 50; i++)
   261 	{
   262 		gamedll_iface[15] = '0' + i;
   263 		g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
   264 		if (g_GameDll.pGameDLL != NULL)
   265 		{
   266 			g_GameDllVersion = i;
   267 			break;
   268 		}
   269 	}
   270 
   271 	if (g_GameDll.pGameDLL == NULL)
   272 	{
   273 		Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
   274 		return false;
   275 	}
   276 
   277 	char gameclients_iface[] = "ServerGameClients000";
   278 	for (unsigned int i = 3; i <= 4; i++)
   279 	{
   280 		gameclients_iface[19] = '0' + i;
   281 		g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
   282 		if (g_GameDll.pGameClients != NULL)
   283 		{
   284 			break;
   285 		}
   286 	}
   287 
   288 	char smm_path[PATH_SIZE];
   289 	const char *game_dir;
   290 	GetFileOfAddress((void *)AlternatelyLoadMetamod, smm_path, sizeof(smm_path));
   291 	g_SmmPath.assign(smm_path);
   292 
   293 	game_dir = CommandLine()->ParmValue("-game", "hl2");
   294 	abspath(smm_path, game_dir);
   295 	g_ModPath.assign(smm_path);
   296 
   297 	InitMainStates();
   298 
   299 	if (!StartupMetamod(ifaceFactory, true))
   300 	{
   301 		return false;
   302 	}
   303 
   304 	g_PluginMngr.SetAllLoaded();
   305 
   306 	return true;
   307 }
   308 
   309 bool GameInit_handler()
   310 {
   311 	if (bGameInit)
   312 	{
   313 		RETURN_META_VALUE(MRES_IGNORED, true);
   314 	}
   315 
   316 	if (g_SmmAPI.VSPEnabled() && !g_VspListener.IsRootLoadMethod())
   317 	{
   318 		g_SmmAPI.LoadAsVSP();
   319 	}
   320 
   321 	if (g_VspListener.IsRootLoadMethod())
   322 	{
   323 		DoInitialPluginLoads();
   324 		//gaben
   325 	}
   326 
   327 	bGameInit = true;
   328 
   329 	RETURN_META_VALUE(MRES_IGNORED, true);
   330 }
   331 
   332 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   333 {
   334 	g_PluginMngr.SetAllLoaded();
   335 	RETURN_META_VALUE(MRES_IGNORED, true);
   336 }
   337 
   338 /* This is where the magic happens */
   339 SMM_API void *CreateInterface(const char *iface, int *ret)
   340 {
   341 	/* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
   342 	if (strcmp(iface, PLAPI_NAME) == 0)
   343 	{
   344 		Warning("Do not try loading Metamod:Source as a Metamod:Source plugin");
   345 
   346 		if (ret)
   347 		{
   348 			*ret = IFACE_FAILED;
   349 		}
   350 
   351 		return NULL;
   352 	}
   353 
   354 	/* We check these separately because we can't reply
   355 	 * unless our interface version really matches.
   356 	 */
   357 	if ((strcmp(iface, VSPIFACE_002) == 0)
   358 		|| strcmp(iface, VSPIFACE_001) == 0)
   359 	{
   360 		if (ret)
   361 		{
   362 			*ret = IFACE_OK;
   363 		}
   364 		return &g_VspListener;
   365 	}
   366 
   367 	/* If we're a VSP, bypass this by default */
   368 	if (g_VspListener.IsRootLoadMethod())
   369 	{
   370 		IFACE_MACRO(g_GameDll.factory, GameDLL);
   371 	}
   372 
   373 	if (!gParsedGameInfo)
   374 	{
   375 		gParsedGameInfo = true;
   376 		const char *gameDir = NULL;
   377 		char gamePath[PATH_SIZE];
   378 		char smmPath[PATH_SIZE];
   379 
   380 		/* Get path to SourceMM DLL */
   381 		if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
   382 		{
   383 			Error("GetFileOfAddress() failed! Metamod cannot load.\n");
   384 			return NULL;
   385 		}
   386 
   387 		g_SmmPath.assign(smmPath);
   388 
   389 		/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   390 		gameDir = CommandLine()->ParmValue("-game", "hl2");
   391 
   392 		/* Get absolute path */
   393 		abspath(gamePath, gameDir);
   394 		g_ModPath.assign(gamePath);
   395 
   396 		char tempPath[PATH_SIZE];
   397 
   398 		/* Path to gameinfo.txt */
   399 		g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
   400 
   401 		FILE *fp = fopen(tempPath, "rt");
   402 
   403 		if (!fp)
   404 		{
   405 			Error("Unable to open gameinfo.txt!  Metamod cannot load.\n");
   406 			return NULL;
   407 		}
   408 
   409 		char buffer[255];
   410 		char key[128], val[128];
   411 		size_t len = 0;
   412 		bool search = false;
   413 		bool gamebin = false;
   414 		char *ptr;
   415 		const char *lptr;
   416 		char curPath[PATH_SIZE];
   417 
   418 		getcwd(curPath, PATH_SIZE);
   419 
   420 		while (!feof(fp))
   421 		{
   422 			buffer[0] = '\0';
   423 			fgets(buffer, sizeof(buffer), fp);
   424 			len = strlen(buffer);
   425 			if (buffer[len-1] == '\n')
   426 				buffer[--len] = '\0';
   427 			UTIL_TrimComments(buffer);
   428 			UTIL_TrimLeft(buffer);
   429 			UTIL_TrimRight(buffer);
   430 			if (stricmp(buffer, "SearchPaths") == 0)
   431 				search = true;
   432 			if (!search)
   433 				continue;
   434 			UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   435 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   436 			{
   437 				if (stricmp(key, "Game") == 0)
   438 					gamebin = false;
   439 				else
   440 					gamebin = true;
   441 
   442 				if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
   443 				{
   444 					ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
   445 					if (ptr[0] == '.')
   446 						ptr++;
   447 					lptr = g_ModPath.c_str();
   448 				} else {
   449 					ptr = val;
   450 					lptr = curPath;
   451 				}
   452 
   453 				size_t ptr_len = strlen(ptr);
   454 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   455 					ptr[--ptr_len] = '\0';
   456 
   457 				/* No need to append "bin" if key is GameBin */
   458 				if (gamebin)
   459 				{
   460 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   461 				} else if (!ptr[0]) {
   462 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
   463 				} else {
   464 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   465 				}
   466 
   467 				/* If not path to SourceMM... */
   468 				if (!UTIL_PathCmp(smmPath, tempPath))
   469 				{
   470 					FILE *fp = fopen(tempPath, "rb");
   471 					if (!fp)
   472 						continue;
   473 					//:TODO: Optimize this a bit!
   474 					SourceHook::List<GameDllInfo *>::iterator iter;
   475 					GameDllInfo *pCheck;
   476 					bool found = false;
   477 					for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   478 					{
   479 						pCheck = (*iter);
   480 						if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
   481 						{
   482 							if (UTIL_PathCmp(tempPath, buffer))
   483 							{
   484 								found = true;
   485 								break;
   486 							}
   487 						}
   488 					}
   489 					if (found)
   490 						continue;
   491 					fclose(fp);
   492 					HINSTANCE gamedll = dlmount(tempPath);
   493 					if (gamedll == NULL)
   494 						continue;
   495 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   496 					if (fn == NULL)
   497 					{
   498 						dlclose(gamedll);
   499 						continue;
   500 					}
   501 					GameDllInfo *pInfo = new GameDllInfo;
   502 					pInfo->factory = fn;
   503 					pInfo->lib = gamedll;
   504 					pInfo->loaded = true;
   505 					pInfo->pGameDLL = NULL;
   506 					gamedll_list.push_back(pInfo);
   507 					break;
   508 				}
   509 			}
   510 		}
   511 		fclose(fp);
   512 	}
   513 
   514 	if (!g_GameDll.loaded)
   515 	{
   516 		const char *str = "ServerGameDLL";
   517 		size_t len = strlen(str);
   518 
   519 		if (strncmp(iface, str, len) == 0)
   520 		{
   521 			/* This is the interface we want!  Right now we support versions 3 through 8 */
   522 			g_GameDllVersion = atoi(&(iface[len]));
   523 			int sizeTooBig = 0;	//rename this to sizeWrong in the future!
   524 			if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
   525 			{
   526 				/* Maybe this will get used in the future */
   527 				sizeTooBig = g_GameDllVersion;
   528 				if (ret)
   529 				{
   530 					*ret = IFACE_FAILED;
   531 				}
   532 			}
   533 			SourceHook::List<GameDllInfo *>::iterator iter;
   534 			GameDllInfo *pInfo = NULL;
   535 			void *ptr;
   536 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   537 			{
   538 				pInfo = (*iter);
   539 				ptr = (pInfo->factory)(iface, ret);
   540 				if (ptr)
   541 				{
   542 					/* This is our GameDLL. Unload the others. */
   543 					gamedll_list.erase(iter);
   544 					ClearGamedllList();
   545 					pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
   546 					g_GameDll = *pInfo;
   547 					delete pInfo;
   548 					break;
   549 				}
   550 			}
   551 			if (g_GameDll.loaded)
   552 			{
   553 				if (sizeTooBig)
   554 				{
   555 					Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
   556 					if (ret)
   557 					{
   558 						*ret = IFACE_FAILED;
   559 					}
   560 					return NULL;
   561 				} else {
   562 					InitMainStates();
   563 				}
   564 			} else {
   565 				sizeTooBig = 0;
   566 				if (ret)
   567 					*ret = IFACE_FAILED;
   568 				return NULL;
   569 			}
   570 		} else {
   571 			/* wtf do we do... */
   572 			/* :TODO: .. something a bit more intelligent? */
   573 			Error("Engine requested unknown interface before GameDLL was known!\n");
   574 			return NULL;
   575 		}
   576 	}
   577 
   578 	/* We use this interface for responding to the meta client command */
   579 	if (strncmp(iface, "ServerGameClients", 17) == 0)
   580 	{
   581 		void *ptr = (g_GameDll.factory)(iface, ret);
   582 		g_GameDll.pGameClients = static_cast<IServerGameClients *>(ptr);
   583 
   584 		return ptr;
   585 	}
   586 
   587 	/* If we got here, there's definitely a GameDLL */
   588 	IFACE_MACRO(g_GameDll.factory, GameDLL);
   589 }
   590 
   591 void ClearGamedllList()
   592 {
   593 	SourceHook::List<GameDllInfo *>::iterator iter;
   594 
   595 	GameDllInfo *pInfo;
   596 	for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   597 	{
   598 		pInfo = (*iter);
   599 		dlclose(pInfo->lib);
   600 		delete pInfo;
   601 	}
   602 
   603 	gamedll_list.clear();
   604 }
   605 
   606 void UnloadMetamod(bool shutting_down)
   607 {
   608 	/* Unload plugins */
   609 	g_PluginMngr.UnloadAll();
   610 
   611 	if (shutting_down)
   612 	{
   613 		/* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
   614 		g_SMConVarAccessor.MarkCommandsAsGameDLL();
   615 		g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
   616 
   617 		SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
   618 	}
   619 
   620 	SH_RELEASE_CALLCLASS(g_GameDllPatch);
   621 	SH_RELEASE_CALLCLASS(g_CvarPatch);
   622 	g_GameDllPatch = NULL;
   623 	g_CvarPatch = NULL;
   624 
   625 	g_SourceHook.CompleteShutdown();
   626 
   627 	if (g_GameDll.lib && g_GameDll.loaded)
   628 	{
   629 		dlclose(g_GameDll.lib);
   630 	}
   631 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   632 }
   633 
   634 void DLLShutdown_handler()
   635 {
   636 	UnloadMetamod(true);
   637 	RETURN_META(MRES_SUPERCEDE);
   638 }
   639 
   640 void LoadFromVDF(const char *file)
   641 {
   642 	PluginId id;
   643 	bool already, kvfileLoaded;
   644 	KeyValues *pValues;
   645 	const char *plugin_file, *alias;
   646 	char full_path[256], error[256];
   647 	
   648 	pValues = new KeyValues("Metamod Plugin");
   649 
   650 	if (g_Engine.original)
   651 	{
   652 		/* The Ship must use a special version of this function */
   653 		kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
   654 	}
   655 	else
   656 	{
   657 		kvfileLoaded = pValues->LoadFromFile(baseFs, file);
   658 	}
   659 
   660 	if (!kvfileLoaded)
   661 	{
   662 		pValues->deleteThis();
   663 		return;
   664 	}
   665 
   666 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   667 	{
   668 		pValues->deleteThis();
   669 		return;
   670 	}
   671 
   672 	if ((alias = pValues->GetString("alias", NULL)) != NULL)
   673 	{
   674 		g_PluginMngr.SetAlias(alias, plugin_file);
   675 	}
   676 
   677 	/* Attempt to find a file extension */
   678 	if (UTIL_GetExtension(plugin_file) == NULL)
   679 	{
   680 		g_SmmAPI.PathFormat(full_path, 
   681 			sizeof(full_path), 
   682 			"%s/%s%s", 
   683 			g_ModPath.c_str(), 
   684 			plugin_file, 
   685 #if defined WIN32 || defined _WIN32
   686 			".dll"
   687 #else
   688 			"_i486.so"
   689 #endif
   690 			);
   691 	}
   692 	else
   693 	{
   694 		g_SmmAPI.PathFormat(full_path,
   695 			sizeof(full_path),
   696 			"%s/%s", 
   697 			g_ModPath.c_str(),
   698 			plugin_file);
   699 	}
   700 
   701 	id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   702 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   703 	{
   704 		LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
   705 	}
   706 
   707 	pValues->deleteThis();
   708 }
   709 
   710 void LookForVDFs(const char *dir)
   711 {
   712 	char path[MAX_PATH];
   713 	int extidx;
   714 
   715 #if defined _MSC_VER
   716 	HANDLE hFind;
   717 	WIN32_FIND_DATA fd;
   718 	char error[255];
   719 
   720 	g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.*", dir);
   721 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
   722 	{
   723 		DWORD dw = GetLastError();
   724 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   725 			NULL,
   726 			dw,
   727 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   728 			error,
   729 			sizeof(error),
   730 			NULL);
   731 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
   732 		return;
   733 	}
   734 
   735 	do
   736 	{
   737 		if (strcmp(fd.cFileName, ".") == 0
   738 			|| strcmp(fd.cFileName, "..") == 0)
   739 		{
   740 			continue;
   741 		}
   742 		extidx = strlen(fd.cFileName) - 4;
   743 		if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
   744 		{
   745 			continue;
   746 		}
   747 		g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
   748 		LoadFromVDF(path);
   749 	} while (FindNextFile(hFind, &fd));
   750 
   751 	FindClose(hFind);
   752 #else
   753 	DIR *pDir;
   754 	struct dirent *pEnt;
   755 
   756 	if ((pDir = opendir(dir)) == NULL)
   757 	{
   758 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
   759 		return;
   760 	}
   761 
   762 	while ((pEnt = readdir(pDir)) != NULL)
   763 	{
   764 		if (strcmp(pEnt->d_name, ".") == 0
   765 			|| strcmp(pEnt->d_name, "..") == 0)
   766 		{
   767 			continue;
   768 		}
   769 		extidx = strlen(pEnt->d_name) - 4;
   770 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
   771 		{
   772 			continue;
   773 		}
   774 		g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
   775 		LoadFromVDF(path);
   776 	}
   777 
   778 	closedir(pDir);
   779 #endif
   780 }
   781 
   782 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
   783 {
   784 	Assert(filesystem);
   785 #ifdef _MSC_VER
   786 	Assert(_heapchk() == _HEAPOK);
   787 #endif
   788 
   789 	FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
   790 	if (!f)
   791 		return false;
   792 
   793 	// load file into a null-terminated buffer
   794 	int fileSize = filesystem->Size(f);
   795 	char *buffer = (char *)MemAllocScratch(fileSize + 1);
   796 	
   797 	Assert(buffer);
   798 	
   799 	filesystem->Read(buffer, fileSize, f); // read into local buffer
   800 
   801 	buffer[fileSize] = 0; // null terminate file as EOF
   802 
   803 	filesystem->Close( f );	// close file after reading
   804 
   805 	bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
   806 
   807 	MemFreeScratch();
   808 
   809 	return retOK;
   810 }
   811 
   812 int LoadPluginsFromFile(const char *_file)
   813 {
   814 	FILE *fp;
   815 	int total = 0, skipped=0;
   816 	PluginId id;
   817 	bool already;
   818 
   819 	fp = fopen(_file, "rt");
   820 	if (!fp)
   821 	{
   822 		LogMessage("[META] Could not open plugins file %s\n", _file);
   823 		return -1;
   824 	}
   825 
   826 	char buffer[255], error[255], full_path[255];
   827 	const char *ptr, *ext, *file;
   828 	size_t length;
   829 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   830 	{
   831 		UTIL_TrimLeft(buffer);
   832 		UTIL_TrimRight(buffer);
   833 
   834 		length = strlen(buffer);
   835 		if (!length)
   836 		{
   837 			continue;
   838 		}
   839 
   840 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   841 		{
   842 			continue;
   843 		}
   844 
   845 		file = buffer;
   846 		if (buffer[0] == '"')
   847 		{
   848 			char *cptr = buffer;
   849 			file = ++cptr;
   850 
   851 			while (*cptr)
   852 			{
   853 				if (*cptr == '"')
   854 				{
   855 					*cptr = '\0';
   856 					break;
   857 				}
   858 				cptr++;
   859 			}
   860 		}
   861 		else
   862 		{
   863 			char *cptr = buffer;
   864 			while (*cptr)
   865 			{
   866 				if (isspace(*cptr))
   867 				{
   868 					char *optr = cptr;
   869 					while (*cptr && isspace(*cptr))
   870 					{
   871 						cptr++;
   872 					}
   873 					*optr = '\0';
   874 					UTIL_TrimRight(cptr);
   875 					if (*cptr && isalpha(*cptr))
   876 					{
   877 						g_PluginMngr.SetAlias(buffer, cptr);
   878 						file = cptr;
   879 					}
   880 					break;
   881 				}
   882 				cptr++;
   883 			}
   884 		}
   885 		if (!file[0])
   886 		{
   887 			continue;
   888 		}
   889 		/* First find if it's an absolute path or not... */
   890 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   891 		{
   892 			/* If we're in an absolute path, ignore our normal heuristics */
   893 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   894 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   895 			{
   896 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   897 			}
   898 			else
   899 			{
   900 				if (already)
   901 				{
   902 					skipped++;
   903 				}
   904 				else
   905 				{
   906 					total++;
   907 				}
   908 			}
   909 		}
   910 		else
   911 		{
   912 			/* Attempt to find a file extension */
   913 			ptr = UTIL_GetExtension(file);
   914 			/* Add an extension if there's none there */
   915 			if (!ptr)
   916 			{
   917 #if defined WIN32 || defined _WIN32
   918 				ext = ".dll";
   919 #else
   920 				ext = "_i486.so";
   921 #endif
   922 			}
   923 			else
   924 			{
   925 				ext = "";
   926 			}
   927 			/* Format the new path */
   928 			g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
   929 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   930 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   931 			{
   932 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   933 			}
   934 			else
   935 			{
   936 				if (already)
   937 				{
   938 					skipped++;
   939 				}
   940 				else
   941 				{
   942 					total++;
   943 				}
   944 			}
   945 		}
   946 	}
   947 	fclose(fp);
   948 
   949 	if (skipped)
   950 	{
   951 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   952 	}
   953 	else
   954 	{
   955 		LogMessage("[META] Loaded %d plugins from file.", total);
   956 	}
   957 
   958 	return total;
   959 }
   960 
   961 
   962 /* Wrapper function.  This is called when the GameDLL thinks it's using
   963  * the engine's real engineFactory.
   964  */
   965 void *EngineFactory(const char *iface, int *ret)
   966 {
   967 	IFACE_MACRO(g_Engine.engineFactory, Engine);
   968 }
   969 
   970 /* Wrapper function.  This is called when the GameDLL thinks it's using
   971  * the engine's real physicsFactory.
   972  */
   973 void *PhysicsFactory(const char *iface, int *ret)
   974 {
   975 	IFACE_MACRO(g_Engine.physicsFactory, Physics);
   976 }
   977 
   978 /* Wrapper function.  This is called when the GameDLL thinks it's using
   979  * the engine's real fileSystemFactory.
   980  */
   981 void *FileSystemFactory(const char *iface, int *ret)
   982 {
   983 	IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
   984 }
   985 
   986 void LogMessage(const char *msg, ...)
   987 {
   988 	va_list ap;
   989 	static char buffer[2048];
   990 
   991 	va_start(ap, msg);
   992 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   993 	va_end(ap);
   994 
   995 	buffer[len++] = '\n';
   996 	buffer[len] = '\0';
   997 
   998 	if (!g_Engine.engine)
   999 	{
  1000 		fprintf(stdout, "%s", buffer);
  1001 	} else {
  1002 		g_Engine.engine->LogPrint(buffer);
  1003 	}
  1004 }
  1005 
  1006 void LevelShutdown_handler(void)
  1007 {
  1008 	if (!bInFirstLevel)
  1009 	{
  1010 		char full_path[255];
  1011 
  1012 		g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
  1013 		LoadPluginsFromFile(full_path);
  1014 
  1015 		g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
  1016 		LookForVDFs(full_path);
  1017 	}
  1018 	else
  1019 	{
  1020 		bInFirstLevel = false;
  1021 	}
  1022 
  1023 	g_bLevelChanged = true;
  1024 
  1025 	ITER_EVENT(OnLevelShutdown, ());
  1026 
  1027 	RETURN_META(MRES_IGNORED);
  1028 }
  1029 
  1030 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
  1031 {
  1032 	if (!g_SmmAPI.CmdCacheSuccessful())
  1033 	{
  1034 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
  1035 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
  1036 	}
  1037 
  1038 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
  1039 
  1040 	RETURN_META_VALUE(MRES_IGNORED, false);
  1041 }
  1042 
  1043 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
  1044 void * operator new(size_t size) {
  1045 	return(calloc(1, size)); 
  1046 }
  1047 
  1048 void * operator new[](size_t size) {
  1049 	return(calloc(1, size)); 
  1050 }
  1051 
  1052 void operator delete(void * ptr) {
  1053 	if(ptr)
  1054 		free(ptr);
  1055 }
  1056 
  1057 void operator delete[](void * ptr) {
  1058 	if(ptr)
  1059 		free(ptr);
  1060 }
  1061 #endif