3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "sm_globals.h"
34 #include "sm_trie_tpl.h"
35 #include "CellArray.h"
37 #include "sourcemm_api.h"
38 #include "LibrarySys.h"
39 #include "TextParsers.h"
40 #include "sm_stringutil.h"
41 #include "sourcemod.h"
43 #include "HandleSys.h"
45 using namespace SourceHook;
51 char name[PLATFORM_MAX_PATH];
52 char path[PLATFORM_MAX_PATH];
53 time_t last_modified_time;
58 #define MAPLIST_FLAG_MAPSFOLDER (1<<0) /**< On failure, use all maps in the maps folder. */
59 #define MAPLIST_FLAG_CLEARARRAY (1<<1) /**< If an input array is specified, clear it before adding. */
60 #define MAPLIST_FLAG_NO_DEFAULT (1<<2) /**< Do not read "default" or "mapcyclefile" on failure. */
62 class MapLists : public SMGlobalClass, public ITextListener_SMC
74 m_pMapCycleFile = NULL;
75 m_ConfigLastChanged = 0;
78 void OnSourceModAllInitialized()
80 g_SourceMod.BuildPath(Path_SM, m_ConfigFile, sizeof(m_ConfigFile), "configs/maplists.cfg");
82 void OnSourceModShutdown()
86 void AddOrUpdateDefault(const char *name, const char *file)
88 char path[PLATFORM_MAX_PATH];
89 maplist_info_t *pMapList, **ppMapList;
91 if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
93 pMapList = new maplist_info_t;
94 pMapList->bIsCompat = true;
95 pMapList->bIsPath = true;
96 pMapList->last_modified_time = 0;
97 strncopy(pMapList->name, name, sizeof(pMapList->name));
98 pMapList->pArray = NULL;
99 g_SourceMod.BuildPath(Path_Game,
101 sizeof(pMapList->path),
104 pMapList->serial = 0;
105 m_ListLookup.insert(name, pMapList);
106 m_MapLists.push_back(pMapList);
110 pMapList = *ppMapList;
112 /* Don't modify if it's from the config file */
113 if (!pMapList->bIsCompat)
118 g_SourceMod.BuildPath(Path_Game,
124 /* If the path matches, don't reset the serial/time */
125 if (strcmp(path, pMapList->path) == 0)
130 strncopy(pMapList->path, path, sizeof(pMapList->path));
131 pMapList->bIsPath = true;
132 pMapList->last_modified_time = 0;
133 pMapList->serial = 0;
140 SMCStates states = {0, 0};
142 fileFound = g_LibSys.FileTime(m_ConfigFile, FileTime_LastChange, &fileTime);
144 /* If the file is found and hasn't changed, bail out now. */
145 if (fileFound && fileTime == m_ConfigLastChanged)
150 /* If the file wasn't found, and we already have entries, we bail out too.
151 * This case lets us optimize when a user deletes the config file, so we
152 * don't reparse every single time the function is called.
154 if (!fileFound && m_MapLists.size() > 0)
159 m_pMapCycleFile = icvar->FindVar("mapcyclefile");
161 /* Dump everything we know about. */
162 List<maplist_info_t *> compat;
165 /* All this is to add the default entry back in. */
166 maplist_info_t *pDefList = new maplist_info_t;
168 pDefList->bIsPath = true;
169 strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name));
170 g_SourceMod.BuildPath(Path_Game,
172 sizeof(pDefList->path),
174 m_pMapCycleFile ? m_pMapCycleFile->GetString() : "mapcycle.txt");
175 pDefList->last_modified_time = 0;
176 pDefList->pArray = NULL;
177 pDefList->serial = 0;
179 m_ListLookup.insert("mapcyclefile", pDefList);
180 m_MapLists.push_back(pDefList);
182 /* Now parse the config file even if we don't know about it.
183 * This will give us a nice error message.
185 if ((error = g_TextParser.ParseFile_SMC(m_ConfigFile, this, &states))
188 const char *errmsg = g_TextParser.GetSMCErrorString(error);
191 errmsg = "Unknown error";
193 g_Logger.LogError("[SM] Could not parse file \"%s\"", m_ConfigFile);
194 g_Logger.LogError("[SM] Error on line %d (col %d): %s",
201 m_ConfigLastChanged = fileTime;
204 /* Now, re-add compat stuff back in if we can. */
205 List<maplist_info_t *>::iterator iter = compat.begin();
206 while (iter != compat.end())
208 if (m_ListLookup.retrieve((*iter)->name) != NULL)
210 /* The compatibility shim is no longer needed. */
211 delete (*iter)->pArray;
216 m_ListLookup.insert((*iter)->name, (*iter));
217 m_MapLists.push_back((*iter));
219 iter = compat.erase(iter);
222 void ReadSMC_ParseStart()
224 m_CurState = MPS_NONE;
226 m_pCurMapList = NULL;
228 SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
233 return SMCResult_Continue;
236 if (m_CurState == MPS_NONE)
238 if (strcmp(name, "MapLists") == 0)
240 m_CurState = MPS_GLOBAL;
247 else if (m_CurState == MPS_GLOBAL)
249 m_pCurMapList = new maplist_info_t;
251 memset(m_pCurMapList, 0, sizeof(maplist_info_t));
252 strncopy(m_pCurMapList->name, name, sizeof(m_pCurMapList->name));
254 m_CurState = MPS_MAPLIST;
256 else if (m_CurState == MPS_MAPLIST)
261 return SMCResult_Continue;
263 SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
265 if (m_IgnoreLevel || m_pCurMapList == NULL)
267 return SMCResult_Continue;
270 if (strcmp(key, "file") == 0)
272 g_SourceMod.BuildPath(Path_Game,
274 sizeof(m_pCurMapList->path),
277 m_pCurMapList->bIsPath = true;
279 else if (strcmp(key, "target") == 0)
281 strncopy(m_pCurMapList->path, value, sizeof(m_pCurMapList->path));
282 m_pCurMapList->bIsPath = false;
285 return SMCResult_Continue;
287 SMCResult ReadSMC_LeavingSection(const SMCStates *states)
292 return SMCResult_Continue;
295 if (m_CurState == MPS_MAPLIST)
297 if (m_pCurMapList != NULL
298 && m_pCurMapList->path[0] != '\0'
299 && m_ListLookup.retrieve(m_pCurMapList->name) == NULL)
301 m_ListLookup.insert(m_pCurMapList->name, m_pCurMapList);
302 m_MapLists.push_back(m_pCurMapList);
303 m_pCurMapList = NULL;
307 delete m_pCurMapList;
308 m_pCurMapList = NULL;
310 m_CurState = MPS_GLOBAL;
312 else if (m_CurState == MPS_GLOBAL)
314 m_CurState = MPS_NONE;
317 return SMCResult_Continue;
319 void ReadSMC_ParseEnd(bool halted, bool failed)
321 delete m_pCurMapList;
322 m_pCurMapList = NULL;
324 static int sort_maps_in_adt_array(const void *str1, const void *str2)
326 return strcmp((char *)str1, (char *)str2);
328 CellArray *UpdateMapList(CellArray *pUseArray, const char *name, int *pSerial, unsigned int flags)
331 CellArray *pNewArray = NULL;
332 bool success, free_new_array;
334 free_new_array = false;
336 if ((success = GetMapList(&pNewArray, name, &change_serial)) == false)
338 if ((flags & MAPLIST_FLAG_NO_DEFAULT) != MAPLIST_FLAG_NO_DEFAULT)
340 /* If this list failed, and it's not the default, try the default.
342 if (strcmp(name, "default") != 0)
344 success = GetMapList(&pNewArray, name, &change_serial);
346 /* If either of the last two conditions failed, try again if we can. */
347 if (!success && strcmp(name, "mapcyclefile") != 0)
349 success = GetMapList(&pNewArray, "mapcyclefile", &change_serial);
354 /* If there was a success, and the serial has not changed, bail out. */
355 if (success && *pSerial == change_serial)
361 * If there was a success but no map list, we need to look in the maps folder.
362 * If there was a failure and the flag is specified, we need to look in the maps folder.
364 if ((success && pNewArray == NULL)
365 || (!success && ((flags & MAPLIST_FLAG_MAPSFOLDER) == MAPLIST_FLAG_MAPSFOLDER)))
370 pNewArray = new CellArray(64);
371 free_new_array = true;
372 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "maps");
374 if ((pDir = g_LibSys.OpenDirectory(path)) != NULL)
378 char buffer[PLATFORM_MAX_PATH];
380 while (pDir->MoreFiles())
382 if (!pDir->IsEntryFile()
383 || strcmp(pDir->GetEntryName(), ".") == 0
384 || strcmp(pDir->GetEntryName(), "..") == 0)
389 strncopy(buffer, pDir->GetEntryName(), sizeof(buffer));
390 if ((ptr = strstr(buffer, ".bsp")) == NULL)
396 if (!engine->IsMapValid(buffer))
401 if ((blk = pNewArray->push()) == NULL)
406 strncopy((char *)blk, buffer, 255);
409 g_LibSys.CloseDirectory(pDir);
412 /* Remove the array if there were no items. */
413 if (pNewArray->size() == 0)
420 qsort(pNewArray->base(),
422 pNewArray->blocksize() * sizeof(cell_t),
423 sort_maps_in_adt_array);
429 /* If there is still no array by this point, bail out. */
430 if (pNewArray == NULL)
436 *pSerial = change_serial;
438 /* If there is no input array, return something temporary. */
439 if (pUseArray == NULL)
447 return pNewArray->clone();
451 /* Clear the input array if necessary. */
452 if ((flags & MAPLIST_FLAG_CLEARARRAY) == MAPLIST_FLAG_CLEARARRAY)
460 for (size_t i = 0; i < pNewArray->size(); i++)
462 blk_dst = pUseArray->push();
463 blk_src = pNewArray->at(i);
464 strncopy((char *)blk_dst, (char *)blk_src, pUseArray->blocksize() * sizeof(cell_t));
467 /* Free resources if necessary. */
473 /* Return the array we were given. */
477 bool GetMapList(CellArray **ppArray, const char *name, int *pSerial)
480 maplist_info_t *pMapList, **ppMapList;
482 if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
487 pMapList = *ppMapList;
489 if (!pMapList->bIsPath)
491 return GetMapList(ppArray, pMapList->path, pSerial);
494 /* If it is a path, and the path is "*", assume all files must be used. */
495 if (strcmp(pMapList->path, "*") == 0)
501 if (m_pMapCycleFile != NULL && strcmp(name, "mapcyclefile") == 0)
503 char path[PLATFORM_MAX_PATH];
504 g_SourceMod.BuildPath(Path_Game,
508 m_pMapCycleFile ? m_pMapCycleFile->GetString() : "mapcycle.txt");
510 if (strcmp(path, pMapList->path) != 0)
512 strncopy(pMapList->path, path, sizeof(pMapList->path));
513 pMapList->last_modified_time = 0;
517 if (!g_LibSys.FileTime(pMapList->path, FileTime_LastChange, &last_time)
518 || last_time > pMapList->last_modified_time)
525 if ((fp = fopen(pMapList->path, "rt")) == NULL)
530 delete pMapList->pArray;
531 pMapList->pArray = new CellArray(64);
533 while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
535 size_t len = strlen(buffer);
536 char *ptr = UTIL_TrimWhitespace(buffer, len);
539 || strncmp(ptr, "//", 2) == 0)
543 if (!engine->IsMapValid(ptr))
547 if ((blk = pMapList->pArray->push()) != NULL)
549 strncopy((char *)blk, ptr, 255);
555 pMapList->last_modified_time = last_time;
556 pMapList->serial = ++m_nSerialChange;
559 if (pMapList->pArray == NULL || pMapList->pArray->size() == 0)
564 *pSerial = pMapList->serial;
565 *ppArray = pMapList->pArray;
569 void DumpCache(List<maplist_info_t *> *compat_list)
571 m_ListLookup.clear();
573 List<maplist_info_t *>::iterator iter = m_MapLists.begin();
574 while (iter != m_MapLists.end())
576 if (compat_list != NULL && (*iter)->bIsCompat)
578 compat_list->push_back((*iter));
582 delete (*iter)->pArray;
585 iter = m_MapLists.erase(iter);
589 char m_ConfigFile[PLATFORM_MAX_PATH];
590 time_t m_ConfigLastChanged;
591 ConVar *m_pMapCycleFile;
592 KTrie<maplist_info_t *> m_ListLookup;
593 List<maplist_info_t *> m_MapLists;
594 MapListState m_CurState;
595 unsigned int m_IgnoreLevel;
596 maplist_info_t *m_pCurMapList;
600 static cell_t LoadMapList(IPluginContext *pContext, const cell_t *params)
605 CellArray *pArray, *pNewArray;
608 pContext->LocalToPhysAddr(params[2], &addr);
609 pContext->LocalToString(params[3], &str);
612 /* Make sure the input Handle is valid */
614 if (hndl != BAD_HANDLE)
617 HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
619 if ((err = g_HandleSys.ReadHandle(hndl, htCellArray, &sec, (void **)&pArray))
622 return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
626 /* Make sure the map list cache is up to date at the root */
627 s_MapLists.UpdateCache();
629 /* Try to get the map list. */
630 if ((pNewArray = s_MapLists.UpdateMapList(pArray, str, addr, flags)) == NULL)
635 /* If the user wanted a new array, create it now. */
636 if (hndl == BAD_HANDLE)
638 if ((hndl = g_HandleSys.CreateHandle(htCellArray, pNewArray, pContext->GetIdentity(), g_pCoreIdent, NULL))
650 static cell_t SetMapListCompatBind(IPluginContext *pContext, const cell_t *params)
654 pContext->LocalToString(params[1], &name);
655 pContext->LocalToString(params[2], &file);
657 s_MapLists.UpdateCache();
658 s_MapLists.AddOrUpdateDefault(name, file);
663 REGISTER_NATIVES(mapListNatives)
665 {"ReadMapList", LoadMapList},
666 {"SetMapListCompatBind", SetMapListCompatBind},