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"
33 #include <interface.h>
36 #include "metamod_provider.h"
37 #include "metamod_plugins.h"
38 #include "metamod_util.h"
39 #include "metamod_console.h"
45 using namespace SourceMM;
46 using namespace SourceHook;
47 using namespace SourceHook::Impl;
50 * @brief Implementation of main SourceMM GameDLL functionality
54 SH_DECL_MANUALHOOK4(SGD_DLLInit, 0, 0, 0, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
55 SH_DECL_MANUALHOOK0(SGD_GameInit, 0, 0, 0, bool);
56 SH_DECL_MANUALHOOK6(SGD_LevelInit, 0, 0, 0, bool, const char *, const char *, const char *, const char *, bool, bool);
57 SH_DECL_MANUALHOOK0_void(SGD_LevelShutdown, 0, 0, 0);
58 SH_DECL_MANUALHOOK0_void(SGD_DLLShutdown, 0, 0, 0);
60 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
61 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
62 void Handler_DLLShutdown();
63 void Handler_LevelShutdown();
64 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
65 bool Handler_GameInit();
67 void LookForVDFs(const char *dir);
72 CreateInterfaceFn factory;
78 bool parsed_game_info = false;
80 int gamedll_version = 0;
81 int engine_build = SOURCE_ENGINE_UNKNOWN;
82 List<game_dll_t *> gamedll_list;
83 bool is_gamedll_loaded = false;
84 bool in_first_level = true;
85 bool is_game_init = false;
86 bool vsp_load_attempted = false;
87 bool vsp_load_requested = false;
88 bool vsp_loaded = false;
89 game_dll_t gamedll_info;
90 ConVar *metamod_version = NULL;
91 ConVar *mm_pluginsfile = NULL;
92 ConVar *mm_basedir = NULL;
93 IServerGameDLL *server = NULL;
94 CreateInterfaceFn engine_factory = NULL;
95 CreateInterfaceFn physics_factory = NULL;
96 CreateInterfaceFn filesystem_factory = NULL;
97 CGlobalVars *gpGlobals = NULL;
98 CSourceHookImpl g_SourceHook;
99 CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
100 ISourceHook *g_SHPtr = &g_SourceHook;
101 PluginId g_PLID = Pl_Console;
102 META_RES last_meta_res;
103 IServerPluginCallbacks *vsp_callbacks = NULL;
104 bool were_plugins_loaded = false;
106 MetamodSource g_Metamod;
107 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
109 void ClearGamedllList();
112 #define IFACE_MACRO(orig,nam) \
113 CPluginManager::CPlugin *pl; \
114 SourceHook::List<IMetamodListener *>::iterator event; \
115 IMetamodListener *api; \
118 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
120 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
122 mret = IFACE_FAILED; \
123 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
124 if (ret) *ret = mret; \
129 return (orig)(iface, ret);
131 #define ITER_EVENT(evn, args) \
132 CPluginManager::CPlugin *pl; \
133 SourceHook::List<IMetamodListener *>::iterator event; \
134 IMetamodListener *api; \
135 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
137 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
143 /* Initialize everything here */
144 void InitializeForLoad()
146 char full_path[PATH_SIZE] = {0};
147 GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
148 full_bin_path.assign(full_path);
150 /* Like Metamod, reload plugins at the end of the map.
151 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
152 * if the server is shut down (silly, but rare case).
154 in_first_level = true;
156 SourceHook::MemFuncInfo info;
158 if (!provider->GetHookInfo(ProvidedHook_DLLInit, &info))
160 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLInit");
162 SH_MANUALHOOK_RECONFIGURE(SGD_DLLInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
163 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit, false);
164 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit_Post, true);
166 if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
168 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
170 SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
171 SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
173 if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
175 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
177 SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
178 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
180 if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
182 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
184 SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
185 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
187 if (!provider->GetHookInfo(ProvidedHook_DLLShutdown, &info))
189 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLShutdown");
191 SH_MANUALHOOK_RECONFIGURE(SGD_DLLShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
192 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLShutdown, server, Handler_DLLShutdown, false);
195 bool DetectGameInformation()
197 char mm_path[PATH_SIZE];
198 char game_path[PATH_SIZE];
200 /* Get path to SourceMM DLL */
201 if (!GetFileOfAddress((void *)InitializeForLoad, mm_path, sizeof(mm_path)))
206 metamod_path.assign(mm_path);
208 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
209 const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
211 /* Get absolute path */
212 abspath(game_path, game_dir);
213 mod_path.assign(game_path);
215 engine_build = provider->DetermineSourceEngine(game_dir);;
220 /* This is where the magic happens */
221 SMM_API void *CreateInterface(const char *iface, int *ret)
223 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
224 if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
226 provider->DisplayWarning("Do not try loading Metamod:Source as a plugin.\n");
236 if (strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
238 vsp_callbacks = provider->GetVSPCallbacks(iface);
240 if (vsp_callbacks != NULL && vsp_version == 0)
242 vsp_version = atoi(&iface[22]);
247 *ret = (vsp_callbacks != NULL) ? IFACE_OK : IFACE_FAILED;
250 return vsp_callbacks;
253 if (provider->IsAlternatelyLoaded())
255 IFACE_MACRO(gamedll_info.factory, GameDLL);
258 if (!parsed_game_info)
260 parsed_game_info = true;
262 if (!DetectGameInformation())
264 provider->DisplayError("GetFileOfAddress() failed! Metamod cannot load.\n");
268 char temp_path[PATH_SIZE];
270 /* Path to gameinfo.txt */
271 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s", mod_path.c_str(), "gameinfo.txt");
273 FILE *fp = fopen(temp_path, "rt");
277 provider->DisplayError("Unable to open gameinfo.txt! Metamod cannot load.\n");
282 char key[128], val[128];
284 bool gamebin = false;
287 char cur_path[PATH_SIZE];
289 getcwd(cur_path, PATH_SIZE);
291 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
293 UTIL_TrimComments(buffer);
294 UTIL_TrimLeft(buffer);
295 UTIL_TrimRight(buffer);
297 if (stricmp(buffer, "SearchPaths") == 0)
307 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
308 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
310 if (stricmp(key, "Game") == 0)
319 if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
321 ptr = &(val[sizeof("|gameinfo_path|") - 1]);
326 lptr = mod_path.c_str();
332 size_t ptr_len = strlen(ptr);
333 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
335 ptr[--ptr_len] = '\0';
338 /* No need to append "bin" if key is GameBin */
341 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
345 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
349 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
352 /* If not path to SourceMM... */
353 if (!UTIL_PathCmp(metamod_path.c_str(), temp_path))
355 FILE *temp_fp = fopen(temp_path, "rb");
362 /* Search for a matching game dll */
363 List<game_dll_t *>::iterator iter;
366 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
369 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
371 if (UTIL_PathCmp(temp_path, buffer))
384 HINSTANCE gamedll = dlmount(temp_path);
390 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
397 game_dll_t *pInfo = new game_dll_t;
399 pInfo->lib = gamedll;
400 gamedll_list.push_back(pInfo);
408 if (!is_gamedll_loaded)
410 if (strncmp(iface, "ServerGameDLL", 13) == 0)
412 List<game_dll_t *>::iterator iter;
414 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
417 if ((server = (IServerGameDLL *)((pInfo->factory)(iface, ret))) != NULL)
419 if ((gamedll_version = provider->TryServerGameDLL(iface)) != 0)
421 /* We have a match. Erase us from the list and save our info. */
422 gamedll_list.erase(iter);
423 gamedll_info = *pInfo;
425 is_gamedll_loaded = true;
428 /* :TODO: error otherwise? */
432 if (is_gamedll_loaded)
448 /* wtf do we do... */
449 /* :TODO: .. something a bit more intelligent? */
450 provider->DisplayError("Engine requested unknown interface before GameDLL was known!\n");
455 /* If we got here, there's definitely a GameDLL */
456 IFACE_MACRO(gamedll_info.factory, GameDLL);
459 void ClearGamedllList()
461 List<game_dll_t *>::iterator iter;
464 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
471 gamedll_list.clear();
474 int LoadPluginsFromFile(const char *_file)
477 int total = 0, skipped=0;
481 fp = fopen(_file, "rt");
484 LogMessage("[META] Could not open plugins file %s\n", _file);
488 char buffer[255], error[255], full_path[255];
489 const char *ptr, *ext, *file;
491 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
493 UTIL_TrimLeft(buffer);
494 UTIL_TrimRight(buffer);
496 length = strlen(buffer);
502 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
508 if (buffer[0] == '"')
531 while (*cptr && isspace(*cptr))
536 UTIL_TrimRight(cptr);
537 if (*cptr && isalpha(*cptr))
539 g_PluginMngr.SetAlias(buffer, cptr);
551 /* First find if it's an absolute path or not... */
552 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
554 /* If we're in an absolute path, ignore our normal heuristics */
555 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
556 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
558 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
589 /* Format the new path */
590 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
591 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
592 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
594 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
613 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
617 LogMessage("[META] Loaded %d plugins from file.", total);
625 if (provider->IsAlternatelyLoaded())
631 char engine_file[PATH_SIZE];
632 char engine_path[PATH_SIZE];
633 char rel_path[PATH_SIZE * 2];
635 GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
637 /* Chop off the "engine" file part */
638 len = strlen(engine_file);
639 for (size_t i = len - 1; i >= 0 && i < len; i--)
641 if (engine_file[i] == '/' || engine_file[i] == '\\')
643 engine_file[i] = '\0';
647 abspath(engine_path, engine_file);
649 const char *usepath = metamod_path.c_str();
650 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
655 char command[PATH_SIZE * 2];
656 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
657 provider->ServerCommand(command);
660 /* Wrapper function. This is called when the GameDLL thinks it's using
661 * the engine's real engineFactory.
663 void *EngineFactory(const char *iface, int *ret)
665 IFACE_MACRO(engine_factory, Engine);
668 /* Wrapper function. This is called when the GameDLL thinks it's using
669 * the engine's real physicsFactory.
671 void *PhysicsFactory(const char *iface, int *ret)
673 IFACE_MACRO(physics_factory, Physics);
676 /* Wrapper function. This is called when the GameDLL thinks it's using
677 * the engine's real fileSystemFactory.
679 void *FileSystemFactory(const char *iface, int *ret)
681 IFACE_MACRO(filesystem_factory, FileSystem);
684 void LogMessage(const char *msg, ...)
687 static char buffer[2048];
690 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
693 buffer[len++] = '\n';
696 if (!provider->LogMessage(buffer))
698 fprintf(stdout, "%s", buffer);
702 void DoInitialPluginLoads()
704 const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
705 const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
708 pluginFile = provider->GetConVarString(mm_pluginsfile);
709 if (pluginFile == NULL)
711 pluginFile = "addons/metamod/metaplugins.ini";
716 mmBaseDir = provider->GetConVarString(mm_basedir);
717 if (mmBaseDir == NULL)
719 mmBaseDir = "addons/metamod";
725 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
726 LoadPluginsFromFile(full_path);
728 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
729 LookForVDFs(full_path);
732 void StartupMetamod(bool is_vsp_load)
740 is_vsp_load ? "V" : "");
742 metamod_version = provider->CreateConVar("metamod_version",
744 "Metamod:Source Version",
745 ConVarFlag_Notify|ConVarFlag_Replicated|ConVarFlag_SpOnly);
747 provider->SetConVarString(metamod_version, buffer);
749 mm_pluginsfile = provider->CreateConVar("mm_pluginsfile",
750 #if defined WIN32 || defined _WIN32
751 "addons\\metamod\\metaplugins.ini",
753 "addons/metamod/metaplugins.ini",
755 "Metamod:Source Plugins File",
758 mm_basedir = provider->CreateConVar("mm_basedir",
759 #if defined __linux__
764 "Metamod:Source Base Folder",
769 DoInitialPluginLoads();
770 in_first_level = true;
774 void InitializeGlobals(CreateInterfaceFn engineFactory,
775 CreateInterfaceFn physicsFactory,
776 CreateInterfaceFn filesystemFactory,
777 CGlobalVars *pGlobals)
779 engine_factory = engineFactory;
780 physics_factory = physicsFactory;
781 filesystem_factory = filesystemFactory;
782 gpGlobals = pGlobals;
783 provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
786 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
788 InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
789 StartupMetamod(false);
791 RETURN_META_VALUE(MRES_IGNORED, true);
794 bool Handler_GameInit()
801 if (vsp_load_requested)
806 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
808 DoInitialPluginLoads();
809 g_PluginMngr.SetAllLoaded();
810 were_plugins_loaded = true;
815 RETURN_META_VALUE(MRES_IGNORED, true);
818 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
820 g_PluginMngr.SetAllLoaded();
821 RETURN_META_VALUE(MRES_IGNORED, true);
827 g_PluginMngr.UnloadAll();
829 provider->Notify_DLLShutdown_Pre();
831 if (is_gamedll_loaded)
833 SH_CALL(server, &IServerGameDLL::DLLShutdown)();
836 g_SourceHook.CompleteShutdown();
838 if (is_gamedll_loaded && gamedll_info.lib)
840 dlclose(gamedll_info.lib);
841 is_gamedll_loaded = false;
845 void Handler_DLLShutdown()
848 RETURN_META(MRES_SUPERCEDE);
851 void Handler_LevelShutdown(void)
853 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
855 g_PluginMngr.SetAllLoaded();
856 DoInitialPluginLoads();
857 were_plugins_loaded = true;
858 in_first_level = true;
865 g_Metamod.PathFormat(full_path,
869 provider->GetConVarString(mm_pluginsfile));
870 LoadPluginsFromFile(full_path);
872 g_Metamod.PathFormat(full_path,
876 provider->GetConVarString(mm_basedir));
877 LookForVDFs(full_path);
881 in_first_level = false;
884 ITER_EVENT(OnLevelShutdown, ());
886 RETURN_META(MRES_IGNORED);
889 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
891 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
893 RETURN_META_VALUE(MRES_IGNORED, false);
896 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
902 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
905 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
908 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
912 return EngineFactory;
915 return engine_factory;
918 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
922 return PhysicsFactory;
925 return physics_factory;
928 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
932 return FileSystemFactory;
935 return filesystem_factory;
938 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
942 return CreateInterface;
945 return gamedll_info.factory;
948 CGlobalVars *MetamodSource::GetCGlobals()
953 void MetamodSource::SetLastMetaReturn(META_RES res)
958 META_RES MetamodSource::GetLastMetaReturn()
960 return last_meta_res;
963 void MetamodSource::ConPrint(const char *str)
965 provider->ConsolePrint(str);
968 void MetamodSource::ConPrintf(const char *fmt, ...)
974 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
977 provider->ConsolePrint(buffer);
980 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
982 major = METAMOD_API_MAJOR;
983 minor = METAMOD_API_MINOR;
984 plvers = METAMOD_PLAPI_VERSION;
985 plmin = PLAPI_MIN_VERSION;
988 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
990 shvers = SH_IFACE_VERSION;
991 shimpl = SH_IMPL_VERSION;
994 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
996 int length = (int)strlen(iface);
1000 for (i = length - 1; i >= 0; i--)
1002 if (!isdigit(iface[i]))
1004 if (i != length - 1)
1012 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
1017 if (i != length - 1)
1019 num = atoi(&(iface[++i]));
1024 snprintf(&(iface[i]), 4, "%03d", num);
1029 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
1031 char _if[256]; /* assume no interface goes beyond this */
1032 size_t len = strlen(iface);
1041 if (len + 4 > sizeof(_if))
1045 *ret = IFACE_FAILED;
1054 if ((pf = (fn)(_if, ret)) != NULL)
1062 } while ((num = FormatIface(_if, len+1)));
1067 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
1069 char buffer[256]; /* assume no interface will go beyond this */
1070 size_t len = strlen(iface);
1071 int ret; /* just in case something doesn't handle NULL properly */
1073 if (len > sizeof(buffer) - 4)
1078 strcpy(buffer, iface);
1082 char *ptr = &buffer[len - 1];
1084 while (isdigit(*ptr) && digits <=3)
1092 /* for now, assume this is an error */
1093 strcpy(buffer, iface);
1098 min = (min == 0) ? 1 : min;
1099 snprintf(num, sizeof(num), "%03d", min);
1100 strcat(buffer, num);
1104 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
1107 const char *MetamodSource::GetBaseDir()
1109 return mod_path.c_str();
1112 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
1116 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
1119 for (size_t i = 0; i < mylen; i++)
1121 if (buffer[i] == ALT_SEP_CHAR)
1123 buffer[i] = PATH_SEP_CHAR;
1130 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
1136 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1139 provider->ClientConsolePrint(client, buffer);
1142 void MetamodSource::EnableVSPListener()
1144 if (is_game_init && !vsp_load_requested && !vsp_loaded)
1149 vsp_load_requested = true;
1152 int MetamodSource::GetVSPVersion()
1157 int MetamodSource::GetGameDLLVersion()
1159 return gamedll_version;
1162 bool MetamodSource::RemotePrintingAvailable()
1164 return provider->IsRemotePrintingAvailable();
1167 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
1179 /* First check ours... we get first chance! */
1180 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
1186 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
1188 else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
1194 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
1196 else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
1202 return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
1205 CPluginManager::CPlugin *pl;
1206 List<IMetamodListener *>::iterator event;
1207 IMetamodListener *api;
1211 for (PluginIter iter = g_PluginMngr._begin();
1212 iter != g_PluginMngr._end();
1216 for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
1219 subret = IFACE_FAILED;
1220 if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
1237 *ret = IFACE_FAILED;
1243 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
1245 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
1247 pl->m_Events.push_back(pListener);
1250 const char *MetamodSource::GetGameBinaryPath()
1252 return full_bin_path.c_str();
1255 const char *MetamodSource::GetPluginsFile()
1257 return provider->GetConVarString(mm_pluginsfile);
1260 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
1262 return provider->GetConCommandBaseAccessor();
1265 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1267 if (provider->IsConCommandBaseACommand(pCommand))
1269 g_PluginMngr.AddPluginCmd(plugin, pCommand);
1273 g_PluginMngr.AddPluginCvar(plugin, pCommand);
1276 return provider->RegisterConCommandBase(pCommand);
1279 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1281 if (provider->IsConCommandBaseACommand(pCommand))
1283 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
1287 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
1290 CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
1291 UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
1294 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
1297 CPluginManager::CPlugin *pPlugin;
1298 List<IMetamodListener *>::iterator event;
1299 IMetamodListener *pML;
1300 for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
1303 if (pPlugin->m_Status < Pl_Paused)
1307 /* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
1308 if (pPlugin->m_API->GetApiVersion() < 12)
1312 for (event=pPlugin->m_Events.begin();
1313 event!=pPlugin->m_Events.end();
1317 pML->OnUnlinkConCommandBase(id, pCommand);
1321 return provider->UnregisterConCommandBase(pCommand);
1324 int MetamodSource::GetUserMessageCount()
1326 return provider->GetUserMessageCount();
1329 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
1331 return provider->FindUserMessage(name, size);
1334 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
1336 return provider->GetUserMessage(index, size);
1339 int MetamodSource::GetSourceEngineBuild()
1341 return engine_build;
1344 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
1346 ITER_EVENT(OnVSPListening, (callbacks));
1349 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
1353 *pVersion = vsp_version;
1356 return vsp_callbacks;
1359 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
1364 va_start(ap, format);
1365 result = FormatArgs(buffer, maxlength, format, ap);
1371 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
1373 return UTIL_FormatArgs(buffer, maxlength, format, ap);
1376 bool MetamodSource::IsLoadedAsGameDLL()
1378 return is_gamedll_loaded;
1381 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
1383 gamedll_info.factory = serverFactory;
1384 gamedll_version = version;
1387 bool MetamodSource::IsAlternateLoadComplete()
1389 return were_plugins_loaded;
1392 void ProcessVDF(const char *path)
1396 char alias[24], file[255], error[255];
1398 if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
1403 if (alias[0] != '\0')
1405 g_PluginMngr.SetAlias(alias, file);
1408 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
1409 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1411 LogMessage("[META] Failed to load plugin %s: %s", file, error);
1415 void LookForVDFs(const char *dir)
1417 char path[MAX_PATH];
1419 #if defined _MSC_VER
1424 g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
1425 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
1427 DWORD dw = GetLastError();
1428 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
1431 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1435 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
1441 if (strcmp(fd.cFileName, ".") == 0
1442 || strcmp(fd.cFileName, "..") == 0)
1446 if (strstr(fd.cFileName, ".vdf") == NULL)
1450 g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
1452 } while (FindNextFile(hFind, &fd));
1457 struct dirent *pEnt;
1459 if ((pDir = opendir(dir)) == NULL)
1461 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
1465 while ((pEnt = readdir(pDir)) != NULL)
1467 if (strcmp(pEnt->d_name, ".") == 0
1468 || strcmp(pEnt->d_name, "..") == 0)
1472 if (strstr(pEnt->d_name, ".vdf") == NULL)
1476 g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);