Push build.
1 /* ======== SourceMM ========
2 * Copyright (C) 2004-2010 Metamod:Source Development Team
3 * No warranties of any kind
7 * Author(s): David "BAILOPAN" Anderson
8 * Contributor(s): Scott "Damaged Soul" Ehlert
9 * : Pavol "PM OnoTo" Marko
10 * ============================
13 #include <interface.h>
15 #include <tier0/icommandline.h>
17 #include "concommands.h"
21 #include "iplayerinfo.h"
22 #include <filesystem.h>
24 using namespace SourceMM;
27 * @brief Implementation of main SourceMM GameDLL functionality
32 DLL_IMPORT ICommandLine *CommandLine();
34 SH_DECL_HOOK0_void(IServerGameDLL, LevelShutdown, SH_NOATTRIB, false);
35 SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, false, bool, const char *, const char *, const char *, const char *, bool, bool);
36 SH_DECL_HOOK1_void(IServerGameClients, ClientCommand, SH_NOATTRIB, 0, edict_t *);
37 SH_DECL_HOOK0(IServerGameDLL, GameInit, SH_NOATTRIB, false, bool);
39 void LevelShutdown_handler();
40 bool LevelInit_handler(char const *pMapName,
41 char const *pMapEntities,
42 char const *pOldLevel,
43 char const *pLandmarkName,
46 bool GameInit_handler();
47 int LoadPlugins(const char *filepath, const char *vdfpath);
48 int LoadVDFPluginsFromDir(const char *dir, int &skipped);
49 bool KVLoadFromFile(KeyValues *kv,
50 IBaseFileSystem *filesystem,
51 const char *resourceName,
52 const char *pathID = NULL);
54 GameDllInfo g_GameDll = {false, NULL, NULL, NULL};
56 SourceHook::CSourceHookImpl g_SourceHook;
57 SourceHook::ISourceHook *g_SHPtr = &g_SourceHook;
58 SourceHook::String g_ModPath;
59 SourceHook::String g_MetamodPath;
60 PluginId g_PLID = Pl_Console; /* Technically, SourceMM is the "Console" plugin... :p */
61 static bool bInFirstLevel = true;
62 bool g_bGameInit = false;
63 int g_GameDllVersion = 0;
64 static const char VSPIFACE_001[] = "ISERVERPLUGINCALLBACKS001";
65 static const char VSPIFACE_002[] = "ISERVERPLUGINCALLBACKS002";
66 static const char GAMEINFO_PATH[] = "|gameinfo_path|";
67 IFileSystem *baseFs = NULL;
68 bool g_bLevelChanged = false;
69 IServerPluginCallbacks *g_pRealVspCallbacks = NULL;
70 unsigned int g_vsp_version = 0;
72 #define ITER_EVENT(evn, args) \
73 CPluginManager::CPlugin *pl; \
74 SourceHook::List<CPluginEventHandler>::iterator event; \
75 IMetamodListener *api; \
76 for (PluginIter iter = g_PluginMngr._begin(); iter != g_PluginMngr._end(); iter++) { \
78 for (event=pl->m_Events.begin(); event!=pl->m_Events.end(); event++) { \
79 api = (*event).event; \
84 ///////////////////////////////////
85 // Main code for HL2 Interaction //
86 ///////////////////////////////////
88 /* Initialize everything here */
91 /* Like Metamod, reload plugins at the end of the map.
92 * This is so plugins can hook everything on load, BUT, new plugins will be reloaded
93 * if the server is shut down (silly, but rare case).
97 char smm_path[PATH_SIZE];
98 const char *game_dir = CommandLine()->ParmValue("-game", "hl2");
99 abspath(smm_path, game_dir);
100 g_ModPath.assign(smm_path);
102 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelShutdown, g_GameDll.pGameDLL, LevelShutdown_handler, true);
103 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, LevelInit, g_GameDll.pGameDLL, LevelInit_handler, true);
104 SH_ADD_HOOK_STATICFUNC(IServerGameDLL, GameInit, g_GameDll.pGameDLL, GameInit_handler, false);
107 void DoInitialPluginLoads()
109 const char *pluginFile = g_Engine.icvar->GetCommandLineValue("mm_pluginsfile");
110 const char *mmBaseDir = g_Engine.icvar->GetCommandLineValue("mm_basedir");
114 pluginFile = GetPluginsFile();
118 mmBaseDir = GetMetamodBaseDir();
121 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
123 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), pluginFile);
124 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), mmBaseDir);
125 LoadPlugins(filepath, vdfpath);
128 bool StartupMetamod(CreateInterfaceFn engineFactory, bool bWaitForGameInit)
130 g_Engine.engine = (IVEngineServer *)((engineFactory)(INTERFACEVERSION_VENGINESERVER, NULL));
132 if (!g_Engine.engine)
134 Error("Could not find IVEngineServer! Metamod cannot load.");
137 g_Engine.icvar = (ICvar *)((engineFactory)(VENGINE_CVAR_INTERFACE_VERSION , NULL));
140 Error("Could not find ICvar! Metamod cannot load.");
144 g_Engine.loaded = true;
146 /* The Ship is the only game known at this time that uses the pre-Episode One engine */
147 g_Engine.original = strcmp(CommandLine()->ParmValue("-game", "hl2"), "ship") == 0;
149 ConCommandBaseMgr::OneTimeInit(static_cast<IConCommandBaseAccessor *>(&g_SMConVarAccessor));
151 if (g_GameDll.pGameClients)
153 SH_ADD_HOOK_STATICFUNC(IServerGameClients, ClientCommand, g_GameDll.pGameClients, ClientCommand_handler, false);
157 /* If IServerGameClients isn't found, this really isn't a fatal error so... */
158 LogMessage("[META] Warning: Could not find IServerGameClients!");
159 LogMessage("[META] Warning: The 'meta' command will not be available to clients.");
162 if (!g_SmmAPI.CacheCmds())
164 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
165 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
168 g_SmmAPI.CacheUserMessages();
170 baseFs = (IFileSystem *)((engineFactory)(FILESYSTEM_INTERFACE_VERSION, NULL));
173 LogMessage("[META] Failed to find filesystem interface, .vdf files will not be parsed.");
176 if (!g_SMConVarAccessor.InitConCommandBaseList())
178 /* This is very unlikely considering it's old engine */
179 LogMessage("[META] Warning: Failed to find ConCommandBase list!");
180 LogMessage("[META] Warning: ConVars and ConCommands cannot be unregistered properly! Please file a bug report.");
183 if (!bWaitForGameInit)
185 DoInitialPluginLoads();
186 bInFirstLevel = true;
192 void LoadAsGameDLL(const gamedll_bridge_info *info)
194 g_Engine.engineFactory = (CreateInterfaceFn)info->engineFactory;
195 g_Engine.fileSystemFactory = (CreateInterfaceFn)info->fsFactory;
196 g_Engine.physicsFactory = (CreateInterfaceFn)info->physicsFactory;
197 g_Engine.pGlobals = (CGlobalVars*)info->pGlobals;
198 g_GameDll.loaded = true;
199 g_GameDll.factory = (CreateInterfaceFn)info->gsFactory;
200 g_GameDll.pGameDLL = (IServerGameDLL*)info->isgd;
201 g_GameDllVersion = info->dllVersion;
202 g_MetamodPath.assign(info->vsp_listener_path);
206 StartupMetamod(g_Engine.engineFactory, false);
209 bool AlternatelyLoadMetamod(CreateInterfaceFn ifaceFactory, CreateInterfaceFn serverFactory)
211 g_Engine.engineFactory = ifaceFactory;
212 g_Engine.fileSystemFactory = ifaceFactory;
213 g_Engine.physicsFactory = ifaceFactory;
215 IPlayerInfoManager *playerInfoManager = (IPlayerInfoManager *)serverFactory("PlayerInfoManager002", NULL);
216 if (playerInfoManager == NULL)
218 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
222 g_Engine.pGlobals = playerInfoManager->GetGlobalVars();
224 /* Now find the server */
225 g_GameDll.factory = serverFactory;
227 char gamedll_iface[] = "ServerGameDLL000";
228 for (unsigned int i = 3; i <= 50; i++)
230 gamedll_iface[15] = '0' + i;
231 g_GameDll.pGameDLL = (IServerGameDLL *)serverFactory(gamedll_iface, NULL);
232 if (g_GameDll.pGameDLL != NULL)
234 g_GameDllVersion = i;
239 if (g_GameDll.pGameDLL == NULL)
241 Error("Metamod:Source requires gameinfo.txt modification to load on this game.");
245 char gameclients_iface[] = "ServerGameClients000";
246 for (unsigned int i = 3; i <= 4; i++)
248 gameclients_iface[19] = '0' + i;
249 g_GameDll.pGameClients = (IServerGameClients *)serverFactory(gameclients_iface, NULL);
250 if (g_GameDll.pGameClients != NULL)
258 if (!StartupMetamod(ifaceFactory, true))
266 bool GameInit_handler()
269 RETURN_META_VALUE(MRES_IGNORED, true);
271 if (g_SmmAPI.VSPEnabled() && !g_bIsBridgedAsVsp)
272 g_SmmAPI.LoadAsVSP();
274 if (g_bIsBridgedAsVsp)
276 DoInitialPluginLoads();
277 g_PluginMngr.SetAllLoaded();
282 RETURN_META_VALUE(MRES_IGNORED, true);
285 void UnloadMetamod(bool shutting_down)
288 g_PluginMngr.UnloadAll();
292 /* Add the FCVAR_GAMEDLL flag to our cvars so the engine removes them properly */
293 g_SMConVarAccessor.MarkCommandsAsGameDLL();
294 g_Engine.icvar->UnlinkVariables(FCVAR_GAMEDLL);
297 g_SourceHook.CompleteShutdown();
300 bool LoadFromVDF(const char *file, bool &skipped)
303 bool already, kvfileLoaded;
305 const char *plugin_file, *alias;
306 char full_path[256], error[256];
308 pValues = new KeyValues("Metamod Plugin");
310 if (g_Engine.original)
312 /* The Ship must use a special version of this function */
313 kvfileLoaded = KVLoadFromFile(pValues, baseFs, file);
317 kvfileLoaded = pValues->LoadFromFile(baseFs, file);
322 pValues->deleteThis();
327 if ((plugin_file = pValues->GetString("file", NULL)) == NULL)
329 pValues->deleteThis();
334 if ((alias = pValues->GetString("alias", NULL)) != NULL)
336 g_PluginMngr.SetAlias(alias, plugin_file);
339 g_SmmAPI.GetFullPluginPath(plugin_file, full_path, sizeof(full_path));
341 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
343 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
345 LogMessage("[META] Failed to load plugin %s: %s", plugin_file, error);
349 pValues->deleteThis();
353 int LoadVDFPluginsFromDir(const char *dir, int &skipped)
366 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\*.vdf", dir);
367 if ((hFind = FindFirstFile(path, &fd)) == INVALID_HANDLE_VALUE)
369 DWORD dw = GetLastError();
370 if (dw == ERROR_FILE_NOT_FOUND)
373 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
376 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
380 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, error);
386 g_SmmAPI.PathFormat(path, sizeof(path), "%s\\%s", dir, fd.cFileName);
387 success = LoadFromVDF(path, skip);
392 } while (FindNextFile(hFind, &fd));
400 if ((pDir = opendir(dir)) == NULL)
402 LogMessage("[META] Could not open folder \"%s\" (%s)", dir, strerror(errno));
406 while ((pEnt = readdir(pDir)) != NULL)
408 if (strcmp(pEnt->d_name, ".") == 0
409 || strcmp(pEnt->d_name, "..") == 0)
413 extidx = strlen(pEnt->d_name) - 4;
414 if (extidx < 0 || stricmp(&pEnt->d_name[extidx], ".vdf"))
418 g_SmmAPI.PathFormat(path, sizeof(path), "%s/%s", dir, pEnt->d_name);
419 success = LoadFromVDF(path, skip);
432 bool KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
436 Assert(_heapchk() == _HEAPOK);
439 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
443 // load file into a null-terminated buffer
444 int fileSize = filesystem->Size(f);
445 char *buffer = (char *)MemAllocScratch(fileSize + 1);
449 filesystem->Read(buffer, fileSize, f); // read into local buffer
451 buffer[fileSize] = 0; // null terminate file as EOF
453 filesystem->Close( f ); // close file after reading
455 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
462 int LoadPluginsFromFile(const char *filepath, int &skipped)
471 fp = fopen(filepath, "rt");
477 char buffer[255], error[255], full_path[PATH_SIZE];
478 const char *ptr, *ext, *file;
480 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
482 UTIL_TrimLeft(buffer);
483 UTIL_TrimRight(buffer);
485 length = strlen(buffer);
491 if (buffer[0] == '\0' || buffer[0] == ';' || strncmp(buffer, "//", 2) == 0)
497 if (buffer[0] == '"')
520 while (*cptr && isspace(*cptr))
525 UTIL_TrimRight(cptr);
526 if (*cptr && isalpha(*cptr))
528 g_PluginMngr.SetAlias(buffer, cptr);
540 g_SmmAPI.GetFullPluginPath(file, full_path, sizeof(full_path));
541 id = g_PluginMngr.Load(full_path, Pl_File, already, error, sizeof(error));
542 if (id < Pl_MinId || g_PluginMngr.FindById(id)->m_Status < Pl_Paused)
544 LogMessage("[META] Failed to load plugin %s. %s", buffer, error);
563 int LoadPlugins(const char *filepath, const char *vdfpath)
565 int total, skipped, fskipped, vskipped;
568 total = LoadPluginsFromFile(filepath, fskipped);
569 total += LoadVDFPluginsFromDir(vdfpath, vskipped);
570 skipped = fskipped + vskipped;
572 if (total == 0 || total > 1)
576 LogMessage("[META] Loaded %d plugin%s (%d already loaded)", total, s, skipped);
578 LogMessage("[META] Loaded %d plugin%s.", total, s);
583 void LogMessage(const char *msg, ...)
586 static char buffer[2048];
589 size_t len = vsnprintf(buffer, sizeof(buffer) - 2, msg, ap);
592 buffer[len++] = '\n';
595 if (!g_Engine.engine)
597 fprintf(stdout, "%s", buffer);
599 g_Engine.engine->LogPrint(buffer);
603 void LevelShutdown_handler(void)
607 char filepath[PATH_SIZE], vdfpath[PATH_SIZE];
609 g_SmmAPI.PathFormat(filepath, sizeof(filepath), "%s/%s", g_ModPath.c_str(), GetPluginsFile());
610 g_SmmAPI.PathFormat(vdfpath, sizeof(vdfpath), "%s/%s", g_ModPath.c_str(), GetMetamodBaseDir());
611 LoadPlugins(filepath, vdfpath);
615 bInFirstLevel = false;
618 g_bLevelChanged = true;
620 ITER_EVENT(OnLevelShutdown, ());
622 RETURN_META(MRES_IGNORED);
625 bool LevelInit_handler(char const *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background)
627 if (!g_SmmAPI.CmdCacheSuccessful())
629 LogMessage("[META] Warning: Failed to initialize Con_Printf. Defaulting to Msg().");
630 LogMessage("[META] Warning: Console messages will not be redirected to rcon console.");
633 ITER_EVENT(OnLevelInit, (pMapName, pMapEntities, pOldLevel, pLandmarkName, loadGame, background));
635 RETURN_META_VALUE(MRES_IGNORED, false);
638 #if defined __GNUC__ && (__GNUC__ == 3 || __GNUC__ == 4)
639 void * operator new(size_t size) {
640 return(calloc(1, size));
643 void * operator new[](size_t size) {
644 return(calloc(1, size));
647 void operator delete(void * ptr) {
652 void operator delete[](void * ptr) {