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