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::HintTextMsg(cell_t *players, int count, const char *msg)
442 bf_write *pBitBuf = NULL;
444 if ((pBitBuf = g_UserMsgs.StartMessage(m_HinTextMsg, players, count, USERMSG_RELIABLE)) == NULL)
449 const char *pre_byte = g_pGameConf->GetKeyValue("HintTextPreByte");
450 if (pre_byte != NULL && strcmp(pre_byte, "yes") == 0)
452 pBitBuf->WriteByte(1);
454 pBitBuf->WriteString(msg);
455 g_UserMsgs.EndMessage();
460 bool CHalfLife2::ShowVGUIMenu(int client, const char *name, KeyValues *data, bool show)
462 bf_write *pBitBuf = NULL;
463 KeyValues *SubKey = NULL;
465 cell_t players[] = {client};
467 if ((pBitBuf = g_UserMsgs.StartMessage(m_VGUIMenu, players, 1, USERMSG_RELIABLE)) == NULL)
474 SubKey = data->GetFirstSubKey();
478 SubKey = SubKey->GetNextKey();
480 SubKey = data->GetFirstSubKey();
483 pBitBuf->WriteString(name);
484 pBitBuf->WriteByte((show) ? 1 : 0);
485 pBitBuf->WriteByte(count);
488 pBitBuf->WriteString(SubKey->GetName());
489 pBitBuf->WriteString(SubKey->GetString());
490 SubKey = SubKey->GetNextKey();
492 g_UserMsgs.EndMessage();
497 void CHalfLife2::AddToFakeCliCmdQueue(int client, int userid, const char *cmd)
499 DelayedFakeCliCmd *pFake;
501 if (m_FreeCmds.empty())
503 pFake = new DelayedFakeCliCmd;
505 pFake = m_FreeCmds.front();
509 pFake->client = client;
510 pFake->userid = userid;
511 pFake->cmd.assign(cmd);
513 m_CmdQueue.push(pFake);
516 void CHalfLife2::ProcessFakeCliCmdQueue()
518 while (!m_CmdQueue.empty())
520 DelayedFakeCliCmd *pFake = m_CmdQueue.first();
522 if (g_Players.GetClientOfUserId(pFake->userid) == pFake->client)
524 CPlayer *pPlayer = g_Players.GetPlayerByIndex(pFake->client);
525 serverpluginhelpers->ClientCommand(pPlayer->GetEdict(), pFake->cmd.c_str());
532 bool CHalfLife2::IsLANServer()
534 sv_lan = icvar->FindVar("sv_lan");
541 return (sv_lan->GetInt() != 0);
544 bool CHalfLife2::KVLoadFromFile(KeyValues *kv, IBaseFileSystem *filesystem, const char *resourceName, const char *pathID)
546 #if defined METAMOD_PLAPI_VERSION
547 if (g_SMAPI->GetSourceEngineBuild() == SOURCE_ENGINE_ORIGINAL)
549 if (strcasecmp(g_SourceMod.GetGameFolderName(), "ship") == 0)
554 Assert(_heapchk() == _HEAPOK);
557 FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
561 // load file into a null-terminated buffer
562 int fileSize = filesystem->Size(f);
563 char *buffer = (char *)MemAllocScratch(fileSize + 1);
567 filesystem->Read(buffer, fileSize, f); // read into local buffer
569 buffer[fileSize] = 0; // null terminate file as EOF
571 filesystem->Close( f ); // close file after reading
573 bool retOK = kv->LoadFromBuffer( resourceName, buffer, filesystem );
581 return kv->LoadFromFile(filesystem, resourceName, pathID);
585 void CHalfLife2::PushCommandStack(const CCommand *cmd)
587 CachedCommandInfo info;
590 #if SOURCE_ENGINE <= SE_DARKMESSIAH
591 strncopy(info.cmd, cmd->Arg(0), sizeof(info.cmd));
594 m_CommandStack.push(info);
597 const CCommand *CHalfLife2::PeekCommandStack()
599 if (m_CommandStack.empty())
604 return m_CommandStack.front().args;
607 void CHalfLife2::PopCommandStack()
609 m_CommandStack.pop();
612 const char *CHalfLife2::CurrentCommandName()
614 #if SOURCE_ENGINE >= SE_ORANGEBOX
615 return m_CommandStack.front().args->Arg(0);
617 return m_CommandStack.front().cmd;
621 void CHalfLife2::AddDelayedKick(int client, int userid, const char *msg)
623 DelayedKickInfo kick;
625 kick.client = client;
626 kick.userid = userid;
627 UTIL_Format(kick.buffer, sizeof(kick.buffer), "%s", msg);
629 m_DelayedKicks.push(kick);
632 void CHalfLife2::ProcessDelayedKicks()
634 while (!m_DelayedKicks.empty())
636 DelayedKickInfo info = m_DelayedKicks.first();
637 m_DelayedKicks.pop();
639 CPlayer *player = g_Players.GetPlayerByIndex(info.client);
640 if (player == NULL || player->GetUserId() != info.userid)
645 player->Kick(info.buffer);
649 edict_t *CHalfLife2::EdictOfIndex(int index)
651 return ::PEntityOfEntIndex(index);
654 int CHalfLife2::IndexOfEdict(edict_t *pEnt)
656 return ::IndexOfEdict(pEnt);
659 edict_t *CHalfLife2::GetHandleEntity(CBaseHandle &hndl)
666 int index = hndl.GetEntryIndex();
668 edict_t *pStoredEdict;
669 CBaseEntity *pStoredEntity;
671 pStoredEdict = GetEntity(index, &pStoredEntity);
673 if (pStoredEdict == NULL || pStoredEntity == NULL)
678 IServerEntity *pSE = pStoredEdict->GetIServerEntity();
685 if (pSE->GetRefEHandle() != hndl)
693 void CHalfLife2::SetHandleEntity(CBaseHandle &hndl, edict_t *pEnt)
695 IServerEntity *pEntOther = pEnt->GetIServerEntity();
697 if (pEntOther == NULL)
705 const char *CHalfLife2::GetCurrentMap()
707 return STRING(gpGlobals->mapname);
710 void CHalfLife2::ServerCommand(const char *buffer)
712 engine->ServerCommand(buffer);
715 cell_t CHalfLife2::EntityToReference(CBaseEntity *pEntity)
717 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
718 CBaseHandle hndl = pUnknown->GetRefEHandle();
719 return (hndl.ToInt() | (1<<31));
722 CBaseEntity *CHalfLife2::ReferenceToEntity(cell_t entRef)
724 CEntInfo *pInfo = NULL;
726 if (entRef & (1<<31))
728 /* Proper ent reference */
729 int hndlValue = entRef & ~(1<<31);
730 CBaseHandle hndl(hndlValue);
732 pInfo = LookupEntity(hndl.GetEntryIndex());
733 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
740 /* Old style index only */
741 pInfo = LookupEntity(entRef);
749 IServerUnknown *pUnk = static_cast<IServerUnknown *>(pInfo->m_pEntity);
752 return pUnk->GetBaseEntity();
759 * Retrieves the CEntInfo pointer from g_EntList for a given entity index
761 CEntInfo *CHalfLife2::LookupEntity(int entIndex)
763 if (!g_EntList || entInfoOffset == -1)
765 /* Attempt to use engine interface instead */
766 static CEntInfo tempInfo;
767 tempInfo.m_pNext = NULL;
768 tempInfo.m_pPrev = NULL;
770 edict_t *pEdict = PEntityOfEntIndex(entIndex);
777 IServerUnknown *pUnk = pEdict->GetUnknown();
784 tempInfo.m_pEntity = pUnk;
785 tempInfo.m_SerialNumber = pUnk->GetRefEHandle().GetSerialNumber();
790 CEntInfo *pArray = (CEntInfo *)(((unsigned char *)g_EntList) + entInfoOffset);
791 return &pArray[entIndex];
795 SERIAL_MASK = 0x7fff (15 bits)
797 #define MAX_EDICT_BITS 11
798 #define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
799 m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
801 Top 5 bits of a handle are unused.
802 Bit 31 - Our 'reference' flag indicator
805 cell_t CHalfLife2::IndexToReference(int entIndex)
807 CBaseEntity *pEnt = ReferenceToEntity(entIndex);
810 return INVALID_EHANDLE_INDEX;
813 return EntityToReference(pEnt);
816 int CHalfLife2::ReferenceToIndex(cell_t entRef)
818 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
820 return INVALID_EHANDLE_INDEX;
823 if (entRef & (1<<31))
825 /* Proper ent reference */
826 int hndlValue = entRef & ~(1<<31);
827 CBaseHandle hndl(hndlValue);
829 CEntInfo *pInfo = LookupEntity(hndl.GetEntryIndex());
831 if (pInfo->m_SerialNumber != hndl.GetSerialNumber())
833 return INVALID_EHANDLE_INDEX;
836 return hndl.GetEntryIndex();
842 cell_t CHalfLife2::EntityToBCompatRef(CBaseEntity *pEntity)
846 return INVALID_EHANDLE_INDEX;
849 IServerUnknown *pUnknown = (IServerUnknown *)pEntity;
850 CBaseHandle hndl = pUnknown->GetRefEHandle();
852 if (hndl.GetEntryIndex() >= MAX_EDICTS)
854 return (hndl.ToInt() | (1<<31));
858 return hndl.GetEntryIndex();
862 cell_t CHalfLife2::ReferenceToBCompatRef(cell_t entRef)
864 if ((unsigned)entRef == INVALID_EHANDLE_INDEX)
866 return INVALID_EHANDLE_INDEX;
869 int hndlValue = entRef & ~(1<<31);
870 CBaseHandle hndl(hndlValue);
872 if (hndl.GetEntryIndex() < MAX_EDICTS)
874 return hndl.GetEntryIndex();
880 void *CHalfLife2::GetGlobalEntityList()