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 "logic_bridge.h"
44 ConVar *sv_lan = NULL;
46 static void *g_EntList = NULL;
47 static int entInfoOffset = -1;
52 int HashFunction<datamap_t *>(datamap_t * const &k)
54 return reinterpret_cast<int>(k);
58 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
64 CHalfLife2::CHalfLife2()
66 m_pClasses = sm_trie_create();
69 CHalfLife2::~CHalfLife2()
71 sm_trie_destroy(m_pClasses);
73 List<DataTableInfo *>::iterator iter;
75 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
83 THash<datamap_t *, DataMapTrie>::iterator h_iter;
84 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
88 sm_trie_destroy(h_iter->val.trie);
89 h_iter->val.trie = NULL;
96 #if SOURCE_ENGINE != SE_DARKMESSIAH
97 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
100 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
101 bool is_original_engine = false;
104 void CHalfLife2::OnSourceModStartup(bool late)
106 #if SOURCE_ENGINE != SE_DARKMESSIAH
108 /* The Ship currently is the only known game to use an older version of the engine */
109 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
110 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
112 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
115 is_original_engine = true;
117 else if (g_pSharedChangeInfo == NULL)
119 g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo();
124 void CHalfLife2::OnSourceModAllInitialized()
126 m_MsgTextMsg = g_UserMsgs.GetMessageIndex("TextMsg");
127 m_HinTextMsg = g_UserMsgs.GetMessageIndex("HintText");
128 m_SayTextMsg = g_UserMsgs.GetMessageIndex("SayText");
129 m_VGUIMenu = g_UserMsgs.GetMessageIndex("VGUIMenu");
130 g_ShareSys.AddInterface(NULL, this);
133 void CHalfLife2::OnSourceModAllInitialized_Post()
138 * gEntList and/or g_pEntityList
140 * First try to lookup pointer directly for platforms with symbols.
141 * If symbols aren't present (Windows or stripped Linux/Mac),
142 * attempt find via LevelShutdown + offset
144 if (g_pGameConf->GetMemSig("gEntList", (void **)&addr))
146 #if !defined PLATFORM_WINDOWS
149 // Key exists so notify if lookup fails, but try other method.
150 g_Logger.LogError("Failed lookup of gEntList directly - Reverting to lookup via LevelShutdown");
155 g_EntList = reinterpret_cast<void *>(addr);
156 #if !defined PLATFORM_WINDOWS
164 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
166 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
172 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
177 if (!g_pGameConf->GetOffset("gEntList", &offset))
179 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
183 g_EntList = *reinterpret_cast<void **>(addr + offset);
188 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
192 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
194 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
199 #if !defined METAMOD_PLAPI_VERSION || PLAPI_VERSION < 11
200 bool CHalfLife2::IsOriginalEngine()
202 return is_original_engine;
206 #if SOURCE_ENGINE != SE_DARKMESSIAH
207 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
209 return engine->GetChangeAccessor( (const edict_t *)this );
213 bool UTIL_FindInSendTable(SendTable *pTable,
215 sm_sendprop_info_t *info,
219 int props = pTable->GetNumProps();
222 for (int i=0; i<props; i++)
224 prop = pTable->GetProp(i);
225 pname = prop->GetName();
226 if (pname && strcmp(name, pname) == 0)
229 info->actual_offset = offset + info->prop->GetOffset();
232 if (prop->GetDataTable())
234 if (UTIL_FindInSendTable(prop->GetDataTable(),
237 offset + prop->GetOffset())
248 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name)
252 for (int i=0; i<pMap->dataNumFields; i++)
254 if (pMap->dataDesc[i].fieldName == NULL)
258 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
260 return &(pMap->dataDesc[i]);
262 if (pMap->dataDesc[i].td)
264 typedescription_t *_td;
265 if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name)) != NULL)
271 pMap = pMap->baseMap;
277 ServerClass *CHalfLife2::FindServerClass(const char *classname)
279 DataTableInfo *pInfo = _FindServerClass(classname);
289 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
291 DataTableInfo *pInfo = NULL;
293 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
295 ServerClass *sc = gamedll->GetAllServerClasses();
298 if (strcmp(classname, sc->GetName()) == 0)
300 pInfo = new DataTableInfo;
302 sm_trie_insert(m_pClasses, classname, pInfo);
303 m_Tables.push_back(pInfo);
317 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
319 DataTableInfo *pInfo;
320 sm_sendprop_info_t *prop;
322 if ((pInfo = _FindServerClass(classname)) == NULL)
327 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
329 sm_sendprop_info_t temp_info;
331 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
336 pInfo->lookup.insert(offset, temp_info);
347 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
349 sm_sendprop_info_t info;
351 if (!FindSendPropInfo(classname, offset, &info))
359 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
361 typedescription_t *td = NULL;
362 DataMapTrie &val = m_Maps[pMap];
366 val.trie = sm_trie_create();
368 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
370 if ((td = UTIL_FindInDataMap(pMap, offset)) != NULL)
372 sm_trie_insert(val.trie, offset, td);
379 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
381 #if SOURCE_ENGINE != SE_DARKMESSIAH
382 if (g_pSharedChangeInfo != NULL)
386 pEdict->StateChanged(offset);
390 pEdict->StateChanged();
396 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
400 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
402 bf_write *pBitBuf = NULL;
403 cell_t players[] = {client};
405 if (dest == HUD_PRINTTALK)
407 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
409 /* Use SayText user message instead */
410 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
413 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
415 if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
420 pBitBuf->WriteByte(0);
421 pBitBuf->WriteString(buffer);
422 pBitBuf->WriteByte(1);
424 g_UserMsgs.EndMessage();
430 if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
435 pBitBuf->WriteByte(dest);
436 pBitBuf->WriteString(msg);
438 g_UserMsgs.EndMessage();
443 bool CHalfLife2::HintTextMsg(int client, const char *msg)
445 bf_write *pBitBuf = NULL;
446 cell_t players[] = {client};
448 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
453 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
454 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
456 pBitBuf->WriteByte(1);
458 pBitBuf->WriteString(msg);
459 g_UserMsgs.EndMessage();
464 bool CHalfLife2::HintTextMsg(cell_t *players, int count, const char *msg)
466 bf_write *pBitBuf = NULL;
468 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
473 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
474 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
476 pBitBuf->WriteByte(1);
478 pBitBuf->WriteString(msg);
479 g_UserMsgs.EndMessage();
484 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
486 bf_write *pBitBuf = NULL;
487 KeyValues *SubKey = NULL;
489 cell_t players[] = {client};
491 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
498 SubKey = data->GetFirstSubKey();
502 SubKey = SubKey->GetNextKey();
504 SubKey = data->GetFirstSubKey();
507 pBitBuf->WriteString(name);
508 pBitBuf->WriteByte((show) ? 1 : 0);
509 pBitBuf->WriteByte(count);
512 pBitBuf->WriteString(SubKey->GetName());
513 pBitBuf->WriteString(SubKey->GetString());
514 SubKey = SubKey->GetNextKey();
516 g_UserMsgs.EndMessage();
521 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
523 DelayedFakeCliCmd *pFake;
525 if (m_FreeCmds.empty())
527 pFake = new DelayedFakeCliCmd;
529 pFake = m_FreeCmds.front();
533 pFake->client = client;
534 pFake->userid = userid;
535 pFake->cmd.assign(cmd);
537 m_CmdQueue.push(pFake);
540 void CHalfLife2::ProcessFakeCliCmdQueue()
542 while (!m_CmdQueue.empty())
544 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
546 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
548 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
549 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
556 bool CHalfLife2::IsLANServer()
558 sv_lan = icvar->FindVar("sv_lan");
565 return (sv_lan->GetInt() != 0);
568 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
570 #if defined METAMOD_PLAPI_VERSION || PLAPI_VERSION >= 11
571 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
573 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
578 Assert(_heapchk() == _HEAPOK);
581 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
585 // load file into a null-terminated buffer
586 int fileSize = filesystem->Size(f);
587 char *buffer = (char *)MemAllocScratch(fileSize + 1);
591 filesystem->Read(buffer, fileSize, f); // read into local buffer
593 buffer[fileSize] = 0; // null terminate file as EOF
595 filesystem->Close( f ); // close file after reading
597 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
605 return kv->LoadFromFile(filesystem, resourceName, pathID);
609 void CHalfLife2::PushCommandStack(const CCommand *cmd)
611 CachedCommandInfo info;
614 #if SOURCE_ENGINE <= SE_DARKMESSIAH
615 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
618 m_CommandStack.push(info);
621 const CCommand *CHalfLife2::PeekCommandStack()
623 if (m_CommandStack.empty())
628 return m_CommandStack.front().args;
631 void CHalfLife2::PopCommandStack()
633 m_CommandStack.pop();
636 const char *CHalfLife2::CurrentCommandName()
638 #if SOURCE_ENGINE >= SE_ORANGEBOX
639 return m_CommandStack.front().args->Arg(0);
641 return m_CommandStack.front().cmd;
645 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
647 DelayedKickInfo kick;
649 kick.client = client;
650 kick.userid = userid;
651 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
653 m_DelayedKicks.push(kick);
656 void CHalfLife2::ProcessDelayedKicks()
658 while (!m_DelayedKicks.empty())
660 DelayedKickInfo info = m_DelayedKicks.first();
661 m_DelayedKicks.pop();
663 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
664 if (player == NULL || player->GetUserId() != info.userid)
669 player->Kick(info.buffer);
673 edict_t *CHalfLife2::EdictOfIndex(int index)
675 return ::PEntityOfEntIndex(index);
678 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
680 return ::IndexOfEdict(pEnt);
683 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
690 int index = hndl.GetEntryIndex();
692 edict_t *pStoredEdict;
693 CBaseEntity *pStoredEntity;
695 if (!IndexToAThings(index, &pStoredEntity, &pStoredEdict))
700 if (pStoredEdict == NULL || pStoredEntity == NULL)
705 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
712 if (pSE->GetRefEHandle() != hndl)
720 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
722 IServerEntity *pEntOther = pEnt->GetIServerEntity();
724 if (pEntOther == NULL)
732 const char *CHalfLife2::GetCurrentMap()
734 return STRING(gpGlobals->mapname);
737 void CHalfLife2::ServerCommand(const char *buffer)
739 engine->ServerCommand(buffer);
742 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
744 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
745 CBaseHandle hndl = pUnknown->GetRefEHandle();
746 return (hndl.ToInt() | (1<<31));
749 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
751 CEntInfo *pInfo = NULL;
753 if (entRef & (1<<31))
755 /* Proper ent reference */
756 int hndlValue = entRef & ~(1<<31);
757 CBaseHandle hndl(hndlValue);
759 pInfo = LookupEntity(hndl.GetEntryIndex());
760 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
767 /* Old style index only */
768 pInfo = LookupEntity(entRef);
776 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
779 return pUnk->GetBaseEntity();
786 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
788 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
790 if (!g_EntList || entInfoOffset == -1)
792 /* Attempt to use engine interface instead */
793 static CEntInfo tempInfo;
794 tempInfo.m_pNext = NULL;
795 tempInfo.m_pPrev = NULL;
797 edict_t *pEdict = PEntityOfEntIndex(entIndex);
804 IServerUnknown *pUnk = pEdict->GetUnknown();
811 tempInfo.m_pEntity = pUnk;
812 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
817 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
818 return &pArray[entIndex];
822 SERIAL_MASK = 0x7fff (15 bits)
824 #define MAX_EDICT_BITS 11
825 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
826 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
828 Top 5 bits of a handle are unused.
829 Bit 31 - Our 'reference' flag indicator
832 cell_t CHalfLife2::IndexToReference(int entIndex)
834 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
837 return INVALID_EHANDLE_INDEX;
840 return EntityToReference(pEnt);
843 int CHalfLife2::ReferenceToIndex(cell_t entRef)
845 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
847 return INVALID_EHANDLE_INDEX;
850 if (entRef & (1<<31))
852 /* Proper ent reference */
853 int hndlValue = entRef & ~(1<<31);
854 CBaseHandle hndl(hndlValue);
856 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
858 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
860 return INVALID_EHANDLE_INDEX;
863 return hndl.GetEntryIndex();
869 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
873 return INVALID_EHANDLE_INDEX;
876 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
877 CBaseHandle hndl = pUnknown->GetRefEHandle();
879 if (hndl.GetEntryIndex() >= MAX_EDICTS)
881 return (hndl.ToInt() | (1<<31));
885 return hndl.GetEntryIndex();
889 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
891 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
893 return INVALID_EHANDLE_INDEX;
896 int hndlValue = entRef & ~(1<<31);
897 CBaseHandle hndl(hndlValue);
899 if (hndl.GetEntryIndex() < MAX_EDICTS)
901 return hndl.GetEntryIndex();
907 void *CHalfLife2::GetGlobalEntityList()
912 int CHalfLife2::GetSendPropOffset(SendProp *prop)
914 return prop->GetOffset();