core/HalfLife2.cpp
author Nicholas Hastings <skamonkey@gmail.com>
Sat Mar 16 13:31:35 2013 -0400 (2013-03-16)
changeset 3813 bf1faf4a16c9
parent 3806 c713139e894c
child 3822 dfee1850a179
permissions -rw-r--r--
Added repeated field handling to PbRead* natives. Deprecate PbReadRepeated* (bug 5633, 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 "HalfLife2.h"
    33 #include "sourcemod.h"
    34 #include "sourcemm_api.h"
    35 #include "UserMessages.h"
    36 #include "PlayerManager.h"
    37 #include "sm_stringutil.h"
    38 #include <IGameConfigs.h>
    39 #include <compat_wrappers.h>
    40 #include <Logger.h>
    41 #include "LibrarySys.h"
    42 #include "logic_bridge.h"
    43 #include <tier0/mem.h>
    44 
    45 #if SOURCE_ENGINE == SE_CSGO
    46 #include <cstrike15_usermessages.pb.h>
    47 #endif
    48 
    49 
    50 typedef ICommandLine *(*FakeGetCommandLine)();
    51 
    52 #if defined _WIN32
    53 #define TIER0_NAME			"tier0.dll"
    54 #define VSTDLIB_NAME		"vstdlib.dll"
    55 #elif defined __APPLE__
    56 #define TIER0_NAME			"libtier0.dylib"
    57 #define VSTDLIB_NAME		"libvstdlib.dylib"
    58 #elif defined __linux__
    59 #if SOURCE_ENGINE == SE_ORANGEBOXVALVE || SOURCE_ENGINE == SE_CSS
    60 #define TIER0_NAME			"libtier0_srv.so"
    61 #define VSTDLIB_NAME		"libvstdlib_srv.so"
    62 #elif SOURCE_ENGINE >= SE_LEFT4DEAD
    63 #define TIER0_NAME			"libtier0.so"
    64 #define VSTDLIB_NAME		"libvstdlib.so"
    65 #else
    66 #define TIER0_NAME			"tier0_i486.so"
    67 #define VSTDLIB_NAME		"vstdlib_i486.so"
    68 #endif
    69 #endif
    70 
    71 CHalfLife2 g_HL2;
    72 ConVar *sv_lan = NULL;
    73 
    74 static void *g_EntList = NULL;
    75 static int entInfoOffset = -1;
    76 
    77 namespace SourceHook
    78 {
    79 	template<>
    80 	int HashFunction<datamap_t *>(datamap_t * const &k)
    81 	{
    82 		return reinterpret_cast<int>(k);
    83 	}
    84 
    85 	template<>
    86 	int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
    87 	{
    88 		return (k1-k2);
    89 	}
    90 }
    91 
    92 CHalfLife2::CHalfLife2()
    93 {
    94 	m_pClasses = sm_trie_create();
    95 }
    96 
    97 CHalfLife2::~CHalfLife2()
    98 {
    99 	sm_trie_destroy(m_pClasses);
   100 
   101 	List<DataTableInfo *>::iterator iter;
   102 	DataTableInfo *pInfo;
   103 	for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
   104 	{
   105 		pInfo = (*iter);
   106 		delete pInfo;
   107 	}
   108 
   109 	m_Tables.clear();
   110 
   111 	THash<datamap_t *, DataMapTrie>::iterator h_iter;
   112 	for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
   113 	{
   114 		if (h_iter->val.trie)
   115 		{
   116 			sm_trie_destroy(h_iter->val.trie);
   117 			h_iter->val.trie = NULL;
   118 		}
   119 	}
   120 
   121 	m_Maps.clear();
   122 }
   123 
   124 #if SOURCE_ENGINE != SE_DARKMESSIAH
   125 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
   126 #endif
   127 
   128 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
   129 bool is_original_engine = false;
   130 #endif
   131 
   132 void CHalfLife2::OnSourceModStartup(bool late)
   133 {
   134 #if SOURCE_ENGINE != SE_DARKMESSIAH
   135 
   136 	/* The Ship currently is the only known game to use an older version of the engine */
   137 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
   138 	if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
   139 #else
   140 	if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
   141 #endif
   142 	{
   143 		is_original_engine = true;
   144 	}
   145 	else if (g_pSharedChangeInfo == NULL)
   146 	{
   147 		g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
   148 	}
   149 #endif
   150 }
   151 
   152 void CHalfLife2::OnSourceModAllInitialized()
   153 {
   154 	m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
   155 	m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
   156 	m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
   157 	m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
   158 	g_ShareSys.AddInterface(NULL, this);
   159 }
   160 
   161 void CHalfLife2::OnSourceModAllInitialized_Post()
   162 {
   163 	InitLogicalEntData();
   164 	InitCommandLine();
   165 }
   166 
   167 void CHalfLife2::InitLogicalEntData()
   168 {
   169 	char *addr = NULL;
   170 
   171 	/*
   172 	 * gEntList and/or g_pEntityList
   173 	 *
   174 	 * First try to lookup pointer directly for platforms with symbols.
   175 	 * If symbols aren't present (Windows or stripped Linux/Mac), 
   176 	 * attempt find via LevelShutdown + offset
   177 	 */
   178 	if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
   179 	{
   180 #if !defined PLATFORM_WINDOWS
   181 		if (!addr)
   182 		{
   183 			// Key exists so notify if lookup fails, but try other method.
   184 			g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
   185 		}
   186 		else
   187 		{
   188 #endif
   189 			g_EntList = reinterpret_cast<void *>(addr);
   190 #if !defined PLATFORM_WINDOWS
   191 		}
   192 #endif
   193 	}
   194 
   195 
   196 	if (!g_EntList)
   197 	{
   198 		if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
   199 		{
   200 			g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
   201 			return;
   202 		}
   203 
   204 		if (!addr)
   205 		{
   206 			g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
   207 			return;
   208 		}
   209 
   210 		int offset;
   211 		if (!g_pGameConf->GetOffset("gEntList", &offset))
   212 		{
   213 			g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
   214 			return;
   215 		}
   216 
   217 		g_EntList = *reinterpret_cast<void **>(addr + offset);
   218 	}
   219 	
   220 	if (!g_EntList)
   221 	{
   222 		g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
   223 		return;
   224 	}
   225 
   226 	if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
   227 	{
   228 		g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
   229 		return;
   230 	}
   231 }
   232 
   233 void CHalfLife2::InitCommandLine()
   234 {
   235 	char path[PLATFORM_MAX_PATH];
   236 	char error[256];
   237 	
   238 	g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
   239 
   240 	if (!g_LibSys.IsPathFile(path))
   241 	{
   242 		g_Logger.LogError("Could not find path for: " TIER0_NAME);
   243 		return;
   244 	}
   245 
   246 	ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
   247 	m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
   248 
   249 	/* '_Tier0' dropped on Alien Swarm version */
   250 	if (m_pGetCommandLine == NULL)
   251 	{
   252 		m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
   253 	}
   254 
   255 	if (m_pGetCommandLine == NULL)
   256 	{
   257 		/* We probably have a Ship engine. */
   258 		lib->CloseLibrary();
   259 		g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
   260 		if (!g_LibSys.IsPathFile(path))
   261 		{
   262 			g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
   263 			return;
   264 		}
   265 
   266 		if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
   267 		{
   268 			g_Logger.LogError("Could not load %s: %s", path, error);
   269 			return;
   270 		}
   271 
   272 		m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
   273 
   274 		if (m_pGetCommandLine == NULL)
   275 		{
   276 			g_Logger.LogError("Could not locate any command line functionality");
   277 		}
   278 
   279 		lib->CloseLibrary();
   280 	}
   281 }
   282 
   283 ICommandLine *CHalfLife2::GetValveCommandLine()
   284 {
   285 	if (!m_pGetCommandLine)
   286 		return NULL;
   287 
   288 	return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
   289 }
   290 
   291 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
   292 bool CHalfLife2::IsOriginalEngine()
   293 {
   294 	return is_original_engine;
   295 }
   296 #endif
   297 
   298 #if SOURCE_ENGINE != SE_DARKMESSIAH
   299 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
   300 {
   301 	return engine->GetChangeAccessor( (const edict_t *)this );
   302 }
   303 #endif
   304 
   305 bool UTIL_FindInSendTable(SendTable *pTable, 
   306 						  const char *name,
   307 						  sm_sendprop_info_t *info,
   308 						  unsigned int offset)
   309 {
   310 	const char *pname;
   311 	int props = pTable->GetNumProps();
   312 	SendProp *prop;
   313 
   314 	for (int i=0; i<props; i++)
   315 	{
   316 		prop = pTable->GetProp(i);
   317 		pname = prop->GetName();
   318 		if (pname && strcmp(name, pname) == 0)
   319 		{
   320 			info->prop = prop;
   321 			info->actual_offset = offset + info->prop->GetOffset();
   322 			return true;
   323 		}
   324 		if (prop->GetDataTable())
   325 		{
   326 			if (UTIL_FindInSendTable(prop->GetDataTable(), 
   327 				name,
   328 				info,
   329 				offset + prop->GetOffset())
   330 				)
   331 			{
   332 				return true;
   333 			}
   334 		}
   335 	}
   336 
   337 	return false;
   338 }
   339 
   340 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name, bool *isNested)
   341 {
   342 	if (isNested)
   343 	{
   344 		*isNested = false;
   345 	}
   346 	
   347 	while (pMap)
   348 	{
   349 		for (int i=0; i<pMap->dataNumFields; i++)
   350 		{
   351 			if (pMap->dataDesc[i].fieldName == NULL)
   352 			{
   353 				continue;
   354 			}
   355 			if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
   356 			{
   357 				return &(pMap->dataDesc[i]);
   358 			}
   359 			if (pMap->dataDesc[i].td)
   360 			{
   361 				if (isNested)
   362 				{
   363 					*isNested = (UTIL_FindInDataMap(pMap->dataDesc[i].td, name, NULL) != NULL);
   364 					if (*isNested)
   365 					{
   366 						return NULL;
   367 					} else {
   368 						continue;
   369 					}
   370 				} else { // Use the old behaviour, we dont want to spring this on extensions - even if they're doing bad things.
   371 					typedescription_t *_td;
   372 					if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name, NULL)) != NULL)
   373 					{
   374 						return _td;
   375 					}
   376 				}
   377 			}
   378 		}
   379 		pMap = pMap->baseMap;
   380 	}
   381 
   382 	return NULL; 
   383 }
   384 
   385 ServerClass *CHalfLife2::FindServerClass(const char *classname)
   386 {
   387 	DataTableInfo *pInfo = _FindServerClass(classname);
   388 
   389 	if (!pInfo)
   390 	{
   391 		return NULL;
   392 	}
   393 
   394 	return pInfo->sc;
   395 }
   396 
   397 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
   398 {
   399 	DataTableInfo *pInfo = NULL;
   400 
   401 	if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
   402 	{
   403 		ServerClass *sc = gamedll->GetAllServerClasses();
   404 		while (sc)
   405 		{
   406 			if (strcmp(classname, sc->GetName()) == 0)
   407 			{
   408 				pInfo = new DataTableInfo;
   409 				pInfo->sc = sc;
   410 				sm_trie_insert(m_pClasses, classname, pInfo);
   411 				m_Tables.push_back(pInfo);
   412 				break;
   413 			}
   414 			sc = sc->m_pNext;
   415 		}
   416 		if (!pInfo)
   417 		{
   418 			return NULL;
   419 		}
   420 	}
   421 
   422 	return pInfo;
   423 }
   424 
   425 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
   426 {
   427 	DataTableInfo *pInfo;
   428 	sm_sendprop_info_t *prop;
   429 
   430 	if ((pInfo = _FindServerClass(classname)) == NULL)
   431 	{
   432 		return false;
   433 	}
   434 
   435 	if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
   436 	{
   437 		sm_sendprop_info_t temp_info;
   438 
   439 		if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
   440 		{
   441 			return false;
   442 		}
   443 
   444 		pInfo->lookup.insert(offset, temp_info);
   445 		*info = temp_info;
   446 	}
   447 	else
   448 	{
   449 		*info = *prop;
   450 	}
   451 	
   452 	return true;
   453 }
   454 
   455 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
   456 {
   457 	sm_sendprop_info_t info;
   458 
   459 	if (!FindSendPropInfo(classname, offset, &info))
   460 	{
   461 		return NULL;
   462 	}
   463 
   464 	return info.prop;
   465 }
   466 
   467 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
   468 {
   469 	return this->FindInDataMap(pMap, offset, NULL);
   470 }
   471 
   472 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset, bool *isNested)
   473 {
   474 	typedescription_t *td = NULL;
   475 	DataMapTrie &val = m_Maps[pMap];
   476 
   477 	if (!val.trie)
   478 	{
   479 		val.trie = sm_trie_create();
   480 	}
   481 	if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
   482 	{
   483 		if ((td = UTIL_FindInDataMap(pMap, offset, isNested)) != NULL)
   484 		{
   485 			sm_trie_insert(val.trie, offset, td);
   486 		}
   487 	}
   488 
   489 	return td;
   490 }
   491 
   492 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
   493 {
   494 #if SOURCE_ENGINE != SE_DARKMESSIAH
   495 	if (g_pSharedChangeInfo != NULL)
   496 	{
   497 		if (offset)
   498 		{
   499 			pEdict->StateChanged(offset);
   500 		}
   501 		else
   502 		{
   503 			pEdict->StateChanged();
   504 		}
   505 	}
   506 	else
   507 #endif
   508 	{
   509 		pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
   510 	}
   511 }
   512 
   513 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
   514 {
   515 #if SOURCE_ENGINE != SE_CSGO
   516 	bf_write *pBitBuf = NULL;
   517 #endif
   518 	cell_t players[] = {client};
   519 
   520 	if (dest == HUD_PRINTTALK)
   521 	{
   522 		const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
   523 
   524 		/* Use SayText user message instead */
   525 		if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
   526 		{
   527 			char buffer[192];
   528 			UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
   529 
   530 #if SOURCE_ENGINE == SE_CSGO
   531 			CCSUsrMsg_SayText *pMsg;
   532 			if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   533 			{
   534 				return false;
   535 			}
   536 
   537 			pMsg->set_ent_idx(0);
   538 			pMsg->set_text(buffer);
   539 			pMsg->set_chat(false);
   540 #else
   541 			if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   542 			{
   543 				return false;
   544 			}
   545 
   546 			pBitBuf->WriteByte(0);
   547 			pBitBuf->WriteString(buffer);
   548 			pBitBuf->WriteByte(1);
   549 #endif
   550 
   551 			g_UserMsgs.EndMessage();
   552 
   553 			return true;
   554 		}
   555 	}
   556 
   557 #if SOURCE_ENGINE == SE_CSGO
   558 	CCSUsrMsg_TextMsg *pMsg;
   559 	if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   560 	{
   561 		return false;
   562 	}
   563 
   564 	// Client tries to read all 5 'params' and will crash if less
   565 	pMsg->set_msg_dst(dest);
   566 	pMsg->add_params(msg);
   567 	pMsg->add_params("");
   568 	pMsg->add_params("");
   569 	pMsg->add_params("");
   570 	pMsg->add_params("");
   571 #else
   572 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   573 	{
   574 		return false;
   575 	}
   576 
   577 	pBitBuf->WriteByte(dest);
   578 	pBitBuf->WriteString(msg);
   579 #endif
   580 
   581 	g_UserMsgs.EndMessage();
   582 
   583 	return true;
   584 }
   585 
   586 bool CHalfLife2::HintTextMsg(int client, const char *msg)
   587 {
   588 	cell_t players[] = {client};
   589 
   590 #if SOURCE_ENGINE == SE_CSGO
   591 	CCSUsrMsg_HintText *pMsg;
   592 	if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   593 	{
   594 		return false;
   595 	}
   596 
   597 	pMsg->set_text(msg);
   598 #else
   599 	bf_write *pBitBuf = NULL;
   600 
   601 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   602 	{
   603 		return false;
   604 	}
   605 
   606 	const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
   607 	if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
   608 	{
   609 		pBitBuf->WriteByte(1);
   610 	}
   611 	pBitBuf->WriteString(msg);
   612 #endif
   613 	g_UserMsgs.EndMessage();
   614 
   615 	return true;
   616 }
   617 
   618 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
   619 {
   620 #if SOURCE_ENGINE == SE_CSGO
   621 	CCSUsrMsg_HintText *pMsg;
   622 	if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
   623 	{
   624 		return false;
   625 	}
   626 
   627 	pMsg->set_text(msg);
   628 #else
   629 	bf_write *pBitBuf = NULL;
   630 
   631 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
   632 	{
   633 		return false;
   634 	}
   635 
   636 	const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
   637 	if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
   638 	{
   639 		pBitBuf->WriteByte(1);
   640 	}
   641 	pBitBuf->WriteString(msg);
   642 #endif
   643 
   644 	g_UserMsgs.EndMessage();
   645 
   646 	return true;
   647 }
   648 
   649 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
   650 {
   651 	KeyValues *SubKey = NULL;
   652 	int count = 0;
   653 	cell_t players[] = {client};
   654 
   655 #if SOURCE_ENGINE == SE_CSGO
   656 	CCSUsrMsg_VGUIMenu *pMsg;
   657 	if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
   658 	{
   659 		return false;
   660 	}
   661 #else
   662 	bf_write *pBitBuf = NULL;
   663 	if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
   664 	{
   665 		return false;
   666 	}
   667 #endif
   668 
   669 	if (data)
   670 	{
   671 		SubKey = data->GetFirstSubKey();
   672 		while (SubKey)
   673 		{
   674 			count++;
   675 			SubKey = SubKey->GetNextKey();
   676 		}
   677 		SubKey = data->GetFirstSubKey();
   678 	}
   679 
   680 #if SOURCE_ENGINE == SE_CSGO
   681 	pMsg->set_name(name);
   682 	pMsg->set_show(show);
   683 
   684 	while (SubKey)
   685 	{
   686 		CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
   687 		key->set_name(SubKey->GetName());
   688 		key->set_str(SubKey->GetString());
   689 		SubKey = SubKey->GetNextKey();
   690 	}
   691 #else
   692 	pBitBuf->WriteString(name);
   693 	pBitBuf->WriteByte((show) ? 1 : 0);
   694 	pBitBuf->WriteByte(count);
   695 	while (SubKey)
   696 	{
   697 		pBitBuf->WriteString(SubKey->GetName());
   698 		pBitBuf->WriteString(SubKey->GetString());
   699 		SubKey = SubKey->GetNextKey();
   700 	}
   701 #endif
   702 
   703 	g_UserMsgs.EndMessage();
   704 
   705 	return true;
   706 }
   707 
   708 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
   709 {
   710 	DelayedFakeCliCmd *pFake;
   711 
   712 	if (m_FreeCmds.empty())
   713 	{
   714 		pFake = new DelayedFakeCliCmd;
   715 	} else {
   716 		pFake = m_FreeCmds.front();
   717 		m_FreeCmds.pop();
   718 	}
   719 
   720 	pFake->client = client;
   721 	pFake->userid = userid;
   722 	pFake->cmd.assign(cmd);
   723 
   724 	m_CmdQueue.push(pFake);
   725 }
   726 
   727 void CHalfLife2::ProcessFakeCliCmdQueue()
   728 {
   729 	while (!m_CmdQueue.empty())
   730 	{
   731 		DelayedFakeCliCmd *pFake = m_CmdQueue.first();
   732 
   733 		if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
   734 		{
   735 			CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
   736 			serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
   737 		}
   738 
   739 		m_CmdQueue.pop();
   740 	}
   741 }
   742 
   743 bool CHalfLife2::IsLANServer()
   744 {
   745 	sv_lan = icvar->FindVar("sv_lan");
   746 
   747 	if (!sv_lan)
   748 	{
   749 		return false;
   750 	}
   751 
   752 	return (sv_lan->GetInt() != 0);
   753 }
   754 
   755 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
   756 {
   757 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
   758 	if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
   759 #else
   760 	if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
   761 #endif
   762 	{
   763 		Assert(filesystem);
   764 #ifdef _MSC_VER
   765 		Assert(_heapchk() == _HEAPOK);
   766 #endif
   767 
   768 		FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
   769 		if (!f)
   770 			return false;
   771 
   772 		// load file into a null-terminated buffer
   773 		int fileSize = filesystem->Size(f);
   774 		char *buffer = (char *)MemAllocScratch(fileSize + 1);
   775 
   776 		Assert(buffer);
   777 
   778 		filesystem->Read(buffer, fileSize, f); // read into local buffer
   779 
   780 		buffer[fileSize] = 0; // null terminate file as EOF
   781 
   782 		filesystem->Close( f );	// close file after reading
   783 
   784 		bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
   785 
   786 		MemFreeScratch();
   787 
   788 		return retOK;
   789 	}
   790 	else
   791 	{
   792 		return kv->LoadFromFile(filesystem, resourceName, pathID);
   793 	}
   794 }
   795 
   796 void CHalfLife2::PushCommandStack(const CCommand *cmd)
   797 {
   798 	CachedCommandInfo info;
   799 
   800 	info.args = cmd;
   801 #if SOURCE_ENGINE <= SE_DARKMESSIAH
   802 	strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
   803 #endif
   804 
   805 	m_CommandStack.push(info);
   806 }
   807 
   808 const CCommand *CHalfLife2::PeekCommandStack()
   809 {
   810 	if (m_CommandStack.empty())
   811 	{
   812 		return NULL;
   813 	}
   814 
   815 	return m_CommandStack.front().args;
   816 }
   817 
   818 void CHalfLife2::PopCommandStack()
   819 {
   820 	m_CommandStack.pop();
   821 }
   822 
   823 const char *CHalfLife2::CurrentCommandName()
   824 {
   825 #if SOURCE_ENGINE >= SE_ORANGEBOX
   826 	return m_CommandStack.front().args->Arg(0);
   827 #else
   828 	return m_CommandStack.front().cmd;
   829 #endif
   830 }
   831 
   832 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
   833 {
   834 	DelayedKickInfo kick;
   835 
   836 	kick.client = client;
   837 	kick.userid = userid;
   838 	UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
   839 
   840 	m_DelayedKicks.push(kick);
   841 }
   842 
   843 void CHalfLife2::ProcessDelayedKicks()
   844 {
   845 	while (!m_DelayedKicks.empty())
   846 	{
   847 		DelayedKickInfo info = m_DelayedKicks.first();
   848 		m_DelayedKicks.pop();
   849 
   850 		CPlayer *player = g_Players.GetPlayerByIndex(info.client);
   851 		if (player == NULL || player->GetUserId() != info.userid)
   852 		{
   853 			continue;
   854 		}
   855 
   856 		player->Kick(info.buffer);
   857 	}
   858 }
   859 
   860 edict_t *CHalfLife2::EdictOfIndex(int index)
   861 {
   862 	return ::PEntityOfEntIndex(index);
   863 }
   864 
   865 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
   866 {
   867 	return ::IndexOfEdict(pEnt);
   868 }
   869 
   870 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
   871 {
   872 	if (!hndl.IsValid())
   873 	{
   874 		return NULL;
   875 	}
   876 
   877 	int index = hndl.GetEntryIndex();
   878 
   879 	edict_t *pStoredEdict;
   880 	CBaseEntity *pStoredEntity;
   881 
   882 	if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
   883 	{
   884 		return NULL;
   885 	}
   886 
   887 	if (pStoredEdict == NULL || pStoredEntity == NULL)
   888 	{
   889 		return NULL;
   890 	}
   891 
   892 	IServerEntity *pSE = pStoredEdict->GetIServerEntity();
   893 
   894 	if (pSE == NULL)
   895 	{
   896 		return NULL;
   897 	}
   898 
   899 	if (pSE->GetRefEHandle() != hndl)
   900 	{
   901 		return NULL;
   902 	}
   903 
   904 	return pStoredEdict;
   905 }
   906 
   907 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
   908 {
   909 	IServerEntity *pEntOther = pEnt->GetIServerEntity();
   910 
   911 	if (pEntOther == NULL)
   912 	{
   913 		return;
   914 	}
   915 
   916 	hndl.Set(pEntOther);
   917 }
   918 
   919 const char *CHalfLife2::GetCurrentMap()
   920 {
   921 	return STRING(gpGlobals->mapname);
   922 }
   923 
   924 void CHalfLife2::ServerCommand(const char *buffer)
   925 {
   926 	engine->ServerCommand(buffer);
   927 }
   928 
   929 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
   930 {
   931 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
   932 	CBaseHandle hndl = pUnknown->GetRefEHandle();
   933 	return (hndl.ToInt() | (1<<31));
   934 }
   935 
   936 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
   937 {
   938 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
   939 	{
   940 		return NULL;
   941 	}
   942 
   943 	CEntInfo *pInfo = NULL;
   944 
   945 	if (entRef & (1<<31))
   946 	{
   947 		/* Proper ent reference */
   948 		int hndlValue = entRef & ~(1<<31);
   949 		CBaseHandle hndl(hndlValue);
   950 
   951 		pInfo = LookupEntity(hndl.GetEntryIndex());
   952 		if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
   953 		{
   954 			return NULL;
   955 		}
   956 	}
   957 	else
   958 	{
   959 		/* Old style index only */
   960 		pInfo = LookupEntity(entRef);
   961 	}
   962 
   963 	if (!pInfo)
   964 	{
   965 		return NULL;
   966 	}
   967 
   968 	IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
   969 	if (pUnk)
   970 	{
   971 		return pUnk->GetBaseEntity();
   972 	}
   973 
   974 	return NULL;
   975 }
   976 
   977 /**
   978  * Retrieves the CEntInfo pointer from g_EntList for a given entity index
   979  */
   980 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
   981 {
   982 	// Make sure that our index is within the bounds of the global ent array
   983 	if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
   984 	{
   985 		return NULL;
   986 	}
   987 
   988 	if (!g_EntList || entInfoOffset == -1)
   989 	{
   990 		/* Attempt to use engine interface instead */
   991 		static CEntInfo tempInfo;
   992 		tempInfo.m_pNext = NULL;
   993 		tempInfo.m_pPrev = NULL;
   994 
   995 		edict_t *pEdict = PEntityOfEntIndex(entIndex);
   996 
   997 		if (!pEdict)
   998 		{
   999 			return NULL;
  1000 		}
  1001 
  1002 		IServerUnknown *pUnk = pEdict->GetUnknown();
  1003 
  1004 		if (!pUnk)
  1005 		{
  1006 			return NULL;
  1007 		}
  1008 
  1009 		tempInfo.m_pEntity = pUnk;
  1010 		tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
  1011 
  1012 		return &tempInfo;
  1013 	}
  1014 
  1015 	CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
  1016 	return &pArray[entIndex];
  1017 }
  1018 
  1019 /**
  1020 	SERIAL_MASK = 0x7fff (15 bits)
  1021 
  1022 	#define	MAX_EDICT_BITS				11
  1023 	#define NUM_ENT_ENTRY_BITS		(MAX_EDICT_BITS + 1)
  1024 	m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS); 
  1025 	
  1026 	Top 5 bits of a handle are unused.
  1027 	Bit 31 - Our 'reference' flag indicator
  1028 */
  1029 
  1030 cell_t CHalfLife2::IndexToReference(int entIndex)
  1031 {
  1032 	CBaseEntity *pEnt = ReferenceToEntity(entIndex);
  1033 	if (!pEnt)
  1034 	{
  1035 		return INVALID_EHANDLE_INDEX;
  1036 	}
  1037 
  1038 	return EntityToReference(pEnt);
  1039 }
  1040 
  1041 int CHalfLife2::ReferenceToIndex(cell_t entRef)
  1042 {
  1043 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
  1044 	{
  1045 		return INVALID_EHANDLE_INDEX;
  1046 	}
  1047 
  1048 	if (entRef & (1<<31))
  1049 	{
  1050 		/* Proper ent reference */
  1051 		int hndlValue = entRef & ~(1<<31);
  1052 		CBaseHandle hndl(hndlValue);
  1053 
  1054 		CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
  1055 
  1056 		if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
  1057 		{
  1058 			return INVALID_EHANDLE_INDEX;
  1059 		}
  1060 
  1061 		return hndl.GetEntryIndex();
  1062 	}
  1063 
  1064 	return entRef;
  1065 }
  1066 
  1067 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
  1068 {
  1069 	if (pEntity == NULL)
  1070 	{
  1071 		return INVALID_EHANDLE_INDEX;
  1072 	}
  1073 
  1074 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
  1075 	CBaseHandle hndl = pUnknown->GetRefEHandle();
  1076 
  1077 	if (hndl == INVALID_EHANDLE_INDEX)
  1078 	{
  1079 		return INVALID_EHANDLE_INDEX;
  1080 	}
  1081 	
  1082 	if (hndl.GetEntryIndex() >= MAX_EDICTS)
  1083 	{
  1084 		return (hndl.ToInt() | (1<<31));
  1085 	}
  1086 	else
  1087 	{
  1088 		return hndl.GetEntryIndex();
  1089 	}
  1090 }
  1091 
  1092 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
  1093 {
  1094 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
  1095 	{
  1096 		return INVALID_EHANDLE_INDEX;
  1097 	}
  1098 
  1099 	int hndlValue = entRef & ~(1<<31);
  1100 	CBaseHandle hndl(hndlValue);
  1101 
  1102 	if (hndl.GetEntryIndex() < MAX_EDICTS)
  1103 	{
  1104 		return hndl.GetEntryIndex();
  1105 	}
  1106 
  1107 	return entRef;
  1108 }
  1109 
  1110 void *CHalfLife2::GetGlobalEntityList()
  1111 {
  1112 	return g_EntList;
  1113 }
  1114 
  1115 int CHalfLife2::GetSendPropOffset(SendProp *prop)
  1116 {
  1117 	return prop->GetOffset();
  1118 }
  1119 
  1120 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
  1121 {
  1122 	if (pEdict == NULL || pEdict->IsFree())
  1123 	{
  1124 		return NULL;
  1125 	}
  1126 	
  1127 	IServerUnknown *pUnk = pEdict->GetUnknown();
  1128 	if (pUnk == NULL)
  1129 	{
  1130 		return NULL;
  1131 	}
  1132 	
  1133 	CBaseEntity * pEntity = pUnk->GetBaseEntity();
  1134 	
  1135 	if (pEntity == NULL)
  1136 	{
  1137 		return NULL;
  1138 	}
  1139 	
  1140 	return GetEntityClassname(pEntity);
  1141 }
  1142 
  1143 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
  1144 {
  1145 	static int offset = -1;
  1146 	if (offset == -1)
  1147 	{
  1148 		datamap_t *pMap = GetDataMap(pEntity);
  1149 		typedescription_t *pDesc = FindInDataMap(pMap, "m_iClassname");
  1150 		offset = GetTypeDescOffs(pDesc);
  1151 	}
  1152 
  1153 	return *(const char **)(((unsigned char *)pEntity) + offset);
  1154 }
  1155 
  1156 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1157 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
  1158 {
  1159 	static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
  1160 	if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
  1161 		return false;
  1162 
  1163 	static size_t helperCmdLen = strlen(pHelperCmd->GetName());
  1164 
  1165 	CUtlVector<CUtlString> results;
  1166 	pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
  1167 	if (results.Count() == 0)
  1168 		return false;
  1169 
  1170 	// Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
  1171 	// so skip ahead to start of map path/name
  1172 
  1173 	// Like the engine, we're only going to deal with the first match.
  1174 
  1175 	strncopy(outFullname, &results[0][helperCmdLen + 1], size);
  1176 
  1177 	return true;
  1178 }
  1179 #endif
  1180 
  1181 bool CHalfLife2::IsMapValid(const char *map)
  1182 {
  1183 	bool ret = engine->IsMapValid(map);
  1184 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1185 	if (!ret)
  1186 	{
  1187 		static char szFuzzyName[PLATFORM_MAX_PATH];
  1188 		if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
  1189 		{
  1190 			ret = engine->IsMapValid(szFuzzyName);
  1191 		}
  1192 	}
  1193 #endif
  1194 	return ret;
  1195 }