core/logic/smn_maplists.cpp
author Ryan Stecker <voidedweasel@gmail.com>
Wed Jul 03 23:14:55 2013 -0400 (2013-07-03)
changeset 3929 0bc0ffdb2eba
parent 3789 42e367aa4a00
child 3966 5d8b87f98355
permissions -rw-r--r--
Fixed ReadMapList not seeing maps in all valveFS paths (bug 5715, r=asherkin).
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include <sh_list.h>
    33 #include <sm_trie_tpl.h>
    34 #include "common_logic.h"
    35 #include "CellArray.h"
    36 #include <IGameHelpers.h>
    37 #include <ILibrarySys.h>
    38 #include <ITextParsers.h>
    39 #include <ISourceMod.h>
    40 #include "stringutil.h"
    41 
    42 using namespace SourceHook;
    43 
    44 struct maplist_info_t
    45 {
    46 	bool bIsCompat;
    47 	bool bIsPath;
    48 	char name[PLATFORM_MAX_PATH];
    49 	char path[PLATFORM_MAX_PATH];
    50 	time_t last_modified_time;
    51 	CellArray *pArray;
    52 	int serial;
    53 };
    54 
    55 #define MAPLIST_FLAG_MAPSFOLDER		(1<<0)		/**< On failure, use all maps in the maps folder. */
    56 #define MAPLIST_FLAG_CLEARARRAY		(1<<1)		/**< If an input array is specified, clear it before adding. */
    57 #define MAPLIST_FLAG_NO_DEFAULT		(1<<2)		/**< Do not read "default" or "mapcyclefile" on failure. */
    58 
    59 class MapLists : public SMGlobalClass, public ITextListener_SMC
    60 {
    61 public:
    62 	enum MapListState
    63 	{
    64 		MPS_NONE,
    65 		MPS_GLOBAL,
    66 		MPS_MAPLIST,
    67 	};
    68 public:
    69 	MapLists()
    70 	{
    71 		m_pMapCycleFile = NULL;
    72 		m_ConfigLastChanged = 0;
    73 		m_nSerialChange = 0;
    74 	}
    75 	void OnSourceModAllInitialized()
    76 	{
    77 		g_pSM->BuildPath(Path_SM, m_ConfigFile, sizeof(m_ConfigFile), "configs/maplists.cfg");
    78 	}
    79 	void OnSourceModShutdown()
    80 	{
    81 		DumpCache(NULL);
    82 	}
    83 	void AddOrUpdateDefault(const char *name, const char *file)
    84 	{
    85 		char path[PLATFORM_MAX_PATH];
    86 		maplist_info_t *pMapList, **ppMapList;
    87 
    88 		if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
    89 		{
    90 			pMapList = new maplist_info_t;
    91 			pMapList->bIsCompat = true;
    92 			pMapList->bIsPath = true;
    93 			pMapList->last_modified_time = 0;
    94 			smcore.strncopy(pMapList->name, name, sizeof(pMapList->name));
    95 			pMapList->pArray = NULL;
    96 			g_pSM->BuildPath(Path_Game, pMapList->path, sizeof(pMapList->path), "%s", file);
    97 			pMapList->serial = 0;
    98 			m_ListLookup.insert(name, pMapList);
    99 			m_MapLists.push_back(pMapList);
   100 			return;
   101 		}
   102 
   103 		pMapList = *ppMapList;
   104 
   105 		/* Don't modify if it's from the config file */
   106 		if (!pMapList->bIsCompat)
   107 		{
   108 			return;
   109 		}
   110 
   111 		g_pSM->BuildPath(Path_Game, path, sizeof(path), "%s", file);
   112 
   113 		/* If the path matches, don't reset the serial/time */
   114 		if (strcmp(path, pMapList->path) == 0)
   115 		{
   116 			return;
   117 		}
   118 
   119 		smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
   120 		pMapList->bIsPath = true;
   121 		pMapList->last_modified_time = 0;
   122 		pMapList->serial = 0;
   123 	}
   124 	void UpdateCache()
   125 	{
   126 		bool fileFound;
   127 		SMCError error;
   128 		time_t fileTime;
   129 		SMCStates states = {0, 0};
   130 		
   131 		fileFound = libsys->FileTime(m_ConfigFile, FileTime_LastChange, &fileTime);
   132 
   133 		/* If the file is found and hasn't changed, bail out now. */
   134 		if (fileFound && fileTime == m_ConfigLastChanged)
   135 		{
   136 			return;
   137 		}
   138 
   139 		/* If the file wasn't found, and we already have entries, we bail out too. 
   140 		 * This case lets us optimize when a user deletes the config file, so we 
   141 		 * don't reparse every single time the function is called.
   142 		 */
   143 		if (!fileFound && m_MapLists.size() > 0)
   144 		{
   145 			return;
   146 		}
   147 
   148 		m_pMapCycleFile = smcore.FindConVar("mapcyclefile");
   149 
   150 		/* Dump everything we know about. */
   151 		List<maplist_info_t *> compat;
   152 		DumpCache(&compat);
   153 
   154 		/* All this is to add the default entry back in. */
   155 		maplist_info_t *pDefList = new maplist_info_t;
   156 
   157 		pDefList->bIsPath = true;
   158 		smcore.strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name));
   159 		g_pSM->BuildPath(Path_Game,
   160 			pDefList->path, 
   161 			sizeof(pDefList->path),
   162 			"%s",
   163 			m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt");
   164 		pDefList->last_modified_time = 0;
   165 		pDefList->pArray = NULL;
   166 		pDefList->serial = 0;
   167 
   168 		m_ListLookup.insert("mapcyclefile", pDefList);
   169 		m_MapLists.push_back(pDefList);
   170 
   171 		/* Now parse the config file even if we don't know about it.
   172 		 * This will give us a nice error message.
   173 		 */
   174 		if ((error = textparser->ParseFile_SMC(m_ConfigFile, this, &states))
   175 			!= SMCError_Okay)
   176 		{
   177 			const char *errmsg = textparser->GetSMCErrorString(error);
   178 			if (errmsg == NULL)
   179 			{
   180 				errmsg = "Unknown error";
   181 			}
   182 			smcore.LogError("[SM] Could not parse file \"%s\"", m_ConfigFile);
   183 			smcore.LogError("[SM] Error on line %d (col %d): %s", states.line, states.col, errmsg);
   184 		}
   185 		else
   186 		{
   187 			m_ConfigLastChanged = fileTime;
   188 		}
   189 
   190 		/* Now, re-add compat stuff back in if we can. */
   191 		List<maplist_info_t *>::iterator iter = compat.begin();
   192 		while (iter != compat.end())
   193 		{
   194 			if (m_ListLookup.retrieve((*iter)->name) != NULL)
   195 			{
   196 				/* The compatibility shim is no longer needed. */
   197 				delete (*iter)->pArray;
   198 				delete (*iter);
   199 			}
   200 			else
   201 			{
   202 				m_ListLookup.insert((*iter)->name, (*iter));
   203 				m_MapLists.push_back((*iter));
   204 			}
   205 			iter = compat.erase(iter);
   206 		}
   207 	}
   208 	void ReadSMC_ParseStart()
   209 	{
   210 		m_CurState = MPS_NONE;
   211 		m_IgnoreLevel = 0;
   212 		m_pCurMapList = NULL;
   213 	}
   214 	SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
   215 	{
   216 		if (m_IgnoreLevel)
   217 		{
   218 			m_IgnoreLevel++;
   219 			return SMCResult_Continue;
   220 		}
   221 
   222 		if (m_CurState == MPS_NONE)
   223 		{
   224 			if (strcmp(name, "MapLists") == 0)
   225 			{
   226 				m_CurState = MPS_GLOBAL;
   227 			}
   228 			else
   229 			{
   230 				m_IgnoreLevel = 1;
   231 			}
   232 		}
   233 		else if (m_CurState == MPS_GLOBAL)
   234 		{
   235 			m_pCurMapList = new maplist_info_t;
   236 
   237 			memset(m_pCurMapList, 0, sizeof(maplist_info_t));
   238 			smcore.strncopy(m_pCurMapList->name, name, sizeof(m_pCurMapList->name));
   239 
   240 			m_CurState = MPS_MAPLIST;
   241 		}
   242 		else if (m_CurState == MPS_MAPLIST)
   243 		{
   244 			m_IgnoreLevel++;
   245 		}
   246 
   247 		return SMCResult_Continue;
   248 	}
   249 	SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
   250 	{
   251 		if (m_IgnoreLevel || m_pCurMapList == NULL)
   252 		{
   253 			return SMCResult_Continue;
   254 		}
   255 
   256 		if (strcmp(key, "file") == 0)
   257 		{
   258 			g_pSM->BuildPath(Path_Game, 
   259 				m_pCurMapList->path,
   260 				sizeof(m_pCurMapList->path),
   261 				"%s",
   262 				value);
   263 			m_pCurMapList->bIsPath = true;
   264 		}
   265 		else if (strcmp(key, "target") == 0)
   266 		{
   267 			smcore.strncopy(m_pCurMapList->path, value, sizeof(m_pCurMapList->path));
   268 			m_pCurMapList->bIsPath = false;
   269 		}
   270 
   271 		return SMCResult_Continue;
   272 	}
   273 	SMCResult ReadSMC_LeavingSection(const SMCStates *states)
   274 	{
   275 		if (m_IgnoreLevel)
   276 		{
   277 			m_IgnoreLevel--;
   278 			return SMCResult_Continue;
   279 		}
   280 
   281 		if (m_CurState == MPS_MAPLIST)
   282 		{
   283 			if (m_pCurMapList != NULL
   284 				&& m_pCurMapList->path[0] != '\0'
   285 				&& m_ListLookup.retrieve(m_pCurMapList->name) == NULL)
   286 			{
   287 				m_ListLookup.insert(m_pCurMapList->name, m_pCurMapList);
   288 				m_MapLists.push_back(m_pCurMapList);
   289 				m_pCurMapList = NULL;
   290 			}
   291 			else
   292 			{
   293 				delete m_pCurMapList;
   294 				m_pCurMapList = NULL;
   295 			}
   296 			m_CurState = MPS_GLOBAL;
   297 		}
   298 		else if (m_CurState == MPS_GLOBAL)
   299 		{
   300 			m_CurState = MPS_NONE;
   301 		}
   302 
   303 		return SMCResult_Continue;
   304 	}
   305 	void ReadSMC_ParseEnd(bool halted, bool failed)
   306 	{
   307 		delete m_pCurMapList;
   308 		m_pCurMapList = NULL;
   309 	}
   310 	static int sort_maps_in_adt_array(const void *str1, const void *str2)
   311 	{
   312 		return strcmp((char *)str1, (char *)str2);
   313 	}
   314 	CellArray *UpdateMapList(CellArray *pUseArray, const char *name, int *pSerial, unsigned int flags)
   315 	{
   316 		int change_serial;
   317 		CellArray *pNewArray = NULL;
   318 		bool success, free_new_array;
   319 
   320 		free_new_array = false;
   321 		
   322 		if ((success = GetMapList(&pNewArray, name, &change_serial)) == false)
   323 		{
   324 			if ((flags & MAPLIST_FLAG_NO_DEFAULT) != MAPLIST_FLAG_NO_DEFAULT)
   325 			{
   326 				/* If this list failed, and it's not the default, try the default. 
   327 				 */
   328 				if (strcmp(name, "default") != 0)
   329 				{
   330 					success = GetMapList(&pNewArray, name, &change_serial);
   331 				}
   332 				/* If either of the last two conditions failed, try again if we can. */
   333 				if (!success && strcmp(name, "mapcyclefile") != 0)
   334 				{
   335 					success = GetMapList(&pNewArray, "mapcyclefile", &change_serial);
   336 				}
   337 			}
   338 		}
   339 
   340 		/* If there was a success, and the serial has not changed, bail out. */
   341 		if (success && *pSerial == change_serial)
   342 		{
   343 			return NULL;
   344 		}
   345 
   346 		/**
   347 		 * If there was a success but no map list, we need to look in the maps folder.
   348 		 * If there was a failure and the flag is specified, we need to look in the maps folder.
   349 		 */
   350 		if ((success && pNewArray == NULL)
   351 			|| (!success && ((flags & MAPLIST_FLAG_MAPSFOLDER) == MAPLIST_FLAG_MAPSFOLDER)))
   352 		{
   353 			pNewArray = new CellArray(64);
   354 			free_new_array = true;
   355 
   356 			cell_t *blk;
   357 
   358 			FileFindHandle_t findHandle;
   359 			const char *fileName = smcore.filesystem->FindFirstEx("maps/*.bsp", "GAME", &findHandle);
   360 
   361 			while (fileName)
   362 			{
   363 				char buffer[PLATFORM_MAX_PATH];
   364 
   365 				UTIL_StripExtension(fileName, buffer, sizeof(buffer));
   366 
   367 				if (!engine->IsMapValid(buffer))
   368 				{
   369 					fileName = smcore.filesystem->FindNext(findHandle);
   370 					continue;
   371 				}
   372 
   373 				if ((blk = pNewArray->push()) == NULL)
   374 				{
   375 					fileName = smcore.filesystem->FindNext(findHandle);
   376 					continue;
   377 				}
   378 
   379 				smcore.strncopy((char *)blk, buffer, 255);
   380 
   381 				fileName = smcore.filesystem->FindNext(findHandle);
   382 			}
   383 
   384 			smcore.filesystem->FindClose(findHandle);
   385 
   386 			/* Remove the array if there were no items. */
   387 			if (pNewArray->size() == 0)
   388 			{
   389 				delete pNewArray;
   390 				pNewArray = NULL;
   391 			}
   392 			else
   393 			{
   394 				qsort(pNewArray->base(), 
   395 					pNewArray->size(), 
   396 					pNewArray->blocksize() * sizeof(cell_t), 
   397 					sort_maps_in_adt_array);
   398 			}
   399 
   400 			change_serial = -1;
   401 		}
   402 
   403 		/* If there is still no array by this point, bail out. */
   404 		if (pNewArray == NULL)
   405 		{
   406 			*pSerial = -1;
   407 			return NULL;
   408 		}
   409 
   410 		*pSerial = change_serial;
   411 
   412 		/* If there is no input array, return something temporary. */
   413 		if (pUseArray == NULL)
   414 		{
   415 			if (free_new_array)
   416 			{
   417 				return pNewArray;
   418 			}
   419 			else
   420 			{
   421 				return pNewArray->clone();
   422 			}
   423 		}
   424 
   425 		/* Clear the input array if necessary. */
   426 		if ((flags & MAPLIST_FLAG_CLEARARRAY) == MAPLIST_FLAG_CLEARARRAY)
   427 		{
   428 			pUseArray->clear();
   429 		}
   430 
   431 		/* Copy. */
   432 		cell_t *blk_dst;
   433 		cell_t *blk_src;
   434 		for (size_t i = 0; i < pNewArray->size(); i++)
   435 		{
   436 			blk_dst = pUseArray->push();
   437 			blk_src = pNewArray->at(i);
   438 			smcore.strncopy((char *)blk_dst, (char *)blk_src, pUseArray->blocksize() * sizeof(cell_t));
   439 		}
   440 
   441 		/* Free resources if necessary. */
   442 		if (free_new_array)
   443 		{
   444 			delete pNewArray;
   445 		}
   446 
   447 		/* Return the array we were given. */
   448 		return pUseArray;
   449 	}
   450 private:
   451 	bool GetMapList(CellArray **ppArray, const char *name, int *pSerial)
   452 	{
   453 		time_t last_time;
   454 		maplist_info_t *pMapList, **ppMapList;
   455 
   456 		if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
   457 		{
   458 			return false;
   459 		}
   460 
   461 		pMapList = *ppMapList;
   462 
   463 		if (!pMapList->bIsPath)
   464 		{
   465 			return GetMapList(ppArray, pMapList->path, pSerial);
   466 		}
   467 
   468 		/* If it is a path, and the path is "*", assume all files must be used. */
   469 		if (strcmp(pMapList->path, "*") == 0)
   470 		{
   471 			*ppArray = NULL;
   472 			return true;
   473 		}
   474 
   475 		if (m_pMapCycleFile != NULL && strcmp(name, "mapcyclefile") == 0)
   476 		{
   477 			char path[PLATFORM_MAX_PATH];
   478 			g_pSM->BuildPath(Path_Game,
   479 				path, 
   480 				sizeof(path),
   481 				"%s",
   482 				m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt");
   483 
   484 			if (strcmp(path, pMapList->path) != 0)
   485 			{
   486 				smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
   487 				pMapList->last_modified_time = 0;
   488 			}
   489 		}
   490 
   491 		if (!libsys->FileTime(pMapList->path, FileTime_LastChange, &last_time)
   492 			|| last_time > pMapList->last_modified_time)
   493 		{
   494 			/* Reparse */
   495 			FILE *fp;
   496 			cell_t *blk;
   497 			char buffer[255];
   498 
   499 			if ((fp = fopen(pMapList->path, "rt")) == NULL)
   500 			{
   501 				return false;
   502 			}
   503 
   504 			delete pMapList->pArray;
   505 			pMapList->pArray = new CellArray(64);
   506 
   507 			while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
   508 			{
   509 				size_t len = strlen(buffer);
   510 				char *ptr = smcore.TrimWhitespace(buffer, len);
   511 				if (*ptr == '\0'
   512 					|| *ptr == ';'
   513 					|| strncmp(ptr, "//", 2) == 0)
   514 				{
   515 					continue;
   516 				}
   517 				if (!gamehelpers->IsMapValid(ptr))
   518 				{
   519 					continue;
   520 				}
   521 				if ((blk = pMapList->pArray->push()) != NULL)
   522 				{
   523 					smcore.strncopy((char *)blk, ptr, 255);
   524 				}
   525 			}
   526 
   527 			fclose(fp);
   528 
   529 			pMapList->last_modified_time = last_time;
   530 			pMapList->serial = ++m_nSerialChange;
   531 		}
   532 
   533 		if (pMapList->pArray == NULL || pMapList->pArray->size() == 0)
   534 		{
   535 			return false;
   536 		}
   537 
   538 		*pSerial = pMapList->serial;
   539 		*ppArray = pMapList->pArray;
   540 
   541 		return true;
   542 	}
   543 	void DumpCache(List<maplist_info_t *> *compat_list)
   544 	{
   545 		m_ListLookup.clear();
   546 
   547 		List<maplist_info_t *>::iterator iter = m_MapLists.begin();
   548 		while (iter != m_MapLists.end())
   549 		{
   550 			if (compat_list != NULL && (*iter)->bIsCompat)
   551 			{
   552 				compat_list->push_back((*iter));
   553 			}
   554 			else
   555 			{
   556 				delete (*iter)->pArray;
   557 				delete (*iter);
   558 			}
   559 			iter = m_MapLists.erase(iter);
   560 		}
   561 	}
   562 private:
   563 	char m_ConfigFile[PLATFORM_MAX_PATH];
   564 	time_t m_ConfigLastChanged;
   565 	ConVar *m_pMapCycleFile;
   566 	KTrie<maplist_info_t *> m_ListLookup;
   567 	List<maplist_info_t *> m_MapLists;
   568 	MapListState m_CurState;
   569 	unsigned int m_IgnoreLevel;
   570 	maplist_info_t *m_pCurMapList;
   571 	int m_nSerialChange;
   572 } s_MapLists;
   573 
   574 static cell_t LoadMapList(IPluginContext *pContext, const cell_t *params)
   575 {
   576 	char *str;
   577 	Handle_t hndl;
   578 	cell_t *addr, flags;
   579 	CellArray *pArray, *pNewArray;
   580 
   581 	hndl = params[1];
   582 	pContext->LocalToPhysAddr(params[2], &addr);
   583 	pContext->LocalToString(params[3], &str);
   584 	flags = params[4];
   585 
   586 	/* Make sure the input Handle is valid */
   587 	pArray = NULL;
   588 	if (hndl != BAD_HANDLE)
   589 	{
   590 		HandleError err;
   591 		HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
   592 
   593 		if ((err = handlesys->ReadHandle(hndl, htCellArray, &sec, (void **)&pArray))
   594 			!= HandleError_None)
   595 		{
   596 			return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
   597 		}
   598 	}
   599 
   600 	/* Make sure the map list cache is up to date at the root */
   601 	s_MapLists.UpdateCache();
   602 
   603 	/* Try to get the map list. */
   604 	if ((pNewArray = s_MapLists.UpdateMapList(pArray, str, addr, flags)) == NULL)
   605 	{
   606 		return BAD_HANDLE;
   607 	}
   608 
   609 	/* If the user wanted a new array, create it now. */
   610 	if (hndl == BAD_HANDLE)
   611 	{
   612 		if ((hndl = handlesys->CreateHandle(htCellArray, pNewArray, pContext->GetIdentity(), g_pCoreIdent, NULL))
   613 			== BAD_HANDLE)
   614 		{
   615 			*addr = -1;
   616 			delete pNewArray;
   617 			return BAD_HANDLE;
   618 		}
   619 	}
   620 
   621 	return hndl;
   622 }
   623 
   624 static cell_t SetMapListCompatBind(IPluginContext *pContext, const cell_t *params)
   625 {
   626 	char *name, *file;
   627 
   628 	pContext->LocalToString(params[1], &name);
   629 	pContext->LocalToString(params[2], &file);
   630 
   631 	s_MapLists.UpdateCache();
   632 	s_MapLists.AddOrUpdateDefault(name, file);
   633 
   634 	return 1;
   635 }
   636 
   637 REGISTER_NATIVES(mapListNatives)
   638 {
   639 	{"ReadMapList",				LoadMapList},
   640 	{"SetMapListCompatBind",	SetMapListCompatBind},
   641 	{NULL,						NULL},
   642 };