Initial commit of vsp bridge for new core. Not tested, barely compiles.
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);
54 Handler_DLLInit(CreateInterfaceFn engineFactory,
55 CreateInterfaceFn physicsFactory,
56 CreateInterfaceFn filesystemFactory,
57 CGlobalVars *pGlobals);
60 Handler_DLLInit_Post(CreateInterfaceFn engineFactory,
61 CreateInterfaceFn physicsFactory,
62 CreateInterfaceFn filesystemFactory,
63 CGlobalVars *pGlobals);
66 Handler_DLLShutdown();
69 Handler_LevelShutdown();
72 Handler_LevelInit(char const *pMapName,
73 char const *pMapEntities,
74 char const *pOldLevel,
75 char const *pLandmarkName,
86 LookForVDFs(const char *dir);
91 CreateInterfaceFn factory;
94 static String mod_path;
95 static String metamod_path;
96 static String full_bin_path;
97 static bool parsed_game_info = false;
98 static int vsp_version = 0;
99 static int gamedll_version = 0;
100 static int engine_build = SOURCE_ENGINE_UNKNOWN;
101 static List<game_dll_t *> gamedll_list;
102 static bool is_gamedll_loaded = false;
103 static bool in_first_level = true;
104 static bool is_game_init = false;
105 static bool vsp_load_requested = false;
106 static bool vsp_loaded = false;
107 static game_dll_t gamedll_info;
108 static ConVar *metamod_version = NULL;
109 static ConVar *mm_pluginsfile = NULL;
110 static ConVar *mm_basedir = NULL;
111 static IServerGameDLL *server = NULL;
112 static CreateInterfaceFn engine_factory = NULL;
113 static CreateInterfaceFn physics_factory = NULL;
114 static CreateInterfaceFn filesystem_factory = NULL;
115 static CGlobalVars *gpGlobals = NULL;
116 static CHookManagerAutoGen g_SH_HookManagerAutoGen(&g_SourceHook);
117 static META_RES last_meta_res;
118 static IServerPluginCallbacks *vsp_callbacks = NULL;
119 static bool were_plugins_loaded = false;
120 static bool g_bIsVspBridged = false;
122 MetamodSource g_Metamod;
123 PluginId g_PLID = Pl_Console;
124 CSourceHookImpl g_SourceHook;
125 ISourceHook *g_SHPtr = &g_SourceHook;
126 SourceMM::ISmmAPI *g_pMetamod = &g_Metamod;
132 #define IFACE_MACRO(orig,nam) \
133 CPluginManager::CPlugin *pl; \
134 SourceHook::List<IMetamodListener *>::iterator event; \
135 IMetamodListener *api; \
138 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
140 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
142 mret = IFACE_FAILED; \
143 if ( (val=api->On##nam##Query(iface, &mret)) != NULL ) { \
144 if (ret) *ret = mret; \
149 return (orig)(iface, ret);
151 #define ITER_EVENT(evn, args) \
152 CPluginManager::CPlugin *pl; \
153 SourceHook::List<IMetamodListener *>::iterator event; \
154 IMetamodListener *api; \
155 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
157 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
164 mm_SetVspInfo(IServerPluginCallbacks *ispc, unsigned int version)
166 vsp_version = version;
169 /* Initialize everything here */
171 mm_InitializeForLoad()
173 char full_path[PATH_SIZE] = {0};
174 GetFileOfAddress((void *)gamedll_info.factory, full_path, sizeof(full_path));
175 full_bin_path.assign(full_path);
177 /* Like Metamod, reload plugins at the end of the map.
178 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
179 * if the server is shut down (silly, but rare case).
181 in_first_level = true;
183 SourceHook::MemFuncInfo info;
185 if (!provider->GetHookInfo(ProvidedHook_DLLInit, &info))
187 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLInit");
189 SH_MANUALHOOK_RECONFIGURE(SGD_DLLInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
190 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit, false);
191 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLInit, server, Handler_DLLInit_Post, true);
193 if (!provider->GetHookInfo(ProvidedHook_GameInit, &info))
195 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::GameInit");
197 SH_MANUALHOOK_RECONFIGURE(SGD_GameInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
198 SH_ADD_MANUALHOOK_STATICFUNC(SGD_GameInit, server, Handler_GameInit, false);
200 if (!provider->GetHookInfo(ProvidedHook_LevelInit, &info))
202 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelInit");
204 SH_MANUALHOOK_RECONFIGURE(SGD_LevelInit, info.vtblindex, info.vtbloffs, info.thisptroffs);
205 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelInit, server, Handler_LevelInit, true);
207 if (!provider->GetHookInfo(ProvidedHook_LevelShutdown, &info))
209 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::LevelShutdown");
211 SH_MANUALHOOK_RECONFIGURE(SGD_LevelShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
212 SH_ADD_MANUALHOOK_STATICFUNC(SGD_LevelShutdown, server, Handler_LevelShutdown, true);
214 if (!provider->GetHookInfo(ProvidedHook_DLLShutdown, &info))
216 provider->DisplayError("Metamod:Source could not find a valid hook for IServerGameDLL::DLLShutdown");
218 SH_MANUALHOOK_RECONFIGURE(SGD_DLLShutdown, info.vtblindex, info.vtbloffs, info.thisptroffs);
219 SH_ADD_MANUALHOOK_STATICFUNC(SGD_DLLShutdown, server, Handler_DLLShutdown, false);
223 mm_DetectGameInformation()
225 char mm_path[PATH_SIZE];
226 char game_path[PATH_SIZE];
228 /* Get path to SourceMM DLL */
229 if (!GetFileOfAddress((void *)mm_InitializeForLoad, mm_path, sizeof(mm_path)))
234 metamod_path.assign(mm_path);
236 /* Get value of -game from command line, defaulting to hl2 as engine seems to do */
237 const char *game_dir = provider->GetCommandLineValue("-game", "hl2");
239 /* Get absolute path */
240 abspath(game_path, game_dir);
241 mod_path.assign(game_path);
243 engine_build = provider->DetermineSourceEngine(game_dir);;
248 /* This is where the magic happens */
250 CreateInterface(const char *iface, int *ret)
252 /* Prevent loading of self as a SourceMM plugin or Valve server plugin :x */
253 if (strcmp(iface, METAMOD_PLAPI_NAME) == 0)
255 provider->DisplayWarning("Do not try loading Metamod:Source as a plugin.\n");
265 if (!g_bIsVspBridged && strncmp(iface, "ISERVERPLUGINCALLBACKS", 22) == 0)
267 if (vsp_callbacks != NULL && atoi(&iface[22]) != vsp_version)
274 vsp_version = atoi(&iface[22]);
275 vsp_callbacks = provider->GetVSPCallbacks(vsp_version);
278 *ret = (vsp_callbacks != NULL) ? IFACE_OK : IFACE_FAILED;
280 if (vsp_callbacks == NULL)
283 return vsp_callbacks;
288 IFACE_MACRO(gamedll_info.factory, GameDLL);
291 if (!parsed_game_info)
293 parsed_game_info = true;
295 if (!mm_DetectGameInformation())
297 provider->DisplayError("GetFileOfAddress() failed! Metamod cannot load.\n");
301 char temp_path[PATH_SIZE];
303 /* Path to gameinfo.txt */
304 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s", mod_path.c_str(), "gameinfo.txt");
306 FILE *fp = fopen(temp_path, "rt");
310 provider->DisplayError("Unable to open gameinfo.txt! Metamod cannot load.\n");
315 char key[128], val[128];
317 bool gamebin = false;
320 char cur_path[PATH_SIZE];
322 getcwd(cur_path, PATH_SIZE);
324 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
326 UTIL_TrimComments(buffer);
327 UTIL_TrimLeft(buffer);
328 UTIL_TrimRight(buffer);
330 if (stricmp(buffer, "SearchPaths") == 0)
340 UTIL_KeySplit(buffer, key, sizeof(key) - 1, val, sizeof(val) - 1);
341 if (stricmp(key, "Game") == 0 || stricmp(key, "GameBin") == 0)
343 if (stricmp(key, "Game") == 0)
352 if (strncmp(val, "|gameinfo_path|", sizeof("|gameinfo_path|") - 1) == 0)
354 ptr = &(val[sizeof("|gameinfo_path|") - 1]);
359 lptr = mod_path.c_str();
365 size_t ptr_len = strlen(ptr);
366 if (ptr[ptr_len] == '/' || ptr[ptr_len] == '\\')
368 ptr[--ptr_len] = '\0';
371 /* No need to append "bin" if key is GameBin */
374 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, ptr, SERVER_DLL);
378 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s", lptr, "bin", SERVER_DLL);
382 g_Metamod.PathFormat(temp_path, PATH_SIZE, "%s/%s/%s/%s", lptr, ptr, "bin", SERVER_DLL);
385 /* If not path to SourceMM... */
386 if (!UTIL_PathCmp(metamod_path.c_str(), temp_path))
388 FILE *temp_fp = fopen(temp_path, "rb");
395 /* Search for a matching game dll */
396 List<game_dll_t *>::iterator iter;
399 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
402 if (GetFileOfAddress((void *)pCheck->factory, buffer, sizeof(buffer)))
404 if (UTIL_PathCmp(temp_path, buffer))
417 HINSTANCE gamedll = dlmount(temp_path);
423 CreateInterfaceFn fn = (CreateInterfaceFn)dlsym(gamedll, "CreateInterface");
430 game_dll_t *pInfo = new game_dll_t;
432 pInfo->lib = gamedll;
433 gamedll_list.push_back(pInfo);
441 if (!is_gamedll_loaded)
443 if (strncmp(iface, "ServerGameDLL", 13) == 0)
445 List<game_dll_t *>::iterator iter;
447 for (iter=gamedll_list.begin(); iter!=gamedll_list.end(); iter++)
450 if ((server = (IServerGameDLL *)((pInfo->factory)(iface, ret))) != NULL)
452 if ((gamedll_version = provider->TryServerGameDLL(iface)) != 0)
454 /* We have a match. Erase us from the list and save our info. */
455 gamedll_list.erase(iter);
456 gamedll_info = *pInfo;
458 is_gamedll_loaded = true;
461 /* :TODO: error otherwise? */
465 if (is_gamedll_loaded)
468 mm_InitializeForLoad();
481 /* wtf do we do... */
482 /* :TODO: .. something a bit more intelligent? */
483 provider->DisplayError("Engine requested unknown interface before GameDLL was known!\n");
488 /* If we got here, there's definitely a GameDLL */
489 IFACE_MACRO(gamedll_info.factory, GameDLL);
495 List<game_dll_t *>::iterator iter;
498 for (iter = gamedll_list.begin(); iter != gamedll_list.end(); iter++)
505 gamedll_list.clear();
509 mm_LoadPluginsFromFile(const char *_file)
512 int total = 0, skipped=0;
516 fp = fopen(_file, "rt");
519 LogMessage("[META] Could not open plugins file %s\n", _file);
523 char buffer[255], error[255], full_path[255];
524 const char *ptr, *ext, *file;
526 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
528 UTIL_TrimLeft(buffer);
529 UTIL_TrimRight(buffer);
531 length = strlen(buffer);
537 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
543 if (buffer[0] == '"')
566 while (*cptr && isspace(*cptr))
571 UTIL_TrimRight(cptr);
572 if (*cptr && isalpha(*cptr))
574 g_PluginMngr.SetAlias(buffer, cptr);
586 /* First find if it's an absolute path or not... */
587 if (file[0] == '/' || strncmp(&(file[1]), ":\\", 2) == 0)
589 /* If we're in an absolute path, ignore our normal heuristics */
590 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
591 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
593 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
609 /* Attempt to find a file extension */
610 ptr = UTIL_GetExtension(file);
611 /* Add an extension if there's none there */
614 #if defined WIN32 || defined _WIN32
624 /* Format the new path */
625 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
626 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
627 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
629 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
648 LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
652 LogMessage("[META] Loaded %d plugins from file.", total);
664 char engine_file[PATH_SIZE];
665 char engine_path[PATH_SIZE];
666 char rel_path[PATH_SIZE * 2];
668 GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
670 /* Chop off the "engine" file part */
671 len = strlen(engine_file);
672 for (size_t i = len - 1; i >= 0 && i < len; i--)
674 if (engine_file[i] == '/' || engine_file[i] == '\\')
676 engine_file[i] = '\0';
680 abspath(engine_path, engine_file);
682 const char *usepath = metamod_path.c_str();
683 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
688 char command[PATH_SIZE * 2];
689 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
690 provider->ServerCommand(command);
693 /* Wrapper function. This is called when the GameDLL thinks it's using
694 * the engine's real engineFactory.
697 EngineFactory(const char *iface, int *ret)
699 IFACE_MACRO(engine_factory, Engine);
702 /* Wrapper function. This is called when the GameDLL thinks it's using
703 * the engine's real physicsFactory.
706 PhysicsFactory(const char *iface, int *ret)
708 IFACE_MACRO(physics_factory, Physics);
711 /* Wrapper function. This is called when the GameDLL thinks it's using
712 * the engine's real fileSystemFactory.
715 FileSystemFactory(const char *iface, int *ret)
717 IFACE_MACRO(filesystem_factory, FileSystem);
721 mm_LogMessage(const char *msg, ...)
724 static char buffer[2048];
727 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
730 buffer[len++] = '\n';
733 if (!provider->LogMessage(buffer))
735 fprintf(stdout, "%s", buffer);
740 DoInitialPluginLoads()
742 const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
743 const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
746 pluginFile = provider->GetConVarString(mm_pluginsfile);
747 if (pluginFile == NULL)
749 pluginFile = "addons/metamod/metaplugins.ini";
754 mmBaseDir = provider->GetConVarString(mm_basedir);
755 if (mmBaseDir == NULL)
757 mmBaseDir = "addons/metamod";
763 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
764 mm_LoadPluginsFromFile(full_path);
766 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
767 LookForVDFs(full_path);
771 mm_StartupMetamod(bool is_vsp_load)
779 is_vsp_load ? "V" : "");
781 metamod_version = provider->CreateConVar("metamod_version",
783 "Metamod:Source Version",
784 ConVarFlag_Notify|ConVarFlag_SpOnly);
786 provider->SetConVarString(metamod_version, buffer);
788 mm_pluginsfile = provider->CreateConVar("mm_pluginsfile",
789 #if defined WIN32 || defined _WIN32
790 "addons\\metamod\\metaplugins.ini",
792 "addons/metamod/metaplugins.ini",
794 "Metamod:Source Plugins File",
797 mm_basedir = provider->CreateConVar("mm_basedir",
798 #if defined __linux__
803 "Metamod:Source Base Folder",
806 g_bIsVspBridged = true;
810 DoInitialPluginLoads();
811 in_first_level = true;
816 mm_InitializeGlobals(CreateInterfaceFn engineFactory,
817 CreateInterfaceFn physicsFactory,
818 CreateInterfaceFn filesystemFactory,
819 CGlobalVars *pGlobals)
821 engine_factory = engineFactory;
822 physics_factory = physicsFactory;
823 filesystem_factory = filesystemFactory;
824 gpGlobals = pGlobals;
825 provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
829 Handler_DLLInit(CreateInterfaceFn engineFactory,
830 CreateInterfaceFn physicsFactory,
831 CreateInterfaceFn filesystemFactory,
832 CGlobalVars *pGlobals)
834 mm_InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
835 mm_StartupMetamod(false);
837 RETURN_META_VALUE(MRES_IGNORED, true);
846 if (vsp_load_requested)
849 if (g_bIsVspBridged && !were_plugins_loaded)
851 DoInitialPluginLoads();
852 g_PluginMngr.SetAllLoaded();
853 were_plugins_loaded = true;
858 RETURN_META_VALUE(MRES_IGNORED, true);
862 Handler_DLLInit_Post(CreateInterfaceFn engineFactory,
863 CreateInterfaceFn physicsFactory,
864 CreateInterfaceFn filesystemFactory,
865 CGlobalVars *pGlobals)
867 g_PluginMngr.SetAllLoaded();
868 RETURN_META_VALUE(MRES_IGNORED, true);
875 g_PluginMngr.UnloadAll();
877 provider->Notify_DLLShutdown_Pre();
879 if (is_gamedll_loaded)
881 SH_CALL(server, &IServerGameDLL::DLLShutdown)();
884 g_SourceHook.CompleteShutdown();
886 if (is_gamedll_loaded && gamedll_info.lib)
888 dlclose(gamedll_info.lib);
889 is_gamedll_loaded = false;
894 Handler_DLLShutdown()
897 RETURN_META(MRES_SUPERCEDE);
901 Handler_LevelShutdown(void)
903 if (g_bIsVspBridged && !were_plugins_loaded)
905 g_PluginMngr.SetAllLoaded();
906 DoInitialPluginLoads();
907 were_plugins_loaded = true;
908 in_first_level = true;
915 g_Metamod.PathFormat(full_path,
919 provider->GetConVarString(mm_pluginsfile));
920 mm_LoadPluginsFromFile(full_path);
922 g_Metamod.PathFormat(full_path,
926 provider->GetConVarString(mm_basedir));
927 LookForVDFs(full_path);
931 in_first_level = false;
934 ITER_EVENT(OnLevelShutdown, ());
936 RETURN_META(MRES_IGNORED);
940 Handler_LevelInit(char const *pMapName,
941 char const *pMapEntities,
942 char const *pOldLevel,
943 char const *pLandmarkName,
947 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
949 RETURN_META_VALUE(MRES_IGNORED, false);
952 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
958 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
961 LogMessage("[%s] %s", pl->GetLogTag(), buffer);
964 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
967 return EngineFactory;
968 return engine_factory;
971 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
974 return PhysicsFactory;
975 return physics_factory;
978 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
981 return FileSystemFactory;
982 return filesystem_factory;
985 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
988 return CreateInterface;
989 return gamedll_info.factory;
992 CGlobalVars *MetamodSource::GetCGlobals()
997 void MetamodSource::SetLastMetaReturn(META_RES res)
1002 META_RES MetamodSource::GetLastMetaReturn()
1004 return last_meta_res;
1007 void MetamodSource::ConPrint(const char *str)
1009 provider->ConsolePrint(str);
1012 void MetamodSource::ConPrintf(const char *fmt, ...)
1018 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1021 provider->ConsolePrint(buffer);
1024 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
1026 major = METAMOD_API_MAJOR;
1027 minor = METAMOD_API_MINOR;
1028 plvers = METAMOD_PLAPI_VERSION;
1029 plmin = PLAPI_MIN_VERSION;
1032 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
1034 shvers = SH_IFACE_VERSION;
1035 shimpl = SH_IMPL_VERSION;
1038 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
1040 int length = (int)strlen(iface);
1044 for (i = length - 1; i >= 0; i--)
1046 if (!isdigit(iface[i]))
1048 if (i != length - 1)
1056 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
1061 if (i != length - 1)
1063 num = atoi(&(iface[++i]));
1068 snprintf(&(iface[i]), 4, "%03d", num);
1073 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
1075 char _if[256]; /* assume no interface goes beyond this */
1076 size_t len = strlen(iface);
1085 if (len + 4 > sizeof(_if))
1089 *ret = IFACE_FAILED;
1098 if ((pf = (fn)(_if, ret)) != NULL)
1106 } while ((num = FormatIface(_if, len+1)));
1111 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
1113 char buffer[256]; /* assume no interface will go beyond this */
1114 size_t len = strlen(iface);
1115 int ret; /* just in case something doesn't handle NULL properly */
1117 if (len > sizeof(buffer) - 4)
1122 strcpy(buffer, iface);
1126 char *ptr = &buffer[len - 1];
1128 while (isdigit(*ptr) && digits <=3)
1136 /* for now, assume this is an error */
1137 strcpy(buffer, iface);
1142 min = (min == 0) ? 1 : min;
1143 snprintf(num, sizeof(num), "%03d", min);
1144 strcat(buffer, num);
1148 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
1151 const char *MetamodSource::GetBaseDir()
1153 return mod_path.c_str();
1156 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
1160 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
1163 for (size_t i = 0; i < mylen; i++)
1165 if (buffer[i] == ALT_SEP_CHAR)
1167 buffer[i] = PATH_SEP_CHAR;
1174 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
1180 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1183 provider->ClientConsolePrint(client, buffer);
1186 void MetamodSource::EnableVSPListener()
1188 if (is_game_init && !vsp_load_requested && !vsp_loaded)
1191 vsp_load_requested = true;
1194 int MetamodSource::GetVSPVersion()
1199 int MetamodSource::GetGameDLLVersion()
1201 return gamedll_version;
1204 bool MetamodSource::RemotePrintingAvailable()
1206 return provider->IsRemotePrintingAvailable();
1209 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
1221 /* First check ours... we get first chance! */
1222 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
1228 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
1230 else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
1236 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
1238 else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
1244 return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
1247 CPluginManager::CPlugin *pl;
1248 List<IMetamodListener *>::iterator event;
1249 IMetamodListener *api;
1253 for (PluginIter iter = g_PluginMngr._begin();
1254 iter != g_PluginMngr._end();
1258 for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
1261 subret = IFACE_FAILED;
1262 if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
1279 *ret = IFACE_FAILED;
1285 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
1287 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
1289 pl->m_Events.push_back(pListener);
1292 const char *MetamodSource::GetGameBinaryPath()
1294 return full_bin_path.c_str();
1297 const char *MetamodSource::GetPluginsFile()
1299 return provider->GetConVarString(mm_pluginsfile);
1302 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
1304 return provider->GetConCommandBaseAccessor();
1307 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1309 if (provider->IsConCommandBaseACommand(pCommand))
1311 g_PluginMngr.AddPluginCmd(plugin, pCommand);
1315 g_PluginMngr.AddPluginCvar(plugin, pCommand);
1318 return provider->RegisterConCommandBase(pCommand);
1321 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1323 if (provider->IsConCommandBaseACommand(pCommand))
1325 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
1329 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
1332 CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
1333 UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
1336 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
1339 CPluginManager::CPlugin *pPlugin;
1340 List<IMetamodListener *>::iterator event;
1341 IMetamodListener *pML;
1342 for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
1345 if (pPlugin->m_Status < Pl_Paused)
1349 /* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
1350 if (pPlugin->m_API->GetApiVersion() < 12)
1354 for (event=pPlugin->m_Events.begin();
1355 event!=pPlugin->m_Events.end();
1359 pML->OnUnlinkConCommandBase(id, pCommand);
1363 return provider->UnregisterConCommandBase(pCommand);
1366 int MetamodSource::GetUserMessageCount()
1368 return provider->GetUserMessageCount();
1371 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
1373 return provider->FindUserMessage(name, size);
1376 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
1378 return provider->GetUserMessage(index, size);
1381 int MetamodSource::GetSourceEngineBuild()
1383 return engine_build;
1386 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
1388 ITER_EVENT(OnVSPListening, (callbacks));
1391 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
1395 *pVersion = vsp_version;
1398 return vsp_callbacks;
1401 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
1406 va_start(ap, format);
1407 result = FormatArgs(buffer, maxlength, format, ap);
1413 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
1415 return UTIL_FormatArgs(buffer, maxlength, format, ap);
1418 bool MetamodSource::IsLoadedAsGameDLL()
1420 return is_gamedll_loaded;
1423 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
1425 gamedll_info.factory = serverFactory;
1426 gamedll_version = version;
1430 ProcessVDF(const char *path)
1434 char alias[24], file[255], error[255];
1436 if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
1441 if (alias[0] != '\0')
1443 g_PluginMngr.SetAlias(alias, file);
1446 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
1447 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1449 LogMessage("[META] Failed to load plugin %s: %s", file, error);
1454 LookForVDFs(const char *dir)
1456 char path[MAX_PATH];
1459 #if defined _MSC_VER
1464 g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
1465 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
1467 DWORD dw = GetLastError();
1468 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
1471 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1475 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
1481 if (strcmp(fd.cFileName, ".") == 0
1482 || strcmp(fd.cFileName, "..") == 0)
1486 extidx = strlen(fd.cFileName) - 4;
1487 if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1491 g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
1493 } while (FindNextFile(hFind, &fd));
1498 struct dirent *pEnt;
1500 if ((pDir = opendir(dir)) == NULL)
1502 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
1506 while ((pEnt = readdir(pDir)) != NULL)
1508 if (strcmp(pEnt->d_name, ".") == 0
1509 || strcmp(pEnt->d_name, "..") == 0)
1513 extidx = strlen(pEnt->d_name) - 4;
1514 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
1518 g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
1529 return g_bIsVspBridged;
1533 mm_IsVspLoadComplete()
1535 return were_plugins_loaded;