2 * vim: set ts=4 sw=4 tw=99 noet :
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;
79 CHalfLife2::CHalfLife2()
84 CHalfLife2::~CHalfLife2()
86 for (NameHashSet<DataTableInfo *>::iterator iter = m_Classes.iter(); !iter.empty(); iter.next())
89 for (DataTableMap::iterator iter = m_Maps.iter(); !iter.empty(); iter.next())
93 #if SOURCE_ENGINE != SE_DARKMESSIAH
94 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
97 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
98 bool is_original_engine = false;
101 void CHalfLife2::OnSourceModStartup(bool late)
103 #if SOURCE_ENGINE != SE_DARKMESSIAH
105 /* The Ship currently is the only known game to use an older version of the engine */
106 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
107 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
109 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
112 is_original_engine = true;
114 else if (g_pSharedChangeInfo == NULL)
116 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
121 void CHalfLife2::OnSourceModAllInitialized()
123 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
124 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
125 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
126 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
127 sharesys->AddInterface(NULL, this);
130 void CHalfLife2::OnSourceModAllInitialized_Post()
132 InitLogicalEntData();
136 void CHalfLife2::InitLogicalEntData()
141 * gEntList and/or g_pEntityList
143 * First try to lookup pointer directly for platforms with symbols.
144 * If symbols aren't present (Windows or stripped Linux/Mac),
145 * attempt find via LevelShutdown + offset
147 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
149 #if !defined PLATFORM_WINDOWS
152 // Key exists so notify if lookup fails, but try other method.
153 g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
158 g_EntList = reinterpret_cast<void *>(addr);
159 #if !defined PLATFORM_WINDOWS
167 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
169 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
175 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
180 if (!g_pGameConf->GetOffset("gEntList", &offset))
182 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
186 g_EntList = *reinterpret_cast<void **>(addr + offset);
191 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
195 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
197 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
202 void CHalfLife2::InitCommandLine()
204 char path[PLATFORM_MAX_PATH];
207 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" TIER0_NAME);
209 if (!g_LibSys.IsPathFile(path))
211 g_Logger.LogError("Could not find path for: " TIER0_NAME);
215 ILibrary *lib = g_LibSys.OpenLibrary(path, error, sizeof(error));
216 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
218 /* '_Tier0' dropped on Alien Swarm version */
219 if (m_pGetCommandLine == NULL)
221 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
224 if (m_pGetCommandLine == NULL)
226 /* We probably have a Ship engine. */
228 g_SourceMod.BuildPath(Path_Game, path, sizeof(path), "../bin/" VSTDLIB_NAME);
229 if (!g_LibSys.IsPathFile(path))
231 g_Logger.LogError("Could not find path for: " VSTDLIB_NAME);
235 if ((lib = g_LibSys.OpenLibrary(path, error, sizeof(error))) == NULL)
237 g_Logger.LogError("Could not load %s: %s", path, error);
241 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
243 if (m_pGetCommandLine == NULL)
245 g_Logger.LogError("Could not locate any command line functionality");
252 ICommandLine *CHalfLife2::GetValveCommandLine()
254 if (!m_pGetCommandLine)
257 return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
260 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
261 bool CHalfLife2::IsOriginalEngine()
263 return is_original_engine;
267 #if SOURCE_ENGINE != SE_DARKMESSIAH
268 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
270 #if SOURCE_ENGINE == SE_DOTA
271 return engine->GetChangeAccessor( IndexOfEdict((const edict_t *)this) );
273 return engine->GetChangeAccessor( (const edict_t *)this );
278 bool UTIL_FindInSendTable(SendTable *pTable,
280 sm_sendprop_info_t *info,
284 int props = pTable->GetNumProps();
287 for (int i=0; i<props; i++)
289 prop = pTable->GetProp(i);
290 pname = prop->GetName();
291 if (pname && strcmp(name, pname) == 0)
294 info->actual_offset = offset + info->prop->GetOffset();
297 if (prop->GetDataTable())
299 if (UTIL_FindInSendTable(prop->GetDataTable(),
302 offset + prop->GetOffset())
313 bool UTIL_FindDataMapInfo(datamap_t *pMap, const char *name, sm_datatable_info_t *pDataTable)
317 for (int i = 0; i < pMap->dataNumFields; ++i)
319 if (pMap->dataDesc[i].fieldName == NULL)
323 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
325 pDataTable->prop = &(pMap->dataDesc[i]);
326 pDataTable->actual_offset = GetTypeDescOffs(pDataTable->prop);
329 if (pMap->dataDesc[i].td == NULL || !UTIL_FindDataMapInfo(pMap->dataDesc[i].td, name, pDataTable))
334 pDataTable->actual_offset += GetTypeDescOffs(&(pMap->dataDesc[i]));
338 pMap = pMap->baseMap;
344 ServerClass *CHalfLife2::FindServerClass(const char *classname)
346 DataTableInfo *pInfo = _FindServerClass(classname);
354 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
356 DataTableInfo *pInfo = NULL;
357 if (!m_Classes.retrieve(classname, &pInfo))
359 ServerClass *sc = gamedll->GetAllServerClasses();
362 if (strcmp(classname, sc->GetName()) == 0)
364 pInfo = new DataTableInfo(sc);
365 m_Classes.insert(classname, pInfo);
377 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
379 DataTableInfo *pInfo;
380 sm_sendprop_info_t *prop;
382 if ((pInfo = _FindServerClass(classname)) == NULL)
387 if (!pInfo->lookup.retrieve(offset, info))
389 sm_sendprop_info_t temp_info;
391 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
396 pInfo->lookup.insert(offset, temp_info);
403 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
405 sm_sendprop_info_t info;
407 if (!FindSendPropInfo(classname, offset, &info))
415 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
417 sm_datatable_info_t dt_info;
419 if (!(this->FindDataMapInfo(pMap, offset, &dt_info)))
427 bool CHalfLife2::FindDataMapInfo(datamap_t *pMap, const char *offset, sm_datatable_info_t *pDataTable)
429 DataTableMap::Insert i = m_Maps.findForAdd(pMap);
431 m_Maps.add(i, pMap, new DataMapCache());
433 DataMapCache *cache = i->value;
435 sm_datatable_info_t *pNewTable;
436 if (!cache->retrieve(offset, pDataTable))
438 if (!UTIL_FindDataMapInfo(pMap, offset, pDataTable))
440 cache->insert(offset, *pDataTable);
446 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
448 #if SOURCE_ENGINE != SE_DARKMESSIAH
449 if (g_pSharedChangeInfo != NULL)
453 pEdict->StateChanged(offset);
457 pEdict->StateChanged();
463 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
467 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
469 #ifndef USE_PROTOBUF_USERMESSAGES
470 bf_write *pBitBuf = NULL;
472 cell_t players[] = {client};
474 if (dest == HUD_PRINTTALK)
476 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
478 /* Use SayText user message instead */
479 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
482 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
484 #if SOURCE_ENGINE == SE_DOTA
485 CUserMsg_SayText *pMsg;
486 if ((pMsg = (CUserMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
492 pMsg->set_text(buffer);
493 pMsg->set_chat(false);
494 #elif SOURCE_ENGINE == SE_CSGO
495 CCSUsrMsg_SayText *pMsg;
496 if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
501 pMsg->set_ent_idx(0);
502 pMsg->set_text(buffer);
503 pMsg->set_chat(false);
505 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
510 pBitBuf->WriteByte(0);
511 pBitBuf->WriteString(buffer);
512 pBitBuf->WriteByte(1);
515 g_UserMsgs.EndMessage();
521 #if SOURCE_ENGINE == SE_DOTA
522 CUserMsg_TextMsg *pMsg;
523 if ((pMsg = (CUserMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
528 pMsg->set_dest(dest);
529 pMsg->add_param(msg);
534 #elif SOURCE_ENGINE == SE_CSGO
535 CCSUsrMsg_TextMsg *pMsg;
536 if ((pMsg = (CCSUsrMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
541 // Client tries to read all 5 'params' and will crash if less
542 pMsg->set_msg_dst(dest);
543 pMsg->add_params(msg);
544 pMsg->add_params("");
545 pMsg->add_params("");
546 pMsg->add_params("");
547 pMsg->add_params("");
549 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
554 pBitBuf->WriteByte(dest);
555 pBitBuf->WriteString(msg);
558 g_UserMsgs.EndMessage();
563 bool CHalfLife2::HintTextMsg(int client, const char *msg)
565 cell_t players[] = {client};
567 #if SOURCE_ENGINE == SE_DOTA
568 CUserMsg_HintText *pMsg;
569 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
574 pMsg->set_message(msg);
575 #elif SOURCE_ENGINE == SE_CSGO
576 CCSUsrMsg_HintText *pMsg;
577 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
584 bf_write *pBitBuf = NULL;
586 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
591 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
592 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
594 pBitBuf->WriteByte(1);
596 pBitBuf->WriteString(msg);
598 g_UserMsgs.EndMessage();
603 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
605 #if SOURCE_ENGINE == SE_DOTA
606 CUserMsg_HintText *pMsg;
607 if ((pMsg = (CUserMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
612 pMsg->set_message(msg);
613 #elif SOURCE_ENGINE == SE_CSGO
614 CCSUsrMsg_HintText *pMsg;
615 if ((pMsg = (CCSUsrMsg_HintText *)g_UserMsgs.StartProtobufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
622 bf_write *pBitBuf = NULL;
624 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
629 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
630 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
632 pBitBuf->WriteByte(1);
634 pBitBuf->WriteString(msg);
637 g_UserMsgs.EndMessage();
642 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
644 KeyValues *SubKey = NULL;
646 cell_t players[] = {client};
648 #if SOURCE_ENGINE == SE_DOTA
649 CUserMsg_VGUIMenu *pMsg;
650 if ((pMsg = (CUserMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
654 #elif SOURCE_ENGINE == SE_CSGO
655 CCSUsrMsg_VGUIMenu *pMsg;
656 if ((pMsg = (CCSUsrMsg_VGUIMenu *)g_UserMsgs.StartProtobufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
661 bf_write *pBitBuf = NULL;
662 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
670 SubKey = data->GetFirstSubKey();
674 SubKey = SubKey->GetNextKey();
676 SubKey = data->GetFirstSubKey();
679 #if SOURCE_ENGINE == SE_DOTA
680 pMsg->set_name(name);
681 pMsg->set_show(show);
685 CUserMsg_VGUIMenu_Keys *key = pMsg->add_keys();
686 key->set_name(SubKey->GetName());
687 key->set_value(SubKey->GetString());
688 SubKey = SubKey->GetNextKey();
690 #elif SOURCE_ENGINE == SE_CSGO
691 pMsg->set_name(name);
692 pMsg->set_show(show);
696 CCSUsrMsg_VGUIMenu_Subkey *key = pMsg->add_subkeys();
697 key->set_name(SubKey->GetName());
698 key->set_str(SubKey->GetString());
699 SubKey = SubKey->GetNextKey();
702 pBitBuf->WriteString(name);
703 pBitBuf->WriteByte((show) ? 1 : 0);
704 pBitBuf->WriteByte(count);
707 pBitBuf->WriteString(SubKey->GetName());
708 pBitBuf->WriteString(SubKey->GetString());
709 SubKey = SubKey->GetNextKey();
713 g_UserMsgs.EndMessage();
718 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
720 DelayedFakeCliCmd *pFake;
722 if (m_FreeCmds.empty())
724 pFake = new DelayedFakeCliCmd;
726 pFake = m_FreeCmds.front();
730 pFake->client = client;
731 pFake->userid = userid;
732 pFake->cmd.assign(cmd);
734 m_CmdQueue.push(pFake);
737 void CHalfLife2::ProcessFakeCliCmdQueue()
739 while (!m_CmdQueue.empty())
741 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
743 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
745 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
746 #if SOURCE_ENGINE == SE_DOTA
747 engine->ClientCommand(pPlayer->GetIndex(), "%s", pFake->cmd.c_str());
749 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
757 bool CHalfLife2::IsLANServer()
759 sv_lan = icvar->FindVar("sv_lan");
766 return (sv_lan->GetInt() != 0);
769 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
771 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
772 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
774 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
779 Assert(_heapchk() == _HEAPOK);
782 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
786 // load file into a null-terminated buffer
787 int fileSize = filesystem->Size(f);
788 char *buffer = (char *)MemAllocScratch(fileSize + 1);
792 filesystem->Read(buffer, fileSize, f); // read into local buffer
794 buffer[fileSize] = 0; // null terminate file as EOF
796 filesystem->Close( f ); // close file after reading
798 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
806 return kv->LoadFromFile(filesystem, resourceName, pathID);
810 void CHalfLife2::PushCommandStack(const CCommand *cmd)
812 CachedCommandInfo info;
815 #if SOURCE_ENGINE <= SE_DARKMESSIAH
816 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
819 m_CommandStack.push(info);
822 const CCommand *CHalfLife2::PeekCommandStack()
824 if (m_CommandStack.empty())
829 return m_CommandStack.front().args;
832 void CHalfLife2::PopCommandStack()
834 m_CommandStack.pop();
837 const char *CHalfLife2::CurrentCommandName()
839 #if SOURCE_ENGINE >= SE_ORANGEBOX
840 return m_CommandStack.front().args->Arg(0);
842 return m_CommandStack.front().cmd;
846 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
848 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
849 if (!pPlayer || !pPlayer->IsConnected() || pPlayer->IsInKickQueue())
854 pPlayer->MarkAsBeingKicked();
856 DelayedKickInfo kick;
858 kick.client = client;
859 kick.userid = userid;
860 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
862 m_DelayedKicks.push(kick);
865 void CHalfLife2::ProcessDelayedKicks()
867 while (!m_DelayedKicks.empty())
869 DelayedKickInfo info = m_DelayedKicks.first();
870 m_DelayedKicks.pop();
872 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
873 if (player == NULL || player->GetUserId() != info.userid)
878 player->Kick(info.buffer);
882 edict_t *CHalfLife2::EdictOfIndex(int index)
884 return ::PEntityOfEntIndex(index);
887 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
889 return ::IndexOfEdict(pEnt);
892 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
899 int index = hndl.GetEntryIndex();
901 edict_t *pStoredEdict;
902 CBaseEntity *pStoredEntity;
904 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
909 if (pStoredEdict == NULL || pStoredEntity == NULL)
914 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
921 if (pSE->GetRefEHandle() != hndl)
929 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
931 IServerEntity *pEntOther = pEnt->GetIServerEntity();
933 if (pEntOther == NULL)
941 const char *CHalfLife2::GetCurrentMap()
943 return STRING(gpGlobals->mapname);
946 void CHalfLife2::ServerCommand(const char *buffer)
948 engine->ServerCommand(buffer);
951 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
953 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
954 CBaseHandle hndl = pUnknown->GetRefEHandle();
955 return (hndl.ToInt() | (1<<31));
958 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
960 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
965 CEntInfo *pInfo = NULL;
967 if (entRef & (1<<31))
969 /* Proper ent reference */
970 int hndlValue = entRef & ~(1<<31);
971 CBaseHandle hndl(hndlValue);
973 pInfo = LookupEntity(hndl.GetEntryIndex());
974 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
981 /* Old style index only */
982 pInfo = LookupEntity(entRef);
990 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
993 return pUnk->GetBaseEntity();
1000 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
1002 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
1004 // Make sure that our index is within the bounds of the global ent array
1005 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
1010 if (!g_EntList || entInfoOffset == -1)
1012 /* Attempt to use engine interface instead */
1013 static CEntInfo tempInfo;
1014 tempInfo.m_pNext = NULL;
1015 tempInfo.m_pPrev = NULL;
1017 edict_t *pEdict = PEntityOfEntIndex(entIndex);
1024 IServerUnknown *pUnk = pEdict->GetUnknown();
1031 tempInfo.m_pEntity = pUnk;
1032 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
1037 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
1038 return &pArray[entIndex];
1042 SERIAL_MASK = 0x7fff (15 bits)
1044 #define MAX_EDICT_BITS 11
1045 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
1046 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
1048 Top 5 bits of a handle are unused.
1049 Bit 31 - Our 'reference' flag indicator
1052 cell_t CHalfLife2::IndexToReference(int entIndex)
1054 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
1057 return INVALID_EHANDLE_INDEX;
1060 return EntityToReference(pEnt);
1063 int CHalfLife2::ReferenceToIndex(cell_t entRef)
1065 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1067 return INVALID_EHANDLE_INDEX;
1070 if (entRef & (1<<31))
1072 /* Proper ent reference */
1073 int hndlValue = entRef & ~(1<<31);
1074 CBaseHandle hndl(hndlValue);
1076 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
1078 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
1080 return INVALID_EHANDLE_INDEX;
1083 return hndl.GetEntryIndex();
1089 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
1091 if (pEntity == NULL)
1093 return INVALID_EHANDLE_INDEX;
1096 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1097 CBaseHandle hndl = pUnknown->GetRefEHandle();
1099 if (hndl == INVALID_EHANDLE_INDEX)
1101 return INVALID_EHANDLE_INDEX;
1104 if (hndl.GetEntryIndex() >= MAX_EDICTS)
1106 return (hndl.ToInt() | (1<<31));
1110 return hndl.GetEntryIndex();
1114 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
1116 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1118 return INVALID_EHANDLE_INDEX;
1121 int hndlValue = entRef & ~(1<<31);
1122 CBaseHandle hndl(hndlValue);
1124 if (hndl.GetEntryIndex() < MAX_EDICTS)
1126 return hndl.GetEntryIndex();
1132 void *CHalfLife2::GetGlobalEntityList()
1137 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1139 return prop->GetOffset();
1142 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
1144 if (pEdict == NULL || pEdict->IsFree())
1149 IServerUnknown *pUnk = pEdict->GetUnknown();
1155 CBaseEntity * pEntity = pUnk->GetBaseEntity();
1157 if (pEntity == NULL)
1162 return GetEntityClassname(pEntity);
1165 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
1167 static int offset = -1;
1170 CBaseEntity *pGetterEnt = ReferenceToEntity(0);
1171 datamap_t *pMap = GetDataMap(pGetterEnt);
1173 sm_datatable_info_t info;
1174 if (!FindDataMapInfo(pMap, "m_iClassname", &info))
1179 offset = info.actual_offset;
1182 return *(const char **)(((unsigned char *)pEntity) + offset);
1185 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1186 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
1188 static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
1189 if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
1192 static size_t helperCmdLen = strlen(pHelperCmd->GetName());
1194 CUtlVector<CUtlString> results;
1195 pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
1196 if (results.Count() == 0)
1199 // Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
1200 // so skip ahead to start of map path/name
1202 // Like the engine, we're only going to deal with the first match.
1204 strncopy(outFullname, &results[0][helperCmdLen + 1], size);
1210 bool CHalfLife2::IsMapValid(const char *map)
1212 if (!map || !map[0])
1215 bool ret = engine->IsMapValid(map);
1216 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1219 static char szFuzzyName[PLATFORM_MAX_PATH];
1220 if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
1222 ret = engine->IsMapValid(szFuzzyName);