Build against MM:S 1.10.
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
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.
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
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/>.
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>.
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>
41 #include "LibrarySys.h"
42 #include "logic_bridge.h"
43 #include <tier0/mem.h>
45 #if SOURCE_ENGINE == SE_DOTA
46 #include <game/shared/protobuf/usermessages.pb.h>
47 #elif SOURCE_ENGINE == SE_CSGO
48 #include <cstrike15_usermessages.pb.h>
52 typedef ICommandLine *(*FakeGetCommandLine)();
55 #define TIER0_NAME "tier0.dll"
56 #define VSTDLIB_NAME "vstdlib.dll"
57 #elif defined __APPLE__
58 #define TIER0_NAME "libtier0.dylib"
59 #define VSTDLIB_NAME "libvstdlib.dylib"
60 #elif defined __linux__
61 #if SOURCE_ENGINE == SE_HL2DM || SOURCE_ENGINE == SE_DODS || SOURCE_ENGINE == SE_CSS || SOURCE_ENGINE == SE_TF2 || SOURCE_ENGINE == SE_LEFT4DEAD2
62 #define TIER0_NAME "libtier0_srv.so"
63 #define VSTDLIB_NAME "libvstdlib_srv.so"
64 #elif SOURCE_ENGINE >= SE_LEFT4DEAD
65 #define TIER0_NAME "libtier0.so"
66 #define VSTDLIB_NAME "libvstdlib.so"
68 #define TIER0_NAME "tier0_i486.so"
69 #define VSTDLIB_NAME "vstdlib_i486.so"
74 ConVar *sv_lan = NULL;
76 static void *g_EntList = NULL;
77 static int entInfoOffset = -1;
82 int HashFunction<datamap_t *>(datamap_t * const &k)
84 return reinterpret_cast<int>(k);
88 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
94 CHalfLife2::CHalfLife2()
96 m_pClasses = sm_trie_create();
99 CHalfLife2::~CHalfLife2()
101 sm_trie_destroy(m_pClasses);
103 List<DataTableInfo *>::iterator iter;
104 DataTableInfo *pInfo;
105 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
113 THash<datamap_t *, DataMapTrie>::iterator h_iter;
114 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
116 if (h_iter->val.trie)
118 sm_trie_destroy(h_iter->val.trie);
119 h_iter->val.trie = NULL;
126 #if SOURCE_ENGINE != SE_DARKMESSIAH
127 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
130 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
131 bool is_original_engine = false;
134 void CHalfLife2::OnSourceModStartup(bool late)
136 #if SOURCE_ENGINE != SE_DARKMESSIAH
138 /* The Ship currently is the only known game to use an older version of the engine */
139 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
140 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
142 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
145 is_original_engine = true;
147 else if (g_pSharedChangeInfo == NULL)
149 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
154 void CHalfLife2::OnSourceModAllInitialized()
156 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
157 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
158 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
159 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
160 sharesys->AddInterface(NULL, this);
163 void CHalfLife2::OnSourceModAllInitialized_Post()
165 InitLogicalEntData();
169 void CHalfLife2::InitLogicalEntData()
174 * gEntList and/or g_pEntityList
176 * First try to lookup pointer directly for platforms with symbols.
177 * If symbols aren't present (Windows or stripped Linux/Mac),
178 * attempt find via LevelShutdown + offset
180 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
182 #if !defined PLATFORM_WINDOWS
185 // Key exists so notify if lookup fails, but try other method.
186 g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
191 g_EntList = reinterpret_cast<void *>(addr);
192 #if !defined PLATFORM_WINDOWS
200 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
202 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
208 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
213 if (!g_pGameConf->GetOffset("gEntList", &offset))
215 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
219 g_EntList = *reinterpret_cast<void **>(addr + offset);
224 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
228 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
230 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
235 void CHalfLife2::InitCommandLine()
237 char path[PLATFORM_MAX_PATH];
240 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
242 if (!g_LibSys.IsPathFile(path))
244 g_Logger.LogError("Could not find path for: " TIER0_NAME);
248 ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
249 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
251 /* '_Tier0' dropped on Alien Swarm version */
252 if (m_pGetCommandLine == NULL)
254 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
257 if (m_pGetCommandLine == NULL)
259 /* We probably have a Ship engine. */
261 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
262 if (!g_LibSys.IsPathFile(path))
264 g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
268 if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
270 g_Logger.LogError("Could not load %s: %s", path, error);
274 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
276 if (m_pGetCommandLine == NULL)
278 g_Logger.LogError("Could not locate any command line functionality");
285 ICommandLine *CHalfLife2::GetValveCommandLine()
287 if (!m_pGetCommandLine)
290 return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
293 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
294 bool CHalfLife2::IsOriginalEngine()
296 return is_original_engine;
300 #if SOURCE_ENGINE != SE_DARKMESSIAH
301 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
303 #if SOURCE_ENGINE == SE_DOTA
304 return engine->GetChangeAccessor( IndexOfEdict((const edict_t *)this) );
306 return engine->GetChangeAccessor( (const edict_t *)this );
311 bool UTIL_FindInSendTable(SendTable *pTable,
313 sm_sendprop_info_t *info,
317 int props = pTable->GetNumProps();
320 for (int i=0; i<props; i++)
322 prop = pTable->GetProp(i);
323 pname = prop->GetName();
324 if (pname && strcmp(name, pname) == 0)
327 info->actual_offset = offset + info->prop->GetOffset();
330 if (prop->GetDataTable())
332 if (UTIL_FindInSendTable(prop->GetDataTable(),
335 offset + prop->GetOffset())
346 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name, bool *isNested)
355 for (int i=0; i<pMap->dataNumFields; i++)
357 if (pMap->dataDesc[i].fieldName == NULL)
361 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
363 return &(pMap->dataDesc[i]);
365 if (pMap->dataDesc[i].td)
369 *isNested = (UTIL_FindInDataMap(pMap->dataDesc[i].td, name, NULL) != NULL);
376 } else { // Use the old behaviour, we dont want to spring this on extensions - even if they're doing bad things.
377 typedescription_t *_td;
378 if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name, NULL)) != NULL)
385 pMap = pMap->baseMap;
391 ServerClass *CHalfLife2::FindServerClass(const char *classname)
393 DataTableInfo *pInfo = _FindServerClass(classname);
403 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
405 DataTableInfo *pInfo = NULL;
407 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
409 ServerClass *sc = gamedll->GetAllServerClasses();
412 if (strcmp(classname, sc->GetName()) == 0)
414 pInfo = new DataTableInfo;
416 sm_trie_insert(m_pClasses, classname, pInfo);
417 m_Tables.push_back(pInfo);
431 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
433 DataTableInfo *pInfo;
434 sm_sendprop_info_t *prop;
436 if ((pInfo = _FindServerClass(classname)) == NULL)
441 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
443 sm_sendprop_info_t temp_info;
445 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
450 pInfo->lookup.insert(offset, temp_info);
461 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
463 sm_sendprop_info_t info;
465 if (!FindSendPropInfo(classname, offset, &info))
473 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
475 return this->FindInDataMap(pMap, offset, NULL);
478 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset, bool *isNested)
480 typedescription_t *td = NULL;
481 DataMapTrie &val = m_Maps[pMap];
485 val.trie = sm_trie_create();
487 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
489 if ((td = UTIL_FindInDataMap(pMap, offset, isNested)) != NULL)
491 sm_trie_insert(val.trie, offset, td);
498 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
500 #if SOURCE_ENGINE != SE_DARKMESSIAH
501 if (g_pSharedChangeInfo != NULL)
505 pEdict->StateChanged(offset);
509 pEdict->StateChanged();
515 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
519 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
521 #ifndef USE_PROTOBUF_USERMESSAGES
522 bf_write *pBitBuf = NULL;
524 cell_t players[] = {client};
526 if (dest == HUD_PRINTTALK)
528 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
530 /* Use SayText user message instead */
531 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
534 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
536 #if SOURCE_ENGINE == SE_DOTA
537 CUserMsg_SayText *pMsg;
538 if ((pMsg = (CUserMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
544 pMsg->set_text(buffer);
545 pMsg->set_chat(false);
546 #elif SOURCE_ENGINE == SE_CSGO
547 CCSUsrMsg_SayText *pMsg;
548 if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
553 pMsg->set_ent_idx(0);
554 pMsg->set_text(buffer);
555 pMsg->set_chat(false);
557 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
562 pBitBuf->WriteByte(0);
563 pBitBuf->WriteString(buffer);
564 pBitBuf->WriteByte(1);
567 g_UserMsgs.EndMessage();
573 #if SOURCE_ENGINE == SE_DOTA
574 CUserMsg_TextMsg *pMsg;
575 if ((pMsg = (CUserMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
580 pMsg->set_dest(dest);
581 pMsg->add_param(msg);
586 #elif SOURCE_ENGINE == SE_CSGO
587 CCSUsrMsg_TextMsg *pMsg;
588 if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
593 // Client tries to read all 5 'params' and will crash if less
594 pMsg->set_msg_dst(dest);
595 pMsg->add_params(msg);
596 pMsg->add_params("");
597 pMsg->add_params("");
598 pMsg->add_params("");
599 pMsg->add_params("");
601 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
606 pBitBuf->WriteByte(dest);
607 pBitBuf->WriteString(msg);
610 g_UserMsgs.EndMessage();
615 bool CHalfLife2::HintTextMsg(int client, const char *msg)
617 cell_t players[] = {client};
619 #if SOURCE_ENGINE == SE_DOTA
620 CUserMsg_HintText *pMsg;
621 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
626 pMsg->set_message(msg);
627 #elif SOURCE_ENGINE == SE_CSGO
628 CCSUsrMsg_HintText *pMsg;
629 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
636 bf_write *pBitBuf = NULL;
638 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
643 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
644 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
646 pBitBuf->WriteByte(1);
648 pBitBuf->WriteString(msg);
650 g_UserMsgs.EndMessage();
655 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
657 #if SOURCE_ENGINE == SE_DOTA
658 CUserMsg_HintText *pMsg;
659 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
664 pMsg->set_message(msg);
665 #elif SOURCE_ENGINE == SE_CSGO
666 CCSUsrMsg_HintText *pMsg;
667 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
674 bf_write *pBitBuf = NULL;
676 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
681 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
682 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
684 pBitBuf->WriteByte(1);
686 pBitBuf->WriteString(msg);
689 g_UserMsgs.EndMessage();
694 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
696 KeyValues *SubKey = NULL;
698 cell_t players[] = {client};
700 #if SOURCE_ENGINE == SE_DOTA
701 CUserMsg_VGUIMenu *pMsg;
702 if ((pMsg = (CUserMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
706 #elif SOURCE_ENGINE == SE_CSGO
707 CCSUsrMsg_VGUIMenu *pMsg;
708 if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
713 bf_write *pBitBuf = NULL;
714 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
722 SubKey = data->GetFirstSubKey();
726 SubKey = SubKey->GetNextKey();
728 SubKey = data->GetFirstSubKey();
731 #if SOURCE_ENGINE == SE_DOTA
732 pMsg->set_name(name);
733 pMsg->set_show(show);
737 CUserMsg_VGUIMenu_Keys *key = pMsg->add_keys();
738 key->set_name(SubKey->GetName());
739 key->set_value(SubKey->GetString());
740 SubKey = SubKey->GetNextKey();
742 #elif SOURCE_ENGINE == SE_CSGO
743 pMsg->set_name(name);
744 pMsg->set_show(show);
748 CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
749 key->set_name(SubKey->GetName());
750 key->set_str(SubKey->GetString());
751 SubKey = SubKey->GetNextKey();
754 pBitBuf->WriteString(name);
755 pBitBuf->WriteByte((show) ? 1 : 0);
756 pBitBuf->WriteByte(count);
759 pBitBuf->WriteString(SubKey->GetName());
760 pBitBuf->WriteString(SubKey->GetString());
761 SubKey = SubKey->GetNextKey();
765 g_UserMsgs.EndMessage();
770 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
772 DelayedFakeCliCmd *pFake;
774 if (m_FreeCmds.empty())
776 pFake = new DelayedFakeCliCmd;
778 pFake = m_FreeCmds.front();
782 pFake->client = client;
783 pFake->userid = userid;
784 pFake->cmd.assign(cmd);
786 m_CmdQueue.push(pFake);
789 void CHalfLife2::ProcessFakeCliCmdQueue()
791 while (!m_CmdQueue.empty())
793 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
795 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
797 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
798 #if SOURCE_ENGINE == SE_DOTA
799 engine->ClientCommand(pPlayer->GetIndex(), "%s", pFake->cmd.c_str());
801 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
809 bool CHalfLife2::IsLANServer()
811 sv_lan = icvar->FindVar("sv_lan");
818 return (sv_lan->GetInt() != 0);
821 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
823 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
824 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
826 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
831 Assert(_heapchk() == _HEAPOK);
834 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
838 // load file into a null-terminated buffer
839 int fileSize = filesystem->Size(f);
840 char *buffer = (char *)MemAllocScratch(fileSize + 1);
844 filesystem->Read(buffer, fileSize, f); // read into local buffer
846 buffer[fileSize] = 0; // null terminate file as EOF
848 filesystem->Close( f ); // close file after reading
850 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
858 return kv->LoadFromFile(filesystem, resourceName, pathID);
862 void CHalfLife2::PushCommandStack(const CCommand *cmd)
864 CachedCommandInfo info;
867 #if SOURCE_ENGINE <= SE_DARKMESSIAH
868 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
871 m_CommandStack.push(info);
874 const CCommand *CHalfLife2::PeekCommandStack()
876 if (m_CommandStack.empty())
881 return m_CommandStack.front().args;
884 void CHalfLife2::PopCommandStack()
886 m_CommandStack.pop();
889 const char *CHalfLife2::CurrentCommandName()
891 #if SOURCE_ENGINE >= SE_ORANGEBOX
892 return m_CommandStack.front().args->Arg(0);
894 return m_CommandStack.front().cmd;
898 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
900 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
901 if (!pPlayer || !pPlayer->IsConnected() || pPlayer->IsInKickQueue())
906 pPlayer->MarkAsBeingKicked();
908 DelayedKickInfo kick;
910 kick.client = client;
911 kick.userid = userid;
912 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
914 m_DelayedKicks.push(kick);
917 void CHalfLife2::ProcessDelayedKicks()
919 while (!m_DelayedKicks.empty())
921 DelayedKickInfo info = m_DelayedKicks.first();
922 m_DelayedKicks.pop();
924 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
925 if (player == NULL || player->GetUserId() != info.userid)
930 player->Kick(info.buffer);
934 edict_t *CHalfLife2::EdictOfIndex(int index)
936 return ::PEntityOfEntIndex(index);
939 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
941 return ::IndexOfEdict(pEnt);
944 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
951 int index = hndl.GetEntryIndex();
953 edict_t *pStoredEdict;
954 CBaseEntity *pStoredEntity;
956 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
961 if (pStoredEdict == NULL || pStoredEntity == NULL)
966 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
973 if (pSE->GetRefEHandle() != hndl)
981 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
983 IServerEntity *pEntOther = pEnt->GetIServerEntity();
985 if (pEntOther == NULL)
993 const char *CHalfLife2::GetCurrentMap()
995 return STRING(gpGlobals->mapname);
998 void CHalfLife2::ServerCommand(const char *buffer)
1000 engine->ServerCommand(buffer);
1003 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
1005 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1006 CBaseHandle hndl = pUnknown->GetRefEHandle();
1007 return (hndl.ToInt() | (1<<31));
1010 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
1012 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1017 CEntInfo *pInfo = NULL;
1019 if (entRef & (1<<31))
1021 /* Proper ent reference */
1022 int hndlValue = entRef & ~(1<<31);
1023 CBaseHandle hndl(hndlValue);
1025 pInfo = LookupEntity(hndl.GetEntryIndex());
1026 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
1033 /* Old style index only */
1034 pInfo = LookupEntity(entRef);
1042 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
1045 return pUnk->GetBaseEntity();
1052 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
1054 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
1056 // Make sure that our index is within the bounds of the global ent array
1057 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
1062 if (!g_EntList || entInfoOffset == -1)
1064 /* Attempt to use engine interface instead */
1065 static CEntInfo tempInfo;
1066 tempInfo.m_pNext = NULL;
1067 tempInfo.m_pPrev = NULL;
1069 edict_t *pEdict = PEntityOfEntIndex(entIndex);
1076 IServerUnknown *pUnk = pEdict->GetUnknown();
1083 tempInfo.m_pEntity = pUnk;
1084 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
1089 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
1090 return &pArray[entIndex];
1094 SERIAL_MASK = 0x7fff (15 bits)
1096 #define MAX_EDICT_BITS 11
1097 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
1098 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
1100 Top 5 bits of a handle are unused.
1101 Bit 31 - Our 'reference' flag indicator
1104 cell_t CHalfLife2::IndexToReference(int entIndex)
1106 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
1109 return INVALID_EHANDLE_INDEX;
1112 return EntityToReference(pEnt);
1115 int CHalfLife2::ReferenceToIndex(cell_t entRef)
1117 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1119 return INVALID_EHANDLE_INDEX;
1122 if (entRef & (1<<31))
1124 /* Proper ent reference */
1125 int hndlValue = entRef & ~(1<<31);
1126 CBaseHandle hndl(hndlValue);
1128 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
1130 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
1132 return INVALID_EHANDLE_INDEX;
1135 return hndl.GetEntryIndex();
1141 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
1143 if (pEntity == NULL)
1145 return INVALID_EHANDLE_INDEX;
1148 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1149 CBaseHandle hndl = pUnknown->GetRefEHandle();
1151 if (hndl == INVALID_EHANDLE_INDEX)
1153 return INVALID_EHANDLE_INDEX;
1156 if (hndl.GetEntryIndex() >= MAX_EDICTS)
1158 return (hndl.ToInt() | (1<<31));
1162 return hndl.GetEntryIndex();
1166 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
1168 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1170 return INVALID_EHANDLE_INDEX;
1173 int hndlValue = entRef & ~(1<<31);
1174 CBaseHandle hndl(hndlValue);
1176 if (hndl.GetEntryIndex() < MAX_EDICTS)
1178 return hndl.GetEntryIndex();
1184 void *CHalfLife2::GetGlobalEntityList()
1189 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1191 return prop->GetOffset();
1194 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
1196 if (pEdict == NULL || pEdict->IsFree())
1201 IServerUnknown *pUnk = pEdict->GetUnknown();
1207 CBaseEntity * pEntity = pUnk->GetBaseEntity();
1209 if (pEntity == NULL)
1214 return GetEntityClassname(pEntity);
1217 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
1219 static int offset = -1;
1222 CBaseEntity *pGetterEnt = ReferenceToEntity(0);
1223 datamap_t *pMap = GetDataMap(pGetterEnt);
1224 typedescription_t *pDesc = FindInDataMap(pMap, "m_iClassname");
1225 offset = GetTypeDescOffs(pDesc);
1228 return *(const char **)(((unsigned char *)pEntity) + offset);
1231 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1232 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
1234 static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
1235 if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
1238 static size_t helperCmdLen = strlen(pHelperCmd->GetName());
1240 CUtlVector<CUtlString> results;
1241 pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
1242 if (results.Count() == 0)
1245 // Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
1246 // so skip ahead to start of map path/name
1248 // Like the engine, we're only going to deal with the first match.
1250 strncopy(outFullname, &results[0][helperCmdLen + 1], size);
1256 bool CHalfLife2::IsMapValid(const char *map)
1258 if (!map || !map[0])
1261 bool ret = engine->IsMapValid(map);
1262 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1265 static char szFuzzyName[PLATFORM_MAX_PATH];
1266 if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
1268 ret = engine->IsMapValid(szFuzzyName);