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 "GameConfigs.h"
39 #include <compat_wrappers.h>
43 ConVar *sv_lan = NULL;
45 static void *g_EntList = NULL;
46 static int entInfoOffset = -1;
51 int HashFunction<datamap_t *>(datamap_t * const &k)
53 return reinterpret_cast<int>(k);
57 int Compare<datamap_t *>(datamap_t * const &k1, datamap_t * const &k2)
63 CHalfLife2::CHalfLife2()
65 m_pClasses = sm_trie_create();
68 CHalfLife2::~CHalfLife2()
70 sm_trie_destroy(m_pClasses);
72 List<DataTableInfo *>::iterator iter;
74 for (iter=m_Tables.begin(); iter!=m_Tables.end(); iter++)
82 THash<datamap_t *, DataMapTrie>::iterator h_iter;
83 for (h_iter=m_Maps.begin(); h_iter!=m_Maps.end(); h_iter++)
87 sm_trie_destroy(h_iter->val.trie);
88 h_iter->val.trie = NULL;
95 #if SOURCE_ENGINE != SE_DARKMESSIAH
96 CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL;
99 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
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 g_ShareSys.AddInterface(NULL, this);
130 void CHalfLife2::OnSourceModAllInitialized_Post()
133 #ifdef PLATFORM_WINDOWS
136 /* gEntList and/or g_pEntityList */
137 if (!g_pGameConf->GetMemSig("LevelShutdown", (void **)&addr))
139 g_Logger.LogError("Logical Entities not supported by this mod (LevelShutdown) - Reverting to networkable entities only");
144 g_Logger.LogError("Failed lookup of LevelShutdown - Reverting to networkable entities only");
147 if (!g_pGameConf->GetOffset("gEntList", &offset))
149 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
152 g_EntList = *reinterpret_cast<void **>(addr + offset);
153 #elif defined PLATFORM_LINUX
154 /* gEntList and/or g_pEntityList */
155 if (!g_pGameConf->GetMemSig("gEntList", (void **)&addr))
157 g_Logger.LogError("Logical Entities not supported by this mod (gEntList) - Reverting to networkable entities only");
162 g_Logger.LogError("Failed lookup of gEntList - Reverting to networkable entities only");
165 g_EntList = reinterpret_cast<void *>(addr);
168 if (!g_pGameConf->GetOffset("EntInfo", &entInfoOffset))
170 g_Logger.LogError("Logical Entities not supported by this mod (EntInfo) - Reverting to networkable entities only");
175 #if !defined METAMOD_PLAPI_VERSION
176 bool CHalfLife2::IsOriginalEngine()
178 return is_original_engine;
182 #if SOURCE_ENGINE != SE_DARKMESSIAH
183 IChangeInfoAccessor *CBaseEdict::GetChangeAccessor()
185 return engine->GetChangeAccessor( (const edict_t *)this );
189 bool UTIL_FindInSendTable(SendTable *pTable,
191 sm_sendprop_info_t *info,
195 int props = pTable->GetNumProps();
198 for (int i=0; i<props; i++)
200 prop = pTable->GetProp(i);
201 pname = prop->GetName();
202 if (pname && strcmp(name, pname) == 0)
205 info->actual_offset = offset + info->prop->GetOffset();
208 if (prop->GetDataTable())
210 if (UTIL_FindInSendTable(prop->GetDataTable(),
213 offset + prop->GetOffset())
224 typedescription_t *UTIL_FindInDataMap(datamap_t *pMap, const char *name)
228 for (int i=0; i<pMap->dataNumFields; i++)
230 if (pMap->dataDesc[i].fieldName == NULL)
234 if (strcmp(name, pMap->dataDesc[i].fieldName) == 0)
236 return &(pMap->dataDesc[i]);
238 if (pMap->dataDesc[i].td)
240 typedescription_t *_td;
241 if ((_td=UTIL_FindInDataMap(pMap->dataDesc[i].td, name)) != NULL)
247 pMap = pMap->baseMap;
253 ServerClass *CHalfLife2::FindServerClass(const char *classname)
255 DataTableInfo *pInfo = _FindServerClass(classname);
265 DataTableInfo *CHalfLife2::_FindServerClass(const char *classname)
267 DataTableInfo *pInfo = NULL;
269 if (!sm_trie_retrieve(m_pClasses, classname, (void **)&pInfo))
271 ServerClass *sc = gamedll->GetAllServerClasses();
274 if (strcmp(classname, sc->GetName()) == 0)
276 pInfo = new DataTableInfo;
278 sm_trie_insert(m_pClasses, classname, pInfo);
279 m_Tables.push_back(pInfo);
293 bool CHalfLife2::FindSendPropInfo(const char *classname, const char *offset, sm_sendprop_info_t *info)
295 DataTableInfo *pInfo;
296 sm_sendprop_info_t *prop;
298 if ((pInfo = _FindServerClass(classname)) == NULL)
303 if ((prop = pInfo->lookup.retrieve(offset)) == NULL)
305 sm_sendprop_info_t temp_info;
307 if (!UTIL_FindInSendTable(pInfo->sc->m_pTable, offset, &temp_info, 0))
312 pInfo->lookup.insert(offset, temp_info);
323 SendProp *CHalfLife2::FindInSendTable(const char *classname, const char *offset)
325 sm_sendprop_info_t info;
327 if (!FindSendPropInfo(classname, offset, &info))
335 typedescription_t *CHalfLife2::FindInDataMap(datamap_t *pMap, const char *offset)
337 typedescription_t *td = NULL;
338 DataMapTrie &val = m_Maps[pMap];
342 val.trie = sm_trie_create();
344 if (!sm_trie_retrieve(val.trie, offset, (void **)&td))
346 if ((td = UTIL_FindInDataMap(pMap, offset)) != NULL)
348 sm_trie_insert(val.trie, offset, td);
355 void CHalfLife2::SetEdictStateChanged(edict_t *pEdict, unsigned short offset)
357 #if SOURCE_ENGINE != SE_DARKMESSIAH
358 if (g_pSharedChangeInfo != NULL)
362 pEdict->StateChanged(offset);
366 pEdict->StateChanged();
372 pEdict->m_fStateFlags |= FL_EDICT_CHANGED;
376 bool CHalfLife2::TextMsg(int client, int dest, const char *msg)
378 bf_write *pBitBuf = NULL;
379 cell_t players[] = {client};
381 if (dest == HUD_PRINTTALK)
383 const char *chat_saytext = g_pGameConf->GetKeyValue("ChatSayText");
385 /* Use SayText user message instead */
386 if (chat_saytext != NULL && strcmp(chat_saytext, "yes") == 0)
389 UTIL_Format(buffer, sizeof(buffer), "%s\1\n", msg);
391 if ((pBitBuf = g_UserMsgs.StartMessage(m_SayTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
396 pBitBuf->WriteByte(0);
397 pBitBuf->WriteString(buffer);
398 pBitBuf->WriteByte(1);
400 g_UserMsgs.EndMessage();
406 if ((pBitBuf = g_UserMsgs.StartMessage(m_MsgTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
411 pBitBuf->WriteByte(dest);
412 pBitBuf->WriteString(msg);
414 g_UserMsgs.EndMessage();
419 bool CHalfLife2::HintTextMsg(int client, const char *msg)
421 bf_write *pBitBuf = NULL;
422 cell_t players[] = {client};
424 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, 1, USERMSG_RELIABLE)) == NULL)
429 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
430 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
432 pBitBuf->WriteByte(1);
434 pBitBuf->WriteString(msg);
435 g_UserMsgs.EndMessage();
440 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
442 bf_write *pBitBuf = NULL;
443 KeyValues *SubKey = NULL;
445 cell_t players[] = {client};
447 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
454 SubKey = data->GetFirstSubKey();
458 SubKey = SubKey->GetNextKey();
460 SubKey = data->GetFirstSubKey();
463 pBitBuf->WriteString(name);
464 pBitBuf->WriteByte((show) ? 1 : 0);
465 pBitBuf->WriteByte(count);
468 pBitBuf->WriteString(SubKey->GetName());
469 pBitBuf->WriteString(SubKey->GetString());
470 SubKey = SubKey->GetNextKey();
472 g_UserMsgs.EndMessage();
477 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
479 DelayedFakeCliCmd *pFake;
481 if (m_FreeCmds.empty())
483 pFake = new DelayedFakeCliCmd;
485 pFake = m_FreeCmds.front();
489 pFake->client = client;
490 pFake->userid = userid;
491 pFake->cmd.assign(cmd);
493 m_CmdQueue.push(pFake);
496 void CHalfLife2::ProcessFakeCliCmdQueue()
498 while (!m_CmdQueue.empty())
500 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
502 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
504 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
505 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
512 bool CHalfLife2::IsLANServer()
514 sv_lan = icvar->FindVar("sv_lan");
521 return (sv_lan->GetInt() != 0);
524 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
526 #if defined METAMOD_PLAPI_VERSION
527 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
529 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
534 Assert(_heapchk() == _HEAPOK);
537 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
541 // load file into a null-terminated buffer
542 int fileSize = filesystem->Size(f);
543 char *buffer = (char *)MemAllocScratch(fileSize + 1);
547 filesystem->Read(buffer, fileSize, f); // read into local buffer
549 buffer[fileSize] = 0; // null terminate file as EOF
551 filesystem->Close( f ); // close file after reading
553 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
561 return kv->LoadFromFile(filesystem, resourceName, pathID);
565 void CHalfLife2::PushCommandStack(const CCommand *cmd)
567 CachedCommandInfo info;
570 #if SOURCE_ENGINE <= SE_DARKMESSIAH
571 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
574 m_CommandStack.push(info);
577 const CCommand *CHalfLife2::PeekCommandStack()
579 if (m_CommandStack.empty())
584 return m_CommandStack.front().args;
587 void CHalfLife2::PopCommandStack()
589 m_CommandStack.pop();
592 const char *CHalfLife2::CurrentCommandName()
594 #if SOURCE_ENGINE >= SE_ORANGEBOX
595 return m_CommandStack.front().args->Arg(0);
597 return m_CommandStack.front().cmd;
601 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
603 DelayedKickInfo kick;
605 kick.client = client;
606 kick.userid = userid;
607 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
609 m_DelayedKicks.push(kick);
612 void CHalfLife2::ProcessDelayedKicks()
614 while (!m_DelayedKicks.empty())
616 DelayedKickInfo info = m_DelayedKicks.first();
617 m_DelayedKicks.pop();
619 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
620 if (player == NULL || player->GetUserId() != info.userid)
625 player->Kick(info.buffer);
629 edict_t *CHalfLife2::EdictOfIndex(int index)
631 return ::PEntityOfEntIndex(index);
634 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
636 return ::IndexOfEdict(pEnt);
639 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
646 int index = hndl.GetEntryIndex();
648 edict_t *pStoredEdict;
649 CBaseEntity *pStoredEntity;
651 pStoredEdict = GetEntity(index, &pStoredEntity);
653 if (pStoredEdict == NULL || pStoredEntity == NULL)
658 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
665 if (pSE->GetRefEHandle() != hndl)
673 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
675 IServerEntity *pEntOther = pEnt->GetIServerEntity();
677 if (pEntOther == NULL)
685 const char *CHalfLife2::GetCurrentMap()
687 return STRING(gpGlobals->mapname);
690 void CHalfLife2::ServerCommand(const char *buffer)
692 engine->ServerCommand(buffer);
695 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
697 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
698 CBaseHandle hndl = pUnknown->GetRefEHandle();
699 return (hndl.ToInt() | (1<<31));
702 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
704 CEntInfo *pInfo = NULL;
706 if (entRef & (1<<31))
708 /* Proper ent reference */
709 int hndlValue = entRef & ~(1<<31);
710 CBaseHandle hndl(hndlValue);
712 pInfo = LookupEntity(hndl.GetEntryIndex());
713 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
720 /* Old style index only */
721 pInfo = LookupEntity(entRef);
729 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
732 return pUnk->GetBaseEntity();
739 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
741 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
743 if (!g_EntList || entInfoOffset == -1)
745 /* Attempt to use engine interface instead */
746 static CEntInfo tempInfo;
747 tempInfo.m_pNext = NULL;
748 tempInfo.m_pPrev = NULL;
750 edict_t *pEdict = PEntityOfEntIndex(entIndex);
757 IServerUnknown *pUnk = pEdict->GetUnknown();
764 tempInfo.m_pEntity = pUnk;
765 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
770 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
771 return &pArray[entIndex];
775 SERIAL_MASK = 0x7fff (15 bits)
777 #define MAX_EDICT_BITS 11
778 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
779 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
781 Top 5 bits of a handle are unused.
782 Bit 31 - Our 'reference' flag indicator
785 cell_t CHalfLife2::IndexToReference(int entIndex)
787 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
790 return INVALID_EHANDLE_INDEX;
793 return EntityToReference(pEnt);
796 int CHalfLife2::ReferenceToIndex(cell_t entRef)
798 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
800 return INVALID_EHANDLE_INDEX;
803 if (entRef & (1<<31))
805 /* Proper ent reference */
806 int hndlValue = entRef & ~(1<<31);
807 CBaseHandle hndl(hndlValue);
809 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
811 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
813 return INVALID_EHANDLE_INDEX;
816 return hndl.GetEntryIndex();
822 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
826 return INVALID_EHANDLE_INDEX;
829 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
830 CBaseHandle hndl = pUnknown->GetRefEHandle();
832 if (hndl.GetEntryIndex() >= MAX_EDICTS)
834 return (hndl.ToInt() | (1<<31));
838 return hndl.GetEntryIndex();
842 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
844 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
846 return INVALID_EHANDLE_INDEX;
849 int hndlValue = entRef & ~(1<<31);
850 CBaseHandle hndl(hndlValue);
852 if (hndl.GetEntryIndex() < MAX_EDICTS)
854 return hndl.GetEntryIndex();
860 void *CHalfLife2::GetGlobalEntityList()