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;
62 const char VSPIFACE[] = "ISERVERPLUGINCALLBACKS";
63 const char GAMEINFO_PATH[] = "|gameinfo_path|";
65 void ClearGamedllList();
68 #define IFACE_MACRO(orig,nam) \
69 CPluginManager::CPlugin *pl; \
70 SourceHook::List<IMetamodListener *>::iterator event; \
71 IMetamodListener *api; \
74 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
76 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
78 mret = IFACE_FAILED; \
79 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
80 if (ret) *ret = mret; \
85 return (orig)(iface, ret);
87 #define ITER_EVENT(evn, args) \
88 CPluginManager::CPlugin *pl; \
89 SourceHook::List<IMetamodListener *>::iterator event; \
90 IMetamodListener *api; \
91 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
93 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
99 ///////////////////////////////////
100 // Main code for HL2 Interaction //
101 ///////////////////////////////////
103 /* Initialize everything here */
104 void InitMainStates()
106 char full_path[PATH_SIZE] = {0};
107 GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path));
108 g_BinPath.assign(full_path);
110 /* Like Metamod, reload plugins at the end of the map.
111 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
112 * if the server is shut down (silly, but rare case).
114 bInFirstLevel = true;
116 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
117 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
118 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
119 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
120 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
121 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
124 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
126 g_Engine.engineFactory = engineFactory;
127 g_Engine.fileSystemFactory = filesystemFactory;
128 g_Engine.physicsFactory = physicsFactory;
129 g_Engine.pGlobals = pGlobals;
131 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
132 if (!g_Engine.engine)
134 Error("Could not find IVEngineServer! Metamod cannot load.");
137 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
140 Error("Could not find ICvar! Metamod cannot load.");
144 g_Engine.loaded = true;
146 /* Initialize our console hooks */
147 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
149 g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
151 if (g_GameDll.pGameClients)
153 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
155 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
156 LogMessage("[META] Warning: Could not find IServerGameClients!");
157 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
160 if (!g_SmmAPI.CacheCmds())
162 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
163 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
166 if (!g_SmmAPI.CacheUserMessages())
168 /* Don't know of a mod that has stripped out user messages completely,
169 * but perhaps should do something different here?
171 LogMessage("[META] Warning: Failed to get list of user messages.");
172 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
175 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
178 pluginFile = GetPluginsFile();
182 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), pluginFile);
184 LoadPluginsFromFile(full_path);
186 bInFirstLevel = true;
188 RETURN_META_VALUE(MRES_IGNORED, true);
191 bool GameInit_handler()
198 if (g_SmmAPI.VSPEnabled())
200 g_SmmAPI.LoadAsVSP();
205 RETURN_META_VALUE(MRES_IGNORED, true);
208 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
210 g_PluginMngr.SetAllLoaded();
211 RETURN_META_VALUE(MRES_IGNORED, true);
214 /* This is where the magic happens */
215 SMM_API void *CreateInterface(const char *iface, int *ret)
217 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
218 if (strcmp(iface, PLAPI_NAME) == 0)
220 Warning("Do not try loading Metamod:Source as a SourceMM or Valve server plugin.\n");
230 if (strncmp(iface, VSPIFACE, 22) == 0)
232 g_VspVersion = atoi(&(iface[22]));
234 if (g_VspVersion <= MAX_VSP_VERSION)
240 return &g_VspListener;
244 if (!gParsedGameInfo)
246 gParsedGameInfo = true;
247 const char *gameDir = NULL;
248 char gamePath[PATH_SIZE];
249 char smmPath[PATH_SIZE];
251 /* Get path to SourceMM DLL */
252 if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
254 Error("GetFileOfAddress() failed! Metamod cannot load.\n");
258 g_SmmPath.assign(smmPath);
260 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
261 gameDir = CommandLine()->ParmValue("-game", "hl2");
263 /* Get absolute path */
264 abspath(gamePath, gameDir);
265 g_ModPath.assign(gamePath);
267 char tempPath[PATH_SIZE];
269 /* Path to gameinfo.txt */
270 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
272 FILE *fp = fopen(tempPath, "rt");
276 Error("Unable to open gameinfo.txt! Metamod cannot load.\n");
281 char key[128], val[128];
284 bool gamebin = false;
287 char curPath[PATH_SIZE];
289 getcwd(curPath, PATH_SIZE);
294 fgets(buffer, sizeof(buffer), fp);
295 len = strlen(buffer);
296 if (buffer[len-1] == '\n')
297 buffer[--len] = '\0';
298 UTIL_TrimComments(buffer);
299 UTIL_TrimLeft(buffer);
300 UTIL_TrimRight(buffer);
301 if (stricmp(buffer, "SearchPaths") == 0)
305 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
306 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
308 if (stricmp(key, "Game") == 0)
313 if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
315 ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
318 lptr = g_ModPath.c_str();
324 size_t ptr_len = strlen(ptr);
325 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
326 ptr[--ptr_len] = '\0';
328 /* No need to append "bin" if key is GameBin */
331 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
332 } else if (!ptr[0]) {
333 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
335 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
338 /* If not path to SourceMM... */
339 if (!UTIL_PathCmp(smmPath, tempPath))
341 FILE *fp = fopen(tempPath, "rb");
344 //:TODO: Optimize this a bit!
345 SourceHook::List<GameDllInfo *>::iterator iter;
348 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
351 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
353 if (UTIL_PathCmp(tempPath, buffer))
363 HINSTANCE gamedll = dlmount(tempPath);
366 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
372 GameDllInfo *pInfo = new GameDllInfo;
374 pInfo->lib = gamedll;
375 pInfo->loaded = true;
376 pInfo->pGameDLL = NULL;
377 gamedll_list.push_back(pInfo);
385 if (!g_GameDll.loaded)
387 const char *str = "ServerGameDLL";
388 size_t len = strlen(str);
390 if (strncmp(iface, str, len) == 0)
392 /* This is the interface we want! Right now we support versions 3 through 8 */
393 g_GameDllVersion = atoi(&(iface[len]));
394 int sizeTooBig = 0; //rename this to sizeWrong in the future!
395 if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
397 /* Maybe this will get used in the future */
398 sizeTooBig = g_GameDllVersion;
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)
426 Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
442 /* wtf do we do... */
443 /* :TODO: .. something a bit more intelligent? */
444 Error("Engine requested unknown interface before GameDLL was known!\n");
449 /* We use this interface for responding to the meta client command */
450 if (strncmp(iface, "ServerGameClients", 17) == 0)
452 void *ptr = (g_GameDll.factory)(iface, ret);
453 g_GameDll.pGameClients = static_cast<IServerGameClients *>(ptr);
458 /* If we got here, there's definitely a GameDLL */
459 IFACE_MACRO(g_GameDll.factory, GameDLL);
462 void ClearGamedllList()
464 SourceHook::List<GameDllInfo *>::iterator iter;
467 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
474 gamedll_list.clear();
477 void DLLShutdown_handler()
480 g_PluginMngr.UnloadAll();
482 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
483 g_SMConVarAccessor.MarkCommandsAsGameDLL();
484 g_SMConVarAccessor.UnregisterGameDLLCommands();
486 SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
488 SH_RELEASE_CALLCLASS(g_GameDllPatch);
489 g_GameDllPatch = NULL;
491 g_SourceHook.CompleteShutdown();
493 if (g_GameDll.lib && g_GameDll.loaded)
494 dlclose(g_GameDll.lib);
495 memset(&g_GameDll, 0, sizeof(GameDllInfo));
497 RETURN_META(MRES_SUPERCEDE);
500 int LoadPluginsFromFile(const char *_file)
503 int total = 0, skipped=0;
507 fp = fopen(_file, "rt");
510 LogMessage("[META] Could not open plugins file %s\n", _file);
514 char buffer[255], error[255], full_path[255];
515 const char *ptr, *ext, *file;
520 fgets(buffer, sizeof(buffer), fp);
521 length = strlen(buffer);
524 if (buffer[length-1] == '\n')
525 buffer[--length] = '\0';
527 UTIL_TrimLeft(buffer);
528 UTIL_TrimRight(buffer);
530 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
533 if (buffer[0] == '"')
554 while (*cptr && isspace(*cptr))
557 UTIL_TrimRight(cptr);
558 if (*cptr && isalpha(*cptr))
560 g_PluginMngr.SetAlias(buffer, cptr);
572 /* First find if it's an absolute path or not... */
573 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
575 /* If we're in an absolute path, ignore our normal heuristics */
576 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
577 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
579 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
587 /* Attempt to find a file extension */
588 ptr = UTIL_GetExtension(file);
589 /* Add an extension if there's none there */
592 #if defined WIN32 || defined _WIN32
600 /* Format the new path */
601 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
602 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
603 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
605 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
618 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
620 LogMessage("[META] Loaded %d plugins from file.", total);
626 /* Wrapper function. This is called when the GameDLL thinks it's using
627 * the engine's real engineFactory.
629 void *EngineFactory(const char *iface, int *ret)
631 IFACE_MACRO(g_Engine.engineFactory, Engine);
634 /* Wrapper function. This is called when the GameDLL thinks it's using
635 * the engine's real physicsFactory.
637 void *PhysicsFactory(const char *iface, int *ret)
639 IFACE_MACRO(g_Engine.physicsFactory, Physics);
642 /* Wrapper function. This is called when the GameDLL thinks it's using
643 * the engine's real fileSystemFactory.
645 void *FileSystemFactory(const char *iface, int *ret)
647 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
650 void LogMessage(const char *msg, ...)
653 static char buffer[2048];
656 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
659 buffer[len++] = '\n';
662 if (!g_Engine.engine)
664 fprintf(stdout, "%s", buffer);
666 g_Engine.engine->LogPrint(buffer);
670 void LevelShutdown_handler(void)
675 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
677 LoadPluginsFromFile(full_path);
679 bInFirstLevel = false;
682 ITER_EVENT(OnLevelShutdown, ());
684 RETURN_META(MRES_IGNORED);
687 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
689 if (!g_SmmAPI.CmdCacheSuccessful())
691 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
692 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
695 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
697 RETURN_META_VALUE(MRES_IGNORED, false);
700 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
701 void * operator new(size_t size) {
702 return(calloc(1, size));
705 void * operator new[](size_t size) {
706 return(calloc(1, size));
709 void operator delete(void * ptr) {
714 void operator delete[](void * ptr) {