3 * ======================================================
5 * Copyright (C) 2004-2007 AlliedModders LLC and authors.
7 * ======================================================
9 * This software is provided 'as-is', without any express or implied warranty.
10 * In no event will the authors be held liable for any damages arising from
11 * the use of this software.
13 * Permission is granted to anyone to use this software for any purpose,
14 * including commercial applications, and to alter it and redistribute it
15 * freely, subject to the following restrictions:
17 * 1. The origin of this software must not be misrepresented; you must not
18 * claim that you wrote the original software. If you use this software in a
19 * product, an acknowledgment in the product documentation would be
20 * appreciated but is not required.
21 * 2. Altered source versions must be plainly marked as such, and must not be
22 * misrepresented as being the original software.
23 * 3. This notice may not be removed or altered from any source distribution.
28 #include "metamod_oslink.h"
30 #include <interface.h>
32 #include "metamod_provider.h"
33 #include "metamod_plugins.h"
34 #include "metamod_util.h"
35 #include "metamod_console.h"
37 using namespace SourceMM;
38 using namespace SourceHook;
39 using namespace SourceHook::Impl;
42 * @brief Implementation of main SourceMM GameDLL functionality
46 SH_DECL_MANUALHOOK4(SGD_DLLInit, 0, 0, 0, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
47 SH_DECL_MANUALHOOK0(SGD_GameInit, 0, 0, 0, bool);
48 SH_DECL_MANUALHOOK6(SGD_LevelInit, 0, 0, 0, bool, const char *, const char *, const char *, const char *, bool, bool);
49 SH_DECL_MANUALHOOK0_void(SGD_LevelShutdown, 0, 0, 0);
50 SH_DECL_MANUALHOOK0_void(SGD_DLLShutdown, 0, 0, 0);
52 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
53 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
54 void Handler_DLLShutdown();
55 void Handler_LevelShutdown();
56 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
57 bool Handler_GameInit();
59 void LookForVDFs(const char *dir);
64 CreateInterfaceFn factory;
70 bool parsed_game_info = false;
72 int gamedll_version = 0;
73 int engine_build = SOURCE_ENGINE_UNKNOWN;
74 List<game_dll_t *> gamedll_list;
75 bool is_gamedll_loaded = false;
76 bool in_first_level = true;
77 bool is_game_init = false;
78 bool vsp_load_attempted = false;
79 bool vsp_load_requested = false;
80 bool vsp_loaded = false;
81 game_dll_t gamedll_info;
82 ConVar *metamod_version = NULL;
83 ConVar *mm_pluginsfile = NULL;
84 ConVar *mm_basedir = NULL;
85 IServerGameDLL *server = NULL;
86 CreateInterfaceFn engine_factory = NULL;
87 CreateInterfaceFn physics_factory = NULL;
88 CreateInterfaceFn filesystem_factory = NULL;
89 CGlobalVars *gpGlobals = NULL;
90 CSourceHookImpl g_SourceHook;
91 CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
92 ISourceHook *g_SHPtr = &g_SourceHook;
93 PluginId g_PLID = Pl_Console;
94 META_RES last_meta_res;
95 IServerPluginCallbacks *vsp_callbacks = NULL;
96 bool were_plugins_loaded = false;
98 MetamodSource g_Metamod;
99 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
101 void ClearGamedllList();
104 #define IFACE_MACRO(orig,nam) \
105 CPluginManager::CPlugin *pl; \
106 SourceHook::List<IMetamodListener *>::iterator event; \
107 IMetamodListener *api; \
110 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
112 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
114 mret = IFACE_FAILED; \
115 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
116 if (ret) *ret = mret; \
121 return (orig)(iface, ret);
123 #define ITER_EVENT(evn, args) \
124 CPluginManager::CPlugin *pl; \
125 SourceHook::List<IMetamodListener *>::iterator event; \
126 IMetamodListener *api; \
127 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
129 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
135 /* Initialize everything here */
136 void InitializeForLoad()
138 char full_path[PATH_SIZE] = {0};
139 GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
140 full_bin_path.assign(full_path);
142 /* Like Metamod, reload plugins at the end of the map.
143 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
144 * if the server is shut down (silly, but rare case).
146 in_first_level = true;
148 SourceHook::MemFuncInfo info;
150 if (!provider->GetHookInfo(ProvidedHook_DLLInit, &info))
152 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLInit");
154 SH_MANUALHOOK_RECONFIGURE(SGD_DLLInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
155 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit, false);
156 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit_Post, true);
158 if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
160 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
162 SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
163 SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
165 if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
167 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
169 SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
170 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
172 if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
174 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
176 SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
177 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
179 if (!provider->GetHookInfo(ProvidedHook_DLLShutdown, &info))
181 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLShutdown");
183 SH_MANUALHOOK_RECONFIGURE(SGD_DLLShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
184 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLShutdown, server, Handler_DLLShutdown, false);
187 bool DetectGameInformation()
189 char mm_path[PATH_SIZE];
190 char game_path[PATH_SIZE];
192 /* Get path to SourceMM DLL */
193 if (!GetFileOfAddress((void *)InitializeForLoad, mm_path, sizeof(mm_path)))
198 metamod_path.assign(mm_path);
200 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
201 const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
203 /* Get absolute path */
204 abspath(game_path, game_dir);
205 mod_path.assign(game_path);
207 engine_build = provider->DetermineSourceEngine(game_dir);;
212 /* This is where the magic happens */
213 SMM_API void *CreateInterface(const char *iface, int *ret)
215 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
216 if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
218 provider->DisplayWarning("Do not try loading Metamod:Source as a plugin.\n");
228 if (strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
230 vsp_callbacks = provider->GetVSPCallbacks(iface);
232 if (vsp_callbacks != NULL && vsp_version == 0)
234 vsp_version = atoi(&iface[22]);
239 *ret = (vsp_callbacks != NULL) ? IFACE_OK : IFACE_FAILED;
242 return vsp_callbacks;
245 if (provider->IsAlternatelyLoaded())
247 IFACE_MACRO(gamedll_info.factory, GameDLL);
250 if (!parsed_game_info)
252 parsed_game_info = true;
254 if (!DetectGameInformation())
256 provider->DisplayError("GetFileOfAddress() failed! Metamod cannot load.\n");
260 char temp_path[PATH_SIZE];
262 /* Path to gameinfo.txt */
263 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s", mod_path.c_str(), "gameinfo.txt");
265 FILE *fp = fopen(temp_path, "rt");
269 provider->DisplayError("Unable to open gameinfo.txt! Metamod cannot load.\n");
274 char key[128], val[128];
276 bool gamebin = false;
279 char cur_path[PATH_SIZE];
281 getcwd(cur_path, PATH_SIZE);
283 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
285 UTIL_TrimComments(buffer);
286 UTIL_TrimLeft(buffer);
287 UTIL_TrimRight(buffer);
289 if (stricmp(buffer, "SearchPaths") == 0)
299 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
300 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
302 if (stricmp(key, "Game") == 0)
311 if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
313 ptr = &(val[sizeof("|gameinfo_path|") - 1]);
318 lptr = mod_path.c_str();
324 size_t ptr_len = strlen(ptr);
325 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
327 ptr[--ptr_len] = '\0';
330 /* No need to append "bin" if key is GameBin */
333 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
337 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
341 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
344 /* If not path to SourceMM... */
345 if (!UTIL_PathCmp(metamod_path.c_str(), temp_path))
347 FILE *temp_fp = fopen(temp_path, "rb");
354 /* Search for a matching game dll */
355 List<game_dll_t *>::iterator iter;
358 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
361 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
363 if (UTIL_PathCmp(temp_path, buffer))
376 HINSTANCE gamedll = dlmount(temp_path);
382 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
389 game_dll_t *pInfo = new game_dll_t;
391 pInfo->lib = gamedll;
392 gamedll_list.push_back(pInfo);
400 if (!is_gamedll_loaded)
402 if (strncmp(iface, "ServerGameDLL", 13) == 0)
404 List<game_dll_t *>::iterator iter;
406 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
409 if ((server = (IServerGameDLL *)((pInfo->factory)(iface, ret))) != NULL)
411 if ((gamedll_version = provider->TryServerGameDLL(iface)) != 0)
413 /* We have a match. Erase us from the list and save our info. */
414 gamedll_list.erase(iter);
415 gamedll_info = *pInfo;
417 is_gamedll_loaded = true;
420 /* :TODO: error otherwise? */
424 if (is_gamedll_loaded)
440 /* wtf do we do... */
441 /* :TODO: .. something a bit more intelligent? */
442 provider->DisplayError("Engine requested unknown interface before GameDLL was known!\n");
447 /* If we got here, there's definitely a GameDLL */
448 IFACE_MACRO(gamedll_info.factory, GameDLL);
451 void ClearGamedllList()
453 List<game_dll_t *>::iterator iter;
456 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
463 gamedll_list.clear();
466 int LoadPluginsFromFile(const char *_file)
469 int total = 0, skipped=0;
473 fp = fopen(_file, "rt");
476 LogMessage("[META] Could not open plugins file %s\n", _file);
480 char buffer[255], error[255], full_path[255];
481 const char *ptr, *ext, *file;
483 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
485 UTIL_TrimLeft(buffer);
486 UTIL_TrimRight(buffer);
488 length = strlen(buffer);
494 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
500 if (buffer[0] == '"')
523 while (*cptr && isspace(*cptr))
528 UTIL_TrimRight(cptr);
529 if (*cptr && isalpha(*cptr))
531 g_PluginMngr.SetAlias(buffer, cptr);
543 /* First find if it's an absolute path or not... */
544 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
546 /* If we're in an absolute path, ignore our normal heuristics */
547 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
548 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
550 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
566 /* Attempt to find a file extension */
567 ptr = UTIL_GetExtension(file);
568 /* Add an extension if there's none there */
571 #if defined WIN32 || defined _WIN32
581 /* Format the new path */
582 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
583 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
584 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
586 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
605 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
609 LogMessage("[META] Loaded %d plugins from file.", total);
617 if (provider->IsAlternatelyLoaded())
623 char engine_file[PATH_SIZE];
624 char engine_path[PATH_SIZE];
625 char rel_path[PATH_SIZE * 2];
627 GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
629 /* Chop off the "engine" file part */
630 len = strlen(engine_file);
631 for (size_t i = len - 1; i >= 0 && i < len; i--)
633 if (engine_file[i] == '/' || engine_file[i] == '\\')
635 engine_file[i] = '\0';
639 abspath(engine_path, engine_file);
641 const char *usepath = metamod_path.c_str();
642 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
647 char command[PATH_SIZE * 2];
648 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
649 provider->ServerCommand(command);
652 /* Wrapper function. This is called when the GameDLL thinks it's using
653 * the engine's real engineFactory.
655 void *EngineFactory(const char *iface, int *ret)
657 IFACE_MACRO(engine_factory, Engine);
660 /* Wrapper function. This is called when the GameDLL thinks it's using
661 * the engine's real physicsFactory.
663 void *PhysicsFactory(const char *iface, int *ret)
665 IFACE_MACRO(physics_factory, Physics);
668 /* Wrapper function. This is called when the GameDLL thinks it's using
669 * the engine's real fileSystemFactory.
671 void *FileSystemFactory(const char *iface, int *ret)
673 IFACE_MACRO(filesystem_factory, FileSystem);
676 void LogMessage(const char *msg, ...)
679 static char buffer[2048];
682 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
685 buffer[len++] = '\n';
688 if (!provider->LogMessage(buffer))
690 fprintf(stdout, "%s", buffer);
694 void DoInitialPluginLoads()
696 const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
697 const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
700 pluginFile = provider->GetConVarString(mm_pluginsfile);
701 if (pluginFile == NULL)
703 pluginFile = "addons/metamod/metaplugins.ini";
708 mmBaseDir = provider->GetConVarString(mm_basedir);
709 if (mmBaseDir == NULL)
711 mmBaseDir = "addons/metamod";
717 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
718 LoadPluginsFromFile(full_path);
720 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
721 LookForVDFs(full_path);
724 void StartupMetamod(bool is_vsp_load)
732 is_vsp_load ? "V" : "");
734 metamod_version = provider->CreateConVar("metamod_version",
736 "Metamod:Source Version",
737 ConVarFlag_Notify|ConVarFlag_SpOnly);
739 provider->SetConVarString(metamod_version, buffer);
741 mm_pluginsfile = provider->CreateConVar("mm_pluginsfile",
742 #if defined WIN32 || defined _WIN32
743 "addons\\metamod\\metaplugins.ini",
745 "addons/metamod/metaplugins.ini",
747 "Metamod:Source Plugins File",
750 mm_basedir = provider->CreateConVar("mm_basedir",
751 #if defined __linux__
756 "Metamod:Source Base Folder",
761 DoInitialPluginLoads();
762 in_first_level = true;
766 void InitializeGlobals(CreateInterfaceFn engineFactory,
767 CreateInterfaceFn physicsFactory,
768 CreateInterfaceFn filesystemFactory,
769 CGlobalVars *pGlobals)
771 engine_factory = engineFactory;
772 physics_factory = physicsFactory;
773 filesystem_factory = filesystemFactory;
774 gpGlobals = pGlobals;
775 provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
778 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
780 InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
781 StartupMetamod(false);
783 RETURN_META_VALUE(MRES_IGNORED, true);
786 bool Handler_GameInit()
793 if (vsp_load_requested)
798 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
800 DoInitialPluginLoads();
801 g_PluginMngr.SetAllLoaded();
802 were_plugins_loaded = true;
807 RETURN_META_VALUE(MRES_IGNORED, true);
810 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
812 g_PluginMngr.SetAllLoaded();
813 RETURN_META_VALUE(MRES_IGNORED, true);
819 g_PluginMngr.UnloadAll();
821 provider->Notify_DLLShutdown_Pre();
823 if (is_gamedll_loaded)
825 SH_CALL(server, &IServerGameDLL::DLLShutdown)();
828 g_SourceHook.CompleteShutdown();
830 if (is_gamedll_loaded && gamedll_info.lib)
832 dlclose(gamedll_info.lib);
833 is_gamedll_loaded = false;
837 void Handler_DLLShutdown()
840 RETURN_META(MRES_SUPERCEDE);
843 void Handler_LevelShutdown(void)
845 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
847 g_PluginMngr.SetAllLoaded();
848 DoInitialPluginLoads();
849 were_plugins_loaded = true;
850 in_first_level = true;
857 g_Metamod.PathFormat(full_path,
861 provider->GetConVarString(mm_pluginsfile));
862 LoadPluginsFromFile(full_path);
864 g_Metamod.PathFormat(full_path,
868 provider->GetConVarString(mm_basedir));
869 LookForVDFs(full_path);
873 in_first_level = false;
876 ITER_EVENT(OnLevelShutdown, ());
878 RETURN_META(MRES_IGNORED);
881 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
883 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
885 RETURN_META_VALUE(MRES_IGNORED, false);
888 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
894 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
897 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
900 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
904 return EngineFactory;
907 return engine_factory;
910 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
914 return PhysicsFactory;
917 return physics_factory;
920 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
924 return FileSystemFactory;
927 return filesystem_factory;
930 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
934 return CreateInterface;
937 return gamedll_info.factory;
940 CGlobalVars *MetamodSource::GetCGlobals()
945 void MetamodSource::SetLastMetaReturn(META_RES res)
950 META_RES MetamodSource::GetLastMetaReturn()
952 return last_meta_res;
955 void MetamodSource::ConPrint(const char *str)
957 provider->ConsolePrint(str);
960 void MetamodSource::ConPrintf(const char *fmt, ...)
966 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
969 provider->ConsolePrint(buffer);
972 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
974 major = METAMOD_API_MAJOR;
975 minor = METAMOD_API_MINOR;
976 plvers = METAMOD_PLAPI_VERSION;
977 plmin = PLAPI_MIN_VERSION;
980 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
982 shvers = SH_IFACE_VERSION;
983 shimpl = SH_IMPL_VERSION;
986 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
988 int length = (int)strlen(iface);
992 for (i = length - 1; i >= 0; i--)
994 if (!isdigit(iface[i]))
1004 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
1009 if (i != length - 1)
1011 num = atoi(&(iface[++i]));
1016 snprintf(&(iface[i]), 4, "%03d", num);
1021 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
1023 char _if[256]; /* assume no interface goes beyond this */
1024 size_t len = strlen(iface);
1033 if (len + 4 > sizeof(_if))
1037 *ret = IFACE_FAILED;
1046 if ((pf = (fn)(_if, ret)) != NULL)
1054 } while ((num = FormatIface(_if, len+1)));
1059 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
1061 char buffer[256]; /* assume no interface will go beyond this */
1062 size_t len = strlen(iface);
1063 int ret; /* just in case something doesn't handle NULL properly */
1065 if (len > sizeof(buffer) - 4)
1070 strcpy(buffer, iface);
1074 char *ptr = &buffer[len - 1];
1076 while (isdigit(*ptr) && digits <=3)
1084 /* for now, assume this is an error */
1085 strcpy(buffer, iface);
1090 min = (min == 0) ? 1 : min;
1091 snprintf(num, sizeof(num), "%03d", min);
1092 strcat(buffer, num);
1096 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
1099 const char *MetamodSource::GetBaseDir()
1101 return mod_path.c_str();
1104 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
1108 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
1111 for (size_t i = 0; i < mylen; i++)
1113 if (buffer[i] == ALT_SEP_CHAR)
1115 buffer[i] = PATH_SEP_CHAR;
1122 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
1128 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1131 provider->ClientConsolePrint(client, buffer);
1134 void MetamodSource::EnableVSPListener()
1136 if (is_game_init && !vsp_load_requested && !vsp_loaded)
1141 vsp_load_requested = true;
1144 int MetamodSource::GetVSPVersion()
1149 int MetamodSource::GetGameDLLVersion()
1151 return gamedll_version;
1154 bool MetamodSource::RemotePrintingAvailable()
1156 return provider->IsRemotePrintingAvailable();
1159 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
1171 /* First check ours... we get first chance! */
1172 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
1178 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
1180 else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
1186 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
1188 else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
1194 return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
1197 CPluginManager::CPlugin *pl;
1198 List<IMetamodListener *>::iterator event;
1199 IMetamodListener *api;
1203 for (PluginIter iter = g_PluginMngr._begin();
1204 iter != g_PluginMngr._end();
1208 for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
1211 subret = IFACE_FAILED;
1212 if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
1229 *ret = IFACE_FAILED;
1235 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
1237 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
1239 pl->m_Events.push_back(pListener);
1242 const char *MetamodSource::GetGameBinaryPath()
1244 return full_bin_path.c_str();
1247 const char *MetamodSource::GetPluginsFile()
1249 return provider->GetConVarString(mm_pluginsfile);
1252 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
1254 return provider->GetConCommandBaseAccessor();
1257 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1259 if (provider->IsConCommandBaseACommand(pCommand))
1261 g_PluginMngr.AddPluginCmd(plugin, pCommand);
1265 g_PluginMngr.AddPluginCvar(plugin, pCommand);
1268 return provider->RegisterConCommandBase(pCommand);
1271 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1273 if (provider->IsConCommandBaseACommand(pCommand))
1275 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
1279 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
1282 CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
1283 UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
1286 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
1289 CPluginManager::CPlugin *pPlugin;
1290 List<IMetamodListener *>::iterator event;
1291 IMetamodListener *pML;
1292 for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
1295 if (pPlugin->m_Status < Pl_Paused)
1299 /* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
1300 if (pPlugin->m_API->GetApiVersion() < 12)
1304 for (event=pPlugin->m_Events.begin();
1305 event!=pPlugin->m_Events.end();
1309 pML->OnUnlinkConCommandBase(id, pCommand);
1313 return provider->UnregisterConCommandBase(pCommand);
1316 int MetamodSource::GetUserMessageCount()
1318 return provider->GetUserMessageCount();
1321 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
1323 return provider->FindUserMessage(name, size);
1326 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
1328 return provider->GetUserMessage(index, size);
1331 int MetamodSource::GetSourceEngineBuild()
1333 return engine_build;
1336 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
1338 ITER_EVENT(OnVSPListening, (callbacks));
1341 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
1345 *pVersion = vsp_version;
1348 return vsp_callbacks;
1351 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
1356 va_start(ap, format);
1357 result = FormatArgs(buffer, maxlength, format, ap);
1363 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
1365 return UTIL_FormatArgs(buffer, maxlength, format, ap);
1368 bool MetamodSource::IsLoadedAsGameDLL()
1370 return is_gamedll_loaded;
1373 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
1375 gamedll_info.factory = serverFactory;
1376 gamedll_version = version;
1379 bool MetamodSource::IsAlternateLoadComplete()
1381 return were_plugins_loaded;
1384 void ProcessVDF(const char *path)
1388 char alias[24], file[255], error[255];
1390 if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
1395 if (alias[0] != '\0')
1397 g_PluginMngr.SetAlias(alias, file);
1400 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
1401 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1403 LogMessage("[META] Failed to load plugin %s: %s", file, error);
1407 void LookForVDFs(const char *dir)
1409 char path[MAX_PATH];
1411 #if defined _MSC_VER
1417 g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
1418 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
1420 DWORD dw = GetLastError();
1421 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
1424 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1428 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
1434 if (strcmp(fd.cFileName, ".") == 0
1435 || strcmp(fd.cFileName, "..") == 0)
1439 extidx = strlen(fd.cFileName) - 4;
1440 if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1444 g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
1446 } while (FindNextFile(hFind, &fd));
1451 struct dirent *pEnt;
1453 if ((pDir = opendir(dir)) == NULL)
1455 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
1459 while ((pEnt = readdir(pDir)) != NULL)
1461 if (strcmp(pEnt->d_name, ".") == 0
1462 || strcmp(pEnt->d_name, "..") == 0)
1466 extidx = strlen(fd.cFileName) - 4;
1467 if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1471 g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);