core-legacy/sourcemm.cpp
author Scott Ehlert <ds@alliedmods.net>
Wed Nov 19 01:14:16 2008 -0600 (2008-11-19)
changeset 577 80120bac7719
parent 548 dd85920ecaaf
child 580 783e91c5f445
permissions -rw-r--r--
Changed FindFirstFile code in LookForVDFs to look for *.vdf instead of *.*
     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 IServerPluginCallbacks *g_pRealVspCallbacks = &g_VspListener;
    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 		RETURN_META_VALUE(MRES_IGNORED, true);
   313 
   314 	if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
   315 		g_SmmAPI.LoadAsVSP();
   316 
   317 	if (g_bIsBridgedAsVsp)
   318 		DoInitialPluginLoads();
   319 
   320 	bGameInit = true;
   321 
   322 	RETURN_META_VALUE(MRES_IGNORED, true);
   323 }
   324 
   325 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
   326 {
   327 	g_PluginMngr.SetAllLoaded();
   328 	RETURN_META_VALUE(MRES_IGNORED, true);
   329 }
   330 
   331 /* This is where the magic happens */
   332 SMM_API void *CreateInterface(const char *iface, int *ret)
   333 {
   334 	/* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
   335 	if (strcmp(iface, PLAPI_NAME) == 0)
   336 	{
   337 		Warning("Do not try loading Metamod:Source as a Metamod:Source plugin");
   338 
   339 		if (ret)
   340 		{
   341 			*ret = IFACE_FAILED;
   342 		}
   343 
   344 		return NULL;
   345 	}
   346 
   347 	/* We check these separately because we can't reply
   348 	 * unless our interface version really matches.
   349 	 */
   350 	if (!g_bIsBridgedAsVsp &&
   351 		(strcmp(iface, VSPIFACE_002) == 0 ||
   352 		 strcmp(iface, VSPIFACE_001) == 0))
   353 	{
   354 		if (ret)
   355 		{
   356 			*ret = IFACE_OK;
   357 		}
   358 		return &g_VspListener;
   359 	}
   360 
   361 	/* If we're a VSP, bypass this by default */
   362 	if (g_bIsBridgedAsVsp)
   363 	{
   364 		IFACE_MACRO(g_GameDll.factory, GameDLL);
   365 	}
   366 
   367 	if (!gParsedGameInfo)
   368 	{
   369 		gParsedGameInfo = true;
   370 		const char *gameDir = NULL;
   371 		char gamePath[PATH_SIZE];
   372 		char smmPath[PATH_SIZE];
   373 
   374 		/* Get path to SourceMM DLL */
   375 		if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
   376 		{
   377 			Error("GetFileOfAddress() failed! Metamod cannot load.\n");
   378 			return NULL;
   379 		}
   380 
   381 		g_SmmPath.assign(smmPath);
   382 
   383 		/* Get value of -game from command line, defaulting to hl2 as engine seems to do */
   384 		gameDir = CommandLine()->ParmValue("-game", "hl2");
   385 
   386 		/* Get absolute path */
   387 		abspath(gamePath, gameDir);
   388 		g_ModPath.assign(gamePath);
   389 
   390 		char tempPath[PATH_SIZE];
   391 
   392 		/* Path to gameinfo.txt */
   393 		g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
   394 
   395 		FILE *fp = fopen(tempPath, "rt");
   396 
   397 		if (!fp)
   398 		{
   399 			Error("Unable to open gameinfo.txt!  Metamod cannot load.\n");
   400 			return NULL;
   401 		}
   402 
   403 		char buffer[255];
   404 		char key[128], val[128];
   405 		size_t len = 0;
   406 		bool search = false;
   407 		bool gamebin = false;
   408 		char *ptr;
   409 		const char *lptr;
   410 		char curPath[PATH_SIZE];
   411 
   412 		getcwd(curPath, PATH_SIZE);
   413 
   414 		while (!feof(fp))
   415 		{
   416 			buffer[0] = '\0';
   417 			fgets(buffer, sizeof(buffer), fp);
   418 			len = strlen(buffer);
   419 			if (buffer[len-1] == '\n')
   420 				buffer[--len] = '\0';
   421 			UTIL_TrimComments(buffer);
   422 			UTIL_TrimLeft(buffer);
   423 			UTIL_TrimRight(buffer);
   424 			if (stricmp(buffer, "SearchPaths") == 0)
   425 				search = true;
   426 			if (!search)
   427 				continue;
   428 			UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
   429 			if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
   430 			{
   431 				if (stricmp(key, "Game") == 0)
   432 					gamebin = false;
   433 				else
   434 					gamebin = true;
   435 
   436 				if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
   437 				{
   438 					ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
   439 					if (ptr[0] == '.')
   440 						ptr++;
   441 					lptr = g_ModPath.c_str();
   442 				} else {
   443 					ptr = val;
   444 					lptr = curPath;
   445 				}
   446 
   447 				size_t ptr_len = strlen(ptr);
   448 				if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
   449 					ptr[--ptr_len] = '\0';
   450 
   451 				/* No need to append "bin" if key is GameBin */
   452 				if (gamebin)
   453 				{
   454 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
   455 				} else if (!ptr[0]) {
   456 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
   457 				} else {
   458 					g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
   459 				}
   460 
   461 				/* If not path to SourceMM... */
   462 				if (!UTIL_PathCmp(smmPath, tempPath))
   463 				{
   464 					FILE *fp = fopen(tempPath, "rb");
   465 					if (!fp)
   466 						continue;
   467 					//:TODO: Optimize this a bit!
   468 					SourceHook::List<GameDllInfo *>::iterator iter;
   469 					GameDllInfo *pCheck;
   470 					bool found = false;
   471 					for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   472 					{
   473 						pCheck = (*iter);
   474 						if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
   475 						{
   476 							if (UTIL_PathCmp(tempPath, buffer))
   477 							{
   478 								found = true;
   479 								break;
   480 							}
   481 						}
   482 					}
   483 					if (found)
   484 						continue;
   485 					fclose(fp);
   486 					HINSTANCE gamedll = dlmount(tempPath);
   487 					if (gamedll == NULL)
   488 						continue;
   489 					CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
   490 					if (fn == NULL)
   491 					{
   492 						dlclose(gamedll);
   493 						continue;
   494 					}
   495 					GameDllInfo *pInfo = new GameDllInfo;
   496 					pInfo->factory = fn;
   497 					pInfo->lib = gamedll;
   498 					pInfo->loaded = true;
   499 					pInfo->pGameDLL = NULL;
   500 					gamedll_list.push_back(pInfo);
   501 					break;
   502 				}
   503 			}
   504 		}
   505 		fclose(fp);
   506 	}
   507 
   508 	if (!g_GameDll.loaded)
   509 	{
   510 		const char *str = "ServerGameDLL";
   511 		size_t len = strlen(str);
   512 
   513 		if (strncmp(iface, str, len) == 0)
   514 		{
   515 			/* This is the interface we want!  Right now we support versions 3 through 8 */
   516 			g_GameDllVersion = atoi(&(iface[len]));
   517 			int sizeTooBig = 0;	//rename this to sizeWrong in the future!
   518 			if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
   519 			{
   520 				/* Maybe this will get used in the future */
   521 				sizeTooBig = g_GameDllVersion;
   522 				if (ret)
   523 				{
   524 					*ret = IFACE_FAILED;
   525 				}
   526 			}
   527 			SourceHook::List<GameDllInfo *>::iterator iter;
   528 			GameDllInfo *pInfo = NULL;
   529 			void *ptr;
   530 			for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   531 			{
   532 				pInfo = (*iter);
   533 				ptr = (pInfo->factory)(iface, ret);
   534 				if (ptr)
   535 				{
   536 					/* This is our GameDLL. Unload the others. */
   537 					gamedll_list.erase(iter);
   538 					ClearGamedllList();
   539 					pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
   540 					g_GameDll = *pInfo;
   541 					delete pInfo;
   542 					break;
   543 				}
   544 			}
   545 			if (g_GameDll.loaded)
   546 			{
   547 				if (sizeTooBig)
   548 				{
   549 					Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
   550 					if (ret)
   551 					{
   552 						*ret = IFACE_FAILED;
   553 					}
   554 					return NULL;
   555 				} else {
   556 					InitMainStates();
   557 				}
   558 			} else {
   559 				sizeTooBig = 0;
   560 				if (ret)
   561 					*ret = IFACE_FAILED;
   562 				return NULL;
   563 			}
   564 		} else {
   565 			/* wtf do we do... */
   566 			/* :TODO: .. something a bit more intelligent? */
   567 			Error("Engine requested unknown interface before GameDLL was known!\n");
   568 			return NULL;
   569 		}
   570 	}
   571 
   572 	/* We use this interface for responding to the meta client command */
   573 	if (strncmp(iface, "ServerGameClients", 17) == 0)
   574 	{
   575 		void *ptr = (g_GameDll.factory)(iface, ret);
   576 		g_GameDll.pGameClients = static_cast<IServerGameClients *>(ptr);
   577 
   578 		return ptr;
   579 	}
   580 
   581 	/* If we got here, there's definitely a GameDLL */
   582 	IFACE_MACRO(g_GameDll.factory, GameDLL);
   583 }
   584 
   585 void ClearGamedllList()
   586 {
   587 	SourceHook::List<GameDllInfo *>::iterator iter;
   588 
   589 	GameDllInfo *pInfo;
   590 	for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
   591 	{
   592 		pInfo = (*iter);
   593 		dlclose(pInfo->lib);
   594 		delete pInfo;
   595 	}
   596 
   597 	gamedll_list.clear();
   598 }
   599 
   600 void UnloadMetamod(bool shutting_down)
   601 {
   602 	/* Unload plugins */
   603 	g_PluginMngr.UnloadAll();
   604 
   605 	if (shutting_down)
   606 	{
   607 		/* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
   608 		g_SMConVarAccessor.MarkCommandsAsGameDLL();
   609 		g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
   610 
   611 		SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
   612 	}
   613 
   614 	SH_RELEASE_CALLCLASS(g_GameDllPatch);
   615 	SH_RELEASE_CALLCLASS(g_CvarPatch);
   616 	g_GameDllPatch = NULL;
   617 	g_CvarPatch = NULL;
   618 
   619 	g_SourceHook.CompleteShutdown();
   620 
   621 	if (g_GameDll.lib && g_GameDll.loaded)
   622 	{
   623 		dlclose(g_GameDll.lib);
   624 	}
   625 	memset(&g_GameDll, 0, sizeof(GameDllInfo));
   626 }
   627 
   628 void DLLShutdown_handler()
   629 {
   630 	UnloadMetamod(true);
   631 	RETURN_META(MRES_SUPERCEDE);
   632 }
   633 
   634 void LoadFromVDF(const char *file)
   635 {
   636 	PluginId id;
   637 	bool already, kvfileLoaded;
   638 	KeyValues *pValues;
   639 	const char *plugin_file, *alias;
   640 	char full_path[256], error[256];
   641 	
   642 	pValues = new KeyValues("Metamod Plugin");
   643 
   644 	if (g_Engine.original)
   645 	{
   646 		/* The Ship must use a special version of this function */
   647 		kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
   648 	}
   649 	else
   650 	{
   651 		kvfileLoaded = pValues->LoadFromFile(baseFs, file);
   652 	}
   653 
   654 	if (!kvfileLoaded)
   655 	{
   656 		pValues->deleteThis();
   657 		return;
   658 	}
   659 
   660 	if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
   661 	{
   662 		pValues->deleteThis();
   663 		return;
   664 	}
   665 
   666 	if ((alias = pValues->GetString("alias", NULL)) != NULL)
   667 	{
   668 		g_PluginMngr.SetAlias(alias, plugin_file);
   669 	}
   670 
   671 	/* Attempt to find a file extension */
   672 	if (UTIL_GetExtension(plugin_file) == NULL)
   673 	{
   674 		g_SmmAPI.PathFormat(full_path, 
   675 			sizeof(full_path), 
   676 			"%s/%s%s", 
   677 			g_ModPath.c_str(), 
   678 			plugin_file, 
   679 #if defined WIN32 || defined _WIN32
   680 			".dll"
   681 #else
   682 			"_i486.so"
   683 #endif
   684 			);
   685 	}
   686 	else
   687 	{
   688 		g_SmmAPI.PathFormat(full_path,
   689 			sizeof(full_path),
   690 			"%s/%s", 
   691 			g_ModPath.c_str(),
   692 			plugin_file);
   693 	}
   694 
   695 	id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   696 	if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   697 	{
   698 		LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
   699 	}
   700 
   701 	pValues->deleteThis();
   702 }
   703 
   704 void LookForVDFs(const char *dir)
   705 {
   706 	char path[MAX_PATH];
   707 
   708 #if defined _MSC_VER
   709 	HANDLE hFind;
   710 	WIN32_FIND_DATA fd;
   711 	char error[255];
   712 
   713 	g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
   714 	if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
   715 	{
   716 		DWORD dw = GetLastError();
   717 		if (dw == ERROR_FILE_NOT_FOUND)
   718 			return;
   719 
   720 		FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
   721 			NULL,
   722 			dw,
   723 			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   724 			error,
   725 			sizeof(error),
   726 			NULL);
   727 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
   728 		return;
   729 	}
   730 
   731 	do
   732 	{
   733 		g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
   734 		LoadFromVDF(path);
   735 	} while (FindNextFile(hFind, &fd));
   736 
   737 	FindClose(hFind);
   738 #else
   739 	DIR *pDir;
   740 	struct dirent *pEnt;
   741 	int extidx;
   742 
   743 	if ((pDir = opendir(dir)) == NULL)
   744 	{
   745 		LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
   746 		return;
   747 	}
   748 
   749 	while ((pEnt = readdir(pDir)) != NULL)
   750 	{
   751 		if (strcmp(pEnt->d_name, ".") == 0
   752 			|| strcmp(pEnt->d_name, "..") == 0)
   753 		{
   754 			continue;
   755 		}
   756 		extidx = strlen(pEnt->d_name) - 4;
   757 		if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
   758 		{
   759 			continue;
   760 		}
   761 		g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
   762 		LoadFromVDF(path);
   763 	}
   764 
   765 	closedir(pDir);
   766 #endif
   767 }
   768 
   769 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
   770 {
   771 	Assert(filesystem);
   772 #ifdef _MSC_VER
   773 	Assert(_heapchk() == _HEAPOK);
   774 #endif
   775 
   776 	FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
   777 	if (!f)
   778 		return false;
   779 
   780 	// load file into a null-terminated buffer
   781 	int fileSize = filesystem->Size(f);
   782 	char *buffer = (char *)MemAllocScratch(fileSize + 1);
   783 	
   784 	Assert(buffer);
   785 	
   786 	filesystem->Read(buffer, fileSize, f); // read into local buffer
   787 
   788 	buffer[fileSize] = 0; // null terminate file as EOF
   789 
   790 	filesystem->Close( f );	// close file after reading
   791 
   792 	bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
   793 
   794 	MemFreeScratch();
   795 
   796 	return retOK;
   797 }
   798 
   799 int LoadPluginsFromFile(const char *_file)
   800 {
   801 	FILE *fp;
   802 	int total = 0, skipped=0;
   803 	PluginId id;
   804 	bool already;
   805 
   806 	fp = fopen(_file, "rt");
   807 	if (!fp)
   808 	{
   809 		LogMessage("[META] Could not open plugins file %s\n", _file);
   810 		return -1;
   811 	}
   812 
   813 	char buffer[255], error[255], full_path[255];
   814 	const char *ptr, *ext, *file;
   815 	size_t length;
   816 	while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   817 	{
   818 		UTIL_TrimLeft(buffer);
   819 		UTIL_TrimRight(buffer);
   820 
   821 		length = strlen(buffer);
   822 		if (!length)
   823 		{
   824 			continue;
   825 		}
   826 
   827 		if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
   828 		{
   829 			continue;
   830 		}
   831 
   832 		file = buffer;
   833 		if (buffer[0] == '"')
   834 		{
   835 			char *cptr = buffer;
   836 			file = ++cptr;
   837 
   838 			while (*cptr)
   839 			{
   840 				if (*cptr == '"')
   841 				{
   842 					*cptr = '\0';
   843 					break;
   844 				}
   845 				cptr++;
   846 			}
   847 		}
   848 		else
   849 		{
   850 			char *cptr = buffer;
   851 			while (*cptr)
   852 			{
   853 				if (isspace(*cptr))
   854 				{
   855 					char *optr = cptr;
   856 					while (*cptr && isspace(*cptr))
   857 					{
   858 						cptr++;
   859 					}
   860 					*optr = '\0';
   861 					UTIL_TrimRight(cptr);
   862 					if (*cptr && isalpha(*cptr))
   863 					{
   864 						g_PluginMngr.SetAlias(buffer, cptr);
   865 						file = cptr;
   866 					}
   867 					break;
   868 				}
   869 				cptr++;
   870 			}
   871 		}
   872 		if (!file[0])
   873 		{
   874 			continue;
   875 		}
   876 		/* First find if it's an absolute path or not... */
   877 		if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
   878 		{
   879 			/* If we're in an absolute path, ignore our normal heuristics */
   880 			id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
   881 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   882 			{
   883 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   884 			}
   885 			else
   886 			{
   887 				if (already)
   888 				{
   889 					skipped++;
   890 				}
   891 				else
   892 				{
   893 					total++;
   894 				}
   895 			}
   896 		}
   897 		else
   898 		{
   899 			/* Attempt to find a file extension */
   900 			ptr = UTIL_GetExtension(file);
   901 			/* Add an extension if there's none there */
   902 			if (!ptr)
   903 			{
   904 #if defined WIN32 || defined _WIN32
   905 				ext = ".dll";
   906 #else
   907 				ext = "_i486.so";
   908 #endif
   909 			}
   910 			else
   911 			{
   912 				ext = "";
   913 			}
   914 			/* Format the new path */
   915 			g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
   916 			id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
   917 			if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
   918 			{
   919 				LogMessage("[META] Failed to load plugin %s.  %s", buffer, error);
   920 			}
   921 			else
   922 			{
   923 				if (already)
   924 				{
   925 					skipped++;
   926 				}
   927 				else
   928 				{
   929 					total++;
   930 				}
   931 			}
   932 		}
   933 	}
   934 	fclose(fp);
   935 
   936 	if (skipped)
   937 	{
   938 		LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
   939 	}
   940 	else
   941 	{
   942 		LogMessage("[META] Loaded %d plugins from file.", total);
   943 	}
   944 
   945 	return total;
   946 }
   947 
   948 
   949 /* Wrapper function.  This is called when the GameDLL thinks it's using
   950  * the engine's real engineFactory.
   951  */
   952 void *EngineFactory(const char *iface, int *ret)
   953 {
   954 	IFACE_MACRO(g_Engine.engineFactory, Engine);
   955 }
   956 
   957 /* Wrapper function.  This is called when the GameDLL thinks it's using
   958  * the engine's real physicsFactory.
   959  */
   960 void *PhysicsFactory(const char *iface, int *ret)
   961 {
   962 	IFACE_MACRO(g_Engine.physicsFactory, Physics);
   963 }
   964 
   965 /* Wrapper function.  This is called when the GameDLL thinks it's using
   966  * the engine's real fileSystemFactory.
   967  */
   968 void *FileSystemFactory(const char *iface, int *ret)
   969 {
   970 	IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
   971 }
   972 
   973 void LogMessage(const char *msg, ...)
   974 {
   975 	va_list ap;
   976 	static char buffer[2048];
   977 
   978 	va_start(ap, msg);
   979 	size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
   980 	va_end(ap);
   981 
   982 	buffer[len++] = '\n';
   983 	buffer[len] = '\0';
   984 
   985 	if (!g_Engine.engine)
   986 	{
   987 		fprintf(stdout, "%s", buffer);
   988 	} else {
   989 		g_Engine.engine->LogPrint(buffer);
   990 	}
   991 }
   992 
   993 void LevelShutdown_handler(void)
   994 {
   995 	if (!bInFirstLevel)
   996 	{
   997 		char full_path[255];
   998 
   999 		g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
  1000 		LoadPluginsFromFile(full_path);
  1001 
  1002 		g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
  1003 		LookForVDFs(full_path);
  1004 	}
  1005 	else
  1006 	{
  1007 		bInFirstLevel = false;
  1008 	}
  1009 
  1010 	g_bLevelChanged = true;
  1011 
  1012 	ITER_EVENT(OnLevelShutdown, ());
  1013 
  1014 	RETURN_META(MRES_IGNORED);
  1015 }
  1016 
  1017 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
  1018 {
  1019 	if (!g_SmmAPI.CmdCacheSuccessful())
  1020 	{
  1021 		LogMessage("[META] Warning: Failed to initialize Con_Printf.  Defaulting to Msg().");
  1022 		LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
  1023 	}
  1024 
  1025 	ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
  1026 
  1027 	RETURN_META_VALUE(MRES_IGNORED, false);
  1028 }
  1029 
  1030 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
  1031 void * operator new(size_t size) {
  1032 	return(calloc(1, size)); 
  1033 }
  1034 
  1035 void * operator new[](size_t size) {
  1036 	return(calloc(1, size)); 
  1037 }
  1038 
  1039 void operator delete(void * ptr) {
  1040 	if(ptr)
  1041 		free(ptr);
  1042 }
  1043 
  1044 void operator delete[](void * ptr) {
  1045 	if(ptr)
  1046 		free(ptr);
  1047 }
  1048 #endif