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 \
62 || SOURCE_ENGINE == SE_SDK2013 || SOURCE_ENGINE == SE_LEFT4DEAD2 || SOURCE_ENGINE == SE_NUCLEARDAWN
63 #define TIER0_NAME "libtier0_srv.so"
64 #define VSTDLIB_NAME "libvstdlib_srv.so"
65 #elif SOURCE_ENGINE >= SE_LEFT4DEAD
66 #define TIER0_NAME "libtier0.so"
67 #define VSTDLIB_NAME "libvstdlib.so"
69 #define TIER0_NAME "tier0_i486.so"
70 #define VSTDLIB_NAME "vstdlib_i486.so"
75 ConVar *sv_lan = NULL;
77 static void *g_EntList = NULL;
78 static void **g_pEntInfoList = NULL;
79 static int entInfoOffset = -1;
81 static CEntInfo *EntInfoArray()
83 if (g_EntList != NULL)
85 return (CEntInfo *)((intp)g_EntList + entInfoOffset);
87 else if (g_pEntInfoList)
89 return *(CEntInfo **)g_pEntInfoList;
95 CHalfLife2::CHalfLife2()
99 m_pGetCommandLine = NULL;
102 CHalfLife2::~CHalfLife2()
104 for (NameHashSet<DataTableInfo *>::iterator iter = m_Classes.iter(); !iter.empty(); iter.next())
107 for (DataTableMap::iterator iter = m_Maps.iter(); !iter.empty(); iter.next())
111 #if SOURCE_ENGINE != SE_DARKMESSIAH
112 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
115 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
116 bool is_original_engine = false;
119 void CHalfLife2::OnSourceModStartup(bool late)
121 #if SOURCE_ENGINE != SE_DARKMESSIAH
123 /* The Ship currently is the only known game to use an older version of the engine */
124 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
125 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
127 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
130 is_original_engine = true;
132 else if (g_pSharedChangeInfo == NULL)
134 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
139 void CHalfLife2::OnSourceModAllInitialized()
141 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
142 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
143 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
144 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
145 sharesys->AddInterface(NULL, this);
148 void CHalfLife2::OnSourceModAllInitialized_Post()
150 InitLogicalEntData();
154 void CHalfLife2::InitLogicalEntData()
159 * gEntList and/or g_pEntityList
161 * First try to lookup pointer directly for platforms with symbols.
162 * If symbols aren't present (Windows or stripped Linux/Mac),
163 * attempt find via LevelShutdown + offset
165 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
167 #if !defined PLATFORM_WINDOWS
170 // Key exists so notify if lookup fails, but try other method.
171 g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
176 g_EntList = reinterpret_cast<void *>(addr);
177 #if !defined PLATFORM_WINDOWS
184 if (g_pGameConf->GetMemSig("LevelShutdown", (void **) &addr) && addr)
187 if (!g_pGameConf->GetOffset("gEntList", &offset))
189 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
193 g_EntList = *reinterpret_cast<void **>(addr + offset);
198 // If we have g_EntList from either of the above methods, make sure we can get the offset from it to EntInfo as well
199 if (g_EntList && !g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
201 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
206 // If we don't have g_EntList or have it but don't know where EntInfo is on it, use fallback.
207 if (!g_EntList || entInfoOffset == -1)
209 g_pGameConf->GetAddress("EntInfosPtr", (void **)&g_pEntInfoList);
212 if (!g_EntList && !g_pEntInfoList)
214 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
219 void CHalfLife2::InitCommandLine()
223 if (!is_original_engine)
225 ke::AutoPtr<ILibrary> lib(g_LibSys.OpenLibrary(TIER0_NAME, error, sizeof(error)));
228 g_Logger.LogError("Could not load %s: %s", TIER0_NAME, error);
232 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine_Tier0");
234 /* '_Tier0' dropped on Alien Swarm version */
235 if (m_pGetCommandLine == NULL)
237 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
242 ke::AutoPtr<ILibrary> lib(g_LibSys.OpenLibrary(VSTDLIB_NAME, error, sizeof(error)));
245 g_Logger.LogError("Could not load %s: %s", VSTDLIB_NAME, error);
249 m_pGetCommandLine = lib->GetSymbolAddress("CommandLine");
252 if (m_pGetCommandLine == NULL)
254 g_Logger.LogError("Could not locate any command line functionality");
258 ICommandLine *CHalfLife2::GetValveCommandLine()
260 if (!m_pGetCommandLine)
263 return ((FakeGetCommandLine)((FakeGetCommandLine *)m_pGetCommandLine))();
266 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
267 bool CHalfLife2::IsOriginalEngine()
269 return is_original_engine;
273 #if SOURCE_ENGINE != SE_DARKMESSIAH
274 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
276 #if SOURCE_ENGINE == SE_DOTA
277 return engine->GetChangeAccessor( IndexOfEdict((const edict_t *)this) );
279 return engine->GetChangeAccessor( (const edict_t *)this );
284 bool UTIL_FindInSendTable(SendTable *pTable,
286 sm_sendprop_info_t *info,
290 int props = pTable->GetNumProps();
293 for (int i=0; i<props; i++)
295 prop = pTable->GetProp(i);
296 pname = prop->GetName();
297 if (pname && strcmp(name, pname) == 0)
300 info->actual_offset = offset + info->prop->GetOffset();
303 if (prop->GetDataTable())
305 if (UTIL_FindInSendTable(prop->GetDataTable(),
308 offset + prop->GetOffset())
319 bool UTIL_FindDataMapInfo(datamap_t *pMap, const char *name, sm_datatable_info_t *pDataTable)
323 for (int i = 0; i < pMap->dataNumFields; ++i)
325 if (pMap->dataDesc[i].fieldName == NULL)
329 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
331 pDataTable->prop = &(pMap->dataDesc[i]);
332 pDataTable->actual_offset = GetTypeDescOffs(pDataTable->prop);
335 if (pMap->dataDesc[i].td == NULL || !UTIL_FindDataMapInfo(pMap->dataDesc[i].td, name, pDataTable))
340 pDataTable->actual_offset += GetTypeDescOffs(&(pMap->dataDesc[i]));
344 pMap = pMap->baseMap;
350 ServerClass *CHalfLife2::FindServerClass(const char *classname)
352 DataTableInfo *pInfo = _FindServerClass(classname);
360 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
362 DataTableInfo *pInfo = NULL;
363 if (!m_Classes.retrieve(classname, &pInfo))
365 ServerClass *sc = gamedll->GetAllServerClasses();
368 if (strcmp(classname, sc->GetName()) == 0)
370 pInfo = new DataTableInfo(sc);
371 m_Classes.insert(classname, pInfo);
383 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
385 DataTableInfo *pInfo;
387 if ((pInfo = _FindServerClass(classname)) == NULL)
392 if (!pInfo->lookup.retrieve(offset, info))
394 sm_sendprop_info_t temp_info;
396 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
401 pInfo->lookup.insert(offset, temp_info);
408 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
410 sm_sendprop_info_t info;
412 if (!FindSendPropInfo(classname, offset, &info))
420 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
422 sm_datatable_info_t dt_info;
424 if (!(this->FindDataMapInfo(pMap, offset, &dt_info)))
432 bool CHalfLife2::FindDataMapInfo(datamap_t *pMap, const char *offset, sm_datatable_info_t *pDataTable)
434 DataTableMap::Insert i = m_Maps.findForAdd(pMap);
436 m_Maps.add(i, pMap, new DataMapCache());
438 DataMapCache *cache = i->value;
440 if (!cache->retrieve(offset, pDataTable))
442 if (!UTIL_FindDataMapInfo(pMap, offset, pDataTable))
444 cache->insert(offset, *pDataTable);
450 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
452 #if SOURCE_ENGINE != SE_DARKMESSIAH
453 if (g_pSharedChangeInfo != NULL)
457 pEdict->StateChanged(offset);
461 pEdict->StateChanged();
467 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
471 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
473 #ifndef USE_PROTOBUF_USERMESSAGES
474 bf_write *pBitBuf = NULL;
476 cell_t players[] = {client};
478 if (dest == HUD_PRINTTALK)
480 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
482 /* Use SayText user message instead */
483 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
486 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
488 #if SOURCE_ENGINE == SE_DOTA
489 CUserMsg_SayText *pMsg;
490 if ((pMsg = (CUserMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
496 pMsg->set_text(buffer);
497 pMsg->set_chat(false);
498 #elif SOURCE_ENGINE == SE_CSGO
499 CCSUsrMsg_SayText *pMsg;
500 if ((pMsg = (CCSUsrMsg_SayText *)g_UserMsgs.StartProtobufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
505 pMsg->set_ent_idx(0);
506 pMsg->set_text(buffer);
507 pMsg->set_chat(false);
509 if ((pBitBuf = g_UserMsgs.StartBitBufMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
514 pBitBuf->WriteByte(0);
515 pBitBuf->WriteString(buffer);
516 pBitBuf->WriteByte(1);
519 g_UserMsgs.EndMessage();
525 #if SOURCE_ENGINE == SE_DOTA
526 CUserMsg_TextMsg *pMsg;
527 if ((pMsg = (CUserMsg_TextMsg *)g_UserMsgs.StartProtobufMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
532 pMsg->set_dest(dest);
533 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());
754 m_FreeCmds.push(pFake);
758 bool CHalfLife2::IsLANServer()
760 sv_lan = icvar->FindVar("sv_lan");
767 return (sv_lan->GetInt() != 0);
770 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
772 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
773 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
775 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
780 Assert(_heapchk() == _HEAPOK);
783 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
787 // load file into a null-terminated buffer
788 int fileSize = filesystem->Size(f);
789 char *buffer = (char *)MemAllocScratch(fileSize + 1);
793 filesystem->Read(buffer, fileSize, f); // read into local buffer
795 buffer[fileSize] = 0; // null terminate file as EOF
797 filesystem->Close( f ); // close file after reading
799 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
807 return kv->LoadFromFile(filesystem, resourceName, pathID);
811 void CHalfLife2::PushCommandStack(const CCommand *cmd)
813 CachedCommandInfo info;
816 #if SOURCE_ENGINE <= SE_DARKMESSIAH
817 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
820 m_CommandStack.push(info);
823 const CCommand *CHalfLife2::PeekCommandStack()
825 if (m_CommandStack.empty())
830 return m_CommandStack.front().args;
833 void CHalfLife2::PopCommandStack()
835 m_CommandStack.pop();
838 const char *CHalfLife2::CurrentCommandName()
840 #if SOURCE_ENGINE >= SE_ORANGEBOX
841 return m_CommandStack.front().args->Arg(0);
843 return m_CommandStack.front().cmd;
847 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
849 CPlayer *pPlayer = g_Players.GetPlayerByIndex(client);
850 if (!pPlayer || !pPlayer->IsConnected() || pPlayer->IsInKickQueue())
855 pPlayer->MarkAsBeingKicked();
857 DelayedKickInfo kick;
859 kick.client = client;
860 kick.userid = userid;
861 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
863 m_DelayedKicks.push(kick);
866 void CHalfLife2::ProcessDelayedKicks()
868 while (!m_DelayedKicks.empty())
870 DelayedKickInfo info = m_DelayedKicks.first();
871 m_DelayedKicks.pop();
873 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
874 if (player == NULL || player->GetUserId() != info.userid)
879 player->Kick(info.buffer);
883 edict_t *CHalfLife2::EdictOfIndex(int index)
885 return ::PEntityOfEntIndex(index);
888 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
890 return ::IndexOfEdict(pEnt);
893 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
900 int index = hndl.GetEntryIndex();
902 edict_t *pStoredEdict;
903 CBaseEntity *pStoredEntity;
905 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
910 if (pStoredEdict == NULL || pStoredEntity == NULL)
915 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
922 if (pSE->GetRefEHandle() != hndl)
930 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
932 IServerEntity *pEntOther = pEnt->GetIServerEntity();
934 if (pEntOther == NULL)
942 const char *CHalfLife2::GetCurrentMap()
944 return STRING(gpGlobals->mapname);
947 void CHalfLife2::ServerCommand(const char *buffer)
949 engine->ServerCommand(buffer);
952 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
954 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
955 CBaseHandle hndl = pUnknown->GetRefEHandle();
956 return (hndl.ToInt() | (1<<31));
959 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
961 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
966 CEntInfo *pInfo = NULL;
968 if (entRef & (1<<31))
970 /* Proper ent reference */
971 int hndlValue = entRef & ~(1<<31);
972 CBaseHandle hndl(hndlValue);
974 pInfo = LookupEntity(hndl.GetEntryIndex());
975 if (!pInfo || pInfo->m_SerialNumber != hndl.GetSerialNumber())
982 /* Old style index only */
983 pInfo = LookupEntity(entRef);
991 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
994 return pUnk->GetBaseEntity();
1001 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
1003 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
1005 // Make sure that our index is within the bounds of the global ent array
1006 if (entIndex < 0 || entIndex >= NUM_ENT_ENTRIES)
1011 CEntInfo *entInfos = EntInfoArray();
1015 /* Attempt to use engine interface instead */
1016 static CEntInfo tempInfo;
1017 tempInfo.m_pNext = NULL;
1018 tempInfo.m_pPrev = NULL;
1020 edict_t *pEdict = PEntityOfEntIndex(entIndex);
1027 IServerUnknown *pUnk = pEdict->GetUnknown();
1034 tempInfo.m_pEntity = pUnk;
1035 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
1040 return &entInfos[entIndex];
1044 SERIAL_MASK = 0x7fff (15 bits)
1046 #define MAX_EDICT_BITS 11
1047 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
1048 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
1050 Top 5 bits of a handle are unused.
1051 Bit 31 - Our 'reference' flag indicator
1054 cell_t CHalfLife2::IndexToReference(int entIndex)
1056 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
1059 return INVALID_EHANDLE_INDEX;
1062 return EntityToReference(pEnt);
1065 int CHalfLife2::ReferenceToIndex(cell_t entRef)
1067 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1069 return INVALID_EHANDLE_INDEX;
1072 if (entRef & (1<<31))
1074 /* Proper ent reference */
1075 int hndlValue = entRef & ~(1<<31);
1076 CBaseHandle hndl(hndlValue);
1078 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
1080 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
1082 return INVALID_EHANDLE_INDEX;
1085 return hndl.GetEntryIndex();
1091 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
1093 if (pEntity == NULL)
1095 return INVALID_EHANDLE_INDEX;
1098 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
1099 CBaseHandle hndl = pUnknown->GetRefEHandle();
1101 if (hndl == INVALID_EHANDLE_INDEX)
1103 return INVALID_EHANDLE_INDEX;
1106 if (hndl.GetEntryIndex() >= MAX_EDICTS)
1108 return (hndl.ToInt() | (1<<31));
1112 return hndl.GetEntryIndex();
1116 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
1118 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
1120 return INVALID_EHANDLE_INDEX;
1123 int hndlValue = entRef & ~(1<<31);
1124 CBaseHandle hndl(hndlValue);
1126 if (hndl.GetEntryIndex() < MAX_EDICTS)
1128 return hndl.GetEntryIndex();
1134 void *CHalfLife2::GetGlobalEntityList()
1139 int CHalfLife2::GetSendPropOffset(SendProp *prop)
1141 return prop->GetOffset();
1144 const char *CHalfLife2::GetEntityClassname(edict_t * pEdict)
1146 if (pEdict == NULL || pEdict->IsFree())
1151 IServerUnknown *pUnk = pEdict->GetUnknown();
1157 CBaseEntity * pEntity = pUnk->GetBaseEntity();
1159 if (pEntity == NULL)
1164 return GetEntityClassname(pEntity);
1167 const char *CHalfLife2::GetEntityClassname(CBaseEntity *pEntity)
1169 static int offset = -1;
1172 CBaseEntity *pGetterEnt = ReferenceToEntity(0);
1173 datamap_t *pMap = GetDataMap(pGetterEnt);
1175 sm_datatable_info_t info;
1176 if (!FindDataMapInfo(pMap, "m_iClassname", &info))
1181 offset = info.actual_offset;
1184 return *(const char **)(((unsigned char *)pEntity) + offset);
1187 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1188 static bool ResolveFuzzyMapName(const char *fuzzyName, char *outFullname, int size)
1190 static ConCommand *pHelperCmd = g_pCVar->FindCommand("changelevel");
1191 if (!pHelperCmd || !pHelperCmd->CanAutoComplete())
1194 static size_t helperCmdLen = strlen(pHelperCmd->GetName());
1196 CUtlVector<CUtlString> results;
1197 pHelperCmd->AutoCompleteSuggest(fuzzyName, results);
1198 if (results.Count() == 0)
1201 // Results come back as you'd see in autocomplete. (ie. "changelevel fullmapnamehere"),
1202 // so skip ahead to start of map path/name
1204 // Like the engine, we're only going to deal with the first match.
1206 strncopy(outFullname, &results[0][helperCmdLen + 1], size);
1212 bool CHalfLife2::IsMapValid(const char *map)
1214 if (!map || !map[0])
1217 bool ret = engine->IsMapValid(map);
1218 #if SOURCE_ENGINE >= SE_LEFT4DEAD
1221 static char szFuzzyName[PLATFORM_MAX_PATH];
1222 if (ResolveFuzzyMapName(map, szFuzzyName, sizeof(szFuzzyName)))
1224 ret = engine->IsMapValid(szFuzzyName);