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