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