Hello, just one minor thing. Why did I do this again? :\
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 const char VSPIFACE[] = "ISERVERPLUGINCALLBACKS";
62 const char GAMEINFO_PATH[] = "|gameinfo_path|";
64 void ClearGamedllList();
67 #define IFACE_MACRO(orig,nam) \
68 CPluginManager::CPlugin *pl; \
69 SourceHook::List<IMetamodListener *>::iterator event; \
70 IMetamodListener *api; \
73 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
75 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
77 mret = IFACE_FAILED; \
78 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
79 if (ret) *ret = mret; \
84 return (orig)(iface, ret);
86 #define ITER_EVENT(evn, args) \
87 CPluginManager::CPlugin *pl; \
88 SourceHook::List<IMetamodListener *>::iterator event; \
89 IMetamodListener *api; \
90 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
92 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
98 ///////////////////////////////////
99 // Main code for HL2 Interaction //
100 ///////////////////////////////////
102 /* Initialize everything here */
103 void InitMainStates()
105 char full_path[PATH_SIZE] = {0};
106 GetFileOfAddress((void *)g_GameDll.factory, full_path, sizeof(full_path));
107 g_BinPath.assign(full_path);
109 /* Like Metamod, reload plugins at the end of the map.
110 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
111 * if the server is shut down (silly, but rare case).
113 bInFirstLevel = true;
115 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit, false);
116 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLInit, g_GameDll.pGameDLL, DLLInit_Post, true);
117 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, DLLShutdown, g_GameDll.pGameDLL, DLLShutdown_handler, false);
118 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
119 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
120 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
122 if (g_GameDll.pGameClients)
124 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
126 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
127 LogMessage("[META] Warning: Could not find IServerGameClients!");
128 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
132 bool DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
134 g_Engine.engineFactory = engineFactory;
135 g_Engine.fileSystemFactory = filesystemFactory;
136 g_Engine.physicsFactory = physicsFactory;
137 g_Engine.pGlobals = pGlobals;
139 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
140 if (!g_Engine.engine)
142 Error("Could not find IVEngineServer! Metamod cannot load.");
145 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
148 Error("Could not find ICvar! Metamod cannot load.");
152 g_Engine.loaded = true;
154 /* Initialize our console hooks */
155 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
157 g_GameDllPatch = SH_GET_CALLCLASS(g_GameDll.pGameDLL);
159 if (!g_SmmAPI.CacheCmds())
161 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
162 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
165 if (!g_SmmAPI.CacheUserMessages())
167 /* Don't know of a mod that has stripped out user messages completely,
168 * but perhaps should do something different here?
170 LogMessage("[META] Warning: Failed to get list of user messages.");
171 LogMessage("[META] Warning: The 'meta game' command will not display user messages.");
174 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
177 pluginFile = GetPluginsFile();
181 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), pluginFile);
183 LoadPluginsFromFile(full_path);
185 bInFirstLevel = true;
187 RETURN_META_VALUE(MRES_IGNORED, true);
190 bool GameInit_handler()
197 if (g_SmmAPI.VSPEnabled())
199 g_SmmAPI.LoadAsVSP();
204 RETURN_META_VALUE(MRES_IGNORED, true);
207 bool DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
209 g_PluginMngr.SetAllLoaded();
210 RETURN_META_VALUE(MRES_IGNORED, true);
213 /* This is where the magic happens */
214 SMM_API void *CreateInterface(const char *iface, int *ret)
216 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
217 if (strcmp(iface, PLAPI_NAME) == 0)
219 Warning("Do not try loading Metamod:Source as a SourceMM or Valve server plugin.\n");
229 if (strncmp(iface, VSPIFACE, 22) == 0)
236 return &g_VspListener;
239 if (!gParsedGameInfo)
241 gParsedGameInfo = true;
242 const char *gameDir = NULL;
243 char gamePath[PATH_SIZE];
244 char smmPath[PATH_SIZE];
246 /* Get path to SourceMM DLL */
247 if (!GetFileOfAddress((void *)CreateInterface, smmPath, sizeof(smmPath)))
249 Error("GetFileOfAddress() failed! Metamod cannot load.\n");
253 g_SmmPath.assign(smmPath);
255 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
256 gameDir = CommandLine()->ParmValue("-game", "hl2");
258 /* Get absolute path */
259 abspath(gamePath, gameDir);
260 g_ModPath.assign(gamePath);
262 char tempPath[PATH_SIZE];
264 /* Path to gameinfo.txt */
265 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s", g_ModPath.c_str(), "gameinfo.txt");
267 FILE *fp = fopen(tempPath, "rt");
271 Error("Unable to open gameinfo.txt! Metamod cannot load.\n");
276 char key[128], val[128];
279 bool gamebin = false;
282 char curPath[PATH_SIZE];
284 getcwd(curPath, PATH_SIZE);
289 fgets(buffer, sizeof(buffer), fp);
290 len = strlen(buffer);
291 if (buffer[len-1] == '\n')
292 buffer[--len] = '\0';
293 UTIL_TrimComments(buffer);
294 UTIL_TrimLeft(buffer);
295 UTIL_TrimRight(buffer);
296 if (stricmp(buffer, "SearchPaths") == 0)
300 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
301 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
303 if (stricmp(key, "Game") == 0)
308 if (strncmp(val, GAMEINFO_PATH, sizeof(GAMEINFO_PATH) - 1) == 0)
310 ptr = &(val[sizeof(GAMEINFO_PATH) - 1]);
313 lptr = g_ModPath.c_str();
319 size_t ptr_len = strlen(ptr);
320 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
321 ptr[--ptr_len] = '\0';
323 /* No need to append "bin" if key is GameBin */
326 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
327 } else if (!ptr[0]) {
328 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
330 g_SmmAPI.PathFormat(tempPath, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
333 /* If not path to SourceMM... */
334 if (!UTIL_PathCmp(smmPath, tempPath))
336 FILE *fp = fopen(tempPath, "rb");
339 //:TODO: Optimize this a bit!
340 SourceHook::List<GameDllInfo *>::iterator iter;
343 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
346 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
348 if (UTIL_PathCmp(tempPath, buffer))
358 HINSTANCE gamedll = dlmount(tempPath);
361 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
367 GameDllInfo *pInfo = new GameDllInfo;
369 pInfo->lib = gamedll;
370 pInfo->loaded = true;
371 pInfo->pGameDLL = NULL;
372 pInfo->pGameClients = (IServerGameClients *)((fn)(INTERFACEVERSION_SERVERGAMECLIENTS, NULL));
373 gamedll_list.push_back(pInfo);
381 if (!g_GameDll.loaded)
383 const char *str = "ServerGameDLL";
384 size_t len = strlen(str);
386 if (strncmp(iface, str, len) == 0)
388 /* This is the interface we want! Right now we support versions 3 through 8 */
389 g_GameDllVersion = atoi(&(iface[len]));
390 int sizeTooBig = 0; //rename this to sizeWrong in the future!
391 if (g_GameDllVersion < MIN_GAMEDLL_VERSION || g_GameDllVersion > MAX_GAMEDLL_VERSION)
393 /* Maybe this will get used in the future */
394 sizeTooBig = g_GameDllVersion;
400 SourceHook::List<GameDllInfo *>::iterator iter;
401 GameDllInfo *pInfo = NULL;
403 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
406 ptr = (pInfo->factory)(iface, ret);
409 /* This is our GameDLL. Unload the others. */
410 gamedll_list.erase(iter);
412 pInfo->pGameDLL = static_cast<IServerGameDLL *>(ptr);
418 if (g_GameDll.loaded)
422 Error("This mod version requires a SourceMM update (ServerGameDLL%03d)!\n", sizeTooBig);
438 /* wtf do we do... */
439 /* :TODO: .. something a bit more intelligent? */
440 Error("Engine requested unknown interface before GameDLL was known!\n");
445 /* If we got here, there's definitely a GameDLL */
446 IFACE_MACRO(g_GameDll.factory, GameDLL);
449 void ClearGamedllList()
451 SourceHook::List<GameDllInfo *>::iterator iter;
454 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
461 gamedll_list.clear();
464 void DLLShutdown_handler()
467 g_PluginMngr.UnloadAll();
469 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
470 g_SMConVarAccessor.MarkCommandsAsGameDLL();
471 g_SMConVarAccessor.UnregisterGameDLLCommands();
473 SH_CALL(g_GameDllPatch, &IServerGameDLL::DLLShutdown)();
475 SH_RELEASE_CALLCLASS(g_GameDllPatch);
476 g_GameDllPatch = NULL;
478 g_SourceHook.CompleteShutdown();
480 if (g_GameDll.lib && g_GameDll.loaded)
481 dlclose(g_GameDll.lib);
482 memset(&g_GameDll, 0, sizeof(GameDllInfo));
484 RETURN_META(MRES_SUPERCEDE);
487 int LoadPluginsFromFile(const char *_file)
490 int total = 0, skipped=0;
494 fp = fopen(_file, "rt");
497 LogMessage("[META] Could not open plugins file %s\n", _file);
501 char buffer[255], error[255], full_path[255];
502 const char *ptr, *ext, *file;
507 fgets(buffer, sizeof(buffer), fp);
508 length = strlen(buffer);
511 if (buffer[length-1] == '\n')
512 buffer[--length] = '\0';
514 UTIL_TrimLeft(buffer);
515 UTIL_TrimRight(buffer);
517 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
520 if (buffer[0] == '"')
541 while (*cptr && isspace(*cptr))
544 UTIL_TrimRight(cptr);
545 if (*cptr && isalpha(*cptr))
547 g_PluginMngr.SetAlias(buffer, cptr);
559 /* First find if it's an absolute path or not... */
560 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
562 /* If we're in an absolute path, ignore our normal heuristics */
563 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
564 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
566 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
574 /* Attempt to find a file extension */
575 ptr = UTIL_GetExtension(file);
576 /* Add an extension if there's none there */
579 #if defined WIN32 || defined _WIN32
587 /* Format the new path */
588 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s%s", g_ModPath.c_str(), file, ext);
589 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
590 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
592 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
605 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
607 LogMessage("[META] Loaded %d plugins from file.", total);
613 /* Wrapper function. This is called when the GameDLL thinks it's using
614 * the engine's real engineFactory.
616 void *EngineFactory(const char *iface, int *ret)
618 IFACE_MACRO(g_Engine.engineFactory, Engine);
621 /* Wrapper function. This is called when the GameDLL thinks it's using
622 * the engine's real physicsFactory.
624 void *PhysicsFactory(const char *iface, int *ret)
626 IFACE_MACRO(g_Engine.physicsFactory, Physics);
629 /* Wrapper function. This is called when the GameDLL thinks it's using
630 * the engine's real fileSystemFactory.
632 void *FileSystemFactory(const char *iface, int *ret)
634 IFACE_MACRO(g_Engine.fileSystemFactory, FileSystem);
637 void LogMessage(const char *msg, ...)
640 static char buffer[2048];
643 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
646 buffer[len++] = '\n';
649 if (!g_Engine.engine)
651 fprintf(stdout, "%s", buffer);
653 g_Engine.engine->LogPrint(buffer);
657 void LevelShutdown_handler(void)
662 g_SmmAPI.PathFormat(full_path, sizeof(full_path), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
664 LoadPluginsFromFile(full_path);
666 bInFirstLevel = false;
669 ITER_EVENT(OnLevelShutdown, ());
671 RETURN_META(MRES_IGNORED);
674 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
676 if (!g_SmmAPI.CmdCacheSuccessful())
678 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
679 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
682 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
684 RETURN_META_VALUE(MRES_IGNORED, false);
687 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
688 void * operator new(size_t size) {
689 return(calloc(1, size));
692 void * operator new[](size_t size) {
693 return(calloc(1, size));
696 void operator delete(void * ptr) {
701 void operator delete[](void * ptr) {