More re-arranging. Not what we discussed in IRC but I think it works out better, Make can't deal with upward dependencies nicely.
3 * ======================================================
5 * Copyright (C) 2004-2008 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.
29 #include "metamod_oslink.h"
31 #include <interface.h>
33 #include "metamod_provider.h"
34 #include "metamod_plugins.h"
35 #include "metamod_util.h"
36 #include "metamod_console.h"
38 using namespace SourceMM;
39 using namespace SourceHook;
40 using namespace SourceHook::Impl;
43 * @brief Implementation of main SourceMM GameDLL functionality
47 SH_DECL_MANUALHOOK4(SGD_DLLInit, 0, 0, 0, bool, CreateInterfaceFn, CreateInterfaceFn, CreateInterfaceFn, CGlobalVars *);
48 SH_DECL_MANUALHOOK0(SGD_GameInit, 0, 0, 0, bool);
49 SH_DECL_MANUALHOOK6(SGD_LevelInit, 0, 0, 0, bool, const char *, const char *, const char *, const char *, bool, bool);
50 SH_DECL_MANUALHOOK0_void(SGD_LevelShutdown, 0, 0, 0);
51 SH_DECL_MANUALHOOK0_void(SGD_DLLShutdown, 0, 0, 0);
53 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
54 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals);
55 void Handler_DLLShutdown();
56 void Handler_LevelShutdown();
57 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background);
58 bool Handler_GameInit();
60 void LookForVDFs(const char *dir);
65 CreateInterfaceFn factory;
71 bool parsed_game_info = false;
73 int gamedll_version = 0;
74 int engine_build = SOURCE_ENGINE_UNKNOWN;
75 List<game_dll_t *> gamedll_list;
76 bool is_gamedll_loaded = false;
77 bool in_first_level = true;
78 bool is_game_init = false;
79 bool vsp_load_attempted = false;
80 bool vsp_load_requested = false;
81 bool vsp_loaded = false;
82 game_dll_t gamedll_info;
83 ConVar *metamod_version = NULL;
84 ConVar *mm_pluginsfile = NULL;
85 ConVar *mm_basedir = NULL;
86 IServerGameDLL *server = NULL;
87 CreateInterfaceFn engine_factory = NULL;
88 CreateInterfaceFn physics_factory = NULL;
89 CreateInterfaceFn filesystem_factory = NULL;
90 CGlobalVars *gpGlobals = NULL;
91 CSourceHookImpl g_SourceHook;
92 CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
93 ISourceHook *g_SHPtr = &g_SourceHook;
94 PluginId g_PLID = Pl_Console;
95 META_RES last_meta_res;
96 IServerPluginCallbacks *vsp_callbacks = NULL;
97 bool were_plugins_loaded = false;
99 MetamodSource g_Metamod;
100 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
102 void ClearGamedllList();
105 #define IFACE_MACRO(orig,nam) \
106 CPluginManager::CPlugin *pl; \
107 SourceHook::List<IMetamodListener *>::iterator event; \
108 IMetamodListener *api; \
111 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
113 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
115 mret = IFACE_FAILED; \
116 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
117 if (ret) *ret = mret; \
122 return (orig)(iface, ret);
124 #define ITER_EVENT(evn, args) \
125 CPluginManager::CPlugin *pl; \
126 SourceHook::List<IMetamodListener *>::iterator event; \
127 IMetamodListener *api; \
128 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
130 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
136 /* Initialize everything here */
137 void InitializeForLoad()
139 char full_path[PATH_SIZE] = {0};
140 GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
141 full_bin_path.assign(full_path);
143 /* Like Metamod, reload plugins at the end of the map.
144 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
145 * if the server is shut down (silly, but rare case).
147 in_first_level = true;
149 SourceHook::MemFuncInfo info;
151 if (!provider->GetHookInfo(ProvidedHook_DLLInit, &info))
153 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLInit");
155 SH_MANUALHOOK_RECONFIGURE(SGD_DLLInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
156 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit, false);
157 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit_Post, true);
159 if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
161 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
163 SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
164 SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
166 if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
168 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
170 SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
171 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
173 if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
175 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
177 SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
178 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
180 if (!provider->GetHookInfo(ProvidedHook_DLLShutdown, &info))
182 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLShutdown");
184 SH_MANUALHOOK_RECONFIGURE(SGD_DLLShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
185 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLShutdown, server, Handler_DLLShutdown, false);
188 bool DetectGameInformation()
190 char mm_path[PATH_SIZE];
191 char game_path[PATH_SIZE];
193 /* Get path to SourceMM DLL */
194 if (!GetFileOfAddress((void *)InitializeForLoad, mm_path, sizeof(mm_path)))
199 metamod_path.assign(mm_path);
201 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
202 const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
204 /* Get absolute path */
205 abspath(game_path, game_dir);
206 mod_path.assign(game_path);
208 engine_build = provider->DetermineSourceEngine(game_dir);;
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, METAMOD_PLAPI_NAME) == 0)
219 provider->DisplayWarning("Do not try loading Metamod:Source as a plugin.\n");
229 if (strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
231 if (vsp_callbacks != NULL && atoi(&iface[22]) != vsp_version)
240 vsp_version = atoi(&iface[22]);
241 vsp_callbacks = provider->GetVSPCallbacks(vsp_version);
245 *ret = (vsp_callbacks != NULL) ? IFACE_OK : IFACE_FAILED;
248 if (vsp_callbacks == NULL)
253 return vsp_callbacks;
256 if (provider->IsAlternatelyLoaded())
258 IFACE_MACRO(gamedll_info.factory, GameDLL);
261 if (!parsed_game_info)
263 parsed_game_info = true;
265 if (!DetectGameInformation())
267 provider->DisplayError("GetFileOfAddress() failed! Metamod cannot load.\n");
271 char temp_path[PATH_SIZE];
273 /* Path to gameinfo.txt */
274 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s", mod_path.c_str(), "gameinfo.txt");
276 FILE *fp = fopen(temp_path, "rt");
280 provider->DisplayError("Unable to open gameinfo.txt! Metamod cannot load.\n");
285 char key[128], val[128];
287 bool gamebin = false;
290 char cur_path[PATH_SIZE];
292 getcwd(cur_path, PATH_SIZE);
294 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
296 UTIL_TrimComments(buffer);
297 UTIL_TrimLeft(buffer);
298 UTIL_TrimRight(buffer);
300 if (stricmp(buffer, "SearchPaths") == 0)
310 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
311 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
313 if (stricmp(key, "Game") == 0)
322 if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
324 ptr = &(val[sizeof("|gameinfo_path|") - 1]);
329 lptr = mod_path.c_str();
335 size_t ptr_len = strlen(ptr);
336 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
338 ptr[--ptr_len] = '\0';
341 /* No need to append "bin" if key is GameBin */
344 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
348 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
352 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
355 /* If not path to SourceMM... */
356 if (!UTIL_PathCmp(metamod_path.c_str(), temp_path))
358 FILE *temp_fp = fopen(temp_path, "rb");
365 /* Search for a matching game dll */
366 List<game_dll_t *>::iterator iter;
369 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
372 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
374 if (UTIL_PathCmp(temp_path, buffer))
387 HINSTANCE gamedll = dlmount(temp_path);
393 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
400 game_dll_t *pInfo = new game_dll_t;
402 pInfo->lib = gamedll;
403 gamedll_list.push_back(pInfo);
411 if (!is_gamedll_loaded)
413 if (strncmp(iface, "ServerGameDLL", 13) == 0)
415 List<game_dll_t *>::iterator iter;
417 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
420 if ((server = (IServerGameDLL *)((pInfo->factory)(iface, ret))) != NULL)
422 if ((gamedll_version = provider->TryServerGameDLL(iface)) != 0)
424 /* We have a match. Erase us from the list and save our info. */
425 gamedll_list.erase(iter);
426 gamedll_info = *pInfo;
428 is_gamedll_loaded = true;
431 /* :TODO: error otherwise? */
435 if (is_gamedll_loaded)
451 /* wtf do we do... */
452 /* :TODO: .. something a bit more intelligent? */
453 provider->DisplayError("Engine requested unknown interface before GameDLL was known!\n");
458 /* If we got here, there's definitely a GameDLL */
459 IFACE_MACRO(gamedll_info.factory, GameDLL);
462 void ClearGamedllList()
464 List<game_dll_t *>::iterator iter;
467 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
474 gamedll_list.clear();
477 int LoadPluginsFromFile(const char *_file)
480 int total = 0, skipped=0;
484 fp = fopen(_file, "rt");
487 LogMessage("[META] Could not open plugins file %s\n", _file);
491 char buffer[255], error[255], full_path[255];
492 const char *ptr, *ext, *file;
494 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
496 UTIL_TrimLeft(buffer);
497 UTIL_TrimRight(buffer);
499 length = strlen(buffer);
505 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
511 if (buffer[0] == '"')
534 while (*cptr && isspace(*cptr))
539 UTIL_TrimRight(cptr);
540 if (*cptr && isalpha(*cptr))
542 g_PluginMngr.SetAlias(buffer, cptr);
554 /* First find if it's an absolute path or not... */
555 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
557 /* If we're in an absolute path, ignore our normal heuristics */
558 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
559 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
561 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
577 /* Attempt to find a file extension */
578 ptr = UTIL_GetExtension(file);
579 /* Add an extension if there's none there */
582 #if defined WIN32 || defined _WIN32
592 /* Format the new path */
593 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.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);
616 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
620 LogMessage("[META] Loaded %d plugins from file.", total);
628 if (provider->IsAlternatelyLoaded())
634 char engine_file[PATH_SIZE];
635 char engine_path[PATH_SIZE];
636 char rel_path[PATH_SIZE * 2];
638 GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
640 /* Chop off the "engine" file part */
641 len = strlen(engine_file);
642 for (size_t i = len - 1; i >= 0 && i < len; i--)
644 if (engine_file[i] == '/' || engine_file[i] == '\\')
646 engine_file[i] = '\0';
650 abspath(engine_path, engine_file);
652 const char *usepath = metamod_path.c_str();
653 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
658 char command[PATH_SIZE * 2];
659 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
660 provider->ServerCommand(command);
663 /* Wrapper function. This is called when the GameDLL thinks it's using
664 * the engine's real engineFactory.
666 void *EngineFactory(const char *iface, int *ret)
668 IFACE_MACRO(engine_factory, Engine);
671 /* Wrapper function. This is called when the GameDLL thinks it's using
672 * the engine's real physicsFactory.
674 void *PhysicsFactory(const char *iface, int *ret)
676 IFACE_MACRO(physics_factory, Physics);
679 /* Wrapper function. This is called when the GameDLL thinks it's using
680 * the engine's real fileSystemFactory.
682 void *FileSystemFactory(const char *iface, int *ret)
684 IFACE_MACRO(filesystem_factory, FileSystem);
687 void LogMessage(const char *msg, ...)
690 static char buffer[2048];
693 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
696 buffer[len++] = '\n';
699 if (!provider->LogMessage(buffer))
701 fprintf(stdout, "%s", buffer);
705 void DoInitialPluginLoads()
707 const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
708 const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
711 pluginFile = provider->GetConVarString(mm_pluginsfile);
712 if (pluginFile == NULL)
714 pluginFile = "addons/metamod/metaplugins.ini";
719 mmBaseDir = provider->GetConVarString(mm_basedir);
720 if (mmBaseDir == NULL)
722 mmBaseDir = "addons/metamod";
728 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
729 LoadPluginsFromFile(full_path);
731 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
732 LookForVDFs(full_path);
735 void StartupMetamod(bool is_vsp_load)
743 is_vsp_load ? "V" : "");
745 metamod_version = provider->CreateConVar("metamod_version",
747 "Metamod:Source Version",
748 ConVarFlag_Notify|ConVarFlag_SpOnly);
750 provider->SetConVarString(metamod_version, buffer);
752 mm_pluginsfile = provider->CreateConVar("mm_pluginsfile",
753 #if defined WIN32 || defined _WIN32
754 "addons\\metamod\\metaplugins.ini",
756 "addons/metamod/metaplugins.ini",
758 "Metamod:Source Plugins File",
761 mm_basedir = provider->CreateConVar("mm_basedir",
762 #if defined __linux__
767 "Metamod:Source Base Folder",
772 DoInitialPluginLoads();
773 in_first_level = true;
777 void InitializeGlobals(CreateInterfaceFn engineFactory,
778 CreateInterfaceFn physicsFactory,
779 CreateInterfaceFn filesystemFactory,
780 CGlobalVars *pGlobals)
782 engine_factory = engineFactory;
783 physics_factory = physicsFactory;
784 filesystem_factory = filesystemFactory;
785 gpGlobals = pGlobals;
786 provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
789 bool Handler_DLLInit(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
791 InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
792 StartupMetamod(false);
794 RETURN_META_VALUE(MRES_IGNORED, true);
797 bool Handler_GameInit()
804 if (vsp_load_requested)
809 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
811 DoInitialPluginLoads();
812 g_PluginMngr.SetAllLoaded();
813 were_plugins_loaded = true;
818 RETURN_META_VALUE(MRES_IGNORED, true);
821 bool Handler_DLLInit_Post(CreateInterfaceFn engineFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn filesystemFactory, CGlobalVars *pGlobals)
823 g_PluginMngr.SetAllLoaded();
824 RETURN_META_VALUE(MRES_IGNORED, true);
830 g_PluginMngr.UnloadAll();
832 provider->Notify_DLLShutdown_Pre();
834 if (is_gamedll_loaded)
836 SH_CALL(server, &IServerGameDLL::DLLShutdown)();
839 g_SourceHook.CompleteShutdown();
841 if (is_gamedll_loaded && gamedll_info.lib)
843 dlclose(gamedll_info.lib);
844 is_gamedll_loaded = false;
848 void Handler_DLLShutdown()
851 RETURN_META(MRES_SUPERCEDE);
854 void Handler_LevelShutdown(void)
856 if (provider->IsAlternatelyLoaded() && !were_plugins_loaded)
858 g_PluginMngr.SetAllLoaded();
859 DoInitialPluginLoads();
860 were_plugins_loaded = true;
861 in_first_level = true;
868 g_Metamod.PathFormat(full_path,
872 provider->GetConVarString(mm_pluginsfile));
873 LoadPluginsFromFile(full_path);
875 g_Metamod.PathFormat(full_path,
879 provider->GetConVarString(mm_basedir));
880 LookForVDFs(full_path);
884 in_first_level = false;
887 ITER_EVENT(OnLevelShutdown, ());
889 RETURN_META(MRES_IGNORED);
892 bool Handler_LevelInit(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
894 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
896 RETURN_META_VALUE(MRES_IGNORED, false);
899 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
905 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
908 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
911 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
915 return EngineFactory;
918 return engine_factory;
921 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
925 return PhysicsFactory;
928 return physics_factory;
931 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
935 return FileSystemFactory;
938 return filesystem_factory;
941 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
945 return CreateInterface;
948 return gamedll_info.factory;
951 CGlobalVars *MetamodSource::GetCGlobals()
956 void MetamodSource::SetLastMetaReturn(META_RES res)
961 META_RES MetamodSource::GetLastMetaReturn()
963 return last_meta_res;
966 void MetamodSource::ConPrint(const char *str)
968 provider->ConsolePrint(str);
971 void MetamodSource::ConPrintf(const char *fmt, ...)
977 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
980 provider->ConsolePrint(buffer);
983 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
985 major = METAMOD_API_MAJOR;
986 minor = METAMOD_API_MINOR;
987 plvers = METAMOD_PLAPI_VERSION;
988 plmin = PLAPI_MIN_VERSION;
991 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
993 shvers = SH_IFACE_VERSION;
994 shimpl = SH_IMPL_VERSION;
997 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
999 int length = (int)strlen(iface);
1003 for (i = length - 1; i >= 0; i--)
1005 if (!isdigit(iface[i]))
1007 if (i != length - 1)
1015 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
1020 if (i != length - 1)
1022 num = atoi(&(iface[++i]));
1027 snprintf(&(iface[i]), 4, "%03d", num);
1032 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
1034 char _if[256]; /* assume no interface goes beyond this */
1035 size_t len = strlen(iface);
1044 if (len + 4 > sizeof(_if))
1048 *ret = IFACE_FAILED;
1057 if ((pf = (fn)(_if, ret)) != NULL)
1065 } while ((num = FormatIface(_if, len+1)));
1070 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
1072 char buffer[256]; /* assume no interface will go beyond this */
1073 size_t len = strlen(iface);
1074 int ret; /* just in case something doesn't handle NULL properly */
1076 if (len > sizeof(buffer) - 4)
1081 strcpy(buffer, iface);
1085 char *ptr = &buffer[len - 1];
1087 while (isdigit(*ptr) && digits <=3)
1095 /* for now, assume this is an error */
1096 strcpy(buffer, iface);
1101 min = (min == 0) ? 1 : min;
1102 snprintf(num, sizeof(num), "%03d", min);
1103 strcat(buffer, num);
1107 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
1110 const char *MetamodSource::GetBaseDir()
1112 return mod_path.c_str();
1115 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
1119 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
1122 for (size_t i = 0; i < mylen; i++)
1124 if (buffer[i] == ALT_SEP_CHAR)
1126 buffer[i] = PATH_SEP_CHAR;
1133 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
1139 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1142 provider->ClientConsolePrint(client, buffer);
1145 void MetamodSource::EnableVSPListener()
1147 if (is_game_init && !vsp_load_requested && !vsp_loaded)
1152 vsp_load_requested = true;
1155 int MetamodSource::GetVSPVersion()
1160 int MetamodSource::GetGameDLLVersion()
1162 return gamedll_version;
1165 bool MetamodSource::RemotePrintingAvailable()
1167 return provider->IsRemotePrintingAvailable();
1170 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
1182 /* First check ours... we get first chance! */
1183 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
1189 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
1191 else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
1197 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
1199 else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
1205 return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
1208 CPluginManager::CPlugin *pl;
1209 List<IMetamodListener *>::iterator event;
1210 IMetamodListener *api;
1214 for (PluginIter iter = g_PluginMngr._begin();
1215 iter != g_PluginMngr._end();
1219 for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
1222 subret = IFACE_FAILED;
1223 if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
1240 *ret = IFACE_FAILED;
1246 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
1248 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
1250 pl->m_Events.push_back(pListener);
1253 const char *MetamodSource::GetGameBinaryPath()
1255 return full_bin_path.c_str();
1258 const char *MetamodSource::GetPluginsFile()
1260 return provider->GetConVarString(mm_pluginsfile);
1263 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
1265 return provider->GetConCommandBaseAccessor();
1268 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1270 if (provider->IsConCommandBaseACommand(pCommand))
1272 g_PluginMngr.AddPluginCmd(plugin, pCommand);
1276 g_PluginMngr.AddPluginCvar(plugin, pCommand);
1279 return provider->RegisterConCommandBase(pCommand);
1282 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1284 if (provider->IsConCommandBaseACommand(pCommand))
1286 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
1290 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
1293 CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
1294 UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
1297 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
1300 CPluginManager::CPlugin *pPlugin;
1301 List<IMetamodListener *>::iterator event;
1302 IMetamodListener *pML;
1303 for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
1306 if (pPlugin->m_Status < Pl_Paused)
1310 /* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
1311 if (pPlugin->m_API->GetApiVersion() < 12)
1315 for (event=pPlugin->m_Events.begin();
1316 event!=pPlugin->m_Events.end();
1320 pML->OnUnlinkConCommandBase(id, pCommand);
1324 return provider->UnregisterConCommandBase(pCommand);
1327 int MetamodSource::GetUserMessageCount()
1329 return provider->GetUserMessageCount();
1332 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
1334 return provider->FindUserMessage(name, size);
1337 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
1339 return provider->GetUserMessage(index, size);
1342 int MetamodSource::GetSourceEngineBuild()
1344 return engine_build;
1347 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
1349 ITER_EVENT(OnVSPListening, (callbacks));
1352 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
1356 *pVersion = vsp_version;
1359 return vsp_callbacks;
1362 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
1367 va_start(ap, format);
1368 result = FormatArgs(buffer, maxlength, format, ap);
1374 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
1376 return UTIL_FormatArgs(buffer, maxlength, format, ap);
1379 bool MetamodSource::IsLoadedAsGameDLL()
1381 return is_gamedll_loaded;
1384 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
1386 gamedll_info.factory = serverFactory;
1387 gamedll_version = version;
1390 bool MetamodSource::IsAlternateLoadComplete()
1392 return were_plugins_loaded;
1395 void ProcessVDF(const char *path)
1399 char alias[24], file[255], error[255];
1401 if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
1406 if (alias[0] != '\0')
1408 g_PluginMngr.SetAlias(alias, file);
1411 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
1412 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1414 LogMessage("[META] Failed to load plugin %s: %s", file, error);
1418 void LookForVDFs(const char *dir)
1420 char path[MAX_PATH];
1423 #if defined _MSC_VER
1428 g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
1429 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
1431 DWORD dw = GetLastError();
1432 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
1435 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1439 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
1445 if (strcmp(fd.cFileName, ".") == 0
1446 || strcmp(fd.cFileName, "..") == 0)
1450 extidx = strlen(fd.cFileName) - 4;
1451 if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1455 g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
1457 } while (FindNextFile(hFind, &fd));
1462 struct dirent *pEnt;
1464 if ((pDir = opendir(dir)) == NULL)
1466 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
1470 while ((pEnt = readdir(pDir)) != NULL)
1472 if (strcmp(pEnt->d_name, ".") == 0
1473 || strcmp(pEnt->d_name, "..") == 0)
1477 extidx = strlen(pEnt->d_name) - 4;
1478 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
1482 g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);