1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2007 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): David "BAILOPAN" Anderson
8 * Contributor(s): Scott "Damaged Soul" Ehlert
9 * : Pavol "PM OnoTo" Marko
10 * ============================
13 #include <interface.h>
15 #include <tier0/icommandline.h>
17 #include "concommands.h"
21 #include "vsp_listener.h"
23 using namespace SourceMM;
26 * @brief Implementation of main SourceMM GameDLL functionality
31 DLL_IMPORT ICommandLine *CommandLine();
33 SH_DECL_HOOK4(IServerGameDLL, DLLInit, SH_NOATTRIB, false, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
34 SH_DECL_HOOK0_void(IServerGameDLL, DLLShutdown, SH_NOATTRIB, false);
35 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
36 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
37 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
38 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
40 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
41 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
42 void DLLShutdown_handler();
43 void LevelShutdown_handler();
44 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
45 bool GameInit_handler();
47 GameDllInfo g_GameDll = {false, NULL, NULL, NULL, NULL};
49 SourceHook::CSourceHookImpl g_SourceHook;
50 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
51 SourceHook::String g_ModPath;
52 SourceHook::String g_BinPath;
53 SourceHook::String g_SmmPath;
54 PluginId g_PLID = Pl_Console; /* Technically, SourceMM is the "Console" plugin... :p */
55 bool bInFirstLevel = true;
56 bool gParsedGameInfo = false;
57 bool bGameInit = false;
58 SourceHook::List<GameDllInfo *> gamedll_list;
59 SourceHook::CallClass<IServerGameDLL> *g_GameDllPatch;
60 int g_GameDllVersion = 0;
61 int g_GameClientsVersion = 0;
63 int g_SourceEngineVersion = SOURCE_ENGINE_ORIGINAL;
64 const char VSPIFACE[] = "ISERVERPLUGINCALLBACKS";
65 const char GAMEINFO_PATH[] = "|gameinfo_path|";
67 void ClearGamedllList();
70 #define IFACE_MACRO(orig,nam) \
71 CPluginManager::CPlugin *pl; \
72 SourceHook::List<IMetamodListener *>::iterator event; \
73 IMetamodListener *api; \
76 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
78 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
80 mret = IFACE_FAILED; \
81 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
82 if (ret) *ret = mret; \
87 return (orig)(iface, ret);
89 #define ITER_EVENT(evn, args) \
90 CPluginManager::CPlugin *pl; \
91 SourceHook::List<IMetamodListener *>::iterator event; \
92 IMetamodListener *api; \
93 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
95 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
101 ///////////////////////////////////
102 // Main code for HL2 Interaction //
103 ///////////////////////////////////
105 /* Initialize everything here */
106 void InitMainStates()
108 char full_path[PATH_SIZE] = {0};
109 GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path));
110 g_BinPath.assign(full_path);
112 /* Like Metamod, reload plugins at the end of the map.
113 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
114 * if the server is shut down (silly, but rare case).
116 bInFirstLevel = true;
118 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
119 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
120 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
121 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
122 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
123 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
126 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
128 g_Engine.engineFactory = engineFactory;
129 g_Engine.fileSystemFactory = filesystemFactory;
130 g_Engine.physicsFactory = physicsFactory;
131 g_Engine.pGlobals = pGlobals;
133 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
134 if (!g_Engine.engine)
136 Error("Could not find IVEngineServer! Metamod cannot load.");
139 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
142 Error("Could not find ICvar! Metamod cannot load.");
146 g_Engine.loaded = true;
148 /* Initialize our console hooks */
149 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
151 g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
153 if (g_GameDll.pGameClients)
155 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
157 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
158 LogMessage("[META] Warning: Could not find IServerGameClients!");
159 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
162 if (!g_SmmAPI.CacheCmds())
164 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
165 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
168 if (!g_SmmAPI.CacheUserMessages())
170 /* Don't know of a mod that has stripped out user messages completely,
171 * but perhaps should do something different here?
173 LogMessage("[META] Warning: Failed to get list of user messages.");
174 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
177 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
180 pluginFile = GetPluginsFile();
184 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), pluginFile);
186 LoadPluginsFromFile(full_path);
188 bInFirstLevel = true;
190 RETURN_META_VALUE(MRES_IGNORED, true);
193 bool GameInit_handler()
200 if (g_SmmAPI.VSPEnabled())
202 g_SmmAPI.LoadAsVSP();
207 RETURN_META_VALUE(MRES_IGNORED, true);
210 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
212 g_PluginMngr.SetAllLoaded();
213 RETURN_META_VALUE(MRES_IGNORED, true);
216 /* This is where the magic happens */
217 SMM_API void *CreateInterface(const char *iface, int *ret)
219 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
220 if (strcmp(iface, PLAPI_NAME) == 0)
222 Warning("Do not try loading Metamod:Source as a plugin.\n");
232 if (strncmp(iface, VSPIFACE, 22) == 0)
234 g_VspVersion = atoi(&(iface[22]));
236 if (g_VspVersion <= MAX_VSP_VERSION)
242 return &g_VspListener;
246 if (!gParsedGameInfo)
248 gParsedGameInfo = true;
249 const char *gameDir = NULL;
250 char gamePath[PATH_SIZE];
251 char smmPath[PATH_SIZE];
253 /* Get path to SourceMM DLL */
254 if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
256 Error("GetFileOfAddress() failed! Metamod cannot load.\n");
260 g_SmmPath.assign(smmPath);
262 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
263 gameDir = CommandLine()->ParmValue("-game", "hl2");
265 /* Get absolute path */
266 abspath(gamePath, gameDir);
267 g_ModPath.assign(gamePath);
269 char tempPath[PATH_SIZE];
271 /* Path to gameinfo.txt */
272 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
274 FILE *fp = fopen(tempPath, "rt");
278 Error("Unable to open gameinfo.txt! Metamod cannot load.\n");
283 char key[128], val[128];
285 bool gamebin = false;
288 char curPath[PATH_SIZE];
290 getcwd(curPath, PATH_SIZE);
295 fgets(buffer, sizeof(buffer), fp);
296 UTIL_TrimComments(buffer);
297 UTIL_TrimLeft(buffer);
298 UTIL_TrimRight(buffer);
299 if (stricmp(buffer, "SearchPaths") == 0)
303 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
304 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
306 if (stricmp(key, "Game") == 0)
311 if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
313 ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
316 lptr = g_ModPath.c_str();
322 size_t ptr_len = strlen(ptr);
323 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
324 ptr[--ptr_len] = '\0';
326 /* No need to append "bin" if key is GameBin */
329 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
330 } else if (!ptr[0]) {
331 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
333 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
336 /* If not path to SourceMM... */
337 if (!UTIL_PathCmp(smmPath, tempPath))
339 FILE *fp = fopen(tempPath, "rb");
342 //:TODO: Optimize this a bit!
343 SourceHook::List<GameDllInfo *>::iterator iter;
346 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
349 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
351 if (UTIL_PathCmp(tempPath, buffer))
361 HINSTANCE gamedll = dlmount(tempPath);
364 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
370 GameDllInfo *pInfo = new GameDllInfo;
372 pInfo->lib = gamedll;
373 pInfo->loaded = true;
374 pInfo->pGameDLL = NULL;
375 gamedll_list.push_back(pInfo);
383 if (!g_GameDll.loaded)
385 const char *str = "ServerGameDLL";
386 size_t len = strlen(str);
388 if (strncmp(iface, str, len) == 0)
390 /* This is the interface we want! Right now we support versions 3 through 8 */
391 g_GameDllVersion = atoi(&(iface[len]));
392 if (g_GameDllVersion < MIN_GAMEDLL_VERSION)
399 else if (g_GameDllVersion > 3)
401 /* The engine is at least episode 1 */
402 g_SourceEngineVersion = SOURCE_ENGINE_EPISODEONE;
404 SourceHook::List<GameDllInfo *>::iterator iter;
405 GameDllInfo *pInfo = NULL;
407 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
410 ptr = (pInfo->factory)(iface, ret);
413 /* This is our GameDLL. Unload the others. */
414 gamedll_list.erase(iter);
416 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
422 if (g_GameDll.loaded)
433 /* wtf do we do... */
434 /* :TODO: .. something a bit more intelligent? */
435 Error("Engine requested unknown interface before GameDLL was known!\n");
440 /* We use this interface for responding to the meta client command */
441 if (strncmp(iface, "ServerGameClients", 17) == 0)
443 void *ptr = (g_GameDll.factory)(iface, ret);
444 g_GameDll.pGameClients = static_cast<IServerGameClients *>(ptr);
445 g_GameClientsVersion = atoi(&iface[17]);
450 /* If we got here, there's definitely a GameDLL */
451 IFACE_MACRO(g_GameDll.factory, GameDLL);
454 void ClearGamedllList()
456 SourceHook::List<GameDllInfo *>::iterator iter;
459 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
466 gamedll_list.clear();
469 void DLLShutdown_handler()
472 g_PluginMngr.UnloadAll();
474 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
475 g_SMConVarAccessor.MarkCommandsAsGameDLL();
476 g_SMConVarAccessor.UnregisterGameDLLCommands();
478 SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
480 SH_RELEASE_CALLCLASS(g_GameDllPatch);
481 g_GameDllPatch = NULL;
483 g_SourceHook.CompleteShutdown();
485 if (g_GameDll.lib && g_GameDll.loaded)
486 dlclose(g_GameDll.lib);
487 memset(&g_GameDll, 0, sizeof(GameDllInfo));
489 RETURN_META(MRES_SUPERCEDE);
492 int LoadPluginsFromFile(const char *_file)
495 int total = 0, skipped=0;
499 fp = fopen(_file, "rt");
502 LogMessage("[META] Could not open plugins file %s\n", _file);
506 char buffer[255], error[255], full_path[255];
507 const char *ptr, *ext, *file;
512 fgets(buffer, sizeof(buffer), fp);
513 length = strlen(buffer);
516 if (buffer[length-1] == '\n')
517 buffer[--length] = '\0';
519 UTIL_TrimLeft(buffer);
520 UTIL_TrimRight(buffer);
522 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
525 if (buffer[0] == '"')
546 while (*cptr && isspace(*cptr))
549 UTIL_TrimRight(cptr);
550 if (*cptr && isalpha(*cptr))
552 g_PluginMngr.SetAlias(buffer, cptr);
564 /* First find if it's an absolute path or not... */
565 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
567 /* If we're in an absolute path, ignore our normal heuristics */
568 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
569 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
571 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
579 /* Attempt to find a file extension */
580 ptr = UTIL_GetExtension(file);
581 /* Add an extension if there's none there */
584 #if defined WIN32 || defined _WIN32
592 /* Format the new path */
593 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
594 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
595 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
597 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
610 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
612 LogMessage("[META] Loaded %d plugins from file.", total);
618 /* Wrapper function. This is called when the GameDLL thinks it's using
619 * the engine's real engineFactory.
621 void *EngineFactory(const char *iface, int *ret)
623 IFACE_MACRO(g_Engine.engineFactory, Engine);
626 /* Wrapper function. This is called when the GameDLL thinks it's using
627 * the engine's real physicsFactory.
629 void *PhysicsFactory(const char *iface, int *ret)
631 IFACE_MACRO(g_Engine.physicsFactory, Physics);
634 /* Wrapper function. This is called when the GameDLL thinks it's using
635 * the engine's real fileSystemFactory.
637 void *FileSystemFactory(const char *iface, int *ret)
639 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
642 void LogMessage(const char *msg, ...)
645 static char buffer[2048];
648 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
651 buffer[len++] = '\n';
654 if (!g_Engine.engine)
656 fprintf(stdout, "%s", buffer);
658 g_Engine.engine->LogPrint(buffer);
662 void LevelShutdown_handler(void)
667 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
669 LoadPluginsFromFile(full_path);
671 bInFirstLevel = false;
674 ITER_EVENT(OnLevelShutdown, ());
676 RETURN_META(MRES_IGNORED);
679 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
681 if (!g_SmmAPI.CmdCacheSuccessful())
683 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
684 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
687 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
689 RETURN_META_VALUE(MRES_IGNORED, false);
692 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
693 void * operator new(size_t size) {
694 return(calloc(1, size));
697 void * operator new[](size_t size) {
698 return(calloc(1, size));
701 void operator delete(void * ptr) {
706 void operator delete[](void * ptr) {