Fixed up bugs and linking errors - loads but crashes.
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 mm_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 mm_LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
605 /* Attempt to find a file extension */
606 ptr = UTIL_GetExtension(file);
607 /* Add an extension if there's none there */
610 #if defined WIN32 || defined _WIN32
620 /* Format the new path */
621 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s%s", mod_path.c_str(), file, ext);
622 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
623 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
625 mm_LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
639 mm_LogMessage("[META] Loaded %d plugins from file (%d already loaded)", total, skipped);
641 mm_LogMessage("[META] Loaded %d plugins from file.", total);
652 char engine_file[PATH_SIZE];
653 char engine_path[PATH_SIZE];
654 char rel_path[PATH_SIZE * 2];
656 GetFileOfAddress((void *)engine_factory, engine_file, sizeof(engine_file));
658 /* Chop off the "engine" file part */
659 len = strlen(engine_file);
660 for (size_t i = len - 1; i >= 0 && i < len; i--)
662 if (engine_file[i] == '/' || engine_file[i] == '\\')
664 engine_file[i] = '\0';
668 abspath(engine_path, engine_file);
670 const char *usepath = metamod_path.c_str();
671 if (UTIL_Relatize(rel_path, sizeof(rel_path), engine_path, metamod_path.c_str()))
676 char command[PATH_SIZE * 2];
677 UTIL_Format(command, sizeof(command), "plugin_load \"%s\"\n", usepath);
678 provider->ServerCommand(command);
681 /* Wrapper function. This is called when the GameDLL thinks it's using
682 * the engine's real engineFactory.
685 EngineFactory(const char *iface, int *ret)
687 IFACE_MACRO(engine_factory, Engine);
690 /* Wrapper function. This is called when the GameDLL thinks it's using
691 * the engine's real physicsFactory.
694 PhysicsFactory(const char *iface, int *ret)
696 IFACE_MACRO(physics_factory, Physics);
699 /* Wrapper function. This is called when the GameDLL thinks it's using
700 * the engine's real fileSystemFactory.
703 FileSystemFactory(const char *iface, int *ret)
705 IFACE_MACRO(filesystem_factory, FileSystem);
709 mm_LogMessage(const char *msg, ...)
712 static char buffer[2048];
715 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
718 buffer[len++] = '\n';
721 if (!provider->LogMessage(buffer))
723 fprintf(stdout, "%s", buffer);
728 DoInitialPluginLoads()
730 const char *pluginFile = provider->GetCommandLineValue("mm_pluginsfile", NULL);
731 const char *mmBaseDir = provider->GetCommandLineValue("mm_basedir", NULL);
734 pluginFile = provider->GetConVarString(mm_pluginsfile);
735 if (pluginFile == NULL)
737 pluginFile = "addons/metamod/metaplugins.ini";
742 mmBaseDir = provider->GetConVarString(mm_basedir);
743 if (mmBaseDir == NULL)
745 mmBaseDir = "addons/metamod";
751 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), pluginFile);
752 mm_LoadPluginsFromFile(full_path);
754 g_Metamod.PathFormat(full_path, sizeof(full_path), "%s/%s", mod_path.c_str(), mmBaseDir);
755 LookForVDFs(full_path);
759 mm_StartupMetamod(bool is_vsp_load)
767 is_vsp_load ? "V" : "");
769 metamod_version = provider->CreateConVar("metamod_version",
771 "Metamod:Source Version",
772 ConVarFlag_Notify|ConVarFlag_SpOnly);
774 provider->SetConVarString(metamod_version, buffer);
776 mm_pluginsfile = provider->CreateConVar("mm_pluginsfile",
777 #if defined WIN32 || defined _WIN32
778 "addons\\metamod\\metaplugins.ini",
780 "addons/metamod/metaplugins.ini",
782 "Metamod:Source Plugins File",
785 mm_basedir = provider->CreateConVar("mm_basedir",
786 #if defined __linux__
791 "Metamod:Source Base Folder",
794 g_bIsVspBridged = true;
798 DoInitialPluginLoads();
799 in_first_level = true;
804 mm_InitializeGlobals(CreateInterfaceFn engineFactory,
805 CreateInterfaceFn physicsFactory,
806 CreateInterfaceFn filesystemFactory,
807 CGlobalVars *pGlobals)
809 engine_factory = engineFactory;
810 physics_factory = physicsFactory;
811 filesystem_factory = filesystemFactory;
812 gpGlobals = pGlobals;
813 provider->Notify_DLLInit_Pre(engineFactory, gamedll_info.factory);
817 Handler_DLLInit(CreateInterfaceFn engineFactory,
818 CreateInterfaceFn physicsFactory,
819 CreateInterfaceFn filesystemFactory,
820 CGlobalVars *pGlobals)
822 mm_InitializeGlobals(engineFactory, physicsFactory, filesystemFactory, pGlobals);
823 mm_StartupMetamod(false);
825 RETURN_META_VALUE(MRES_IGNORED, true);
834 if (vsp_load_requested)
837 if (g_bIsVspBridged && !were_plugins_loaded)
839 DoInitialPluginLoads();
840 g_PluginMngr.SetAllLoaded();
841 were_plugins_loaded = true;
846 RETURN_META_VALUE(MRES_IGNORED, true);
850 Handler_DLLInit_Post(CreateInterfaceFn engineFactory,
851 CreateInterfaceFn physicsFactory,
852 CreateInterfaceFn filesystemFactory,
853 CGlobalVars *pGlobals)
855 g_PluginMngr.SetAllLoaded();
856 RETURN_META_VALUE(MRES_IGNORED, true);
863 g_PluginMngr.UnloadAll();
865 provider->Notify_DLLShutdown_Pre();
867 if (is_gamedll_loaded)
869 SH_CALL(server, &IServerGameDLL::DLLShutdown)();
872 g_SourceHook.CompleteShutdown();
874 if (is_gamedll_loaded && gamedll_info.lib)
876 dlclose(gamedll_info.lib);
877 is_gamedll_loaded = false;
882 Handler_DLLShutdown()
885 RETURN_META(MRES_SUPERCEDE);
889 Handler_LevelShutdown(void)
891 if (g_bIsVspBridged && !were_plugins_loaded)
893 g_PluginMngr.SetAllLoaded();
894 DoInitialPluginLoads();
895 were_plugins_loaded = true;
896 in_first_level = true;
903 g_Metamod.PathFormat(full_path,
907 provider->GetConVarString(mm_pluginsfile));
908 mm_LoadPluginsFromFile(full_path);
910 g_Metamod.PathFormat(full_path,
914 provider->GetConVarString(mm_basedir));
915 LookForVDFs(full_path);
919 in_first_level = false;
922 ITER_EVENT(OnLevelShutdown, ());
924 RETURN_META(MRES_IGNORED);
928 Handler_LevelInit(char const *pMapName,
929 char const *pMapEntities,
930 char const *pOldLevel,
931 char const *pLandmarkName,
935 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
937 RETURN_META_VALUE(MRES_IGNORED, false);
940 void MetamodSource::LogMsg(ISmmPlugin *pl, const char *msg, ...)
946 UTIL_FormatArgs(buffer, sizeof(buffer), msg, ap);
949 mm_LogMessage("[%s] %s", pl->GetLogTag(), buffer);
952 CreateInterfaceFn MetamodSource::GetEngineFactory(bool syn/* =true */)
955 return EngineFactory;
956 return engine_factory;
959 CreateInterfaceFn MetamodSource::GetPhysicsFactory(bool syn/* =true */)
962 return PhysicsFactory;
963 return physics_factory;
966 CreateInterfaceFn MetamodSource::GetFileSystemFactory(bool syn/* =true */)
969 return FileSystemFactory;
970 return filesystem_factory;
973 CreateInterfaceFn MetamodSource::GetServerFactory(bool syn/* =true */)
976 return CreateInterface;
977 return gamedll_info.factory;
980 CGlobalVars *MetamodSource::GetCGlobals()
985 void MetamodSource::SetLastMetaReturn(META_RES res)
990 META_RES MetamodSource::GetLastMetaReturn()
992 return last_meta_res;
995 void MetamodSource::ConPrint(const char *str)
997 provider->ConsolePrint(str);
1000 void MetamodSource::ConPrintf(const char *fmt, ...)
1006 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1009 provider->ConsolePrint(buffer);
1012 void MetamodSource::GetApiVersions(int &major, int &minor, int &plvers, int &plmin)
1014 major = METAMOD_API_MAJOR;
1015 minor = METAMOD_API_MINOR;
1016 plvers = METAMOD_PLAPI_VERSION;
1017 plmin = PLAPI_MIN_VERSION;
1020 void MetamodSource::GetShVersions(int &shvers, int &shimpl)
1022 shvers = SH_IFACE_VERSION;
1023 shimpl = SH_IMPL_VERSION;
1026 int MetamodSource::FormatIface(char iface[], unsigned int maxlength)
1028 int length = (int)strlen(iface);
1032 for (i = length - 1; i >= 0; i--)
1034 if (!isdigit(iface[i]))
1036 if (i != length - 1)
1044 if ( (num && ((int)maxlength <= length)) || (!num && ((int)maxlength <= length + 3)) )
1049 if (i != length - 1)
1051 num = atoi(&(iface[++i]));
1056 snprintf(&(iface[i]), 4, "%03d", num);
1061 void *MetamodSource::InterfaceSearch(CreateInterfaceFn fn, const char *iface, int max, int *ret)
1063 char _if[256]; /* assume no interface goes beyond this */
1064 size_t len = strlen(iface);
1073 if (len + 4 > sizeof(_if))
1077 *ret = IFACE_FAILED;
1086 if ((pf = (fn)(_if, ret)) != NULL)
1094 } while ((num = FormatIface(_if, len+1)));
1099 void *MetamodSource::VInterfaceMatch(CreateInterfaceFn fn, const char *iface, int min)
1101 char buffer[256]; /* assume no interface will go beyond this */
1102 size_t len = strlen(iface);
1103 int ret; /* just in case something doesn't handle NULL properly */
1105 if (len > sizeof(buffer) - 4)
1110 strcpy(buffer, iface);
1114 char *ptr = &buffer[len - 1];
1116 while (isdigit(*ptr) && digits <=3)
1124 /* for now, assume this is an error */
1125 strcpy(buffer, iface);
1130 min = (min == 0) ? 1 : min;
1131 snprintf(num, sizeof(num), "%03d", min);
1132 strcat(buffer, num);
1136 return InterfaceSearch(fn, buffer, IFACE_MAXNUM, &ret);
1139 const char *MetamodSource::GetBaseDir()
1141 return mod_path.c_str();
1144 size_t MetamodSource::PathFormat(char *buffer, size_t len, const char *fmt, ...)
1148 size_t mylen = UTIL_FormatArgs(buffer, len, fmt, ap);
1151 for (size_t i = 0; i < mylen; i++)
1153 if (buffer[i] == ALT_SEP_CHAR)
1155 buffer[i] = PATH_SEP_CHAR;
1162 void MetamodSource::ClientConPrintf(edict_t *client, const char *fmt, ...)
1168 UTIL_FormatArgs(buffer, sizeof(buffer), fmt, ap);
1171 provider->ClientConsolePrint(client, buffer);
1174 void MetamodSource::EnableVSPListener()
1176 if (is_game_init && !vsp_load_requested && !vsp_loaded)
1179 vsp_load_requested = true;
1182 int MetamodSource::GetVSPVersion()
1187 int MetamodSource::GetGameDLLVersion()
1189 return gamedll_version;
1192 bool MetamodSource::RemotePrintingAvailable()
1194 return provider->IsRemotePrintingAvailable();
1197 void *MetamodSource::MetaFactory(const char *iface, int *ret, PluginId *id)
1209 /* First check ours... we get first chance! */
1210 if (strcmp(iface, MMIFACE_SOURCEHOOK) == 0)
1216 return static_cast<void *>(static_cast<SourceHook::ISourceHook *>(&g_SourceHook));
1218 else if (strcmp(iface, MMIFACE_PLMANAGER) == 0)
1224 return static_cast<void *>(static_cast<ISmmPluginManager *>(&g_PluginMngr));
1226 else if (strcmp(iface, MMIFACE_SH_HOOKMANAUTOGEN) == 0)
1232 return static_cast<void *>(static_cast<SourceHook::IHookManagerAutoGen *>(&g_SH_HookManagerAutoGen));
1235 CPluginManager::CPlugin *pl;
1236 List<IMetamodListener *>::iterator event;
1237 IMetamodListener *api;
1241 for (PluginIter iter = g_PluginMngr._begin();
1242 iter != g_PluginMngr._end();
1246 for (event = pl->m_Events.begin(); event != pl->m_Events.end(); event++)
1249 subret = IFACE_FAILED;
1250 if ((value = api->OnMetamodQuery(iface, &subret)) != NULL)
1267 *ret = IFACE_FAILED;
1273 void MetamodSource::AddListener(ISmmPlugin *plugin, IMetamodListener *pListener)
1275 CPluginManager::CPlugin *pl = g_PluginMngr.FindByAPI(plugin);
1277 pl->m_Events.push_back(pListener);
1280 const char *MetamodSource::GetGameBinaryPath()
1282 return full_bin_path.c_str();
1285 const char *MetamodSource::GetPluginsFile()
1287 return provider->GetConVarString(mm_pluginsfile);
1290 IConCommandBaseAccessor *MetamodSource::GetCvarBaseAccessor()
1292 return provider->GetConCommandBaseAccessor();
1295 bool MetamodSource::RegisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1297 if (provider->IsConCommandBaseACommand(pCommand))
1299 g_PluginMngr.AddPluginCmd(plugin, pCommand);
1303 g_PluginMngr.AddPluginCvar(plugin, pCommand);
1306 return provider->RegisterConCommandBase(pCommand);
1309 void MetamodSource::UnregisterConCommandBase(ISmmPlugin *plugin, ConCommandBase *pCommand)
1311 if (provider->IsConCommandBaseACommand(pCommand))
1313 g_PluginMngr.RemovePluginCmd(plugin, pCommand);
1317 g_PluginMngr.RemovePluginCvar(plugin, pCommand);
1320 CPluginManager::CPlugin *pOrig = g_PluginMngr.FindByAPI(plugin);
1321 UnregisterConCommandBase(pOrig ? pOrig->m_Id : 0, pCommand);
1324 void MetamodSource::UnregisterConCommandBase(PluginId id, ConCommandBase *pCommand)
1327 CPluginManager::CPlugin *pPlugin;
1328 List<IMetamodListener *>::iterator event;
1329 IMetamodListener *pML;
1330 for (iter=g_PluginMngr._begin(); iter!=g_PluginMngr._end(); iter++)
1333 if (pPlugin->m_Status < Pl_Paused)
1337 /* Only valid for plugins >= 12 (v1:6, SourceMM 1.5) */
1338 if (pPlugin->m_API->GetApiVersion() < 12)
1342 for (event=pPlugin->m_Events.begin();
1343 event!=pPlugin->m_Events.end();
1347 pML->OnUnlinkConCommandBase(id, pCommand);
1351 return provider->UnregisterConCommandBase(pCommand);
1354 int MetamodSource::GetUserMessageCount()
1356 return provider->GetUserMessageCount();
1359 int MetamodSource::FindUserMessage(const char *name, int *size/* =NULL */)
1361 return provider->FindUserMessage(name, size);
1364 const char *MetamodSource::GetUserMessage(int index, int *size/* =NULL */)
1366 return provider->GetUserMessage(index, size);
1369 int MetamodSource::GetSourceEngineBuild()
1371 return engine_build;
1374 void MetamodSource::NotifyVSPListening(IServerPluginCallbacks *callbacks)
1376 ITER_EVENT(OnVSPListening, (callbacks));
1379 IServerPluginCallbacks *MetamodSource::GetVSPInfo(int *pVersion)
1383 *pVersion = vsp_version;
1386 return vsp_callbacks;
1389 size_t MetamodSource::Format(char *buffer, size_t maxlength, const char *format, ...)
1394 va_start(ap, format);
1395 result = FormatArgs(buffer, maxlength, format, ap);
1401 size_t MetamodSource::FormatArgs(char *buffer, size_t maxlength, const char *format, va_list ap)
1403 return UTIL_FormatArgs(buffer, maxlength, format, ap);
1406 bool MetamodSource::IsLoadedAsGameDLL()
1408 return is_gamedll_loaded;
1411 void MetamodSource::SetGameDLLInfo(CreateInterfaceFn serverFactory, int version)
1413 gamedll_info.factory = serverFactory;
1414 gamedll_version = version;
1418 ProcessVDF(const char *path)
1422 char alias[24], file[255], error[255];
1424 if (!provider->ProcessVDF(path, file, sizeof(file), alias, sizeof(alias)))
1427 if (alias[0] != '\0')
1428 g_PluginMngr.SetAlias(alias, file);
1430 id = g_PluginMngr.Load(file, Pl_File, already, error, sizeof(error));
1431 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
1432 mm_LogMessage("[META] Failed to load plugin %s: %s", file, error);
1436 LookForVDFs(const char *dir)
1438 char path[MAX_PATH];
1441 #if defined _MSC_VER
1446 g_Metamod.PathFormat(path, sizeof(path), "%s\\*.*", dir);
1447 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
1449 DWORD dw = GetLastError();
1450 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
1453 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1457 mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
1463 if (strcmp(fd.cFileName, ".") == 0
1464 || strcmp(fd.cFileName, "..") == 0)
1468 extidx = strlen(fd.cFileName) - 4;
1469 if (extidx < 0 || stricmp(&fd.cFileName[extidx], ".vdf"))
1473 g_Metamod.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
1475 } while (FindNextFile(hFind, &fd));
1480 struct dirent *pEnt;
1482 if ((pDir = opendir(dir)) == NULL)
1484 mm_LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
1488 while ((pEnt = readdir(pDir)) != NULL)
1490 if (strcmp(pEnt->d_name, ".") == 0
1491 || strcmp(pEnt->d_name, "..") == 0)
1495 extidx = strlen(pEnt->d_name) - 4;
1496 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
1500 g_Metamod.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
1511 return g_bIsVspBridged;
1515 mm_IsVspLoadComplete()
1517 return were_plugins_loaded;