core/HalfLife2.cpp
author David Anderson <dvander@alliedmods.net>
Mon Sep 07 21:29:18 2009 -0700 (2009-09-07)
changeset 2798 6dd90eaa0593
parent 2749 1c3d9e4df885
child 2801 f70c4df158b3
permissions -rw-r--r--
Fixed invalid array access in PluginSys (bug 3933, r=pred).
     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 "GameConfigs.h"
    39 #include <compat_wrappers.h>
    40 #include <Logger.h>
    41 
    42 CHalfLife2 g_HL2;
    43 ConVar *sv_lan = NULL;
    44 
    45 static void *g_EntList = NULL;
    46 static int entInfoOffset = -1;
    47 
    48 namespace SourceHook
    49 {
    50 	template<>
    51 	int HashFunction<datamap_t *>(datamap_t * const &k)
    52 	{
    53 		return reinterpret_cast<int>(k);
    54 	}
    55 
    56 	template<>
    57 	int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
    58 	{
    59 		return (k1-k2);
    60 	}
    61 }
    62 
    63 CHalfLife2::CHalfLife2()
    64 {
    65 	m_pClasses = sm_trie_create();
    66 }
    67 
    68 CHalfLife2::~CHalfLife2()
    69 {
    70 	sm_trie_destroy(m_pClasses);
    71 
    72 	List<DataTableInfo *>::iterator iter;
    73 	DataTableInfo *pInfo;
    74 	for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
    75 	{
    76 		pInfo = (*iter);
    77 		delete pInfo;
    78 	}
    79 
    80 	m_Tables.clear();
    81 
    82 	THash<datamap_t *, DataMapTrie>::iterator h_iter;
    83 	for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
    84 	{
    85 		if (h_iter->val.trie)
    86 		{
    87 			sm_trie_destroy(h_iter->val.trie);
    88 			h_iter->val.trie = NULL;
    89 		}
    90 	}
    91 
    92 	m_Maps.clear();
    93 }
    94 
    95 #if SOURCE_ENGINE != SE_DARKMESSIAH
    96 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
    97 #endif
    98 
    99 bool is_original_engine = false;
   100 
   101 void CHalfLife2::OnSourceModStartup(bool late)
   102 {
   103 #if SOURCE_ENGINE != SE_DARKMESSIAH
   104 
   105 	/* The Ship currently is the only known game to use an older version of the engine */
   106 #if defined METAMOD_PLAPI_VERSION
   107 	if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
   108 #else
   109 	if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
   110 #endif
   111 	{
   112 		is_original_engine = true;
   113 	}
   114 	else if (g_pSharedChangeInfo == NULL)
   115 	{
   116 		g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
   117 	}
   118 #endif
   119 }
   120 
   121 void CHalfLife2::OnSourceModAllInitialized()
   122 {
   123 	m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
   124 	m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
   125 	m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
   126 	m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
   127 	g_ShareSys.AddInterface(NULL, this);
   128 }
   129 
   130 void CHalfLife2::OnSourceModAllInitialized_Post()
   131 {
   132 	char *addr = NULL;
   133 #ifdef PLATFORM_WINDOWS
   134 	int offset;
   135 
   136 	/* gEntList and/or g_pEntityList */
   137 	if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
   138 	{
   139 		g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
   140 		return;
   141 	}
   142 	if (!addr)
   143 	{
   144 		g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
   145 		return;
   146 	}
   147 	if (!g_pGameConf->GetOffset("gEntList", &offset))
   148 	{
   149 		g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
   150 		return;
   151 	}
   152 	g_EntList = *reinterpret_cast<void **>(addr + offset);
   153 #elif defined PLATFORM_LINUX
   154 	/* gEntList and/or g_pEntityList */
   155 	if (!g_pGameConf->GetMemSig("gEntList", (void **)&addr))
   156 	{
   157 		g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
   158 		return;
   159 	}
   160 	if (!addr)
   161 	{
   162 		g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
   163 		return;
   164 	}
   165 	g_EntList = reinterpret_cast<void *>(addr);
   166 #endif
   167 
   168 	if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
   169 	{
   170 		g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
   171 		return;
   172 	}
   173 }
   174 
   175 #if !defined METAMOD_PLAPI_VERSION
   176 bool CHalfLife2::IsOriginalEngine()
   177 {
   178 	return is_original_engine;
   179 }
   180 #endif
   181 
   182 #if SOURCE_ENGINE != SE_DARKMESSIAH
   183 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
   184 {
   185 	return engine->GetChangeAccessor( (const edict_t *)this );
   186 }
   187 #endif
   188 
   189 bool UTIL_FindInSendTable(SendTable *pTable, 
   190 						  const char *name,
   191 						  sm_sendprop_info_t *info,
   192 						  unsigned int offset)
   193 {
   194 	const char *pname;
   195 	int props = pTable->GetNumProps();
   196 	SendProp *prop;
   197 
   198 	for (int i=0; i<props; i++)
   199 	{
   200 		prop = pTable->GetProp(i);
   201 		pname = prop->GetName();
   202 		if (pname && strcmp(name, pname) == 0)
   203 		{
   204 			info->prop = prop;
   205 			info->actual_offset = offset + info->prop->GetOffset();
   206 			return true;
   207 		}
   208 		if (prop->GetDataTable())
   209 		{
   210 			if (UTIL_FindInSendTable(prop->GetDataTable(), 
   211 				name,
   212 				info,
   213 				offset + prop->GetOffset())
   214 				)
   215 			{
   216 				return true;
   217 			}
   218 		}
   219 	}
   220 
   221 	return false;
   222 }
   223 
   224 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name)
   225 {
   226 	while (pMap)
   227 	{
   228 		for (int i=0; i<pMap->dataNumFields; i++)
   229 		{
   230 			if (pMap->dataDesc[i].fieldName == NULL)
   231 			{
   232 				continue;
   233 			}
   234 			if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
   235 			{
   236 				return &(pMap->dataDesc[i]);
   237 			}
   238 			if (pMap->dataDesc[i].td)
   239 			{
   240 				typedescription_t *_td;
   241 				if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name)) != NULL)
   242 				{
   243 					return _td;
   244 				}
   245 			}
   246 		}
   247 		pMap = pMap->baseMap;
   248 	}
   249 
   250 	return NULL; 
   251 }
   252 
   253 ServerClass *CHalfLife2::FindServerClass(const char *classname)
   254 {
   255 	DataTableInfo *pInfo = _FindServerClass(classname);
   256 
   257 	if (!pInfo)
   258 	{
   259 		return NULL;
   260 	}
   261 
   262 	return pInfo->sc;
   263 }
   264 
   265 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
   266 {
   267 	DataTableInfo *pInfo = NULL;
   268 
   269 	if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
   270 	{
   271 		ServerClass *sc = gamedll->GetAllServerClasses();
   272 		while (sc)
   273 		{
   274 			if (strcmp(classname, sc->GetName()) == 0)
   275 			{
   276 				pInfo = new DataTableInfo;
   277 				pInfo->sc = sc;
   278 				sm_trie_insert(m_pClasses, classname, pInfo);
   279 				m_Tables.push_back(pInfo);
   280 				break;
   281 			}
   282 			sc = sc->m_pNext;
   283 		}
   284 		if (!pInfo)
   285 		{
   286 			return NULL;
   287 		}
   288 	}
   289 
   290 	return pInfo;
   291 }
   292 
   293 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
   294 {
   295 	DataTableInfo *pInfo;
   296 	sm_sendprop_info_t *prop;
   297 
   298 	if ((pInfo = _FindServerClass(classname)) == NULL)
   299 	{
   300 		return false;
   301 	}
   302 
   303 	if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
   304 	{
   305 		sm_sendprop_info_t temp_info;
   306 
   307 		if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
   308 		{
   309 			return false;
   310 		}
   311 
   312 		pInfo->lookup.insert(offset, temp_info);
   313 		*info = temp_info;
   314 	}
   315 	else
   316 	{
   317 		*info = *prop;
   318 	}
   319 	
   320 	return true;
   321 }
   322 
   323 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
   324 {
   325 	sm_sendprop_info_t info;
   326 
   327 	if (!FindSendPropInfo(classname, offset, &info))
   328 	{
   329 		return NULL;
   330 	}
   331 
   332 	return info.prop;
   333 }
   334 
   335 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
   336 {
   337 	typedescription_t *td = NULL;
   338 	DataMapTrie &val = m_Maps[pMap];
   339 
   340 	if (!val.trie)
   341 	{
   342 		val.trie = sm_trie_create();
   343 	}
   344 	if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
   345 	{
   346 		if ((td = UTIL_FindInDataMap(pMap, offset)) != NULL)
   347 		{
   348 			sm_trie_insert(val.trie, offset, td);
   349 		}
   350 	}
   351 
   352 	return td;
   353 }
   354 
   355 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
   356 {
   357 #if SOURCE_ENGINE != SE_DARKMESSIAH
   358 	if (g_pSharedChangeInfo != NULL)
   359 	{
   360 		if (offset)
   361 		{
   362 			pEdict->StateChanged(offset);
   363 		}
   364 		else
   365 		{
   366 			pEdict->StateChanged();
   367 		}
   368 	}
   369 	else
   370 #endif
   371 	{
   372 		pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
   373 	}
   374 }
   375 
   376 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
   377 {
   378 	bf_write *pBitBuf = NULL;
   379 	cell_t players[] = {client};
   380 
   381 	if (dest == HUD_PRINTTALK)
   382 	{
   383 		const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
   384 
   385 		/* Use SayText user message instead */
   386 		if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
   387 		{
   388 			char buffer[192];
   389 			UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
   390 
   391 			if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   392 			{
   393 				return false;
   394 			}
   395 
   396 			pBitBuf->WriteByte(0);
   397 			pBitBuf->WriteString(buffer);
   398 			pBitBuf->WriteByte(1);
   399 
   400 			g_UserMsgs.EndMessage();
   401 
   402 			return true;
   403 		}
   404 	}
   405 
   406 	if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   407 	{
   408 		return false;
   409 	}
   410 
   411 	pBitBuf->WriteByte(dest);
   412 	pBitBuf->WriteString(msg);
   413 
   414 	g_UserMsgs.EndMessage();
   415 
   416 	return true;
   417 }
   418 
   419 bool CHalfLife2::HintTextMsg(int client, const char *msg)
   420 {
   421 	bf_write *pBitBuf = NULL;
   422 	cell_t players[] = {client};
   423 
   424 	if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
   425 	{
   426 		return false;
   427 	}
   428 
   429 	const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
   430 	if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
   431 	{
   432 		pBitBuf->WriteByte(1);
   433 	}
   434 	pBitBuf->WriteString(msg);
   435 	g_UserMsgs.EndMessage();
   436 
   437 	return true;
   438 }
   439 
   440 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
   441 {
   442 	bf_write *pBitBuf = NULL;
   443 	KeyValues *SubKey = NULL;
   444 	int count = 0;
   445 	cell_t players[] = {client};
   446 
   447 	if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
   448 	{
   449 		return false;
   450 	}
   451 
   452 	if (data)
   453 	{
   454 		SubKey = data->GetFirstSubKey();
   455 		while (SubKey)
   456 		{
   457 			count++;
   458 			SubKey = SubKey->GetNextKey();
   459 		}
   460 		SubKey = data->GetFirstSubKey();
   461 	}
   462 
   463 	pBitBuf->WriteString(name);
   464 	pBitBuf->WriteByte((show) ? 1 : 0);
   465 	pBitBuf->WriteByte(count);
   466 	while (SubKey)
   467 	{
   468 		pBitBuf->WriteString(SubKey->GetName());
   469 		pBitBuf->WriteString(SubKey->GetString());
   470 		SubKey = SubKey->GetNextKey();
   471 	}
   472 	g_UserMsgs.EndMessage();
   473 
   474 	return true;
   475 }
   476 
   477 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
   478 {
   479 	DelayedFakeCliCmd *pFake;
   480 
   481 	if (m_FreeCmds.empty())
   482 	{
   483 		pFake = new DelayedFakeCliCmd;
   484 	} else {
   485 		pFake = m_FreeCmds.front();
   486 		m_FreeCmds.pop();
   487 	}
   488 
   489 	pFake->client = client;
   490 	pFake->userid = userid;
   491 	pFake->cmd.assign(cmd);
   492 
   493 	m_CmdQueue.push(pFake);
   494 }
   495 
   496 void CHalfLife2::ProcessFakeCliCmdQueue()
   497 {
   498 	while (!m_CmdQueue.empty())
   499 	{
   500 		DelayedFakeCliCmd *pFake = m_CmdQueue.first();
   501 
   502 		if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
   503 		{
   504 			CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
   505 			serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
   506 		}
   507 
   508 		m_CmdQueue.pop();
   509 	}
   510 }
   511 
   512 bool CHalfLife2::IsLANServer()
   513 {
   514 	sv_lan = icvar->FindVar("sv_lan");
   515 
   516 	if (!sv_lan)
   517 	{
   518 		return false;
   519 	}
   520 
   521 	return (sv_lan->GetInt() != 0);
   522 }
   523 
   524 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
   525 {
   526 #if defined METAMOD_PLAPI_VERSION
   527 	if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
   528 #else
   529 	if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
   530 #endif
   531 	{
   532 		Assert(filesystem);
   533 #ifdef _MSC_VER
   534 		Assert(_heapchk() == _HEAPOK);
   535 #endif
   536 
   537 		FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
   538 		if (!f)
   539 			return false;
   540 
   541 		// load file into a null-terminated buffer
   542 		int fileSize = filesystem->Size(f);
   543 		char *buffer = (char *)MemAllocScratch(fileSize + 1);
   544 
   545 		Assert(buffer);
   546 
   547 		filesystem->Read(buffer, fileSize, f); // read into local buffer
   548 
   549 		buffer[fileSize] = 0; // null terminate file as EOF
   550 
   551 		filesystem->Close( f );	// close file after reading
   552 
   553 		bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
   554 
   555 		MemFreeScratch();
   556 
   557 		return retOK;
   558 	}
   559 	else
   560 	{
   561 		return kv->LoadFromFile(filesystem, resourceName, pathID);
   562 	}
   563 }
   564 
   565 void CHalfLife2::PushCommandStack(const CCommand *cmd)
   566 {
   567 	CachedCommandInfo info;
   568 
   569 	info.args = cmd;
   570 #if SOURCE_ENGINE <= SE_DARKMESSIAH
   571 	strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
   572 #endif
   573 
   574 	m_CommandStack.push(info);
   575 }
   576 
   577 const CCommand *CHalfLife2::PeekCommandStack()
   578 {
   579 	if (m_CommandStack.empty())
   580 	{
   581 		return NULL;
   582 	}
   583 
   584 	return m_CommandStack.front().args;
   585 }
   586 
   587 void CHalfLife2::PopCommandStack()
   588 {
   589 	m_CommandStack.pop();
   590 }
   591 
   592 const char *CHalfLife2::CurrentCommandName()
   593 {
   594 #if SOURCE_ENGINE >= SE_ORANGEBOX
   595 	return m_CommandStack.front().args->Arg(0);
   596 #else
   597 	return m_CommandStack.front().cmd;
   598 #endif
   599 }
   600 
   601 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
   602 {
   603 	DelayedKickInfo kick;
   604 
   605 	kick.client = client;
   606 	kick.userid = userid;
   607 	UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
   608 
   609 	m_DelayedKicks.push(kick);
   610 }
   611 
   612 void CHalfLife2::ProcessDelayedKicks()
   613 {
   614 	while (!m_DelayedKicks.empty())
   615 	{
   616 		DelayedKickInfo info = m_DelayedKicks.first();
   617 		m_DelayedKicks.pop();
   618 
   619 		CPlayer *player = g_Players.GetPlayerByIndex(info.client);
   620 		if (player == NULL || player->GetUserId() != info.userid)
   621 		{
   622 			continue;
   623 		}
   624 
   625 		player->Kick(info.buffer);
   626 	}
   627 }
   628 
   629 edict_t *CHalfLife2::EdictOfIndex(int index)
   630 {
   631 	return ::PEntityOfEntIndex(index);
   632 }
   633 
   634 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
   635 {
   636 	return ::IndexOfEdict(pEnt);
   637 }
   638 
   639 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
   640 {
   641 	if (!hndl.IsValid())
   642 	{
   643 		return NULL;
   644 	}
   645 
   646 	int index = hndl.GetEntryIndex();
   647 
   648 	edict_t *pStoredEdict;
   649 	CBaseEntity *pStoredEntity;
   650 
   651 	pStoredEdict = GetEntity(index, &pStoredEntity);
   652 
   653 	if (pStoredEdict == NULL || pStoredEntity == NULL)
   654 	{
   655 		return NULL;
   656 	}
   657 
   658 	IServerEntity *pSE = pStoredEdict->GetIServerEntity();
   659 
   660 	if (pSE == NULL)
   661 	{
   662 		return NULL;
   663 	}
   664 
   665 	if (pSE->GetRefEHandle() != hndl)
   666 	{
   667 		return NULL;
   668 	}
   669 
   670 	return pStoredEdict;
   671 }
   672 
   673 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
   674 {
   675 	IServerEntity *pEntOther = pEnt->GetIServerEntity();
   676 
   677 	if (pEntOther == NULL)
   678 	{
   679 		return;
   680 	}
   681 
   682 	hndl.Set(pEntOther);
   683 }
   684 
   685 const char *CHalfLife2::GetCurrentMap()
   686 {
   687 	return STRING(gpGlobals->mapname);
   688 }
   689 
   690 void CHalfLife2::ServerCommand(const char *buffer)
   691 {
   692 	engine->ServerCommand(buffer);
   693 }
   694 
   695 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
   696 {
   697 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
   698 	CBaseHandle hndl = pUnknown->GetRefEHandle();
   699 	return (hndl.ToInt() | (1<<31));
   700 }
   701 
   702 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
   703 {
   704 	CEntInfo *pInfo = NULL;
   705 
   706 	if (entRef & (1<<31))
   707 	{
   708 		/* Proper ent reference */
   709 		int hndlValue = entRef & ~(1<<31);
   710 		CBaseHandle hndl(hndlValue);
   711 
   712 		pInfo = LookupEntity(hndl.GetEntryIndex());
   713 		if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
   714 		{
   715 			return NULL;
   716 		}
   717 	}
   718 	else
   719 	{
   720 		/* Old style index only */
   721 		pInfo = LookupEntity(entRef);
   722 	}
   723 
   724 	if (!pInfo)
   725 	{
   726 		return NULL;
   727 	}
   728 
   729 	IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
   730 	if (pUnk)
   731 	{
   732 		return pUnk->GetBaseEntity();
   733 	}
   734 
   735 	return NULL;
   736 }
   737 
   738 /**
   739  * Retrieves the CEntInfo pointer from g_EntList for a given entity index
   740  */
   741 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
   742 {
   743 	if (!g_EntList || entInfoOffset == -1)
   744 	{
   745 		/* Attempt to use engine interface instead */
   746 		static CEntInfo tempInfo;
   747 		tempInfo.m_pNext = NULL;
   748 		tempInfo.m_pPrev = NULL;
   749 
   750 		edict_t *pEdict = PEntityOfEntIndex(entIndex);
   751 
   752 		if (!pEdict)
   753 		{
   754 			return NULL;
   755 		}
   756 
   757 		IServerUnknown *pUnk = pEdict->GetUnknown();
   758 
   759 		if (!pUnk)
   760 		{
   761 			return NULL;
   762 		}
   763 
   764 		tempInfo.m_pEntity = pUnk;
   765 		tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
   766 
   767 		return &tempInfo;
   768 	}
   769 
   770 	CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
   771 	return &pArray[entIndex];
   772 }
   773 
   774 /**
   775 	SERIAL_MASK = 0x7fff (15 bits)
   776 
   777 	#define	MAX_EDICT_BITS				11
   778 	#define NUM_ENT_ENTRY_BITS		(MAX_EDICT_BITS + 1)
   779 	m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS); 
   780 	
   781 	Top 5 bits of a handle are unused.
   782 	Bit 31 - Our 'reference' flag indicator
   783 */
   784 
   785 cell_t CHalfLife2::IndexToReference(int entIndex)
   786 {
   787 	CBaseEntity *pEnt = ReferenceToEntity(entIndex);
   788 	if (!pEnt)
   789 	{
   790 		return INVALID_EHANDLE_INDEX;
   791 	}
   792 
   793 	return EntityToReference(pEnt);
   794 }
   795 
   796 int CHalfLife2::ReferenceToIndex(cell_t entRef)
   797 {
   798 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
   799 	{
   800 		return INVALID_EHANDLE_INDEX;
   801 	}
   802 
   803 	if (entRef & (1<<31))
   804 	{
   805 		/* Proper ent reference */
   806 		int hndlValue = entRef & ~(1<<31);
   807 		CBaseHandle hndl(hndlValue);
   808 
   809 		CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
   810 
   811 		if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
   812 		{
   813 			return INVALID_EHANDLE_INDEX;
   814 		}
   815 
   816 		return hndl.GetEntryIndex();
   817 	}
   818 
   819 	return entRef;
   820 }
   821 
   822 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
   823 {
   824 	if (pEntity == NULL)
   825 	{
   826 		return INVALID_EHANDLE_INDEX;
   827 	}
   828 
   829 	IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
   830 	CBaseHandle hndl = pUnknown->GetRefEHandle();
   831 
   832 	if (hndl.GetEntryIndex() >= MAX_EDICTS)
   833 	{
   834 		return (hndl.ToInt() | (1<<31));
   835 	}
   836 	else
   837 	{
   838 		return hndl.GetEntryIndex();
   839 	}
   840 }
   841 
   842 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
   843 {
   844 	if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
   845 	{
   846 		return INVALID_EHANDLE_INDEX;
   847 	}
   848 
   849 	int hndlValue = entRef & ~(1<<31);
   850 	CBaseHandle hndl(hndlValue);
   851 
   852 	if (hndl.GetEntryIndex() < MAX_EDICTS)
   853 	{
   854 		return hndl.GetEntryIndex();
   855 	}
   856 
   857 	return entRef;
   858 }
   859 
   860 void *CHalfLife2::GetGlobalEntityList()
   861 {
   862 	return g_EntList;
   863 }