core/HalfLife2.cpp
author Kyle Sanderson <kyle.leet@gmail.com>
Mon Aug 12 00:45:29 2013 +0100 (2013-08-12)
changeset 3996 4a0daf289347
parent 3961 0dc477c29792
child 3997 59bcfc51eb79
permissions -rw-r--r--
Dump handle information when a plugin is forcefully unloaded. (bug 5666, 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_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_HL2DM || SOURCE_ENGINE == SE_DODS || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_TF2 || 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 	CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
   901 	if (!pPlayer || !pPlayer->IsConnected() || pPlayer->IsInKickQueue())
   902 	{
   903 		return;
   904 	}
   905 	
   906 	pPlayer->MarkAsBeingKicked();
   907 
   908 	DelayedKickInfo kick;
   909 
   910 	kick.client = client;
   911 	kick.userid = userid;
   912 	UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
   913 
   914 	m_DelayedKicks.push(kick);
   915 }
   916 
   917 void CHalfLife2::ProcessDelayedKicks()
   918 {
   919 	while (!m_DelayedKicks.empty())
   920 	{
   921 		DelayedKickInfo info = m_DelayedKicks.first();
   922 		m_DelayedKicks.pop();
   923 
   924 		CPlayer *player = g_Players.GetPlayerByIndex(info.client);
   925 		if (player == NULL || player->GetUserId() != info.userid)
   926 		{
   927 			continue;
   928 		}
   929 
   930 		player->Kick(info.buffer);
   931 	}
   932 }
   933 
   934 edict_t *CHalfLife2::EdictOfIndex(int index)
   935 {
   936 	return ::PEntityOfEntIndex(index);
   937 }
   938 
   939 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
   940 {
   941 	return ::IndexOfEdict(pEnt);
   942 }
   943 
   944 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
   945 {
   946 	if (!hndl.IsValid())
   947 	{
   948 		return NULL;
   949 	}
   950 
   951 	int index = hndl.GetEntryIndex();
   952 
   953 	edict_t *pStoredEdict;
   954 	CBaseEntity *pStoredEntity;
   955 
   956 	if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
   957 	{
   958 		return NULL;
   959 	}
   960 
   961 	if (pStoredEdict == NULL || pStoredEntity == NULL)
   962 	{
   963 		return NULL;
   964 	}
   965 
   966 	IServerEntity *pSE = pStoredEdict->GetIServerEntity();
   967 
   968 	if (pSE == NULL)
   969 	{
   970 		return NULL;
   971 	}
   972 
   973 	if (pSE->GetRefEHandle() != hndl)
   974 	{
   975 		return NULL;
   976 	}
   977 
   978 	return pStoredEdict;
   979 }
   980 
   981 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
   982 {
   983 	IServerEntity *pEntOther = pEnt->GetIServerEntity();
   984 
   985 	if (pEntOther == NULL)
   986 	{
   987 		return;
   988 	}
   989 
   990 	hndl.Set(pEntOther);
   991 }
   992 
   993 const char *CHalfLife2::GetCurrentMap()
   994 {
   995 	return STRING(gpGlobals->mapname);
   996 }
   997 
   998 void CHalfLife2::ServerCommand(const char *buffer)
   999 {
  1000 	engine->ServerCommand(buffer);
  1001 }
  1002 
  1003 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
  1004 {
  1005 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
  1006 	CBaseHandle hndl = pUnknown->GetRefEHandle();
  1007 	return (hndl.ToInt() | (1<<31));
  1008 }
  1009 
  1010 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
  1011 {
  1012 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
  1013 	{
  1014 		return NULL;
  1015 	}
  1016 
  1017 	CEntInfo *pInfo = NULL;
  1018 
  1019 	if (entRef & (1<<31))
  1020 	{
  1021 		/* Proper ent reference */
  1022 		int hndlValue = entRef & ~(1<<31);
  1023 		CBaseHandle hndl(hndlValue);
  1024 
  1025 		pInfo = LookupEntity(hndl.GetEntryIndex());
  1026 		if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
  1027 		{
  1028 			return NULL;
  1029 		}
  1030 	}
  1031 	else
  1032 	{
  1033 		/* Old style index only */
  1034 		pInfo = LookupEntity(entRef);
  1035 	}
  1036 
  1037 	if (!pInfo)
  1038 	{
  1039 		return NULL;
  1040 	}
  1041 
  1042 	IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
  1043 	if (pUnk)
  1044 	{
  1045 		return pUnk->GetBaseEntity();
  1046 	}
  1047 
  1048 	return NULL;
  1049 }
  1050 
  1051 /**
  1052  * Retrieves the CEntInfo pointer from g_EntList for a given entity index
  1053  */
  1054 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
  1055 {
  1056 	// Make sure that our index is within the bounds of the global ent array
  1057 	if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
  1058 	{
  1059 		return NULL;
  1060 	}
  1061 
  1062 	if (!g_EntList || entInfoOffset == -1)
  1063 	{
  1064 		/* Attempt to use engine interface instead */
  1065 		static CEntInfo tempInfo;
  1066 		tempInfo.m_pNext = NULL;
  1067 		tempInfo.m_pPrev = NULL;
  1068 
  1069 		edict_t *pEdict = PEntityOfEntIndex(entIndex);
  1070 
  1071 		if (!pEdict)
  1072 		{
  1073 			return NULL;
  1074 		}
  1075 
  1076 		IServerUnknown *pUnk = pEdict->GetUnknown();
  1077 
  1078 		if (!pUnk)
  1079 		{
  1080 			return NULL;
  1081 		}
  1082 
  1083 		tempInfo.m_pEntity = pUnk;
  1084 		tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
  1085 
  1086 		return &tempInfo;
  1087 	}
  1088 
  1089 	CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
  1090 	return &pArray[entIndex];
  1091 }
  1092 
  1093 /**
  1094 	SERIAL_MASK = 0x7fff (15 bits)
  1095 
  1096 	#define	MAX_EDICT_BITS				11
  1097 	#define NUM_ENT_ENTRY_BITS		(MAX_EDICT_BITS + 1)
  1098 	m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS); 
  1099 	
  1100 	Top 5 bits of a handle are unused.
  1101 	Bit 31 - Our 'reference' flag indicator
  1102 */
  1103 
  1104 cell_t CHalfLife2::IndexToReference(int entIndex)
  1105 {
  1106 	CBaseEntity *pEnt = ReferenceToEntity(entIndex);
  1107 	if (!pEnt)
  1108 	{
  1109 		return INVALID_EHANDLE_INDEX;
  1110 	}
  1111 
  1112 	return EntityToReference(pEnt);
  1113 }
  1114 
  1115 int CHalfLife2::ReferenceToIndex(cell_t entRef)
  1116 {
  1117 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
  1118 	{
  1119 		return INVALID_EHANDLE_INDEX;
  1120 	}
  1121 
  1122 	if (entRef & (1<<31))
  1123 	{
  1124 		/* Proper ent reference */
  1125 		int hndlValue = entRef & ~(1<<31);
  1126 		CBaseHandle hndl(hndlValue);
  1127 
  1128 		CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
  1129 
  1130 		if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
  1131 		{
  1132 			return INVALID_EHANDLE_INDEX;
  1133 		}
  1134 
  1135 		return hndl.GetEntryIndex();
  1136 	}
  1137 
  1138 	return entRef;
  1139 }
  1140 
  1141 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
  1142 {
  1143 	if (pEntity == NULL)
  1144 	{
  1145 		return INVALID_EHANDLE_INDEX;
  1146 	}
  1147 
  1148 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
  1149 	CBaseHandle hndl = pUnknown->GetRefEHandle();
  1150 
  1151 	if (hndl == INVALID_EHANDLE_INDEX)
  1152 	{
  1153 		return INVALID_EHANDLE_INDEX;
  1154 	}
  1155 	
  1156 	if (hndl.GetEntryIndex() >= MAX_EDICTS)
  1157 	{
  1158 		return (hndl.ToInt() | (1<<31));
  1159 	}
  1160 	else
  1161 	{
  1162 		return hndl.GetEntryIndex();
  1163 	}
  1164 }
  1165 
  1166 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
  1167 {
  1168 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
  1169 	{
  1170 		return INVALID_EHANDLE_INDEX;
  1171 	}
  1172 
  1173 	int hndlValue = entRef & ~(1<<31);
  1174 	CBaseHandle hndl(hndlValue);
  1175 
  1176 	if (hndl.GetEntryIndex() < MAX_EDICTS)
  1177 	{
  1178 		return hndl.GetEntryIndex();
  1179 	}
  1180 
  1181 	return entRef;
  1182 }
  1183 
  1184 void *CHalfLife2::GetGlobalEntityList()
  1185 {
  1186 	return g_EntList;
  1187 }
  1188 
  1189 int CHalfLife2::GetSendPropOffset(SendProp *prop)
  1190 {
  1191 	return prop->GetOffset();
  1192 }
  1193 
  1194 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
  1195 {
  1196 	if (pEdict == NULL || pEdict->IsFree())
  1197 	{
  1198 		return NULL;
  1199 	}
  1200 	
  1201 	IServerUnknown *pUnk = pEdict->GetUnknown();
  1202 	if (pUnk == NULL)
  1203 	{
  1204 		return NULL;
  1205 	}
  1206 	
  1207 	CBaseEntity * pEntity = pUnk->GetBaseEntity();
  1208 	
  1209 	if (pEntity == NULL)
  1210 	{
  1211 		return NULL;
  1212 	}
  1213 	
  1214 	return GetEntityClassname(pEntity);
  1215 }
  1216 
  1217 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
  1218 {
  1219 	static int offset = -1;
  1220 	if (offset == -1)
  1221 	{
  1222 		CBaseEntity *pGetterEnt = ReferenceToEntity(0);
  1223 		datamap_t *pMap = GetDataMap(pGetterEnt);
  1224 		typedescription_t *pDesc = FindInDataMap(pMap, "m_iClassname");
  1225 		offset = GetTypeDescOffs(pDesc);
  1226 	}
  1227 
  1228 	return *(const char **)(((unsigned char *)pEntity) + offset);
  1229 }
  1230 
  1231 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1232 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
  1233 {
  1234 	static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
  1235 	if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
  1236 		return false;
  1237 
  1238 	static size_t helperCmdLen = strlen(pHelperCmd->GetName());
  1239 
  1240 	CUtlVector<CUtlString> results;
  1241 	pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
  1242 	if (results.Count() == 0)
  1243 		return false;
  1244 
  1245 	// Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
  1246 	// so skip ahead to start of map path/name
  1247 
  1248 	// Like the engine, we're only going to deal with the first match.
  1249 
  1250 	strncopy(outFullname, &results[0][helperCmdLen + 1], size);
  1251 
  1252 	return true;
  1253 }
  1254 #endif
  1255 
  1256 bool CHalfLife2::IsMapValid(const char *map)
  1257 {
  1258 	if (!map || !map[0])
  1259 		return false;
  1260 
  1261 	bool ret = engine->IsMapValid(map);
  1262 #if SOURCE_ENGINE >= SE_LEFT4DEAD
  1263 	if (!ret)
  1264 	{
  1265 		static char szFuzzyName[PLATFORM_MAX_PATH];
  1266 		if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
  1267 		{
  1268 			ret = engine->IsMapValid(szFuzzyName);
  1269 		}
  1270 	}
  1271 #endif
  1272 	return ret;
  1273 }