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