diff --git a/deps/iw4-open-formats b/deps/iw4-open-formats index a9b9dc86..f4ff5d53 160000 --- a/deps/iw4-open-formats +++ b/deps/iw4-open-formats @@ -1 +1 @@ -Subproject commit a9b9dc86c098ce506b195539df55896340220297 +Subproject commit f4ff5d532aeaac1c3254ef20ace687ab41622ab9 diff --git a/src/Components/Loader.cpp b/src/Components/Loader.cpp index aa3ce5d6..c581c3ec 100644 --- a/src/Components/Loader.cpp +++ b/src/Components/Loader.cpp @@ -15,6 +15,7 @@ #include "Modules/ClientCommand.hpp" #include "Modules/ConnectProtocol.hpp" #include "Modules/Console.hpp" +#include "Modules/ConfigStrings.hpp" #include "Modules/D3D9Ex.hpp" #include "Modules/Debug.hpp" #include "Modules/Discord.hpp" @@ -32,6 +33,7 @@ #include "Modules/MapRotation.hpp" #include "Modules/Materials.hpp" #include "Modules/ModList.hpp" +#include "Modules/ModelCache.hpp" #include "Modules/ModelSurfs.hpp" #include "Modules/NetworkDebug.hpp" #include "Modules/News.hpp" @@ -110,6 +112,8 @@ namespace Components Register(new UIScript()); Register(new ZoneBuilder()); + Register(new ConfigStrings()); // Needs to be there early !! Before modelcache & weapons + Register(new ArenaLength()); Register(new AssetHandler()); Register(new Bans()); @@ -144,6 +148,7 @@ namespace Components Register(new Materials()); Register(new Menus()); Register(new ModList()); + Register(new ModelCache()); Register(new ModelSurfs()); Register(new NetworkDebug()); Register(new News()); @@ -173,7 +178,7 @@ namespace Components Register(new Threading()); Register(new Toast()); Register(new UIFeeder()); - //Register(new Updater()); + Register(new Updater()); Register(new VisionFile()); Register(new Voice()); Register(new Vote()); diff --git a/src/Components/Modules/AssetHandler.cpp b/src/Components/Modules/AssetHandler.cpp index 3ee78ad3..6c400baa 100644 --- a/src/Components/Modules/AssetHandler.cpp +++ b/src/Components/Modules/AssetHandler.cpp @@ -226,10 +226,17 @@ namespace Components void AssetHandler::ModifyAsset(Game::XAssetType type, Game::XAssetHeader asset, const std::string& name) { - if (name == "zfeather_dfog_dtex.hlsl"s) +#ifdef DEBUG + if (type == Game::XAssetType::ASSET_TYPE_IMAGE && name[0] != ',') { - printf(""); + const auto image = asset.image; + const auto cat = static_cast(image->category); + if (cat == Game::ImageCategory::IMG_CATEGORY_UNKNOWN) + { + Logger::Warning(Game::CON_CHANNEL_GFX, "Image {} has wrong category IMG_CATEGORY_UNKNOWN, this is an IMPORTANT ISSUE that should be fixed!\n", name); + } } +#endif if (type == Game::ASSET_TYPE_MATERIAL && (name == "gfx_distortion_knife_trail" || name == "gfx_distortion_heat_far" || name == "gfx_distortion_ring_light" || name == "gfx_distortion_heat") && asset.material->info.sortKey >= 43) { @@ -624,7 +631,7 @@ namespace Components Game::ReallocateAssetPool(Game::ASSET_TYPE_VERTEXSHADER, ZoneBuilder::IsEnabled() ? 0x2000 : 3072); Game::ReallocateAssetPool(Game::ASSET_TYPE_MATERIAL, 8192 * 2); Game::ReallocateAssetPool(Game::ASSET_TYPE_VERTEXDECL, ZoneBuilder::IsEnabled() ? 0x400 : 196); - Game::ReallocateAssetPool(Game::ASSET_TYPE_WEAPON, WEAPON_LIMIT); + Game::ReallocateAssetPool(Game::ASSET_TYPE_WEAPON, Weapon::WEAPON_LIMIT); Game::ReallocateAssetPool(Game::ASSET_TYPE_STRINGTABLE, 800); Game::ReallocateAssetPool(Game::ASSET_TYPE_IMPACT_FX, 8); diff --git a/src/Components/Modules/AssetInterfaces/IXModel.cpp b/src/Components/Modules/AssetInterfaces/IXModel.cpp index 74561206..5daf43fc 100644 --- a/src/Components/Modules/AssetInterfaces/IXModel.cpp +++ b/src/Components/Modules/AssetInterfaces/IXModel.cpp @@ -1,7 +1,5 @@ #include -#include - #include "IXModel.hpp" namespace Assets @@ -11,8 +9,19 @@ namespace Assets { header->model = builder->getIW4OfApi()->read(Game::XAssetType::ASSET_TYPE_XMODEL, name); + if (!header->model) + { + // In that case if we want to convert it later potentially we have to grab it now: + header->model = Game::DB_FindXAssetHeader(Game::XAssetType::ASSET_TYPE_XMODEL, name.data()).model; + } + if (header->model) { + if (Components::ZoneBuilder::zb_sp_to_mp.get()) + { + Assets::IXModel::ConvertPlayerModelFromSingleplayerToMultiplayer(header->model, *builder->getAllocator()); + } + // ??? if (header->model->physCollmap) { @@ -305,16 +314,13 @@ namespace Assets uint8_t IXModel::GetHighestAffectingBoneIndex(const Game::XModelLodInfo* lod) { uint8_t highestBoneIndex = 0; - constexpr auto LENGTH = 6; { for (auto surfIndex = 0; surfIndex < lod->numsurfs; surfIndex++) { const auto surface = &lod->surfs[surfIndex]; - auto vertsBlendOffset = 0; - int rebuiltPartBits[LENGTH]{}; std::unordered_set affectingBones{}; const auto registerBoneAffectingSurface = [&](unsigned int offset) { @@ -380,7 +386,7 @@ namespace Assets const auto lod = &model->lodInfo[i]; int lodPartBits[6]{}; - for (auto surfIndex = 0; surfIndex < lod->numsurfs; surfIndex++) + for (unsigned short surfIndex = 0; surfIndex < lod->numsurfs; surfIndex++) { const auto surface = &lod->surfs[surfIndex]; @@ -400,7 +406,7 @@ namespace Assets // 1 bone weight - for (auto vertIndex = 0; vertIndex < surface->vertInfo.vertCount[0]; vertIndex++) + for (unsigned int vertIndex = 0; vertIndex < surface->vertInfo.vertCount[0]; vertIndex++) { registerBoneAffectingSurface(vertsBlendOffset + 0); @@ -408,7 +414,7 @@ namespace Assets } // 2 bone weights - for (auto vertIndex = 0; vertIndex < surface->vertInfo.vertCount[1]; vertIndex++) + for (unsigned int vertIndex = 0; vertIndex < surface->vertInfo.vertCount[1]; vertIndex++) { registerBoneAffectingSurface(vertsBlendOffset + 0); registerBoneAffectingSurface(vertsBlendOffset + 1); @@ -417,7 +423,7 @@ namespace Assets } // 3 bone weights - for (auto vertIndex = 0; vertIndex < surface->vertInfo.vertCount[2]; vertIndex++) + for (unsigned int vertIndex = 0; vertIndex < surface->vertInfo.vertCount[2]; vertIndex++) { registerBoneAffectingSurface(vertsBlendOffset + 0); registerBoneAffectingSurface(vertsBlendOffset + 1); @@ -427,7 +433,7 @@ namespace Assets } // 4 bone weights - for (auto vertIndex = 0; vertIndex < surface->vertInfo.vertCount[3]; vertIndex++) + for (unsigned int vertIndex = 0; vertIndex < surface->vertInfo.vertCount[3]; vertIndex++) { registerBoneAffectingSurface(vertsBlendOffset + 0); registerBoneAffectingSurface(vertsBlendOffset + 1); @@ -437,7 +443,7 @@ namespace Assets vertsBlendOffset += 7; } - for (auto vertListIndex = 0; vertListIndex < surface->vertListCount; vertListIndex++) + for (unsigned int vertListIndex = 0; vertListIndex < surface->vertListCount; vertListIndex++) { affectingBones.emplace(static_cast(surface->vertList[vertListIndex].boneOffset / sizeof(Game::DObjSkelMat))); } @@ -474,14 +480,15 @@ namespace Assets { assert(GetIndexOfBone(model, boneName) == UCHAR_MAX); +#if DEBUG constexpr auto MAX_BONES = 192; - assert(model->numBones < MAX_BONES); +#endif // Start with backing up parent links that we will have to restore // We'll restore them at the end std::map parentsToRestore{}; - for (int i = model->numRootBones; i < model->numBones; i++) + for (uint8_t i = model->numRootBones; i < model->numBones; i++) { parentsToRestore[Game::SL_ConvertToString(model->boneNames[i])] = GetParentOfBone(model, i); } @@ -498,8 +505,6 @@ namespace Assets const uint8_t newBoneIndex = atPosition; const uint8_t newBoneIndexMinusRoot = atPosition - model->numRootBones; - Components::Logger::Print("Inserting bone {} at position {} (between {} and {})\n", boneName, atPosition, Game::SL_ConvertToString(model->boneNames[atPosition - 1]), Game::SL_ConvertToString(model->boneNames[atPosition + 1])); - // Reallocate const auto newBoneNames = allocator.allocateArray(newBoneCount); const auto newMats = allocator.allocateArray(newBoneCount); @@ -517,13 +522,15 @@ namespace Assets const uint8_t atPositionM1 = atPosition - model->numRootBones; +#if DEBUG // should be equal to model->numBones - int total = lengthOfFirstPart + lengthOfSecondPart; - assert(total = model->numBones); + unsigned int total = lengthOfFirstPart + lengthOfSecondPart; + assert(total == model->numBones); // should be equal to model->numBones - model->numRootBones int totalM1 = lengthOfFirstPartM1 + lengthOfSecondPartM1; assert(totalM1 == model->numBones - model->numRootBones); +#endif // Copy before if (lengthOfFirstPart > 0) @@ -599,9 +606,10 @@ namespace Assets { const auto lod = &model->lodInfo[lodIndex]; - if ((lod->partBits[5] & 0x1) == 0x1) + if ((lod->modelSurfs->partBits[5] & 0x1) == 0x1) { // surface lod already converted (more efficient) + std::memcpy(lod->partBits, lod->modelSurfs->partBits, 6 * sizeof(uint32_t)); continue; } @@ -630,7 +638,7 @@ namespace Assets if (index < 0 || index >= model->numBones) { - Components::Logger::Print("Unexpected 'bone index' {} out of {} bones while working vertex blend of model {} lod {} surf {}\n", index, model->numBones, model->name, lodIndex, surfIndex); + Components::Logger::Print("Unexpected 'bone index' {} out of {} bones while working vertex blend of: xmodel {} lod {} xmodelsurf {} surf #{}", index, model->numBones, model->name, lodIndex, lod->modelSurfs->name, lodIndex, surfIndex); assert(false); } @@ -652,7 +660,7 @@ namespace Assets if (index < 0 || index >= model->numBones) { - Components::Logger::Print("Unexpected 'bone index' {} out of {} bones while working list blend of model {} lod {} surf {}\n", index, model->numBones, model->name, lodIndex, surfIndex); + Components::Logger::Print("Unexpected 'bone index' {} out of {} bones while working vertex list of: xmodel {} lod {} xmodelsurf {} surf #{}\n", index, model->numBones, model->name, lodIndex, lod->modelSurfs->name, surfIndex); assert(false); } @@ -711,28 +719,10 @@ namespace Assets const auto key = kv.first; const auto beforeVal = kv.second; - const auto parentIndex = GetIndexOfBone(model, beforeVal); - const auto index = GetIndexOfBone(model, key); - SetParentIndexOfBone(model, index, parentIndex); - } - -#if DEBUG - // check - for (const auto& kv : parentsToRestore) - { - const auto key = kv.first; - const auto beforeVal = kv.second; - + const auto p = GetIndexOfBone(model, beforeVal); const auto index = GetIndexOfBone(model, key); - const auto afterVal = GetParentOfBone(model, index); - - if (beforeVal != afterVal) - { - printf(""); - } + SetParentIndexOfBone(model, index, p); } - // -#endif return atPosition; // Bone index of added bone }; @@ -740,10 +730,6 @@ namespace Assets void IXModel::TransferWeights(Game::XModel* model, const uint8_t origin, const uint8_t destination) { - const auto from = Game::SL_ConvertToString(model->boneNames[origin]); - const auto to = Game::SL_ConvertToString(model->boneNames[destination]); - Components::Logger::Print("Transferring bone weights from {} to {}\n", from, to); - const auto originalWeights = model->baseMat[origin].transWeight; model->baseMat[origin].transWeight = model->baseMat[destination].transWeight; model->baseMat[destination].transWeight = originalWeights; @@ -887,113 +873,124 @@ namespace Assets void IXModel::ConvertPlayerModelFromSingleplayerToMultiplayer(Game::XModel* model, Utils::Memory::Allocator& allocator) { + std::string requiredBonesForHumanoid[] = { + "j_spinelower", + "j_spineupper", + "j_spine4", + "j_mainroot" + }; + + for (const auto& required : requiredBonesForHumanoid) + { + if (GetIndexOfBone(model, required) == UCHAR_MAX) + { + // Not humanoid - nothing to do + return; + } + } + auto indexOfSpine = GetIndexOfBone(model, "j_spinelower"); - if (indexOfSpine < UCHAR_MAX) // It has a spine so it must be some sort of humanoid + const auto nameOfParent = GetParentOfBone(model, indexOfSpine); + + if (GetIndexOfBone(model, "torso_stabilizer") == UCHAR_MAX) // Singleplayer model is likely { - const auto nameOfParent = GetParentOfBone(model, indexOfSpine); - if (GetIndexOfBone(model, "torso_stabilizer") == UCHAR_MAX) // Singleplayer model is likely - { + Components::Logger::Print("Converting {} skeleton from SP to MP...\n", model->name); - Components::Logger::Print("Converting {}\n", model->name); - - // No stabilizer - let's do surgery - // We're trying to get there: - // tag_origin - // j_main_root - // pelvis - // j_hip_le - // j_hip_ri - // tag_stowed_hip_rear - // torso_stabilizer - // j_spinelower - // back_low - // j_spineupper - // back_mid - // j_spine4 - - - const auto root = GetIndexOfBone(model, "j_mainroot"); - if (root < UCHAR_MAX) { - - // Add pelvis -#if false - const uint8_t backLow = InsertBone(model, "back_low", "j_spinelower", allocator); - TransferWeights(model, GetIndexOfBone(model, "j_spinelower"), backLow); - SetParentIndexOfBone(model, GetIndexOfBone(model, "j_spineupper"), backLow); -#else - const uint8_t indexOfPelvis = InsertBone(model, "pelvis", "j_mainroot", allocator); - SetBoneQuaternion(model, indexOfPelvis, true, -0.494f, -0.506f, -0.506f, 0.494); - - TransferWeights(model, root, indexOfPelvis); - - SetParentIndexOfBone(model, GetIndexOfBone(model, "j_hip_le"), indexOfPelvis); - SetParentIndexOfBone(model, GetIndexOfBone(model, "j_hip_ri"), indexOfPelvis); - SetParentIndexOfBone(model, GetIndexOfBone(model, "tag_stowed_hip_rear"), indexOfPelvis); - - // These two are optional - if (GetIndexOfBone(model, "j_coatfront_le") == UCHAR_MAX) - { - InsertBone(model, "j_coatfront_le", "pelvis", allocator); - } + // No stabilizer - let's do surgery + // We're trying to get there: + // tag_origin + // j_main_root + // pelvis + // j_hip_le + // j_hip_ri + // tag_stowed_hip_rear + // torso_stabilizer + // j_spinelower + // back_low + // j_spineupper + // back_mid + // j_spine4 - if (GetIndexOfBone(model, "j_coatfront_ri") == UCHAR_MAX) - { - InsertBone(model, "j_coatfront_ri", "pelvis", allocator); - } - const uint8_t torsoStabilizer = InsertBone(model, "torso_stabilizer", "pelvis", allocator); - const uint8_t lowerSpine = GetIndexOfBone(model, "j_spinelower"); - SetParentIndexOfBone(model, lowerSpine, torsoStabilizer); + const auto root = GetIndexOfBone(model, "j_mainroot"); + if (root < UCHAR_MAX) { - const uint8_t backLow = InsertBone(model, "back_low", "j_spinelower", allocator); - TransferWeights(model, lowerSpine, backLow); - SetParentIndexOfBone(model, GetIndexOfBone(model, "j_spineupper"), backLow); + // Add pelvis + const uint8_t indexOfPelvis = InsertBone(model, "pelvis", "j_mainroot", allocator); + SetBoneQuaternion(model, indexOfPelvis, true, -0.494f, -0.506f, -0.506f, 0.494f); - const uint8_t backMid = InsertBone(model, "back_mid", "j_spineupper", allocator); - TransferWeights(model, GetIndexOfBone(model, "j_spineupper"), backMid); - SetParentIndexOfBone(model, GetIndexOfBone(model, "j_spine4"), backMid); + TransferWeights(model, root, indexOfPelvis); + SetParentIndexOfBone(model, GetIndexOfBone(model, "j_hip_le"), indexOfPelvis); + SetParentIndexOfBone(model, GetIndexOfBone(model, "j_hip_ri"), indexOfPelvis); + SetParentIndexOfBone(model, GetIndexOfBone(model, "tag_stowed_hip_rear"), indexOfPelvis); - assert(root == GetIndexOfBone(model, "j_mainroot")); - assert(indexOfPelvis == GetIndexOfBone(model, "pelvis")); - assert(backLow == GetIndexOfBone(model, "back_low")); - assert(backMid == GetIndexOfBone(model, "back_mid")); + // These two are optional + if (GetIndexOfBone(model, "j_coatfront_le") == UCHAR_MAX) + { + InsertBone(model, "j_coatfront_le", "pelvis", allocator); + } - // Twister bone - SetBoneQuaternion(model, lowerSpine, false, -0.492f, -0.507f, -0.507f, 0.492f); - SetBoneQuaternion(model, torsoStabilizer, false, 0.494f, 0.506f, 0.506f, 0.494f); + if (GetIndexOfBone(model, "j_coatfront_ri") == UCHAR_MAX) + { + InsertBone(model, "j_coatfront_ri", "pelvis", allocator); + } + const uint8_t torsoStabilizer = InsertBone(model, "torso_stabilizer", "pelvis", allocator); + const uint8_t lowerSpine = GetIndexOfBone(model, "j_spinelower"); + SetParentIndexOfBone(model, lowerSpine, torsoStabilizer); - // This doesn't feel like it should be necessary - // It is, on singleplayer models unfortunately. Could we add an extra bone to compensate this? - // Or compensate it another way? - SetBoneTrans(model, GetIndexOfBone(model, "j_spinelower"), false, 0.07, 0.0f, 5.2f); + const uint8_t backLow = InsertBone(model, "back_low", "j_spinelower", allocator); + TransferWeights(model, lowerSpine, backLow); + SetParentIndexOfBone(model, GetIndexOfBone(model, "j_spineupper"), backLow); - // These are often messed up on civilian models, but there is no obvious way to tell from code - const auto stowedBack = GetIndexOfBone(model, "tag_stowed_back"); - if (stowedBack != UCHAR_MAX) - { - SetBoneTrans(model, stowedBack, false, -0.32f, -6.27f, -2.65F); - SetBoneQuaternion(model, stowedBack, false, -0.044, 0.088, -0.995, 0.025); - SetBoneTrans(model, stowedBack, true, -9.571f, -2.654f, 51.738f); - SetBoneQuaternion(model, stowedBack, true, -0.071f, 0.0f, -0.997f, 0.0f); - } + const uint8_t backMid = InsertBone(model, "back_mid", "j_spineupper", allocator); + TransferWeights(model, GetIndexOfBone(model, "j_spineupper"), backMid); + SetParentIndexOfBone(model, GetIndexOfBone(model, "j_spine4"), backMid); - if (stowedBack != UCHAR_MAX) - { - const auto stowedRear = GetIndexOfBone(model, "tag_stowed_hip_rear"); - SetBoneTrans(model, stowedRear, false, -0.75f, -6.45f, -4.99f); - SetBoneQuaternion(model, stowedRear, false, -0.553f, -0.062f, -0.049f, 0.830f); - SetBoneTrans(model, stowedBack, true, -9.866f, -4.989f, 36.315f); - SetBoneQuaternion(model, stowedRear, true, -0.054, -0.025f, -0.975f, 0.214f); - } -#endif - RebuildPartBits(model); + assert(root == GetIndexOfBone(model, "j_mainroot")); + assert(indexOfPelvis == GetIndexOfBone(model, "pelvis")); + assert(backLow == GetIndexOfBone(model, "back_low")); + assert(backMid == GetIndexOfBone(model, "back_mid")); + + // Twister bone + SetBoneQuaternion(model, lowerSpine, false, -0.492f, -0.507f, -0.507f, 0.492f); + SetBoneQuaternion(model, torsoStabilizer, false, 0.494f, 0.506f, 0.506f, 0.494f); + + + // This doesn't feel like it should be necessary + // It is, on singleplayer models unfortunately. Could we add an extra bone to compensate this? + // Or compensate it another way? + SetBoneTrans(model, GetIndexOfBone(model, "j_spinelower"), false, 0.07f, 0.0f, 5.2f); + + // These are often messed up on civilian models, but there is no obvious way to tell from code + auto stowedBack = GetIndexOfBone(model, "tag_stowed_back"); + if (stowedBack == UCHAR_MAX) + { + stowedBack = InsertBone(model, "tag_stowed_back", "j_spine4", allocator); + } + + SetBoneTrans(model, stowedBack, false, -0.32f, -6.27f, -2.65F); + SetBoneQuaternion(model, stowedBack, false, -0.044f, 0.088f, -0.995f, 0.025f); + SetBoneTrans(model, stowedBack, true, -9.571f, -2.654f, 51.738f); + SetBoneQuaternion(model, stowedBack, true, -0.071f, 0.0f, -0.997f, 0.0f); + + auto stowedRear = GetIndexOfBone(model, "tag_stowed_hip_rear"); + if (stowedRear == UCHAR_MAX) + { + stowedBack = InsertBone(model, "tag_stowed_hip_rear", "pelvis", allocator); } + + SetBoneTrans(model, stowedRear, false, -0.75f, -6.45f, -4.99f); + SetBoneQuaternion(model, stowedRear, false, -0.553f, -0.062f, -0.049f, 0.830f); + SetBoneTrans(model, stowedBack, true, -9.866f, -4.989f, 36.315f); + SetBoneQuaternion(model, stowedRear, true, -0.054f, -0.025f, -0.975f, 0.214f); + + + RebuildPartBits(model); } - printf(""); } } diff --git a/src/Components/Modules/Auth.cpp b/src/Components/Modules/Auth.cpp index d46e58fb..0c5dc938 100644 --- a/src/Components/Modules/Auth.cpp +++ b/src/Components/Modules/Auth.cpp @@ -19,14 +19,17 @@ namespace Components std::vector Auth::BannedUids = { + // No longer necessary 0xf4d2c30b712ac6e3, 0xf7e33c4081337fa3, 0x6f5597f103cc50e9, 0xecd542eee54ffccf, + 0xA46B84C54694FD5B, + 0xECD542EEE54FFCCF, }; bool Auth::HasAccessToReservedSlot; - + void Auth::Frame() { if (TokenContainer.generating) @@ -45,7 +48,7 @@ namespace Components if (mseconds < 0) mseconds = 0; } - Localization::Set("MPUI_SECURITY_INCREASE_MESSAGE", Utils::String::VA("Increasing security level from %d to %d (est. %s)",GetSecurityLevel(), TokenContainer.targetLevel, Utils::String::FormatTimeSpan(static_cast(mseconds)).data())); + Localization::Set("MPUI_SECURITY_INCREASE_MESSAGE", Utils::String::VA("Increasing security level from %d to %d (est. %s)", GetSecurityLevel(), TokenContainer.targetLevel, Utils::String::FormatTimeSpan(static_cast(mseconds)).data())); } else if (TokenContainer.thread.joinable()) { @@ -53,7 +56,7 @@ namespace Components TokenContainer.generating = false; StoreKey(); - Logger::Debug("Security level is {}",GetSecurityLevel()); + Logger::Debug("Security level is {}", GetSecurityLevel()); Command::Execute("closemenu security_increase_popmenu", false); if (!TokenContainer.cancel) @@ -127,6 +130,13 @@ namespace Components Game::SV_Cmd_EndTokenizedString(); + if (GuidToken.toString().empty() && adr.type != Game::NA_LOOPBACK) + { + Game::SV_Cmd_EndTokenizedString(); + Logger::Error(Game::ERR_SERVERDISCONNECT, "Connecting failed: Empty GUID token!"); + return; + } + Proto::Auth::Connect connectData; connectData.set_token(GuidToken.toString()); connectData.set_publickey(GuidKey.getPublicKey()); @@ -212,8 +222,9 @@ namespace Components SteamID guid; guid.bits = xuid; - if (Bans::IsBanned({guid, address.getIP()})) + if (Bans::IsBanned({ guid, address.getIP() })) { + Logger::PrintFail2Ban("Failed connect attempt from IP address: {}\n", Network::AdrToString(address)); Network::Send(address, "error\nEXE_ERR_BANNED_PERM"); return; } @@ -303,18 +314,34 @@ namespace Components xor eax, eax jmp safeContinue - noAccess: - mov eax, dword ptr [edx + 0x10] + noAccess : + mov eax, dword ptr[edx + 0x10] - safeContinue: - // Game code skipped by hook - add esp, 0xC + safeContinue : + // Game code skipped by hook + add esp, 0xC - push 0x460FB3 - ret + push 0x460FB3 + ret } } + std::string Auth::GetGUIDFilePath() + { + const auto appdata = Components::FileSystem::GetAppdataPath(); + Utils::IO::CreateDir(appdata.string()); + + const auto guidPath = appdata / "guid.dat"; + + return guidPath.string(); + } + + void ClientConnectFailedStub(Game::netsrc_t sock, Game::netadr_t adr, const char* data) + { + Logger::PrintFail2Ban("Failed connect attempt from IP address: {}\n", Network::AdrToString(adr)); + Game::NET_OutOfBandPrint(sock, adr, data); + } + unsigned __int64 Auth::GetKeyHash(const std::string& key) { std::string hash = Utils::Cryptography::SHA1::Compute(key); @@ -341,8 +368,9 @@ namespace Components cert.set_token(GuidToken.toString()); cert.set_ctoken(ComputeToken.toString()); cert.set_privatekey(GuidKey.serialize(PK_PRIVATE)); - - Utils::IO::WriteFile("players/guid.dat", cert.SerializeAsString()); + + const auto guidPath = GetGUIDFilePath(); + Utils::IO::WriteFile(guidPath, cert.SerializeAsString()); } } @@ -350,7 +378,7 @@ namespace Components { GuidToken.clear(); ComputeToken.clear(); - GuidKey = Utils::Cryptography::ECC::GenerateKey(512); + GuidKey = Utils::Cryptography::ECC::GenerateKey(512, GetMachineEntropy()); StoreKey(); } @@ -359,8 +387,24 @@ namespace Components if (Dedicated::IsEnabled() || ZoneBuilder::IsEnabled()) return; if (!force && GuidKey.isValid()) return; + const auto guidPath = GetGUIDFilePath(); + +#ifndef REGENERATE_INVALID_KEY + // Migrate old file + const auto oldGuidPath = "players/guid.dat"; + if (Utils::IO::FileExists(oldGuidPath)) + { + if (MoveFileA(oldGuidPath, guidPath.data())) + { + Utils::IO::RemoveFile(oldGuidPath); + } + } +#endif + + const auto guidFile = Utils::IO::ReadFile(guidPath); + Proto::Auth::Certificate cert; - if (cert.ParseFromString(::Utils::IO::ReadFile("players/guid.dat"))) + if (cert.ParseFromString(guidFile)) { GuidKey.deserialize(cert.privatekey()); GuidToken = cert.token(); @@ -371,7 +415,19 @@ namespace Components GuidKey.free(); } - if (!GuidKey.isValid()) + if (GuidKey.isValid()) + { +#ifdef REGENERATE_INVALID_KEY + auto machineKey = Utils::Cryptography::ECC::GenerateKey(512, GetMachineEntropy()); + if (GetKeyHash(machineKey.getPublicKey()) != GetKeyHash()) + { + // kill! The user has changed machine or copied files from another + Auth::GenerateKey(); + } +#endif + //All good, nothing to do + } + else { Auth::GenerateKey(); } @@ -379,7 +435,7 @@ namespace Components uint32_t Auth::GetSecurityLevel() { - return GetZeroBits(GuidToken, GuidKey.getPublicKey()); + return GuidToken.toString().empty() ? 0 : GetZeroBits(GuidToken, GuidKey.getPublicKey()); } void Auth::IncreaseSecurityLevel(uint32_t level, const std::string& command) @@ -397,18 +453,18 @@ namespace Components // Start thread TokenContainer.thread = std::thread([&level]() - { - TokenContainer.generating = true; - TokenContainer.hashes = 0; - TokenContainer.startTime = Game::Sys_Milliseconds(); - IncrementToken(GuidToken, ComputeToken, GuidKey.getPublicKey(), TokenContainer.targetLevel, &TokenContainer.cancel, &TokenContainer.hashes); - TokenContainer.generating = false; - - if (TokenContainer.cancel) { - Logger::Print("Token incrementation thread terminated\n"); - } - }); + TokenContainer.generating = true; + TokenContainer.hashes = 0; + TokenContainer.startTime = Game::Sys_Milliseconds(); + IncrementToken(GuidToken, ComputeToken, GuidKey.getPublicKey(), TokenContainer.targetLevel, &TokenContainer.cancel, &TokenContainer.hashes); + TokenContainer.generating = false; + + if (TokenContainer.cancel) + { + Logger::Print("Token incrementation thread terminated\n"); + } + }); } } @@ -452,7 +508,7 @@ namespace Components } // Check if we already have the desired security level - uint32_t lastLevel = GetZeroBits(token, publicKey); + uint32_t lastLevel = token.toString().empty() ? 0 : GetZeroBits(token, publicKey); uint32_t level = lastLevel; if (level >= zeroBits) return; @@ -476,6 +532,75 @@ namespace Components token = computeToken; } + // A somewhat hardware tied 48 bit value + std::string Auth::GetMachineEntropy() + { + std::string entropy{}; + DWORD volumeID; + if (GetVolumeInformationA("C:\\", + NULL, + NULL, + &volumeID, + NULL, + NULL, + NULL, + NULL + )) + { + // Drive info + entropy += std::to_string(volumeID); + } + + // MAC Address + { + unsigned long outBufLen = 0; + DWORD dwResult = GetAdaptersInfo(NULL, &outBufLen); + if (dwResult == ERROR_BUFFER_OVERFLOW) // This is what we're expecting + { + // Now allocate a structure of the required size. + PIP_ADAPTER_INFO pIpAdapterInfo = reinterpret_cast(malloc(outBufLen)); + dwResult = GetAdaptersInfo(pIpAdapterInfo, &outBufLen); + if (dwResult == ERROR_SUCCESS) + { + while (pIpAdapterInfo) + { + switch (pIpAdapterInfo->Type) + { + case IF_TYPE_IEEE80211: + case MIB_IF_TYPE_ETHERNET: + { + + std::string macAddress{}; + for (size_t i = 0; i < ARRAYSIZE(pIpAdapterInfo->Address); i++) + { + entropy += std::to_string(pIpAdapterInfo->Address[i]); + } + + break; + } + } + + pIpAdapterInfo = pIpAdapterInfo->Next; + } + } + + // Free before going next because clearly this is not working + free(pIpAdapterInfo); + } + + } + + if (entropy.empty()) + { + // ultimate fallback + return std::to_string(Utils::Cryptography::Rand::GenerateLong()); + } + else + { + return entropy; + } + } + Auth::Auth() { TokenContainer.cancel = false; @@ -502,6 +627,9 @@ namespace Components Utils::Hook(0x41D3E3, SendConnectDataStub, HOOK_CALL).install()->quick(); + // Hook for Fail2Ban (Hook near client connect to detect password brute forcing) + Utils::Hook(0x4611CA, ClientConnectFailedStub, HOOK_CALL).install()->quick(); // NET_OutOfBandPrint (Grab IP super easy) + // SteamIDs can only contain 31 bits of actual 'id' data. // The other 33 bits are steam internal data like universe and so on. // Using only 31 bits for fingerprints is pretty insecure. @@ -511,36 +639,36 @@ namespace Components // Guid command Command::Add("guid", [] - { - Logger::Print("Your guid: {:#X}\n", Steam::SteamUser()->GetSteamID().bits); - }); + { + Logger::Print("Your guid: {:#X}\n", Steam::SteamUser()->GetSteamID().bits); + }); if (!Dedicated::IsEnabled() && !ZoneBuilder::IsEnabled()) { Command::Add("securityLevel", [](const Command::Params* params) - { - if (params->size() < 2) { - const auto level = GetZeroBits(GuidToken, GuidKey.getPublicKey()); - Logger::Print("Your current security level is {}\n", level); - Logger::Print("Your security token is: {}\n", Utils::String::DumpHex(GuidToken.toString(), "")); - Logger::Print("Your computation token is: {}\n", Utils::String::DumpHex(ComputeToken.toString(), "")); - - Toast::Show("cardicon_locked", "^5Security Level", Utils::String::VA("Your security level is %d", level), 3000); - } - else - { - const auto level = std::strtoul(params->get(1), nullptr, 10); - IncreaseSecurityLevel(level); - } - }); + if (params->size() < 2) + { + const auto level = GetZeroBits(GuidToken, GuidKey.getPublicKey()); + Logger::Print("Your current security level is {}\n", level); + Logger::Print("Your security token is: {}\n", Utils::String::DumpHex(GuidToken.toString(), "")); + Logger::Print("Your computation token is: {}\n", Utils::String::DumpHex(ComputeToken.toString(), "")); + + Toast::Show("cardicon_locked", "^5Security Level", Utils::String::VA("Your security level is %d", level), 3000); + } + else + { + const auto level = std::strtoul(params->get(1), nullptr, 10); + IncreaseSecurityLevel(level); + } + }); } UIScript::Add("security_increase_cancel", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - TokenContainer.cancel = true; - Logger::Print("Token incrementation process canceled!\n"); - }); + { + TokenContainer.cancel = true; + Logger::Print("Token incrementation process canceled!\n"); + }); } Auth::~Auth() diff --git a/src/Components/Modules/Auth.hpp b/src/Components/Modules/Auth.hpp index 5ab438ce..1d56c1b0 100644 --- a/src/Components/Modules/Auth.hpp +++ b/src/Components/Modules/Auth.hpp @@ -24,6 +24,8 @@ namespace Components static uint32_t GetZeroBits(Utils::Cryptography::Token token, const std::string& publicKey); static void IncrementToken(Utils::Cryptography::Token& token, Utils::Cryptography::Token& computeToken, const std::string& publicKey, uint32_t zeroBits, bool* cancel = nullptr, uint64_t* count = nullptr); + static std::string GetMachineEntropy(); + private: class TokenIncrementing @@ -53,6 +55,8 @@ namespace Components static char* Info_ValueForKeyStub(const char* s, const char* key); static void DirectConnectPrivateClientStub(); + static std::string GetGUIDFilePath(); + static void Frame(); }; } diff --git a/src/Components/Modules/Bots.cpp b/src/Components/Modules/Bots.cpp index 576bcdc8..974f849e 100644 --- a/src/Components/Modules/Bots.cpp +++ b/src/Components/Modules/Bots.cpp @@ -30,6 +30,8 @@ namespace Components std::uint16_t lastAltWeapon; std::uint8_t meleeDist; float meleeYaw; + std::int8_t remoteAngles[2]; + float angles[3]; bool active; }; @@ -54,10 +56,11 @@ namespace Components { "sprint", Game::CMD_BUTTON_SPRINT }, { "leanleft", Game::CMD_BUTTON_LEAN_LEFT }, { "leanright", Game::CMD_BUTTON_LEAN_RIGHT }, - { "ads", Game::CMD_BUTTON_ADS }, + { "ads", Game::CMD_BUTTON_ADS | Game::CMD_BUTTON_THROW }, { "holdbreath", Game::CMD_BUTTON_BREATH }, { "usereload", Game::CMD_BUTTON_USE_RELOAD }, { "activate", Game::CMD_BUTTON_ACTIVATE }, + { "remote", Game::CMD_BUTTON_REMOTE }, }; void Bots::UpdateBotNames() @@ -214,7 +217,10 @@ namespace Components } ZeroMemory(&g_botai[entref.entnum], sizeof(BotMovementInfo)); - g_botai[entref.entnum].weapon = 1; + g_botai[entref.entnum].weapon = static_cast(ent->client->ps.weapCommon.weapon); + g_botai[entref.entnum].angles[0] = ent->client->ps.viewangles[0]; + g_botai[entref.entnum].angles[1] = ent->client->ps.viewangles[1]; + g_botai[entref.entnum].angles[2] = ent->client->ps.viewangles[2]; g_botai[entref.entnum].active = true; }); @@ -311,6 +317,43 @@ namespace Components g_botai[entref.entnum].meleeDist = static_cast(dist); g_botai[entref.entnum].active = true; }); + + GSC::Script::AddMethod("BotRemoteAngles", [](const Game::scr_entref_t entref) // Usage: BotRemoteAngles(, ); + { + const auto* ent = GSC::Script::Scr_GetPlayerEntity(entref); + if (!Game::SV_IsTestClient(ent->s.number)) + { + Game::Scr_Error("BotRemoteAngles: Can only call on a bot!"); + return; + } + + const auto pitch = std::clamp(Game::Scr_GetInt(0), std::numeric_limits::min(), std::numeric_limits::max()); + const auto yaw = std::clamp(Game::Scr_GetInt(1), std::numeric_limits::min(), std::numeric_limits::max()); + + g_botai[entref.entnum].remoteAngles[0] = static_cast(pitch); + g_botai[entref.entnum].remoteAngles[1] = static_cast(yaw); + g_botai[entref.entnum].active = true; + }); + + GSC::Script::AddMethod("BotAngles", [](const Game::scr_entref_t entref) // Usage: BotAngles(, , ); + { + const auto* ent = GSC::Script::Scr_GetPlayerEntity(entref); + if (!Game::SV_IsTestClient(ent->s.number)) + { + Game::Scr_Error("BotAngles: Can only call on a bot!"); + return; + } + + const auto pitch = Game::Scr_GetFloat(0); + const auto yaw = Game::Scr_GetFloat(1); + const auto roll = Game::Scr_GetFloat(2); + + g_botai[entref.entnum].angles[0] = pitch; + g_botai[entref.entnum].angles[1] = yaw; + g_botai[entref.entnum].angles[2] = roll; + + g_botai[entref.entnum].active = true; + }); } void Bots::BotAiAction(Game::client_s* cl) @@ -341,10 +384,12 @@ namespace Components userCmd.primaryWeaponForAltMode = g_botai[clientNum].lastAltWeapon; userCmd.meleeChargeYaw = g_botai[clientNum].meleeYaw; userCmd.meleeChargeDist = g_botai[clientNum].meleeDist; + userCmd.remoteControlAngles[0] = g_botai[clientNum].remoteAngles[0]; + userCmd.remoteControlAngles[1] = g_botai[clientNum].remoteAngles[1]; - userCmd.angles[0] = ANGLE2SHORT((cl->gentity->client->ps.viewangles[0] - cl->gentity->client->ps.delta_angles[0])); - userCmd.angles[1] = ANGLE2SHORT((cl->gentity->client->ps.viewangles[1] - cl->gentity->client->ps.delta_angles[1])); - userCmd.angles[2] = ANGLE2SHORT((cl->gentity->client->ps.viewangles[2] - cl->gentity->client->ps.delta_angles[2])); + userCmd.angles[0] = ANGLE2SHORT(g_botai[clientNum].angles[0] - cl->gentity->client->ps.delta_angles[0]); + userCmd.angles[1] = ANGLE2SHORT(g_botai[clientNum].angles[1] - cl->gentity->client->ps.delta_angles[1]); + userCmd.angles[2] = ANGLE2SHORT(g_botai[clientNum].angles[2] - cl->gentity->client->ps.delta_angles[2]); Game::SV_ClientThink(cl, &userCmd); } diff --git a/src/Components/Modules/ClientCommand.cpp b/src/Components/Modules/ClientCommand.cpp index f7c8f5ca..f1f4012e 100644 --- a/src/Components/Modules/ClientCommand.cpp +++ b/src/Components/Modules/ClientCommand.cpp @@ -1,7 +1,7 @@ #include #include "ClientCommand.hpp" -#include "Weapon.hpp" +#include "ModelCache.hpp" #include "GSC/Script.hpp" @@ -384,9 +384,9 @@ namespace Components Game::XModel* model = nullptr; if (ent->model) { - if (Components::Weapon::GModelIndexHasBeenReallocated) + if (Components::ModelCache::modelsHaveBeenReallocated) { - model = Components::Weapon::G_ModelIndexReallocated[ent->model]; + model = Components::ModelCache::cached_models_reallocated[ent->model]; } else { diff --git a/src/Components/Modules/ConfigStrings.cpp b/src/Components/Modules/ConfigStrings.cpp new file mode 100644 index 00000000..020093d5 --- /dev/null +++ b/src/Components/Modules/ConfigStrings.cpp @@ -0,0 +1,305 @@ +#include +#include "ConfigStrings.hpp" + +namespace Components +{ + // Patch game state + // The structure below is our own implementation of the gameState_t structure + static struct ReallocatedGameState_t + { + int stringOffsets[ConfigStrings::MAX_CONFIGSTRINGS]; + char stringData[131072]; // MAX_GAMESTATE_CHARS + int dataCount; + } cl_gameState{}; + + static short sv_configStrings[ConfigStrings::MAX_CONFIGSTRINGS]{}; + + // New mapping (extra data) + constexpr auto EXTRA_WEAPONS_FIRST = ConfigStrings::BASEGAME_MAX_CONFIGSTRINGS; + constexpr auto EXTRA_WEAPONS_LAST = EXTRA_WEAPONS_FIRST + Weapon::ADDED_WEAPONS - 1; + + constexpr auto EXTRA_MODELCACHE_FIRST = EXTRA_WEAPONS_LAST + 1; + constexpr auto EXTRA_MODELCACHE_LAST = EXTRA_MODELCACHE_FIRST + ModelCache::ADDITIONAL_GMODELS; + + constexpr auto RUMBLE_FIRST = EXTRA_MODELCACHE_LAST + 1; + constexpr auto RUMBLE_LAST = RUMBLE_FIRST + 31; // TODO + + void ConfigStrings::PatchConfigStrings() + { + // bump clientstate fields + Utils::Hook::Set(0x4347A7, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x4982F4, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x4F88B6, MAX_CONFIGSTRINGS); // Save file + Utils::Hook::Set(0x5A1FA7, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x5A210D, MAX_CONFIGSTRINGS); // Game state + Utils::Hook::Set(0x5A840E, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x5A853C, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x5AC392, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x5AC3F5, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x5AC542, MAX_CONFIGSTRINGS); // Game state + Utils::Hook::Set(0x5EADF0, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x625388, MAX_CONFIGSTRINGS); + Utils::Hook::Set(0x625516, MAX_CONFIGSTRINGS); + + Utils::Hook::Set(0x405B72, sv_configStrings); + Utils::Hook::Set(0x468508, sv_configStrings); + Utils::Hook::Set(0x47FD7C, sv_configStrings); + Utils::Hook::Set(0x49830E, sv_configStrings); + Utils::Hook::Set(0x498371, sv_configStrings); + Utils::Hook::Set(0x4983D5, sv_configStrings); + Utils::Hook::Set(0x4A74AD, sv_configStrings); + Utils::Hook::Set(0x4BAE7C, sv_configStrings); + Utils::Hook::Set(0x4BAEC3, sv_configStrings); + Utils::Hook::Set(0x6252F5, sv_configStrings); + Utils::Hook::Set(0x625372, sv_configStrings); + Utils::Hook::Set(0x6253D3, sv_configStrings); + Utils::Hook::Set(0x625480, sv_configStrings); + Utils::Hook::Set(0x6254CB, sv_configStrings); + + // TODO: Check if all of these actually mark the end of the array + // Only 2 actually mark the end, the rest is header data or so + Utils::Hook::Set(0x405B8F, &sv_configStrings[ARRAYSIZE(sv_configStrings)]); + Utils::Hook::Set(0x4A74C9, &sv_configStrings[ARRAYSIZE(sv_configStrings)]); + + Utils::Hook(0x405BBE, ConfigStrings::SV_ClearConfigStrings, HOOK_CALL).install()->quick(); + Utils::Hook(0x593CA4, ConfigStrings::CG_ParseConfigStrings, HOOK_CALL).install()->quick(); + + // Weapon + Utils::Hook(0x4BD52D, ConfigStrings::CL_GetWeaponConfigString, HOOK_CALL).install()->quick(); + Utils::Hook(0x45D19E , ConfigStrings::SV_SetWeaponConfigString, HOOK_CALL).install()->quick(); + + // Cached Models + Utils::Hook(0x589908, ConfigStrings::CL_GetCachedModelConfigString, HOOK_CALL).install()->quick(); + Utils::Hook(0x450A30, ConfigStrings::CL_GetCachedModelConfigString, HOOK_CALL).install()->quick(); + Utils::Hook(0x4503F6, ConfigStrings::CL_GetCachedModelConfigString, HOOK_CALL).install()->quick(); + Utils::Hook(0x4504A0, ConfigStrings::CL_GetCachedModelConfigString, HOOK_CALL).install()->quick(); + Utils::Hook(0x450A30, ConfigStrings::CL_GetCachedModelConfigString, HOOK_CALL).install()->quick(); + + Utils::Hook(0x44F217, ConfigStrings::SV_GetCachedModelConfigStringConst, HOOK_CALL).install()->quick(); + Utils::Hook(0X418F93, ConfigStrings::SV_GetCachedModelConfigStringConst, HOOK_CALL).install()->quick(); + Utils::Hook(0x497B0A, ConfigStrings::SV_GetCachedModelConfigStringConst, HOOK_CALL).install()->quick(); + Utils::Hook(0x4F4493, ConfigStrings::SV_GetCachedModelConfigStringConst, HOOK_CALL).install()->quick(); + Utils::Hook(0x5FC46D, ConfigStrings::SV_GetCachedModelConfigStringConst, HOOK_JUMP).install()->quick(); + + Utils::Hook(0x44F282, ConfigStrings::SV_SetCachedModelConfigString, HOOK_CALL).install()->quick(); + + Utils::Hook::Set(0x44A333, sizeof(cl_gameState)); + Utils::Hook::Set(0x5A1F56, sizeof(cl_gameState)); + Utils::Hook::Set(0x5A2043, sizeof(cl_gameState)); + + Utils::Hook::Set(0x5A2053, sizeof(cl_gameState.stringOffsets)); + Utils::Hook::Set(0x5A2098, sizeof(cl_gameState.stringOffsets)); + Utils::Hook::Set(0x5AC32C, sizeof(cl_gameState.stringOffsets)); + + Utils::Hook::Set(0x4235AC, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x434783, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x44A339, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x44ADB7, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A1FE6, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A2048, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A205A, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A2077, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A2091, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A20D7, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A83FF, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A84B0, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5A84E5, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5AC333, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5AC44A, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5AC4F3, &cl_gameState.stringOffsets); + Utils::Hook::Set(0x5AC57A, &cl_gameState.stringOffsets); + + Utils::Hook::Set(0x4235B7, &cl_gameState.stringData); + Utils::Hook::Set(0x43478D, &cl_gameState.stringData); + Utils::Hook::Set(0x44ADBC, &cl_gameState.stringData); + Utils::Hook::Set(0x5A1FEF, &cl_gameState.stringData); + Utils::Hook::Set(0x5A20E6, &cl_gameState.stringData); + Utils::Hook::Set(0x5AC457, &cl_gameState.stringData); + Utils::Hook::Set(0x5AC502, &cl_gameState.stringData); + Utils::Hook::Set(0x5AC586, &cl_gameState.stringData); + + Utils::Hook::Set(0x5A2071, &cl_gameState.dataCount); + Utils::Hook::Set(0x5A20CD, &cl_gameState.dataCount); + Utils::Hook::Set(0x5A20DC, &cl_gameState.dataCount); + Utils::Hook::Set(0x5A20F3, &cl_gameState.dataCount); + Utils::Hook::Set(0x5A2104, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC33F, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC43B, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC450, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC463, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC471, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC4C3, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC4E8, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC4F8, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC50F, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC528, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC56F, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC580, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC592, &cl_gameState.dataCount); + Utils::Hook::Set(0x5AC59F, &cl_gameState.dataCount); + } + + void ConfigStrings::SV_SetConfigString(int index, const char* data, Game::ConfigString basegameLastPosition, int extendedFirstPosition) + { + if (index > basegameLastPosition) + { + // we jump straight to the reallocated part of the array + const auto relativeIndex = index - (basegameLastPosition + 1); + index = extendedFirstPosition + relativeIndex; + } + + // This will go back to our reallocated game state anyway + return Game::SV_SetConfigstring(index, data); + } + + void ConfigStrings::SV_SetWeaponConfigString(int index, const char* data) + { + SV_SetConfigString(index, data, Game::CS_WEAPONFILES_LAST, EXTRA_WEAPONS_FIRST); + } + + void ConfigStrings::SV_SetCachedModelConfigString(int index, const char* data) + { + SV_SetConfigString(index, data, Game::CS_MODELS_LAST, EXTRA_MODELCACHE_FIRST); + } + + unsigned int ConfigStrings::SV_GetConfigString(int index, Game::ConfigString basegameLastPosition, int extendedFirstPosition) + { + if (index > basegameLastPosition) + { + // It's out of range, because we're loading more weapons than the basegame has + // So we jump straight to the reallocated part of the array + const auto relativeIndex = index - (basegameLastPosition + 1); + + index = extendedFirstPosition + relativeIndex; + } + + // This will go back to our reallocated game state anyway + return Game::SV_GetConfigstringConst(index); + } + + const char* ConfigStrings::CL_GetConfigString(int index, Game::ConfigString basegameLastPosition, int extendedFirstPosition) + { + if (index > basegameLastPosition) + { + // It's out of range, because we're loading more weapons than the basegame has + // So we jump straight to the reallocated part of the array + const auto relativeIndex = index - (basegameLastPosition + 1); + + index = extendedFirstPosition + relativeIndex; + } + + // This will go back to our reallocated game state anyway + return Game::CL_GetConfigString(index); + } + + const char* ConfigStrings::CL_GetCachedModelConfigString(int index) + { + return CL_GetConfigString(index, Game::CS_MODELS_LAST, EXTRA_MODELCACHE_FIRST); + } + + int ConfigStrings::SV_GetCachedModelConfigStringConst(int index) + { + return SV_GetConfigString(index, Game::CS_MODELS_LAST, EXTRA_MODELCACHE_FIRST); + } + + const char* ConfigStrings::CL_GetWeaponConfigString(int index) + { + return CL_GetConfigString(index, Game::CS_WEAPONFILES_LAST, EXTRA_WEAPONS_FIRST); + } + + int ConfigStrings::SV_GetWeaponConfigStringConst(int index) + { + return SV_GetConfigString(index, Game::CS_WEAPONFILES_LAST, EXTRA_WEAPONS_FIRST); + } + + int ConfigStrings::CG_ParseExtraConfigStrings() + { + Command::ClientParams params; + + if (params.size() <= 1) + return 0; + + char* end; + const auto* input = params.get(1); + auto index = std::strtol(input, &end, 10); + + if (input == end) + { + Logger::Warning(Game::CON_CHANNEL_DONT_FILTER, "{} is not a valid input\nUsage: {} \n", + input, params.get(0)); + return 0; + } + + // If it's one of our extra data + // bypass parsing and handle it ourselves! + if (index >= BASEGAME_MAX_CONFIGSTRINGS) + { + // Handle extra weapons + if (index >= EXTRA_WEAPONS_FIRST && index <= EXTRA_WEAPONS_LAST) + { + // Recompute weapon index + index = index - EXTRA_WEAPONS_FIRST + Weapon::BASEGAME_WEAPON_LIMIT; + Game::CG_SetupWeaponConfigString(0, index); + } + // Handle extra models + else if (index >= EXTRA_MODELCACHE_FIRST && index <= EXTRA_MODELCACHE_LAST) + { + const auto name = Game::CL_GetConfigString(index); + + const auto R_RegisterModel = 0x50FA00; + + index = index - EXTRA_MODELCACHE_FIRST + ModelCache::BASE_GMODEL_COUNT; + ModelCache::gameModels_reallocated[index] = Utils::Hook::Call(R_RegisterModel)(name); + } + else + { + // Unknown for now? + // Pass it to the game + return 0; + } + + // We handled it + return 1; + } + + // Pass it to the game + return 0; + } + + __declspec(naked) void ConfigStrings::CG_ParseConfigStrings() + { + __asm + { + push eax + pushad + + call ConfigStrings::CG_ParseExtraConfigStrings + + mov[esp + 20h], eax + popad + + pop eax + + test eax, eax + jz continueParsing + + retn + + continueParsing : + push 592960h + retn + } + } + + int ConfigStrings::SV_ClearConfigStrings(void* dest, int value, int size) + { + memset(Utils::Hook::Get(0x405B72), value, MAX_CONFIGSTRINGS * sizeof(uint16_t)); + return Utils::Hook::Call(0x4C98D0)(dest, value, size); // Com_Memset + } + + + ConfigStrings::ConfigStrings() + { + PatchConfigStrings(); + } +} diff --git a/src/Components/Modules/ConfigStrings.hpp b/src/Components/Modules/ConfigStrings.hpp new file mode 100644 index 00000000..26ff78a3 --- /dev/null +++ b/src/Components/Modules/ConfigStrings.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include "Weapon.hpp" +#include "ModelCache.hpp" +#include "Gamepad.hpp" + +namespace Components +{ + class ConfigStrings : public Component + { + public: + static const int BASEGAME_MAX_CONFIGSTRINGS = Game::MAX_CONFIGSTRINGS; + static const int MAX_CONFIGSTRINGS = + (BASEGAME_MAX_CONFIGSTRINGS + + Weapon::ADDED_WEAPONS + + ModelCache::ADDITIONAL_GMODELS + + Gamepad::RUMBLE_CONFIGSTRINGS_COUNT + ); + + static_assert(MAX_CONFIGSTRINGS < USHRT_MAX); + + ConfigStrings(); + + private: + static void PatchConfigStrings(); + + static void SV_SetConfigString(int index, const char* data, Game::ConfigString basegameLastPosition, int extendedFirstPosition); + static unsigned int SV_GetConfigString(int index, Game::ConfigString basegameLastPosition, int extendedFirstPosition); + static const char* CL_GetConfigString(int index, Game::ConfigString basegameLastPosition, int extendedFirstPosition); + + static const char* CL_GetCachedModelConfigString(int index); + static int SV_GetCachedModelConfigStringConst(int index); + static void SV_SetCachedModelConfigString(int index, const char* data); + + static const char* CL_GetWeaponConfigString(int index); + static int SV_GetWeaponConfigStringConst(int index); + static void SV_SetWeaponConfigString(int index, const char* data); + + static int CG_ParseExtraConfigStrings(); + static void CG_ParseConfigStrings(); + static int SV_ClearConfigStrings(void* dest, int value, int size); + }; +} diff --git a/src/Components/Modules/Download.cpp b/src/Components/Modules/Download.cpp index 237c3ef9..0123504e 100644 --- a/src/Components/Modules/Download.cpp +++ b/src/Components/Modules/Download.cpp @@ -463,7 +463,7 @@ namespace Components void Download::Reply(mg_connection* connection, const std::string& contentType, const std::string& data) { - const auto formatted = std::format("Content-Type: {}\r\n", contentType); + const auto formatted = std::format("Content-Type: {}\r\nAccess-Control-Allow-Origin: *\r\n", contentType); mg_http_reply(connection, 200, formatted.c_str(), "%s", data.c_str()); } diff --git a/src/Components/Modules/FastFiles.cpp b/src/Components/Modules/FastFiles.cpp index d2a35cbd..a1a116ad 100644 --- a/src/Components/Modules/FastFiles.cpp +++ b/src/Components/Modules/FastFiles.cpp @@ -245,8 +245,6 @@ namespace Components const char* FastFiles::GetZoneLocation(const char* file) { - const auto* dir = (*Game::fs_basepath)->current.string; - std::vector paths; const std::string fsGame = (*Game::fs_gameDirVar)->current.string; @@ -270,6 +268,7 @@ namespace Components Utils::String::Replace(zone, "_load", ""); } + // Only check for usermaps on our working directory if (Utils::IO::FileExists(std::format("usermaps\\{}\\{}.ff", zone, filename))) { return Utils::String::Format("usermaps\\{}\\", zone); @@ -280,6 +279,7 @@ namespace Components for (auto& path : paths) { + const auto* dir = (*Game::fs_basepath)->current.string; auto absoluteFile = std::format("{}\\{}{}", dir, path, file); // No ".ff" appended, append it manually @@ -506,11 +506,74 @@ namespace Components return Utils::Hook::Call(0x004925B0)(atStreamStart, surface->numsurfs); } + void FastFiles::DB_BuildOSPath_FromSource_Default(const char* zoneName, Game::FF_DIR source, unsigned int size, char* filename) + { + // TODO: this is where user map and mod.ff check should happen + if (source == Game::FFD_DEFAULT) + { + (void)sprintf_s(filename, size, "%s\\%s%s.ff", FileSystem::Sys_DefaultInstallPath_Hk(), GetZoneLocation(zoneName), zoneName); + } + } + + void FastFiles::DB_BuildOSPath_FromSource_Custom(const char* zoneName, Game::FF_DIR source, unsigned int size, char* filename) + { + // TODO: this is where user map and mod.ff check should happen + if (source == Game::FFD_DEFAULT) + { + (void)sprintf_s(filename, size, "%s\\%s%s.ff", FileSystem::Sys_HomePath_Hk(), GetZoneLocation(zoneName), zoneName); + } + } + + bool FastFiles::DB_FileExists_Hk(const char* zoneName, Game::FF_DIR source) + { + char filename[256]{}; + + DB_BuildOSPath_FromSource_Default(zoneName, source, sizeof(filename), filename); + if (auto zoneFile = Game::Sys_OpenFileReliable(filename); zoneFile != INVALID_HANDLE_VALUE) + { + CloseHandle(zoneFile); + return true; + } + + DB_BuildOSPath_FromSource_Custom(zoneName, source, sizeof(filename), filename); + if (auto zoneFile = Game::Sys_OpenFileReliable(filename); zoneFile != INVALID_HANDLE_VALUE) + { + CloseHandle(zoneFile); + return true; + } + + return false; + } + + Game::Sys_File FastFiles::Sys_CreateFile_Stub(const char* dir, const char* filename) + { + static_assert(sizeof(Game::Sys_File) == 4); + + auto file = Game::Sys_CreateFile(dir, filename); + + static const std::filesystem::path home = FileSystem::Sys_HomePath_Hk(); + if (file.handle == INVALID_HANDLE_VALUE && !home.empty()) + { + file.handle = Game::Sys_OpenFileReliable(Utils::String::VA("%s\\%s%s", FileSystem::Sys_HomePath_Hk(), dir, filename)); + } + + if (file.handle == INVALID_HANDLE_VALUE && ZoneBuilder::IsEnabled()) + { + file = Game::Sys_CreateFile("zone\\zonebuilder\\", filename); + } + + return file; + } + FastFiles::FastFiles() { Dvar::Register("ui_zoneDebug", false, Game::DVAR_ARCHIVE, "Display current loaded zone."); g_loadingInitialZones = Dvar::Register("g_loadingInitialZones", true, Game::DVAR_NONE, "Is loading initial zones"); + Utils::Hook(0x5BC832, Sys_CreateFile_Stub, HOOK_CALL).install()->quick(); + + Utils::Hook(0x4CCDF0, DB_FileExists_Hk, HOOK_JUMP).install()->quick(); + // Fix XSurface assets Utils::Hook(0x0048E8A5, FastFiles::Load_XSurfaceArray, HOOK_CALL).install()->quick(); @@ -626,17 +689,5 @@ namespace Components Logger::Print("Waiting for database...\n"); while (!Game::Sys_IsDatabaseReady()) std::this_thread::sleep_for(100ms); }); - -#ifdef _DEBUG - // ZoneBuilder debugging - Utils::IO::WriteFile("userraw/logs/iw4_reads.log", "", false); - Utils::Hook(0x4A8FA0, FastFiles::LogStreamRead, HOOK_JUMP).install()->quick(); - Utils::Hook(0x4BCB62, [] - { - FastFiles::StreamRead = true; - Utils::Hook::Call(0x4B8DB0)(true); // currently set to Load_GfxWorld - FastFiles::StreamRead = false; - }, HOOK_CALL).install()/*->quick()*/; -#endif } } diff --git a/src/Components/Modules/FastFiles.hpp b/src/Components/Modules/FastFiles.hpp index 24f0a03a..9677c040 100644 --- a/src/Components/Modules/FastFiles.hpp +++ b/src/Components/Modules/FastFiles.hpp @@ -70,5 +70,9 @@ namespace Components static void Load_XSurfaceArray(int atStreamStart, int count); + static void DB_BuildOSPath_FromSource_Default(const char* zoneName, Game::FF_DIR source, unsigned int size, char* filename); + static void DB_BuildOSPath_FromSource_Custom(const char* zoneName, Game::FF_DIR source, unsigned int size, char* filename); + static Game::Sys_File Sys_CreateFile_Stub(const char* dir, const char* filename); + static bool DB_FileExists_Hk(const char* zoneName, Game::FF_DIR source); }; } diff --git a/src/Components/Modules/FileSystem.cpp b/src/Components/Modules/FileSystem.cpp index 02b27006..3880a6d2 100644 --- a/src/Components/Modules/FileSystem.cpp +++ b/src/Components/Modules/FileSystem.cpp @@ -153,7 +153,7 @@ namespace Components CoTaskMemFree(path); }); - return std::filesystem::path(path) / "xlabs"; + return std::filesystem::path(path) / "iw4x"; } std::vector FileSystem::GetFileList(const std::string& path, const std::string& extension) @@ -281,7 +281,7 @@ namespace Components int FileSystem::Cmd_Exec_f_Stub(const char* s0, [[maybe_unused]] const char* s1) { int f; - auto len = Game::FS_FOpenFileByMode(s0, &f, Game::FS_READ); + const auto len = Game::FS_FOpenFileByMode(s0, &f, Game::FS_READ); if (len < 0) { return 1; // Not found @@ -336,6 +336,39 @@ namespace Components return current_path.data(); } + FILE* FileSystem::FS_FileOpenReadText_Hk(const char* file) + { + const auto path = Utils::GetBaseFilesLocation(); + if (!path.empty() && Utils::IO::FileExists((path / file).string())) + { + return Game::FS_FileOpenReadText((path / file).string().data()); + } + + return Game::FS_FileOpenReadText(file); + } + + const char* FileSystem::Sys_DefaultCDPath_Hk() + { + return Sys_DefaultInstallPath_Hk(); + } + + const char* FileSystem::Sys_HomePath_Hk() + { + const auto path = Utils::GetBaseFilesLocation(); + if (!path.empty()) + { + static auto current_path = path.string(); + return current_path.data(); + } + + return ""; + } + + const char* FileSystem::Sys_Cwd_Hk() + { + return Sys_DefaultInstallPath_Hk(); + } + FileSystem::FileSystem() { // Thread safe file system interaction @@ -383,6 +416,21 @@ namespace Components // Set the working dir based on info from the Xlabs launcher Utils::Hook(0x4326E0, Sys_DefaultInstallPath_Hk, HOOK_JUMP).install()->quick(); + + // Make the exe run from a folder other than the game folder + Utils::Hook(0x406D26, FS_FileOpenReadText_Hk, HOOK_CALL).install()->quick(); + + // Make the exe run from a folder other than the game folder + Utils::Hook::Nop(0x4290D8, 5); // FS_IsBasePathValid + Utils::Hook::Set(0x4290DF, 0xEB); + // ^^ This check by the game above is super redundant, IW4x has other checks in place to make sure we + // are running from a properly installed directory. This only breaks the containerized patch and we don't need it + + // Patch FS dvar values + Utils::Hook(0x643194, Sys_DefaultCDPath_Hk, HOOK_CALL).install()->quick(); + Utils::Hook(0x643232, Sys_HomePath_Hk, HOOK_CALL).install()->quick(); + Utils::Hook(0x6431B6, Sys_Cwd_Hk, HOOK_CALL).install()->quick(); + Utils::Hook(0x51C29A, Sys_Cwd_Hk, HOOK_CALL).install()->quick(); } FileSystem::~FileSystem() diff --git a/src/Components/Modules/FileSystem.hpp b/src/Components/Modules/FileSystem.hpp index cb721369..9d4e94cf 100644 --- a/src/Components/Modules/FileSystem.hpp +++ b/src/Components/Modules/FileSystem.hpp @@ -99,6 +99,16 @@ namespace Components static std::vector GetSysFileList(const std::string& path, const std::string& extension, bool folders = false); static bool _DeleteFile(const std::string& folder, const std::string& file); + /** + * The game will check in FS_Startup if homepath != default(base) path + * If they differ which will happen when IW4x is containerized it will register two brand new search paths: + * one for the container and one where the game files are. Pretty cool! + */ + static const char* Sys_DefaultInstallPath_Hk(); + static const char* Sys_DefaultCDPath_Hk(); + static const char* Sys_HomePath_Hk(); + static const char* Sys_Cwd_Hk(); + private: static std::mutex Mutex; static std::recursive_mutex FSMutex; @@ -122,6 +132,6 @@ namespace Components static void IwdFreeStub(Game::iwd_t* iwd); - static const char* Sys_DefaultInstallPath_Hk(); + static FILE* FS_FileOpenReadText_Hk(const char* file); }; } diff --git a/src/Components/Modules/Friends.cpp b/src/Components/Modules/Friends.cpp index 90cf83c7..cc327e1d 100644 --- a/src/Components/Modules/Friends.cpp +++ b/src/Components/Modules/Friends.cpp @@ -315,7 +315,10 @@ namespace Components Friends::LoggedOn = (Steam::Proxy::SteamUser_ && Steam::Proxy::SteamUser_->LoggedOn()); if (!Steam::Proxy::SteamFriends) return; - Game::UI_UpdateArenas(); + if (Game::Sys_IsMainThread()) + { + Game::UI_UpdateArenas(); + } int count = Steam::Proxy::SteamFriends->GetFriendCount(4); diff --git a/src/Components/Modules/Gamepad.hpp b/src/Components/Modules/Gamepad.hpp index 3409d80c..6a9d57a0 100644 --- a/src/Components/Modules/Gamepad.hpp +++ b/src/Components/Modules/Gamepad.hpp @@ -39,6 +39,8 @@ namespace Components }; public: + static const int RUMBLE_CONFIGSTRINGS_COUNT = 31; + Gamepad(); static void OnMouseMove(int x, int y, int dx, int dy); diff --git a/src/Components/Modules/Logger.cpp b/src/Components/Modules/Logger.cpp index 1d90e816..25a50c60 100644 --- a/src/Components/Modules/Logger.cpp +++ b/src/Components/Modules/Logger.cpp @@ -38,32 +38,32 @@ namespace Components void Logger::MessagePrint(const int channel, const std::string& msg) { static const auto shouldPrint = []() -> bool - { - return Flags::HasFlag("stdout") || Loader::IsPerformingUnitTests(); - }(); + { + return Flags::HasFlag("stdout") || Loader::IsPerformingUnitTests(); + }(); - if (shouldPrint) - { - (void)std::fputs(msg.data(), stdout); - (void)std::fflush(stdout); - return; - } + if (shouldPrint) + { + (void)std::fputs(msg.data(), stdout); + (void)std::fflush(stdout); + return; + } #ifdef _DEBUG - if (!IsConsoleReady()) - { - OutputDebugStringA(msg.data()); - } + if (!IsConsoleReady()) + { + OutputDebugStringA(msg.data()); + } #endif - if (!Game::Sys_IsMainThread()) - { - EnqueueMessage(msg); - } - else - { - Game::Com_PrintMessage(channel, msg.data(), 0); - } + if (!Game::Sys_IsMainThread()) + { + EnqueueMessage(msg); + } + else + { + Game::Com_PrintMessage(channel, msg.data(), 0); + } } void Logger::DebugInternal(const std::string_view& fmt, std::format_args&& args, [[maybe_unused]] const std::source_location& loc) @@ -120,33 +120,33 @@ namespace Components void Logger::PrintFail2BanInternal(const std::string_view& fmt, std::format_args&& args) { static const auto shouldPrint = []() -> bool - { - return Flags::HasFlag("fail2ban"); - }(); + { + return Flags::HasFlag("fail2ban"); + }(); - if (!shouldPrint) - { - return; - } + if (!shouldPrint) + { + return; + } - auto msg = std::vformat(fmt, args); + auto msg = std::vformat(fmt, args); - static auto log_next_time_stamp = true; - if (log_next_time_stamp) - { - auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - // Convert to local time - std::tm timeInfo = *std::localtime(&now); + static auto log_next_time_stamp = true; + if (log_next_time_stamp) + { + auto now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + // Convert to local time + std::tm timeInfo = *std::localtime(&now); - std::ostringstream ss; - ss << std::put_time(&timeInfo, "%Y-%m-%d %H:%M:%S "); + std::ostringstream ss; + ss << std::put_time(&timeInfo, "%Y-%m-%d %H:%M:%S "); - msg.insert(0, ss.str()); - } + msg.insert(0, ss.str()); + } - log_next_time_stamp = (msg.find('\n') != std::string::npos); + log_next_time_stamp = (msg.find('\n') != std::string::npos); - Utils::IO::WriteFile(IW4x_fail2ban_location.get(), msg, true); + Utils::IO::WriteFile(IW4x_fail2ban_location.get(), msg, true); } void Logger::Frame() @@ -227,28 +227,28 @@ namespace Components pushad - push [esp + 28h] + push[esp + 28h] call PrintMessagePipe add esp, 4h popad ret - returnPrint: + returnPrint : pushad - push 0 // gLog - push [esp + 2Ch] // data - call NetworkLog - add esp, 8h + push 0 // gLog + push[esp + 2Ch] // data + call NetworkLog + add esp, 8h - popad + popad - push esi - mov esi, [esp + 0Ch] + push esi + mov esi, [esp + 0Ch] - push 4AA835h - ret + push 4AA835h + ret } } @@ -262,13 +262,16 @@ namespace Components { const auto* g_log = (*Game::g_log) ? (*Game::g_log)->current.string : ""; - if (std::strcmp(g_log, file) == 0) + if (g_log) // This can be null - has happened before { - if (std::strcmp(folder, "userraw") != 0) + if (std::strcmp(g_log, file) == 0) { - if (IW4x_one_log.get()) + if (std::strcmp(folder, "userraw") != 0) { - strncpy_s(folder, 256, "userraw", _TRUNCATE); + if (IW4x_one_log.get()) + { + strncpy_s(folder, 256, "userraw", _TRUNCATE); + } } } } @@ -280,8 +283,8 @@ namespace Components { pushad - push [esp + 20h + 8h] - push [esp + 20h + 10h] + push[esp + 20h + 8h] + push[esp + 20h + 10h] call RedirectOSPath add esp, 8h @@ -310,117 +313,140 @@ namespace Components void Logger::AddServerCommands() { Command::AddSV("log_add", [](const Command::Params* params) - { - if (params->size() < 2) return; - - std::unique_lock lock(LoggingMutex); - - Network::Address addr(params->get(1)); - if (std::ranges::find(LoggingAddresses[0], addr) == LoggingAddresses[0].end()) { - LoggingAddresses[0].push_back(addr); - } - }); + if (params->size() < 2) return; - Command::AddSV("log_del", [](const Command::Params* params) - { - if (params->size() < 2) return; + std::unique_lock lock(LoggingMutex); - std::unique_lock lock(LoggingMutex); + Network::Address addr(params->get(1)); + if (std::ranges::find(LoggingAddresses[0], addr) == LoggingAddresses[0].end()) + { + LoggingAddresses[0].push_back(addr); + } + }); - const auto num = std::atoi(params->get(1)); - if (!std::strcmp(VA("%i", num), params->get(1)) && static_cast(num) < LoggingAddresses[0].size()) - { - auto addr = Logger::LoggingAddresses[0].begin() + num; - Print("Address {} removed\n", addr->getString()); - LoggingAddresses[0].erase(addr); - } - else + Command::AddSV("log_del", [](const Command::Params* params) { - Network::Address addr(params->get(1)); + if (params->size() < 2) return; - if (const auto i = std::ranges::find(LoggingAddresses[0], addr); i != LoggingAddresses[0].end()) + std::unique_lock lock(LoggingMutex); + + const auto num = std::atoi(params->get(1)); + if (!std::strcmp(VA("%i", num), params->get(1)) && static_cast(num) < LoggingAddresses[0].size()) { - LoggingAddresses[0].erase(i); - Print("Address {} removed\n", addr.getString()); + auto addr = Logger::LoggingAddresses[0].begin() + num; + Print("Address {} removed\n", addr->getString()); + LoggingAddresses[0].erase(addr); } else { - Print("Address {} not found!\n", addr.getString()); + Network::Address addr(params->get(1)); + + if (const auto i = std::ranges::find(LoggingAddresses[0], addr); i != LoggingAddresses[0].end()) + { + LoggingAddresses[0].erase(i); + Print("Address {} removed\n", addr.getString()); + } + else + { + Print("Address {} not found!\n", addr.getString()); + } } - } - }); + }); Command::AddSV("log_list", []([[maybe_unused]] const Command::Params* params) - { - Print("# ID: Address\n"); - Print("-------------\n"); + { + Print("# ID: Address\n"); + Print("-------------\n"); - std::unique_lock lock(LoggingMutex); + std::unique_lock lock(LoggingMutex); - for (unsigned int i = 0; i < LoggingAddresses[0].size(); ++i) - { - Print("#{:03d}: {}\n", i, LoggingAddresses[0][i].getString()); - } - }); + for (unsigned int i = 0; i < LoggingAddresses[0].size(); ++i) + { + Print("#{:03d}: {}\n", i, LoggingAddresses[0][i].getString()); + } + }); Command::AddSV("g_log_add", [](const Command::Params* params) - { - if (params->size() < 2) return; + { + if (params->size() < 2) return; - std::unique_lock lock(LoggingMutex); + std::unique_lock lock(LoggingMutex); - const Network::Address addr(params->get(1)); - if (std::ranges::find(LoggingAddresses[1], addr) == LoggingAddresses[1].end()) - { - LoggingAddresses[1].push_back(addr); - } - }); + const Network::Address addr(params->get(1)); + if (std::ranges::find(LoggingAddresses[1], addr) == LoggingAddresses[1].end()) + { + LoggingAddresses[1].push_back(addr); + } + }); Command::AddSV("g_log_del", [](const Command::Params* params) - { - if (params->size() < 2) return; + { + if (params->size() < 2) return; - std::unique_lock lock(LoggingMutex); + std::unique_lock lock(LoggingMutex); - const auto num = std::atoi(params->get(1)); - if (!std::strcmp(VA("%i", num), params->get(1)) && static_cast(num) < LoggingAddresses[1].size()) - { - const auto addr = LoggingAddresses[1].begin() + num; - Print("Address {} removed\n", addr->getString()); - LoggingAddresses[1].erase(addr); - } - else - { - const Network::Address addr(params->get(1)); - const auto i = std::ranges::find(LoggingAddresses[1].begin(), LoggingAddresses[1].end(), addr); - if (i != LoggingAddresses[1].end()) + const auto num = std::atoi(params->get(1)); + if (!std::strcmp(VA("%i", num), params->get(1)) && static_cast(num) < LoggingAddresses[1].size()) { - LoggingAddresses[1].erase(i); - Print("Address {} removed\n", addr.getString()); + const auto addr = LoggingAddresses[1].begin() + num; + Print("Address {} removed\n", addr->getString()); + LoggingAddresses[1].erase(addr); } else { - Print("Address {} not found!\n", addr.getString()); + const Network::Address addr(params->get(1)); + const auto i = std::ranges::find(LoggingAddresses[1].begin(), LoggingAddresses[1].end(), addr); + if (i != LoggingAddresses[1].end()) + { + LoggingAddresses[1].erase(i); + Print("Address {} removed\n", addr.getString()); + } + else + { + Print("Address {} not found!\n", addr.getString()); + } } - } - }); + }); Command::AddSV("g_log_list", []([[maybe_unused]] const Command::Params* params) - { - Print("# ID: Address\n"); - Print("-------------\n"); + { + Print("# ID: Address\n"); + Print("-------------\n"); + + std::unique_lock lock(LoggingMutex); + for (std::size_t i = 0; i < LoggingAddresses[1].size(); ++i) + { + Print("#{:03d}: {}\n", i, LoggingAddresses[1][i].getString()); + } + }); + } + + void PrintAliasError(Game::conChannel_t channel, const char* originalMsg, const char* soundName, const char* lastErrorStr) + { + // We add a bit more info and we clear the sound stream when it happens + // to avoid spamming the error + const auto newMsg = std::format("{}Make sure you have the 'miles' folder in your game directory! Otherwise MP3 and other codecs will be unavailable.\n", originalMsg); + Game::Com_PrintError(channel, newMsg.c_str(), soundName, lastErrorStr); - std::unique_lock lock(LoggingMutex); - for (std::size_t i = 0; i < LoggingAddresses[1].size(); ++i) + for (size_t i = 0; i < ARRAYSIZE(Game::milesGlobal->streamReadInfo); i++) + { + if (0 == std::strncmp(Game::milesGlobal->streamReadInfo[i].path, soundName, ARRAYSIZE(Game::milesGlobal->streamReadInfo[i].path))) { - Print("#{:03d}: {}\n", i, LoggingAddresses[1][i].getString()); + Game::milesGlobal->streamReadInfo[i].path[0] = '\x00'; // This kills it and make sure it doesn't get played again for now + break; } - }); + } } Logger::Logger() { + // Print sound aliases errors + if (!Dedicated::IsEnabled()) + { + Utils::Hook(0x64BA67, PrintAliasError, HOOK_CALL).install()->quick(); + } + Utils::Hook(0x642139, BuildOSPath_Stub, HOOK_JUMP).install()->quick(); Scheduler::Loop(Frame, Scheduler::Pipeline::SERVER); @@ -438,10 +464,10 @@ namespace Components Events::OnSVInit(AddServerCommands); Events::OnDvarInit([] - { - IW4x_one_log = Dvar::Register("iw4x_onelog", false, Game::DVAR_LATCH, "Only write the game log to the 'userraw' OS folder"); - IW4x_fail2ban_location = Dvar::Register("iw4x_fail2ban_location", "/var/log/iw4x.log", Game::DVAR_NONE, "Fail2Ban logfile location"); - }); + { + IW4x_one_log = Dvar::Register("iw4x_onelog", false, Game::DVAR_LATCH, "Only write the game log to the 'userraw' OS folder"); + IW4x_fail2ban_location = Dvar::Register("iw4x_fail2ban_location", "/var/log/iw4x.log", Game::DVAR_NONE, "Fail2Ban logfile location"); + }); } Logger::~Logger() diff --git a/src/Components/Modules/Logger.hpp b/src/Components/Modules/Logger.hpp index 8b43704d..ead3d695 100644 --- a/src/Components/Modules/Logger.hpp +++ b/src/Components/Modules/Logger.hpp @@ -23,12 +23,12 @@ namespace Components static void Print(const std::string_view& fmt) { - PrintInternal(Game::CON_CHANNEL_DONT_FILTER, fmt, std::make_format_args(0)); + PrintInternal(Game::CON_CHANNEL_DONT_FILTER, fmt, std::make_format_args()); } static void Print(Game::conChannel_t channel, const std::string_view& fmt) { - PrintInternal(channel, fmt, std::make_format_args(0)); + PrintInternal(channel, fmt, std::make_format_args()); } template @@ -47,7 +47,7 @@ namespace Components static void Error(Game::errorParm_t error, const std::string_view& fmt) { - ErrorInternal(error, fmt, std::make_format_args(0)); + ErrorInternal(error, fmt, std::make_format_args()); } template @@ -59,7 +59,7 @@ namespace Components static void Warning(Game::conChannel_t channel, const std::string_view& fmt) { - WarningInternal(channel, fmt, std::make_format_args(0)); + WarningInternal(channel, fmt, std::make_format_args()); } template @@ -71,7 +71,7 @@ namespace Components static void PrintError(Game::conChannel_t channel, const std::string_view& fmt) { - PrintErrorInternal(channel, fmt, std::make_format_args(0)); + PrintErrorInternal(channel, fmt, std::make_format_args()); } template @@ -83,7 +83,7 @@ namespace Components static void PrintFail2Ban(const std::string_view& fmt) { - PrintFail2BanInternal(fmt, std::make_format_args(0)); + PrintFail2BanInternal(fmt, std::make_format_args()); } template diff --git a/src/Components/Modules/Maps.cpp b/src/Components/Modules/Maps.cpp index 112762b5..c86a856b 100644 --- a/src/Components/Modules/Maps.cpp +++ b/src/Components/Modules/Maps.cpp @@ -103,9 +103,9 @@ namespace Components const char* Maps::LoadArenaFileStub(const char* name, char* buffer, int size) { - std::string data = RawFiles::ReadRawFile(name, buffer, size); + std::string data; - if (Maps::UserMap.isValid()) + if (Maps::UserMap.isValid()) { const auto mapname = Maps::UserMap.getName(); const auto arena = GetArenaPath(mapname); @@ -116,6 +116,10 @@ namespace Components data = Utils::IO::ReadFile(arena); } } + else + { + data = RawFiles::ReadRawFile(name, buffer, size); + } strncpy_s(buffer, size, data.data(), _TRUNCATE); return buffer; @@ -141,11 +145,11 @@ namespace Components Maps::CurrentDependencies.clear(); auto dependencies = GetDependenciesForMap(zoneInfo->name); - + std::vector data; Utils::Merge(&data, zoneInfo, zoneCount); Utils::Memory::Allocator allocator; - + if (dependencies.requiresTeamZones) { auto teams = dependencies.requiredTeams; @@ -177,7 +181,7 @@ namespace Components auto patchZone = std::format("patch_{}", zoneInfo->name); if (FastFiles::Exists(patchZone)) { - data.push_back({patchZone.data(), zoneInfo->allocFlags, zoneInfo->freeFlags}); + data.push_back({ patchZone.data(), zoneInfo->allocFlags, zoneInfo->freeFlags }); } return FastFiles::LoadLocalizeZones(data.data(), data.size(), sync); @@ -185,18 +189,18 @@ namespace Components void Maps::OverrideMapEnts(Game::MapEnts* ents) { - auto callback = [] (Game::XAssetHeader header, void* ents) - { - Game::MapEnts* mapEnts = reinterpret_cast(ents); - Game::clipMap_t* clipMap = header.clipMap; - - if (clipMap && mapEnts && !_stricmp(mapEnts->name, clipMap->name)) + auto callback = [](Game::XAssetHeader header, void* ents) { - clipMap->mapEnts = mapEnts; - //*Game::marMapEntsPtr = mapEnts; - //Game::G_SpawnEntitiesFromString(); - } - }; + Game::MapEnts* mapEnts = reinterpret_cast(ents); + Game::clipMap_t* clipMap = header.clipMap; + + if (clipMap && mapEnts && !_stricmp(mapEnts->name, clipMap->name)) + { + clipMap->mapEnts = mapEnts; + //*Game::marMapEntsPtr = mapEnts; + //Game::G_SpawnEntitiesFromString(); + } + }; // Internal doesn't lock the thread, as locking is impossible, due to executing this in the thread that holds the current lock Game::DB_EnumXAssets_Internal(Game::XAssetType::ASSET_TYPE_CLIPMAP_MP, callback, ents, true); @@ -271,7 +275,7 @@ namespace Components Logger::Print("Waiting for database...\n"); while (!Game::Sys_IsDatabaseReady()) std::this_thread::sleep_for(10ms); - if (!Game::DB_XAssetPool[Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP].gameWorldMp || !Game::DB_XAssetPool[Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP].gameWorldMp->name || + if (!Game::DB_XAssetPool[Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP].gameWorldMp || !Game::DB_XAssetPool[Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP].gameWorldMp->name || !Game::DB_XAssetPool[Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP].gameWorldMp->g_glassData || Maps::SPMap) { return Game::DB_XAssetPool[Game::XAssetType::ASSET_TYPE_GAMEWORLD_SP].gameWorldSp->g_glassData; @@ -289,7 +293,7 @@ namespace Components call Maps::GetWorldData - mov [esp + 20h], eax + mov[esp + 20h], eax popad pop eax @@ -309,6 +313,28 @@ namespace Components } } + void Maps::ForceRefreshArenas() + { + if (Game::Sys_IsMainThread()) + { + if (*Game::g_quitRequested) + { + // No need to refresh if we're exiting the game + return; + } + + Game::sharedUiInfo_t* uiInfo = reinterpret_cast(0x62E4B78); + uiInfo->updateArenas = 1; + Game::UI_UpdateArenas(); + } + else + { + // Dangerous!! + assert(false && "Arenas refreshed from wrong thread??"); + Logger::Print("Tried to refresh arenas from a thread that is NOT the main thread!! This could have lead to a crash. Please report this bug and how you got it!"); + } + } + // TODO : Remove hook entirely? void Maps::GetBSPName(char* buffer, size_t size, const char* format, const char* mapname) { @@ -454,7 +480,7 @@ namespace Components char hashBuf[100] = { 0 }; unsigned int hash = atoi(Game::MSG_ReadStringLine(msg, hashBuf, sizeof hashBuf)); - if(!Maps::CheckMapInstalled(mapname, false, true) || hash && hash != Maps::GetUsermapHash(mapname)) + if (!Maps::CheckMapInstalled(mapname, false, true) || hash && hash != Maps::GetUsermapHash(mapname)) { // Reconnecting forces the client to download the new map Command::Execute("disconnect", false); @@ -475,12 +501,12 @@ namespace Components push eax pushad - push [esp + 28h] + push[esp + 28h] push ebp call Maps::TriggerReconnectForMap add esp, 8h - mov [esp + 20h], eax + mov[esp + 20h], eax popad pop eax @@ -490,7 +516,7 @@ namespace Components push 487C50h // Rotate map - skipRotation: + skipRotation : retn } } @@ -501,7 +527,7 @@ namespace Components { pushad - push [esp + 24h] + push[esp + 24h] call Maps::PrepareUsermap pop eax @@ -518,7 +544,7 @@ namespace Components { pushad - push [esp + 24h] + push[esp + 24h] call Maps::PrepareUsermap pop eax @@ -663,7 +689,7 @@ namespace Components Logger::Error(Game::ERR_DISCONNECT, "Missing map file {}.\nYou may have a damaged installation or are attempting to load a non-existent map.", mapname); } - + return false; } @@ -701,7 +727,7 @@ namespace Components void Maps::G_SpawnTurretHook(Game::gentity_s* ent, int unk, int unk2) { - if (Maps::CurrentMainZone == "mp_backlot_sh"s || Maps::CurrentMainZone == "mp_con_spring"s || + if (Maps::CurrentMainZone == "mp_backlot_sh"s || Maps::CurrentMainZone == "mp_con_spring"s || Maps::CurrentMainZone == "mp_mogadishu_sh"s || Maps::CurrentMainZone == "mp_nightshift_sh"s) { return; @@ -731,7 +757,7 @@ namespace Components Logger::Error(Game::errorParm_t::ERR_DROP, "Invalid trigger index ({}) in entities exceeds the maximum trigger count ({}) defined in the clipmap. Check your map ents, or your clipmap!", triggerIndex, ents->trigger.count); return 0; } - else + else { return Utils::Hook::Call(0x4416C0)(triggerIndex, bounds); } @@ -739,29 +765,29 @@ namespace Components return 0; } - + Maps::Maps() { Scheduler::Once([] - { - Dvar::Register("isDlcInstalled_All", false, Game::DVAR_EXTERNAL | Game::DVAR_INIT, ""); - Maps::RListSModels = Dvar::Register("r_listSModels", false, Game::DVAR_NONE, "Display a list of visible SModels"); + { + Dvar::Register("isDlcInstalled_All", false, Game::DVAR_EXTERNAL | Game::DVAR_INIT, ""); + Maps::RListSModels = Dvar::Register("r_listSModels", false, Game::DVAR_NONE, "Display a list of visible SModels"); - Maps::AddDlc({ 1, "Stimulus Pack", {"mp_complex", "mp_compact", "mp_storm", "mp_overgrown", "mp_crash"} }); - Maps::AddDlc({ 2, "Resurgence Pack", {"mp_abandon", "mp_vacant", "mp_trailerpark", "mp_strike", "mp_fuel2"} }); - Maps::AddDlc({ 3, "IW4x Classics", {"mp_nuked", "mp_cross_fire", "mp_cargoship", "mp_bloc", "mp_killhouse", "mp_bog_sh", "mp_cargoship_sh", "mp_shipment", "mp_shipment_long", "mp_rust_long", "mp_firingrange", "mp_bloc_sh", "mp_crash_tropical", "mp_estate_tropical", "mp_fav_tropical", "mp_storm_spring"} }); - Maps::AddDlc({ 4, "Call Of Duty 4 Pack", {"mp_farm", "mp_backlot", "mp_pipeline", "mp_countdown", "mp_crash_snow", "mp_carentan", "mp_broadcast", "mp_showdown", "mp_convoy", "mp_citystreets"} }); - Maps::AddDlc({ 5, "Modern Warfare 3 Pack", {"mp_dome", "mp_hardhat", "mp_paris", "mp_seatown", "mp_bravo", "mp_underground", "mp_plaza2", "mp_village", "mp_alpha"}}); + Maps::AddDlc({ 1, "Stimulus Pack", {"mp_complex", "mp_compact", "mp_storm", "mp_overgrown", "mp_crash"} }); + Maps::AddDlc({ 2, "Resurgence Pack", {"mp_abandon", "mp_vacant", "mp_trailerpark", "mp_strike", "mp_fuel2"} }); + Maps::AddDlc({ 3, "IW4x Classics", {"mp_nuked", "mp_cross_fire", "mp_cargoship", "mp_bloc", "mp_killhouse", "mp_bog_sh", "mp_cargoship_sh", "mp_shipment", "mp_shipment_long", "mp_rust_long", "mp_firingrange", "mp_bloc_sh", "mp_crash_tropical", "mp_estate_tropical", "mp_fav_tropical", "mp_storm_spring"} }); + Maps::AddDlc({ 4, "Call Of Duty 4 Pack", {"mp_farm", "mp_backlot", "mp_pipeline", "mp_countdown", "mp_crash_snow", "mp_carentan", "mp_broadcast", "mp_showdown", "mp_convoy", "mp_citystreets"} }); + Maps::AddDlc({ 5, "Modern Warfare 3 Pack", {"mp_dome", "mp_hardhat", "mp_paris", "mp_seatown", "mp_bravo", "mp_underground", "mp_plaza2", "mp_village", "mp_alpha"} }); - Maps::UpdateDlcStatus(); + Maps::UpdateDlcStatus(); - UIScript::Add("downloadDLC", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - const auto dlc = token.get(); + UIScript::Add("downloadDLC", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) + { + const auto dlc = token.get(); - Game::ShowMessageBox(Utils::String::VA("DLC %d does not exist!", dlc), "ERROR"); - }); - }, Scheduler::Pipeline::MAIN); + Game::ShowMessageBox(Utils::String::VA("DLC %d does not exist!", dlc), "ERROR"); + }); + }, Scheduler::Pipeline::MAIN); // disable turrets on CoD:OL 448+ maps for now Utils::Hook(0x5EE577, Maps::G_SpawnTurretHook, HOOK_CALL).install()->quick(); @@ -777,7 +803,7 @@ namespace Components #endif // - + //#define SORT_SMODELS #if !defined(DEBUG) || !defined(SORT_SMODELS) // Don't sort static models @@ -820,13 +846,13 @@ namespace Components Utils::Hook(0x5B34DD, Maps::LoadMapLoadscreenStub, HOOK_CALL).install()->quick(); Command::Add("delayReconnect", []() - { - Scheduler::Once([] { - Command::Execute("closemenu popup_reconnectingtoparty", false); - Command::Execute("reconnect", false); - }, Scheduler::Pipeline::CLIENT, 10s); - }); + Scheduler::Once([] + { + Command::Execute("closemenu popup_reconnectingtoparty", false); + Command::Execute("reconnect", false); + }, Scheduler::Pipeline::CLIENT, 10s); + }); if (Dedicated::IsEnabled()) { @@ -840,14 +866,6 @@ namespace Components // Load usermap arena file Utils::Hook(0x630A88, Maps::LoadArenaFileStub, HOOK_CALL).install()->quick(); - // Always refresh arena when loading or unloading a zone - Utils::Hook::Nop(0x485017, 2); - Utils::Hook::Nop(0x4FD8C7, 2); // Gametypes - Utils::Hook::Nop(0x4BDFB7, 2); // Unknown - Utils::Hook::Nop(0x45ED6F, 2); // loadGameInfo - Utils::Hook::Nop(0x4A5888, 2); // UI_InitOnceForAllClients - - // Allow hiding specific smodels Utils::Hook(0x50E67C, Maps::HideModelStub, HOOK_CALL).install()->quick(); @@ -858,33 +876,33 @@ namespace Components // Client only Scheduler::Loop([] - { - auto*& gameWorld = *reinterpret_cast(0x66DEE94); - if (!Game::CL_IsCgameInitialized() || !gameWorld || !Maps::RListSModels.get()) return; - - std::map models; - for (unsigned int i = 0; i < gameWorld->dpvs.smodelCount; ++i) { - if (gameWorld->dpvs.smodelVisData[0][i]) + auto*& gameWorld = *reinterpret_cast(0x66DEE94); + if (!Game::CL_IsCgameInitialized() || !gameWorld || !Maps::RListSModels.get()) return; + + std::map models; + for (unsigned int i = 0; i < gameWorld->dpvs.smodelCount; ++i) { - std::string name = gameWorld->dpvs.smodelDrawInsts[i].model->name; + if (gameWorld->dpvs.smodelVisData[0][i]) + { + std::string name = gameWorld->dpvs.smodelDrawInsts[i].model->name; - if (!models.contains(name)) models[name] = 1; - else models[name]++; + if (!models.contains(name)) models[name] = 1; + else models[name]++; + } } - } - Game::Font_s* font = Game::R_RegisterFont("fonts/smallFont", 0); - auto height = Game::R_TextHeight(font); - auto scale = 0.75f; - float color[4] = {0.0f, 1.0f, 0.0f, 1.0f}; + Game::Font_s* font = Game::R_RegisterFont("fonts/smallFont", 0); + auto height = Game::R_TextHeight(font); + auto scale = 0.75f; + float color[4] = { 0.0f, 1.0f, 0.0f, 1.0f }; - unsigned int i = 0; - for (auto& model : models) - { - Game::R_AddCmdDrawText(Utils::String::VA("%d %s", model.second, model.first.data()), std::numeric_limits::max(), font, 15.0f, (height * scale + 1) * (i++ + 1) + 15.0f, scale, scale, 0.0f, color, Game::ITEM_TEXTSTYLE_NORMAL); - } - }, Scheduler::Pipeline::RENDERER); + unsigned int i = 0; + for (auto& model : models) + { + Game::R_AddCmdDrawText(Utils::String::VA("%d %s", model.second, model.first.data()), std::numeric_limits::max(), font, 15.0f, (height * scale + 1) * (i++ + 1) + 15.0f, scale, scale, 0.0f, color, Game::ITEM_TEXTSTYLE_NORMAL); + } + }, Scheduler::Pipeline::RENDERER); } Maps::~Maps() diff --git a/src/Components/Modules/Maps.hpp b/src/Components/Modules/Maps.hpp index 356cf6fe..aca7d6bc 100644 --- a/src/Components/Modules/Maps.hpp +++ b/src/Components/Modules/Maps.hpp @@ -13,7 +13,7 @@ namespace Components { ZeroMemory(&this->searchPath, sizeof this->searchPath); this->hash = Maps::GetUsermapHash(this->mapname); - Game::UI_UpdateArenas(); + Maps::ForceRefreshArenas(); } ~UserMapContainer() @@ -29,7 +29,10 @@ namespace Components { bool wasValid = this->isValid(); this->mapname.clear(); - if (wasValid) Game::UI_UpdateArenas(); + if (wasValid) + { + Maps::ForceRefreshArenas(); + } } void loadIwd(); @@ -95,6 +98,8 @@ namespace Components static Dvar::Var RListSModels; + static void ForceRefreshArenas(); + static void GetBSPName(char* buffer, size_t size, const char* format, const char* mapname); static void LoadAssetRestrict(Game::XAssetType type, Game::XAssetHeader asset, const std::string& name, bool* restrict); static void LoadMapZones(Game::XZoneInfo *zoneInfo, unsigned int zoneCount, int sync); diff --git a/src/Components/Modules/ModelCache.cpp b/src/Components/Modules/ModelCache.cpp new file mode 100644 index 00000000..0893303c --- /dev/null +++ b/src/Components/Modules/ModelCache.cpp @@ -0,0 +1,105 @@ +#include +#include "ModelCache.hpp" + +namespace Components +{ + Game::XModel* ModelCache::cached_models_reallocated[G_MODELINDEX_LIMIT]; + Game::XModel* ModelCache::gameModels_reallocated[G_MODELINDEX_LIMIT]; // Partt of cgs_t + bool ModelCache::modelsHaveBeenReallocated; + + void ModelCache::R_RegisterModel_InitGraphics(const char* name, void* atAddress) + { + const unsigned int gameModelsOriginalAddress = 0x7ED658; // Don't put in Game:: + unsigned int index = (reinterpret_cast(atAddress) - gameModelsOriginalAddress) / sizeof(Game::XModel*); + index++; // Models start at 1 (index 0 is unused) + + // R_REgisterModel + gameModels_reallocated[index] = Utils::Hook::Call(0x50FA00)(name); + } + + __declspec(naked) void ModelCache::R_RegisterModel_Hook() + { + _asm + { + pushad; + push esi; + push eax; + call R_RegisterModel_InitGraphics; + pop esi; + pop eax; + popad; + + push 0x58991B; + retn; + } + } + + ModelCache::ModelCache() + { + // To push the model limit we need to update the network protocol because it uses custom integer size + // (currently 9 bits per model, not enough) + const auto oldBitLength = static_cast(std::floor(std::log2(BASE_GMODEL_COUNT - 1)) + 1); + const auto newBitLength = static_cast(std::floor(std::log2(G_MODELINDEX_LIMIT - 1)) + 1); + + assert(oldBitLength == 9); + + if (oldBitLength != newBitLength) + { + static const std::unordered_set fieldsToUpdate = { + "modelindex", + "attachModelIndex[0]", + "attachModelIndex[1]", + "attachModelIndex[2]", + "attachModelIndex[3]", + "attachModelIndex[4]", + "attachModelIndex[5]", + }; + + size_t currentBitOffset = 0; + + for (size_t i = 0; i < Game::clientStateFieldsCount; i++) + { + auto field = & Game::clientStateFields[i]; + + if (fieldsToUpdate.contains(field->name)) + { + assert(static_cast(field->bits) == oldBitLength); + + Utils::Hook::Set(&field->bits, newBitLength); + currentBitOffset++; + } + } + } + + // Reallocate G_ModelIndex + Utils::Hook::Set(0x420654 + 3, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x43BCE4 + 3, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x44F27B + 3, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x479087 + 1, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x48069D + 3, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x48F088 + 3, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x4F457C + 3, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x5FC762 + 3, ModelCache::cached_models_reallocated); + Utils::Hook::Set(0x5FC7BE + 3, ModelCache::cached_models_reallocated); + + // Reallocate cg models + Utils::Hook::Set(0x44506D + 3, ModelCache::gameModels_reallocated); + Utils::Hook::Set(0x46D49C + 3, ModelCache::gameModels_reallocated); + Utils::Hook::Set(0x586015 + 3, ModelCache::gameModels_reallocated); + Utils::Hook::Set(0x586613 + 3, ModelCache::gameModels_reallocated); + Utils::Hook::Set(0x594E1D + 3, ModelCache::gameModels_reallocated); + + // This one is offset by a compiler optimization + Utils::Hook::Set(0x592B3D + 3, reinterpret_cast(ModelCache::gameModels_reallocated) - Game::CS_MODELS * sizeof(Game::XModel*)); + + // This one is annoying to catch + Utils::Hook(0x589916, R_RegisterModel_Hook, HOOK_JUMP).install()->quick(); + + // Patch limit + Utils::Hook::Set(0x479080 + 1, ModelCache::G_MODELINDEX_LIMIT * sizeof(void*)); + Utils::Hook::Set(0x44F256 + 2, ModelCache::G_MODELINDEX_LIMIT); + Utils::Hook::Set(0x44F231 + 2, ModelCache::G_MODELINDEX_LIMIT); + + modelsHaveBeenReallocated = true; + } +} diff --git a/src/Components/Modules/ModelCache.hpp b/src/Components/Modules/ModelCache.hpp new file mode 100644 index 00000000..cbbef0db --- /dev/null +++ b/src/Components/Modules/ModelCache.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "Weapon.hpp" + +namespace Components +{ + class ModelCache : public Component + { + public: + static const int BASE_GMODEL_COUNT = 512; + + // Double the limit to allow loading of some heavy-duty MW3 maps + static const int ADDITIONAL_GMODELS = 512; + + static const int G_MODELINDEX_LIMIT = (BASE_GMODEL_COUNT + Weapon::WEAPON_LIMIT - Weapon::BASEGAME_WEAPON_LIMIT + ADDITIONAL_GMODELS); + + // Server + static Game::XModel* cached_models_reallocated[G_MODELINDEX_LIMIT]; + + // Client game + static Game::XModel* gameModels_reallocated[G_MODELINDEX_LIMIT]; + + static bool modelsHaveBeenReallocated; + + static void R_RegisterModel_InitGraphics(const char* name, void* atAddress); + static void R_RegisterModel_Hook(); + + ModelCache(); + }; +} diff --git a/src/Components/Modules/Node.cpp b/src/Components/Modules/Node.cpp index 4f170bb4..898f5b85 100644 --- a/src/Components/Modules/Node.cpp +++ b/src/Components/Modules/Node.cpp @@ -342,12 +342,12 @@ namespace Components for (const auto& nodeListData : nodeListReponseMessages) { Scheduler::Once([=] - { + { #ifdef NODE_SYSTEM_DEBUG - Logger::Debug("Sending {} nodeListResponse length to {}\n", nodeListData.length(), address.getCString()); + Logger::Debug("Sending {} nodeListResponse length to {}\n", nodeListData.length(), address.getCString()); #endif - Session::Send(address, "nodeListResponse", nodeListData); - }, Scheduler::Pipeline::MAIN, NODE_SEND_RATE * i++); + Session::Send(address, "nodeListResponse", nodeListData); + }, Scheduler::Pipeline::MAIN, NODE_SEND_RATE * i++); } } @@ -397,48 +397,54 @@ namespace Components Node::Node() { + if (ZoneBuilder::IsEnabled()) + { + return; + } + net_natFix = Game::Dvar_RegisterBool("net_natFix", false, 0, "Fix node registration for certain firewalls/routers"); Scheduler::Loop([] - { - StoreNodes(false); - }, Scheduler::Pipeline::ASYNC, 5min); + { + StoreNodes(false); + }, Scheduler::Pipeline::ASYNC, 5min); Scheduler::Loop(RunFrame, Scheduler::Pipeline::MAIN); - Session::Handle("nodeListResponse", HandleResponse); - Session::Handle("nodeListRequest", [](const Network::Address& address, [[maybe_unused]] const std::string& data) - { - SendList(address); - }); - Scheduler::OnGameInitialized([] - { - Migrate(); - LoadNodePreset(); - LoadNodes(); - }, Scheduler::Pipeline::MAIN); + { - Command::Add("listNodes", [](const Command::Params*) - { - Logger::Print("Nodes: {}\n", Nodes.size()); + Session::Handle("nodeListResponse", HandleResponse); + Session::Handle("nodeListRequest", [](const Network::Address& address, [[maybe_unused]] const std::string& data) + { + SendList(address); + }); + + Migrate(); + LoadNodePreset(); + LoadNodes(); + }, Scheduler::Pipeline::MAIN); - std::lock_guard _(Mutex); - for (const auto& node : Nodes) + Command::Add("listNodes", [](const Command::Params*) { - Logger::Print("{}\t({})\n", node.address.getString(), node.isValid() ? "Valid" : "Invalid"); - } - }); + Logger::Print("Nodes: {}\n", Nodes.size()); + + std::lock_guard _(Mutex); + for (const auto& node : Nodes) + { + Logger::Print("{}\t({})\n", node.address.getString(), node.isValid() ? "Valid" : "Invalid"); + } + }); Command::Add("addNode", [](const Command::Params* params) - { - if (params->size() < 2) return; - auto address = Network::Address{ params->get(1) }; - if (address.isValid()) { - Add(address); - } - }); + if (params->size() < 2) return; + auto address = Network::Address{ params->get(1) }; + if (address.isValid()) + { + Add(address); + } + }); } void Node::preDestroy() diff --git a/src/Components/Modules/Party.cpp b/src/Components/Modules/Party.cpp index fadefcb1..a52c915f 100644 --- a/src/Components/Modules/Party.cpp +++ b/src/Components/Modules/Party.cpp @@ -193,6 +193,11 @@ namespace Components Party::Party() { + if (ZoneBuilder::IsEnabled()) + { + return; + } + PartyEnable = Dvar::Register("party_enable", Dedicated::IsEnabled(), Game::DVAR_NONE, "Enable party system"); Dvar::Register("xblive_privatematch", true, Game::DVAR_INIT, ""); diff --git a/src/Components/Modules/QuickPatch.cpp b/src/Components/Modules/QuickPatch.cpp index eafc0b47..ca8dfc9d 100644 --- a/src/Components/Modules/QuickPatch.cpp +++ b/src/Components/Modules/QuickPatch.cpp @@ -244,12 +244,12 @@ namespace Components return; } - auto workingDir = std::filesystem::current_path().string(); - const std::string binary = *Game::sys_exitCmdLine; - const std::string command = binary == "iw4x-sp.exe" ? "iw4x-sp" : "iw4x"; + const std::filesystem::path workingDir = std::filesystem::current_path(); + const std::wstring binary = Utils::String::Convert(*Game::sys_exitCmdLine); + const std::wstring commandLine = std::format(L"\"{}\" iw4x --pass \"{}\"", (workingDir / binary).wstring(), Utils::GetLaunchParameters()); - SetEnvironmentVariableA("MW2_INSTALL", workingDir.data()); - Utils::Library::LaunchProcess(binary, std::format("{} --pass \"{}\"", command, GetCommandLineA()), workingDir); + SetEnvironmentVariableA("MW2_INSTALL", workingDir.string().data()); + Utils::Library::LaunchProcess(binary, commandLine, workingDir); } __declspec(naked) void QuickPatch::SND_GetAliasOffset_Stub() @@ -298,24 +298,8 @@ namespace Components return Game::Dvar_RegisterBool(dvarName, value_, flags, description); } - void DObjCalcAnim(Game::DObj *a1, int *partBits, Game::XAnimCalcAnimInfo *a3) - { - printf(""); - - if (a1->models[0]->name == "body_urban_civ_female_a"s) - { - printf(""); - } - - Utils::Hook::Call(0x49E230)(a1, partBits, a3); - - printf(""); - } - QuickPatch::QuickPatch() { - - // Filtering any mapents that is intended for Spec:Ops gamemode (CODO) and prevent them from spawning Utils::Hook(0x5FBD6E, QuickPatch::IsDynClassname_Stub, HOOK_CALL).install()->quick(); diff --git a/src/Components/Modules/RCon.cpp b/src/Components/Modules/RCon.cpp index 87a20462..792f11bf 100644 --- a/src/Components/Modules/RCon.cpp +++ b/src/Components/Modules/RCon.cpp @@ -11,9 +11,6 @@ namespace Components std::vector RCon::RConAddresses; - RCon::Container RCon::RConContainer; - Utils::Cryptography::ECC::Key RCon::RConKey; - std::string RCon::Password; Dvar::Var RCon::RConPassword; @@ -96,25 +93,6 @@ namespace Components Network::SendCommand(target, "rconSafe", directive.SerializeAsString()); }); - Command::Add("remoteCommand", [](const Command::Params* params) - { - if (params->size() < 2) return; - - RConContainer.command = params->get(1); - - auto* addr = reinterpret_cast(0xA5EA44); - Network::Address target(addr); - if (!target.isValid() || target.getIP().full == 0) - { - target = Party::Target(); - } - - if (target.isValid()) - { - Network::SendCommand(target, "rconRequest"); - } - }); - Command::AddSV("RconWhitelistAdd", [](const Command::Params* params) { if (params->size() < 2) @@ -261,47 +239,9 @@ namespace Components if (!Dedicated::IsEnabled()) { - Network::OnClientPacket("rconAuthorization", [](const Network::Address& address, [[maybe_unused]] const std::string& data) - { - if (RConContainer.command.empty()) - { - return; - } - - const auto& key = CryptoKeyECC::Get(); - const auto signedMsg = Utils::Cryptography::ECC::SignMessage(key, data); - - Proto::RCon::Command rconExec; - rconExec.set_command(RConContainer.command); - rconExec.set_signature(signedMsg); - - Network::SendCommand(address, "rconExecute", rconExec.SerializeAsString()); - }); - return; } - // Load public key - static std::uint8_t publicKey[] = - { - 0x04, 0x01, 0x9D, 0x18, 0x7F, 0x57, 0xD8, 0x95, 0x4C, 0xEE, 0xD0, 0x21, - 0xB5, 0x00, 0x53, 0xEC, 0xEB, 0x54, 0x7C, 0x4C, 0x37, 0x18, 0x53, 0x89, - 0x40, 0x12, 0xF7, 0x08, 0x8D, 0x9A, 0x8D, 0x99, 0x9C, 0x79, 0x79, 0x59, - 0x6E, 0x32, 0x06, 0xEB, 0x49, 0x1E, 0x00, 0x99, 0x71, 0xCB, 0x4A, 0xE1, - 0x90, 0xF1, 0x7C, 0xB7, 0x4D, 0x60, 0x88, 0x0A, 0xB7, 0xF3, 0xD7, 0x0D, - 0x4F, 0x08, 0x13, 0x7C, 0xEB, 0x01, 0xFF, 0x00, 0x32, 0xEE, 0xE6, 0x23, - 0x07, 0xB1, 0xC2, 0x9E, 0x45, 0xD6, 0xD7, 0xBD, 0xED, 0x05, 0x23, 0xB5, - 0xE7, 0x83, 0xEF, 0xD7, 0x8E, 0x36, 0xDC, 0x16, 0x79, 0x74, 0xD1, 0xD5, - 0xBA, 0x2C, 0x4C, 0x28, 0x61, 0x29, 0x5C, 0x49, 0x7D, 0xD4, 0xB6, 0x56, - 0x17, 0x75, 0xF5, 0x2B, 0x58, 0xCD, 0x0D, 0x76, 0x65, 0x10, 0xF7, 0x51, - 0x69, 0x1D, 0xB9, 0x0F, 0x38, 0xF6, 0x53, 0x3B, 0xF7, 0xCE, 0x76, 0x4F, - 0x08 - }; - - RConKey.set(std::string(reinterpret_cast(publicKey), sizeof(publicKey))); - - RConContainer.timestamp = 0; - Events::OnDvarInit([] { RConPassword = Dvar::Register("rcon_password", "", Game::DVAR_NONE, "The password for rcon"); @@ -359,6 +299,7 @@ namespace Components if (!key.isValid()) { Logger::PrintError(Game::CON_CHANNEL_NETWORK, "RSA public key is invalid\n"); + return; } Proto::RCon::Command directive; @@ -382,96 +323,6 @@ namespace Components RConSafeExecutor(address, s); }, Scheduler::Pipeline::MAIN); }); - - Network::OnClientPacket("rconRequest", [](const Network::Address& address, [[maybe_unused]] const std::string& data) - { - RConContainer.address = address; - RConContainer.challenge = Utils::Cryptography::Rand::GenerateChallenge(); - RConContainer.timestamp = Game::Sys_Milliseconds(); - - Network::SendCommand(address, "rconAuthorization", RConContainer.challenge); - }); - - Network::OnClientPacket("rconExecute", [](const Network::Address& address, [[maybe_unused]] const std::string& data) - { - if (address != RConContainer.address) return; // Invalid IP - if (!RConContainer.timestamp || (Game::Sys_Milliseconds() - RConContainer.timestamp) > (1000 * 10)) return; // Timeout - - RConContainer.timestamp = 0; - - Proto::RCon::Command rconExec; - rconExec.ParseFromString(data); - - if (!Utils::Cryptography::ECC::VerifyMessage(RConKey, RConContainer.challenge, rconExec.signature())) - { - return; - } - - RConContainer.output.clear(); - Logger::PipeOutput([](const std::string& output) - { - RConContainer.output.append(output); - }); - - Command::Execute(rconExec.command(), true); - - Logger::PipeOutput(nullptr); - - Network::SendCommand(address, "print", RConContainer.output); - RConContainer.output.clear(); - }); - } - - bool RCon::CryptoKeyECC::LoadKey(Utils::Cryptography::ECC::Key& key) - { - std::string data; - if (!Utils::IO::ReadFile("./private.key", &data)) - { - return false; - } - - key.deserialize(data); - return key.isValid(); - } - - Utils::Cryptography::ECC::Key RCon::CryptoKeyECC::GenerateKey() - { - auto key = Utils::Cryptography::ECC::GenerateKey(512); - if (!key.isValid()) - { - throw std::runtime_error("Failed to generate server key!"); - } - - if (!Utils::IO::WriteFile("./private.key", key.serialize())) - { - throw std::runtime_error("Failed to write server key!"); - } - - return key; - } - - Utils::Cryptography::ECC::Key RCon::CryptoKeyECC::LoadOrGenerateKey() - { - Utils::Cryptography::ECC::Key key; - if (LoadKey(key)) - { - return key; - } - - return GenerateKey(); - } - - Utils::Cryptography::ECC::Key RCon::CryptoKeyECC::GetKeyInternal() - { - auto key = LoadOrGenerateKey(); - Utils::IO::WriteFile("./public.key", key.getPublicKey()); - return key; - } - - Utils::Cryptography::ECC::Key& RCon::CryptoKeyECC::Get() - { - static auto key = GetKeyInternal(); - return key; } Utils::Cryptography::RSA::Key RCon::CryptoKeyRSA::LoadPublicKey() diff --git a/src/Components/Modules/RCon.hpp b/src/Components/Modules/RCon.hpp index ef691ce1..ad4136db 100644 --- a/src/Components/Modules/RCon.hpp +++ b/src/Components/Modules/RCon.hpp @@ -18,17 +18,6 @@ namespace Components Network::Address address{}; }; - class CryptoKeyECC - { - public: - static Utils::Cryptography::ECC::Key& Get(); - private: - static bool LoadKey(Utils::Cryptography::ECC::Key& key); - static Utils::Cryptography::ECC::Key GenerateKey(); - static Utils::Cryptography::ECC::Key LoadOrGenerateKey(); - static Utils::Cryptography::ECC::Key GetKeyInternal(); - }; - class CryptoKeyRSA { public: @@ -52,9 +41,6 @@ namespace Components static std::vector RConAddresses; - static Container RConContainer; - static Utils::Cryptography::ECC::Key RConKey; - static std::string Password; static std::string RConOutputBuffer; diff --git a/src/Components/Modules/Renderer.cpp b/src/Components/Modules/Renderer.cpp index 8df1b33f..191b82f5 100644 --- a/src/Components/Modules/Renderer.cpp +++ b/src/Components/Modules/Renderer.cpp @@ -713,32 +713,6 @@ namespace Components return result; } - void DebugTest() - { - //auto clientNum = Game::CG_GetClientNum(); - //auto* clientEntity = &Game::g_entities[clientNum]; - - //// Ingame only & player only - //if (!Game::CL_IsCgameInitialized() || clientEntity->client == nullptr) - //{ - // return; - //} - - - //static std::string str = ""; - - //str += std::format("\n{} => {} {} {} {} {} {}", "s.partBits", clientEntity->s.partBits[0], clientEntity->s.partBits[1], clientEntity->s.partBits[2], clientEntity->s.partBits[3], clientEntity->s.partBits[4], clientEntity->s.partBits[5]); - // - - //const auto clientNumber = clientEntity->r.ownerNum.number; - //Game::scene->sceneDObj[clientNumber].obj->hidePartBits; - - //str += std::format("\n{} => {} {} {} {} {} {}", "DOBJ hidePartBits", clientEntity->s.partBits[0], clientEntity->s.partBits[1], clientEntity->s.partBits[2], clientEntity->s.partBits[3], clientEntity->s.partBits[4], clientEntity->s.partBits[5]); - - //Game::R_AddCmdDrawText(); - - } - Renderer::Renderer() { if (Dedicated::IsEnabled()) return; @@ -757,7 +731,6 @@ namespace Components ListSamplers(); DrawPrimaryLights(); DebugDrawClipmap(); - DebugTest(); } }, Scheduler::Pipeline::RENDERER); diff --git a/src/Components/Modules/ServerList.cpp b/src/Components/Modules/ServerList.cpp index fd496edb..38c66564 100644 --- a/src/Components/Modules/ServerList.cpp +++ b/src/Components/Modules/ServerList.cpp @@ -270,7 +270,7 @@ namespace Components if ((ui_browserMod == 0 && static_cast(serverInfo->mod.size())) || (ui_browserMod == 1 && serverInfo->mod.empty())) continue; // Filter by gametype - if (ui_joinGametype > 0 && (ui_joinGametype - 1) < *Game::gameTypeCount && Game::gameTypes[(ui_joinGametype - 1)].gameType != serverInfo->gametype) continue; + if (ui_joinGametype > 0 && (ui_joinGametype - 1) < *Game::gameTypeCount && Game::gameTypes[(ui_joinGametype - 1)].gameType != serverInfo->gametype) continue; VisibleList.push_back(i); } @@ -322,6 +322,19 @@ namespace Components continue; } + if (!entry.HasMember("ip") || !entry["protocol"].IsInt()) + { + continue; + } + + const auto protocol = entry["protocol"].GetInt(); + + if (protocol != PROTOCOL) + { + // We can't connect to it anyway + continue; + } + // Using VA because it's faster Network::Address server(Utils::String::VA("%s:%u", entry["ip"].GetString(), entry["port"].GetInt())); server.setType(Game::NA_IP); // Just making sure... @@ -371,7 +384,7 @@ namespace Components Toast::Show("cardicon_headshot", "Server Browser", "Fetching servers...", 3000); - const auto* url = "http://iw4x.plutools.pw/v1/servers/iw4x"; + const auto url = std::format("http://iw4x.getserve.rs/v1/servers/iw4x?protocol={}", PROTOCOL); const auto reply = Utils::WebIO("IW4x", url).setTimeout(5000)->get(); if (reply.empty()) { @@ -397,7 +410,7 @@ namespace Components void ServerList::StoreFavourite(const std::string& server) { std::vector servers; - + const auto parseData = Utils::IO::ReadFile(FavouriteFile); if (!parseData.empty()) { @@ -480,7 +493,7 @@ namespace Components auto* list = GetList(); if (list) list->clear(); - + RefreshVisibleListInternal(UIScript::Token(), nullptr); } @@ -535,7 +548,7 @@ namespace Components container.target = address; auto alreadyInserted = false; - for (auto &server : RefreshContainer.servers) + for (auto& server : RefreshContainer.servers) { if (server.target == container.target) { @@ -610,7 +623,15 @@ namespace Components std::hash hashFn; server.hash = hashFn(server); + // more secure server.hostname = TextRenderer::StripMaterialTextIcons(server.hostname); + + if (server.hostname.empty() || std::all_of(server.hostname.begin(), server.hostname.end(), isspace)) + { + // Invalid server name containing only emojis + return; + } + server.mapname = TextRenderer::StripMaterialTextIcons(server.mapname); server.gametype = TextRenderer::StripMaterialTextIcons(server.gametype); server.mod = TextRenderer::StripMaterialTextIcons(server.mod); @@ -722,36 +743,36 @@ namespace Components if (!IsServerListOpen()) return; std::ranges::stable_sort(VisibleList, [](const unsigned int& server1, const unsigned int& server2) -> bool - { - ServerInfo* info1 = nullptr; - ServerInfo* info2 = nullptr; + { + ServerInfo* info1 = nullptr; + ServerInfo* info2 = nullptr; - auto* list = GetList(); - if (!list) return false; + auto* list = GetList(); + if (!list) return false; - if (list->size() > server1) info1 = &(*list)[server1]; - if (list->size() > server2) info2 = &(*list)[server2]; + if (list->size() > server1) info1 = &(*list)[server1]; + if (list->size() > server2) info2 = &(*list)[server2]; - if (!info1) return false; - if (!info2) return false; + if (!info1) return false; + if (!info2) return false; - // Numerical comparisons - if (SortKey == static_cast>(Column::Ping)) - { - return info1->ping < info2->ping; - } + // Numerical comparisons + if (SortKey == static_cast>(Column::Ping)) + { + return info1->ping < info2->ping; + } - if (SortKey == static_cast>(Column::Players)) - { - return info1->clients < info2->clients; - } + if (SortKey == static_cast>(Column::Players)) + { + return info1->clients < info2->clients; + } - auto text1 = Utils::String::ToLower(TextRenderer::StripColors(GetServerInfoText(info1, SortKey, true))); - auto text2 = Utils::String::ToLower(TextRenderer::StripColors(GetServerInfoText(info2, SortKey, true))); + auto text1 = Utils::String::ToLower(TextRenderer::StripColors(GetServerInfoText(info1, SortKey, true))); + auto text2 = Utils::String::ToLower(TextRenderer::StripColors(GetServerInfoText(info2, SortKey, true))); - // ASCII-based comparison - return text1.compare(text2) < 0; - }); + // ASCII-based comparison + return text1.compare(text2) < 0; + }); if (!SortAsc) std::ranges::reverse(VisibleList); } @@ -910,17 +931,17 @@ namespace Components VisibleList.clear(); Events::OnDvarInit([] - { - UIServerSelected = Dvar::Register("ui_serverSelected", false, + { + UIServerSelected = Dvar::Register("ui_serverSelected", false, Game::DVAR_NONE, "Whether a server has been selected in the serverlist"); - UIServerSelectedMap = Dvar::Register("ui_serverSelectedMap", "mp_afghan", - Game::DVAR_NONE, "Map of the selected server"); + UIServerSelectedMap = Dvar::Register("ui_serverSelectedMap", "mp_afghan", + Game::DVAR_NONE, "Map of the selected server"); - NETServerQueryLimit = Dvar::Register("net_serverQueryLimit", 1, - 1, 10, Dedicated::IsEnabled() ? Game::DVAR_NONE : Game::DVAR_ARCHIVE, "Amount of server queries per frame"); - NETServerFrames = Dvar::Register("net_serverFrames", 30, - 1, 60, Dedicated::IsEnabled() ? Game::DVAR_NONE : Game::DVAR_ARCHIVE, "Amount of server query frames per second"); - }); + NETServerQueryLimit = Dvar::Register("net_serverQueryLimit", 1, + 1, 10, Dedicated::IsEnabled() ? Game::DVAR_NONE : Game::DVAR_ARCHIVE, "Amount of server queries per frame"); + NETServerFrames = Dvar::Register("net_serverFrames", 30, + 1, 60, Dedicated::IsEnabled() ? Game::DVAR_NONE : Game::DVAR_ARCHIVE, "Amount of server query frames per second"); + }); // Fix ui_netsource dvar Utils::Hook::Nop(0x4CDEEC, 5); // Don't reset the netsource when gametypes aren't loaded @@ -928,35 +949,35 @@ namespace Components Localization::Set("MPUI_SERVERQUERIED", "Servers: 0\nPlayers: 0 (0)"); Network::OnClientPacket("getServersResponse", [](const Network::Address& address, [[maybe_unused]] const std::string& data) - { - if (RefreshContainer.host != address) return; // Only parse from host we sent to + { + if (RefreshContainer.host != address) return; // Only parse from host we sent to - RefreshContainer.awatingList = false; + RefreshContainer.awatingList = false; - std::lock_guard _(RefreshContainer.mutex); + std::lock_guard _(RefreshContainer.mutex); - auto offset = 0; - const auto count = RefreshContainer.servers.size(); - MasterEntry* entry; + auto offset = 0; + const auto count = RefreshContainer.servers.size(); + MasterEntry* entry; - // Find first entry - do - { - entry = reinterpret_cast(const_cast(data.data()) + offset++); - } while (!entry->HasSeparator() && !entry->IsEndToken()); + // Find first entry + do + { + entry = reinterpret_cast(const_cast(data.data()) + offset++); + } while (!entry->HasSeparator() && !entry->IsEndToken()); - for (int i = 0; !entry[i].IsEndToken() && entry[i].HasSeparator(); ++i) - { - Network::Address serverAddr = address; - serverAddr.setIP(entry[i].ip); - serverAddr.setPort(ntohs(entry[i].port)); - serverAddr.setType(Game::NA_IP); + for (int i = 0; !entry[i].IsEndToken() && entry[i].HasSeparator(); ++i) + { + Network::Address serverAddr = address; + serverAddr.setIP(entry[i].ip); + serverAddr.setPort(ntohs(entry[i].port)); + serverAddr.setType(Game::NA_IP); - InsertRequest(serverAddr); - } + InsertRequest(serverAddr); + } - Logger::Print("Parsed {} servers from master\n", RefreshContainer.servers.size() - count); - }); + Logger::Print("Parsed {} servers from master\n", RefreshContainer.servers.size() - count); + }); // Set default masterServerName + port and save it Utils::Hook::Set(0x60AD92, "server.alterware.dev"); @@ -973,69 +994,69 @@ namespace Components UIScript::Add("RefreshServers", Refresh); UIScript::Add("JoinServer", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - auto* serverInfo = GetServer(CurrentServer); - if (serverInfo) { - Party::Connect(serverInfo->addr); - } - }); + auto* serverInfo = GetServer(CurrentServer); + if (serverInfo) + { + Party::Connect(serverInfo->addr); + } + }); UIScript::Add("ServerSort", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - const auto key = token.get(); - if (SortKey == key) - { - SortAsc = !SortAsc; - } - else { - SortKey = key; - SortAsc = true; - } + const auto key = token.get(); + if (SortKey == key) + { + SortAsc = !SortAsc; + } + else + { + SortKey = key; + SortAsc = true; + } - Logger::Print("Sorting server list by token: {}\n", SortKey); - SortList(); - }); + Logger::Print("Sorting server list by token: {}\n", SortKey); + SortList(); + }); UIScript::Add("CreateListFavorite", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - auto* serverInfo = GetCurrentServer(); - if (info && serverInfo && serverInfo->addr.isValid()) { - StoreFavourite(serverInfo->addr.getString()); - } - }); + auto* serverInfo = GetCurrentServer(); + if (info && serverInfo && serverInfo->addr.isValid()) + { + StoreFavourite(serverInfo->addr.getString()); + } + }); UIScript::Add("CreateFavorite", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - const auto value = Dvar::Var("ui_favoriteAddress").get(); - if (!value.empty()) { - StoreFavourite(value); - } - }); + const auto value = Dvar::Var("ui_favoriteAddress").get(); + if (!value.empty()) + { + StoreFavourite(value); + } + }); UIScript::Add("CreateCurrentServerFavorite", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - if (Game::CL_IsCgameInitialized()) { - const auto addressText = Network::Address(*Game::connectedHost).getString(); - if (addressText != "0.0.0.0:0"s && addressText != "loopback"s) + if (Game::CL_IsCgameInitialized()) { - StoreFavourite(addressText); + const auto addressText = Network::Address(*Game::connectedHost).getString(); + if (addressText != "0.0.0.0:0"s && addressText != "loopback"s) + { + StoreFavourite(addressText); + } } - } - }); + }); UIScript::Add("DeleteFavorite", []([[maybe_unused]] const UIScript::Token& token, [[maybe_unused]] const Game::uiInfo_s* info) - { - auto* serverInfo = GetCurrentServer(); - if (serverInfo) { - RemoveFavourite(serverInfo->addr.getString()); - } - }); + auto* serverInfo = GetCurrentServer(); + if (serverInfo) + { + RemoveFavourite(serverInfo->addr.getString()); + } + }); // Add required ownerDraws UIScript::AddOwnerDraw(220, UpdateSource); diff --git a/src/Components/Modules/ServerList.hpp b/src/Components/Modules/ServerList.hpp index abe61896..193b789b 100644 --- a/src/Components/Modules/ServerList.hpp +++ b/src/Components/Modules/ServerList.hpp @@ -23,6 +23,7 @@ namespace Components int ping; int matchType; int securityLevel; + int protocol; bool hardcore; bool svRunning; bool aimassist; diff --git a/src/Components/Modules/StructuredData.cpp b/src/Components/Modules/StructuredData.cpp index 34f9e6c9..ca55b76b 100644 --- a/src/Components/Modules/StructuredData.cpp +++ b/src/Components/Modules/StructuredData.cpp @@ -3,6 +3,8 @@ namespace Components { + constexpr auto BASE_PLAYERSTATS_VERSION = 155; + Utils::Memory::Allocator StructuredData::MemAllocator; const char* StructuredData::EnumTranslation[COUNT] = @@ -26,6 +28,11 @@ namespace Components { if (!data || type >= StructuredData::PlayerDataType::COUNT) return; + // Reallocate them before patching + Game::StructuredDataEnum* newEnums = MemAllocator.allocateArray(data->enumCount); + std::memcpy(newEnums, data->enums, sizeof(Game::StructuredDataEnum) * data->enumCount); + data->enums = newEnums; + Game::StructuredDataEnum* dataEnum = &data->enums[type]; // Build index-sorted data vector @@ -87,23 +94,52 @@ namespace Components void StructuredData::PatchCustomClassLimit(Game::StructuredDataDef* data, int count) { - const int customClassSize = 64; + constexpr auto CLASS_ARRAY = 5; + const auto originalClassCount = data->indexedArrays[CLASS_ARRAY].arraySize; - for (int i = 0; i < data->structs[0].propertyCount; ++i) + if (count != originalClassCount) { - // 3003 is the offset of the customClasses structure - if (data->structs[0].properties[i].offset >= 3643) + const int customClassSize = 64; + + // We need to recreate the struct list cause it's used in order definitions + auto newStructs = StructuredData::MemAllocator.allocateArray(data->structCount); + std::memcpy(newStructs, data->structs, data->structCount * sizeof(Game::StructuredDataStruct)); + data->structs = newStructs; + + constexpr auto structIndex = 0; { - // -10 because 10 is the default amount of custom classes. - data->structs[0].properties[i].offset += ((count - 10) * customClassSize); + auto strct = &data->structs[structIndex]; + + auto newProperties = StructuredData::MemAllocator.allocateArray(strct->propertyCount); + std::memcpy(newProperties, strct->properties, strct->propertyCount * sizeof(Game::StructuredDataStructProperty)); + strct->properties = newProperties; + + for (int propertyIndex = 0; propertyIndex < strct->propertyCount; ++propertyIndex) + { + // 3643 is the offset of the customClasses structure + if (strct->properties[propertyIndex].offset >= 3643) + { + // -10 because 10 is the default amount of custom classes. + strct->properties[propertyIndex].offset += ((count - originalClassCount) * customClassSize); + } + } } - } - // update structure size - data->size += ((count - 10) * customClassSize); + // update structure size + data->size += ((count - originalClassCount) * customClassSize); + + // Update amount of custom classes + if (data->indexedArrays[CLASS_ARRAY].arraySize != count) + { + // We need to recreate the whole array - this reference could be reused accross definitions + auto newIndexedArray = StructuredData::MemAllocator.allocateArray(data->indexedArrayCount); + std::memcpy(newIndexedArray, data->indexedArrays, data->indexedArrayCount * sizeof(Game::StructuredDataIndexedArray)); + data->indexedArrays = newIndexedArray; - // Update amount of custom classes - data->indexedArrays[5].arraySize = count; + // Add classes + data->indexedArrays[CLASS_ARRAY].arraySize = count; + } + } } void StructuredData::PatchAdditionalData(Game::StructuredDataDef* data, std::unordered_map& patches) @@ -119,26 +155,44 @@ namespace Components bool StructuredData::UpdateVersionOffsets(Game::StructuredDataDefSet* set, Game::StructuredDataBuffer* buffer, Game::StructuredDataDef* whatever) { - Game::StructuredDataDef* newDef = &set->defs[0]; - Game::StructuredDataDef* oldDef = &set->defs[0]; - - for (unsigned int i = 0; i < set->defCount; ++i) + if (set->defCount > 1) { - if (newDef->version < set->defs[i].version) - { - newDef = &set->defs[i]; - } + int bufferVersion = *reinterpret_cast(buffer->data); - if (set->defs[i].version == *reinterpret_cast(buffer->data)) + for (size_t i = 0; i < set->defCount; i++) { - oldDef = &set->defs[i]; + if (set->defs[i].version == bufferVersion) + { + if (i == 0) + { + // No update to conduct + } + else + { + Game::StructuredDataDef* newDef = &set->defs[i - 1]; + Game::StructuredDataDef* oldDef = &set->defs[i]; + + if (newDef->version == 159 && oldDef->version <= 158) + { + // this should move the data 320 bytes infront + std::memmove(&buffer->data[3963], &buffer->data[3643], oldDef->size - 3643); + } + else if (newDef->version > 159 && false) + { + // 159 cannot be translated upwards and it's hard to say why + // Reading it fails in various ways + // might be the funky class bump...? + + Command::Execute("setPlayerData prestige 10"); + Command::Execute("setPlayerData experience 2516000"); + } + + return Utils::Hook::Call(0x456830)(set, buffer, whatever); + } + } } - } - if (newDef->version >= 159 && oldDef->version <= 158) - { - // this should move the data 320 bytes infront - std::memmove(&buffer->data[3963], &buffer->data[3643], oldDef->size - 3643); + return Utils::Hook::Call(0x456830)(set, buffer, whatever); } // StructuredData_UpdateVersion @@ -182,7 +236,7 @@ namespace Components return; } - if (data->defs[0].version != 155) + if (data->defs[0].version != BASE_PLAYERSTATS_VERSION) { Logger::Error(Game::ERR_FATAL, "Initial PlayerDataDef is not version 155, patching not possible!"); return; @@ -262,16 +316,10 @@ namespace Components auto* newData = StructuredData::MemAllocator.allocateArray(data->defCount + patchDefinitions.size()); std::memcpy(&newData[patchDefinitions.size()], data->defs, sizeof Game::StructuredDataDef * data->defCount); - // Prepare the buffers + // Set the versions for (unsigned int i = 0; i < patchDefinitions.size(); ++i) { - std::memcpy(&newData[i], data->defs, sizeof Game::StructuredDataDef); - newData[i].version = (patchDefinitions.size() - i) + 155; - - // Reallocate the enum array - auto* newEnums = StructuredData::MemAllocator.allocateArray(data->defs->enumCount); - std::memcpy(newEnums, data->defs->enums, sizeof Game::StructuredDataEnum * data->defs->enumCount); - newData[i].enums = newEnums; + newData[i].version = (patchDefinitions.size() - i) + BASE_PLAYERSTATS_VERSION; } // Apply new data @@ -279,10 +327,18 @@ namespace Components data->defCount += patchDefinitions.size(); // Patch the definition - for (unsigned int i = 0; i < data->defCount; ++i) + for (int i = data->defCount - 1; i >= 0; --i) { // No need to patch version 155 - if (newData[i].version == 155) continue; + if (newData[i].version == BASE_PLAYERSTATS_VERSION) + { + continue; + } + + // We start from the previous one + const auto version = newData[i].version; + data->defs[i] = data->defs[i + 1]; + newData[i].version = version; if (patchDefinitions.contains(newData[i].version)) { diff --git a/src/Components/Modules/TextRenderer.cpp b/src/Components/Modules/TextRenderer.cpp index 91d9ff52..8eb0fe05 100644 --- a/src/Components/Modules/TextRenderer.cpp +++ b/src/Components/Modules/TextRenderer.cpp @@ -1414,7 +1414,7 @@ namespace Components std::string TextRenderer::StripMaterialTextIcons(const std::string& in) { char buffer[1000]{}; // Should be more than enough - StripAllTextIcons(in.data(), buffer, sizeof(buffer)); + StripMaterialTextIcons(in.data(), buffer, sizeof(buffer)); return std::string{ buffer }; } diff --git a/src/Components/Modules/Vote.cpp b/src/Components/Modules/Vote.cpp index 9679907d..8a2d6c2c 100644 --- a/src/Components/Modules/Vote.cpp +++ b/src/Components/Modules/Vote.cpp @@ -2,11 +2,14 @@ #include "ClientCommand.hpp" #include "MapRotation.hpp" #include "Vote.hpp" +#include "Events.hpp" using namespace Utils::String; namespace Components { + Dvar::Var Vote::SV_VotesRequired; + std::unordered_map Vote::VoteCommands = { {"map_restart", HandleMapRestart}, @@ -37,6 +40,17 @@ namespace Components Game::SV_SetConfigstring(Game::CS_VOTE_NO, VA("%i", Game::level->voteNo)); } + int Vote::VotesRequired() + { + auto votesRequired = Vote::SV_VotesRequired.get(); + + if (votesRequired > 0) + { + return votesRequired; + } + return Game::level->numConnectedClients / 2 + 1; + } + bool Vote::IsInvalidVoteString(const std::string& input) { static const char* separators[] = { "\n", "\r", ";" }; @@ -204,7 +218,7 @@ namespace Components return; } - if (Game::level->numConnectedClients < 2) + if (Game::level->numConnectedClients < VotesRequired()) { Game::SV_GameSendServerCommand(ent - Game::g_entities, Game::SV_CMD_CAN_IGNORE, VA("%c \"GAME_VOTINGNOTENOUGHPLAYERS\"", 0x65)); return; @@ -218,7 +232,7 @@ namespace Components return; } - if (ent->client->sess.voteCount >= 3) + if (ent->client->sess.voteCount >= VotesRequired()) { Game::SV_GameSendServerCommand(ent - Game::g_entities, Game::SV_CMD_CAN_IGNORE, VA("%c \"GAME_MAXVOTESCALLED\"", 0x65)); return; @@ -321,6 +335,10 @@ namespace Components // Replicate g_allowVote Utils::Hook::Set(0x5E3A4F, Game::DVAR_INTERNAL | Game::DVAR_CODINFO); + Events::OnDvarInit([]{ + Vote::SV_VotesRequired = Game::Dvar_RegisterInt("sv_votesRequired", 0, 0, 18, Game::DVAR_NONE, "Set the amount of votes required for a vote to pass.\n0 = (players / 2) + 1"); + }); + ClientCommand::Add("callvote", Cmd_CallVote_f); ClientCommand::Add("vote", Cmd_Vote_f); diff --git a/src/Components/Modules/Vote.hpp b/src/Components/Modules/Vote.hpp index 82b35d22..ac4f4405 100644 --- a/src/Components/Modules/Vote.hpp +++ b/src/Components/Modules/Vote.hpp @@ -11,11 +11,14 @@ namespace Components using CommandHandler = std::function; static std::unordered_map VoteCommands; + static Dvar::Var SV_VotesRequired; + static constexpr auto* CallVoteDesc = "%c \"GAME_VOTECOMMANDSARE\x15 map_restart, map_rotate, map , g_gametype , typemap , " "kick , tempBanUser \""; static void DisplayVote(const Game::gentity_s* ent); static bool IsInvalidVoteString(const std::string& input); + static int VotesRequired(); static bool HandleMapRestart(const Game::gentity_s* ent, const Command::ServerParams* params); static bool HandleMapRotate(const Game::gentity_s* ent, const Command::ServerParams* params); diff --git a/src/Components/Modules/Weapon.cpp b/src/Components/Modules/Weapon.cpp index 5f3fd9f0..9d1e036d 100644 --- a/src/Components/Modules/Weapon.cpp +++ b/src/Components/Modules/Weapon.cpp @@ -6,8 +6,6 @@ namespace Components { const Game::dvar_t* Weapon::BGWeaponOffHandFix; - Game::XModel* Weapon::G_ModelIndexReallocated[G_MODELINDEX_LIMIT]; - bool Weapon::GModelIndexHasBeenReallocated; Game::WeaponCompleteDef* Weapon::LoadWeaponCompleteDef(const char* name) { @@ -20,12 +18,6 @@ namespace Components return Game::DB_IsXAssetDefault(Game::ASSET_TYPE_WEAPON, name) ? nullptr : zoneWeaponFile; } - const char* Weapon::GetWeaponConfigString(int index) - { - if (index >= (1200 + 2804)) index += (2939 - 2804); - return Game::CL_GetConfigString(index); - } - void Weapon::SaveRegisteredWeapons() { *reinterpret_cast(0x1A86098) = 0; @@ -34,217 +26,10 @@ namespace Components { for (unsigned int i = 1; i < Game::BG_GetNumWeapons(); ++i) { - Game::SV_SetConfigstring(i + (i >= 1200 ? 2939 : 2804), Game::BG_GetWeaponName(i)); + Game::SV_SetConfigstring(i + (i >= BASEGAME_WEAPON_LIMIT ? 2939 : 2804), Game::BG_GetWeaponName(i)); } } } - - int Weapon::ParseWeaponConfigStrings() - { - Command::ClientParams params; - - if (params.size() <= 1) - return 0; - - char* end; - const auto* input = params.get(1); - auto index = std::strtol(input, &end, 10); - - if (input == end) - { - Logger::Warning(Game::CON_CHANNEL_DONT_FILTER, "{} is not a valid input\nUsage: {} \n", - input, params.get(0)); - return 0; - } - - if (index >= 4139) - { - index -= 2939; - } - else if (index > 2804 && index <= 2804 + 1200) - { - index -= 2804; - } - else - { - return 0; - } - - Game::CG_SetupWeaponDef(0, index); - return 1; - } - - __declspec(naked) void Weapon::ParseConfigStrings() - { - __asm - { - push eax - pushad - - push edi - call Weapon::ParseWeaponConfigStrings - pop edi - - mov [esp + 20h], eax - popad - pop eax - - test eax, eax - jz continueParsing - - retn - - continueParsing: - push 592960h - retn - } - } - - int Weapon::ClearConfigStrings(void* dest, int value, int size) - { - memset(Utils::Hook::Get(0x405B72), value, MAX_CONFIGSTRINGS * 2); - return Utils::Hook::Call(0x4C98D0)(dest, value, size); // Com_Memset - } - - void Weapon::PatchConfigStrings() - { - Utils::Hook::Set(0x4347A7, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x4982F4, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x4F88B6, MAX_CONFIGSTRINGS); // Save file - Utils::Hook::Set(0x5A1FA7, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x5A210D, MAX_CONFIGSTRINGS); // Game state - Utils::Hook::Set(0x5A840E, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x5A853C, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x5AC392, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x5AC3F5, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x5AC542, MAX_CONFIGSTRINGS); // Game state - Utils::Hook::Set(0x5EADF0, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x625388, MAX_CONFIGSTRINGS); - Utils::Hook::Set(0x625516, MAX_CONFIGSTRINGS); - - // Adjust weapon count index - // Actually this has to stay the way it is! - //Utils::Hook::Set(0x4EB7B3, MAX_CONFIGSTRINGS - 1); - //Utils::Hook::Set(0x5929BA, MAX_CONFIGSTRINGS - 1); - //Utils::Hook::Set(0x5E2FAA, MAX_CONFIGSTRINGS - 1); - - static short configStrings[MAX_CONFIGSTRINGS]; - ZeroMemory(&configStrings, sizeof(configStrings)); - - Utils::Hook::Set(0x405B72, configStrings); - Utils::Hook::Set(0x468508, configStrings); - Utils::Hook::Set(0x47FD7C, configStrings); - Utils::Hook::Set(0x49830E, configStrings); - Utils::Hook::Set(0x498371, configStrings); - Utils::Hook::Set(0x4983D5, configStrings); - Utils::Hook::Set(0x4A74AD, configStrings); - Utils::Hook::Set(0x4BAE7C, configStrings); - Utils::Hook::Set(0x4BAEC3, configStrings); - Utils::Hook::Set(0x6252F5, configStrings); - Utils::Hook::Set(0x625372, configStrings); - Utils::Hook::Set(0x6253D3, configStrings); - Utils::Hook::Set(0x625480, configStrings); - Utils::Hook::Set(0x6254CB, configStrings); - - // This has nothing to do with configstrings - //Utils::Hook::Set(0x608095, configStrings[4139 - 0x16]); - //Utils::Hook::Set(0x6080BC, configStrings[4139 - 0x16]); - //Utils::Hook::Set(0x6082AC, configStrings[4139 - 0x16]); - //Utils::Hook::Set(0x6082B3, configStrings[4139 - 0x16]); - - //Utils::Hook::Set(0x608856, configStrings[4139 - 0x14]); - - // TODO: Check if all of these actually mark the end of the array - // Only 2 actually mark the end, the rest is header data or so - Utils::Hook::Set(0x405B8F, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x459121, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x45A476, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x49FD56, &configStrings[ARRAYSIZE(configStrings)]); - Utils::Hook::Set(0x4A74C9, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x4C8196, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x4EBCE6, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x4F36D6, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x60807C, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x6080A9, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x6080D0, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x6081C4, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x608211, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x608274, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x6083D6, &configStrings[ARRAYSIZE(configStrings)]); - //Utils::Hook::Set(0x60848E, &configStrings[ARRAYSIZE(configStrings)]); - - Utils::Hook(0x405BBE, Weapon::ClearConfigStrings, HOOK_CALL).install()->quick(); - Utils::Hook(0x593CA4, Weapon::ParseConfigStrings, HOOK_CALL).install()->quick(); - Utils::Hook(0x4BD52D, Weapon::GetWeaponConfigString, HOOK_CALL).install()->quick(); - Utils::Hook(0x45D170, Weapon::SaveRegisteredWeapons, HOOK_JUMP).install()->quick(); - - // Patch game state - // The structure below is our own implementation of the gameState_t structure - static struct newGameState_t - { - int stringOffsets[MAX_CONFIGSTRINGS]; - char stringData[131072]; // MAX_GAMESTATE_CHARS - int dataCount; - } gameState; - - ZeroMemory(&gameState, sizeof(gameState)); - - Utils::Hook::Set(0x44A333, sizeof(gameState)); - Utils::Hook::Set(0x5A1F56, sizeof(gameState)); - Utils::Hook::Set(0x5A2043, sizeof(gameState)); - - Utils::Hook::Set(0x5A2053, sizeof(gameState.stringOffsets)); - Utils::Hook::Set(0x5A2098, sizeof(gameState.stringOffsets)); - Utils::Hook::Set(0x5AC32C, sizeof(gameState.stringOffsets)); - - Utils::Hook::Set(0x4235AC, &gameState.stringOffsets); - Utils::Hook::Set(0x434783, &gameState.stringOffsets); - Utils::Hook::Set(0x44A339, &gameState.stringOffsets); - Utils::Hook::Set(0x44ADB7, &gameState.stringOffsets); - Utils::Hook::Set(0x5A1FE6, &gameState.stringOffsets); - Utils::Hook::Set(0x5A2048, &gameState.stringOffsets); - Utils::Hook::Set(0x5A205A, &gameState.stringOffsets); - Utils::Hook::Set(0x5A2077, &gameState.stringOffsets); - Utils::Hook::Set(0x5A2091, &gameState.stringOffsets); - Utils::Hook::Set(0x5A20D7, &gameState.stringOffsets); - Utils::Hook::Set(0x5A83FF, &gameState.stringOffsets); - Utils::Hook::Set(0x5A84B0, &gameState.stringOffsets); - Utils::Hook::Set(0x5A84E5, &gameState.stringOffsets); - Utils::Hook::Set(0x5AC333, &gameState.stringOffsets); - Utils::Hook::Set(0x5AC44A, &gameState.stringOffsets); - Utils::Hook::Set(0x5AC4F3, &gameState.stringOffsets); - Utils::Hook::Set(0x5AC57A, &gameState.stringOffsets); - - Utils::Hook::Set(0x4235B7, &gameState.stringData); - Utils::Hook::Set(0x43478D, &gameState.stringData); - Utils::Hook::Set(0x44ADBC, &gameState.stringData); - Utils::Hook::Set(0x5A1FEF, &gameState.stringData); - Utils::Hook::Set(0x5A20E6, &gameState.stringData); - Utils::Hook::Set(0x5AC457, &gameState.stringData); - Utils::Hook::Set(0x5AC502, &gameState.stringData); - Utils::Hook::Set(0x5AC586, &gameState.stringData); - - Utils::Hook::Set(0x5A2071, &gameState.dataCount); - Utils::Hook::Set(0x5A20CD, &gameState.dataCount); - Utils::Hook::Set(0x5A20DC, &gameState.dataCount); - Utils::Hook::Set(0x5A20F3, &gameState.dataCount); - Utils::Hook::Set(0x5A2104, &gameState.dataCount); - Utils::Hook::Set(0x5AC33F, &gameState.dataCount); - Utils::Hook::Set(0x5AC43B, &gameState.dataCount); - Utils::Hook::Set(0x5AC450, &gameState.dataCount); - Utils::Hook::Set(0x5AC463, &gameState.dataCount); - Utils::Hook::Set(0x5AC471, &gameState.dataCount); - Utils::Hook::Set(0x5AC4C3, &gameState.dataCount); - Utils::Hook::Set(0x5AC4E8, &gameState.dataCount); - Utils::Hook::Set(0x5AC4F8, &gameState.dataCount); - Utils::Hook::Set(0x5AC50F, &gameState.dataCount); - Utils::Hook::Set(0x5AC528, &gameState.dataCount); - Utils::Hook::Set(0x5AC56F, &gameState.dataCount); - Utils::Hook::Set(0x5AC580, &gameState.dataCount); - Utils::Hook::Set(0x5AC592, &gameState.dataCount); - Utils::Hook::Set(0x5AC59F, &gameState.dataCount); - } - void Weapon::PatchLimit() { Utils::Hook::Set(0x403783, WEAPON_LIMIT); @@ -283,8 +68,8 @@ namespace Components // And http://reverseengineering.stackexchange.com/questions/1397/how-can-i-reverse-optimized-integer-division-modulo-by-constant-operations // The game's magic number is computed using this formula: (1 / 1200) * (2 ^ (32 + 7) // I'm too lazy to generate the new magic number, so we can make use of the fact that using powers of 2 as scales allows to change the compensating shift - static_assert(((WEAPON_LIMIT / 1200) * 1200) == WEAPON_LIMIT && (WEAPON_LIMIT / 1200) != 0 && !((WEAPON_LIMIT / 1200) & ((WEAPON_LIMIT / 1200) - 1)), "WEAPON_LIMIT / 1200 is not a power of 2!"); - const unsigned char compensation = 7 + static_cast(log2(WEAPON_LIMIT / 1200)); // 7 is the compensation the game uses + static_assert(((WEAPON_LIMIT / BASEGAME_WEAPON_LIMIT) * BASEGAME_WEAPON_LIMIT) == WEAPON_LIMIT && (WEAPON_LIMIT / BASEGAME_WEAPON_LIMIT) != 0 && !((WEAPON_LIMIT / BASEGAME_WEAPON_LIMIT) & ((WEAPON_LIMIT / BASEGAME_WEAPON_LIMIT) - 1)), "WEAPON_LIMIT / 1200 is not a power of 2!"); + const unsigned char compensation = 7 + static_cast(log2(WEAPON_LIMIT / BASEGAME_WEAPON_LIMIT)); // 7 is the compensation the game uses Utils::Hook::Set(0x49263D, compensation); Utils::Hook::Set(0x5E250C, compensation); Utils::Hook::Set(0x5E2B43, compensation); @@ -407,49 +192,34 @@ namespace Components // Patch bg_weaponDefs on the stack Utils::Hook::Set(0x40C31D, sizeof(bg_weaponDefs)); Utils::Hook::Set(0x40C32F, sizeof(bg_weaponDefs)); - Utils::Hook::Set(0x40C311, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); - Utils::Hook::Set(0x40C45F, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); - Utils::Hook::Set(0x40C478, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); - Utils::Hook::Set(0x40C434, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); - Utils::Hook::Set(0x40C434, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); + Utils::Hook::Set(0x40C311, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); + Utils::Hook::Set(0x40C45F, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); + Utils::Hook::Set(0x40C478, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); + Utils::Hook::Set(0x40C434, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); + Utils::Hook::Set(0x40C434, 0x258C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); // Move second buffer pointers - Utils::Hook::Set(0x40C336, 0x12E4 + ((sizeof(bg_weaponDefs)) - (1200 * 4))); - Utils::Hook::Set(0x40C3C6, 0x12DC + ((sizeof(bg_weaponDefs)) - (1200 * 4))); - Utils::Hook::Set(0x40C3CE, 0x12DC + ((sizeof(bg_weaponDefs)) - (1200 * 4))); + Utils::Hook::Set(0x40C336, 0x12E4 + ((sizeof(bg_weaponDefs)) - (BASEGAME_WEAPON_LIMIT * 4))); + Utils::Hook::Set(0x40C3C6, 0x12DC + ((sizeof(bg_weaponDefs)) - (BASEGAME_WEAPON_LIMIT * 4))); + Utils::Hook::Set(0x40C3CE, 0x12DC + ((sizeof(bg_weaponDefs)) - (BASEGAME_WEAPON_LIMIT * 4))); // Move arg0 pointers - Utils::Hook::Set(0x40C365, 0x259C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); - Utils::Hook::Set(0x40C44E, 0x259C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); - Utils::Hook::Set(0x40C467, 0x259C + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); + Utils::Hook::Set(0x40C365, 0x259C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); + Utils::Hook::Set(0x40C44E, 0x259C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); + Utils::Hook::Set(0x40C467, 0x259C + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); // Move arg4 pointers - Utils::Hook::Set(0x40C344, 0x25B4 + ((sizeof(bg_weaponDefs) * 2) - (1200 * 4 * 2))); + Utils::Hook::Set(0x40C344, 0x25B4 + ((sizeof(bg_weaponDefs) * 2) - (BASEGAME_WEAPON_LIMIT * 4 * 2))); // Patch bg_sharedAmmoCaps on the stack Utils::Hook::Set(0x4F76E6, sizeof(bg_sharedAmmoCaps)); - Utils::Hook::Set(0x4F7621, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); - Utils::Hook::Set(0x4F76AF, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); - Utils::Hook::Set(0x4F76DA, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); - Utils::Hook::Set(0x4F77C5, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); + Utils::Hook::Set(0x4F7621, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); + Utils::Hook::Set(0x4F76AF, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); + Utils::Hook::Set(0x4F76DA, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); + Utils::Hook::Set(0x4F77C5, 0x12C8 + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); // Move arg0 pointers - Utils::Hook::Set(0x4F766D, 0x12DC + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); - Utils::Hook::Set(0x4F76B7, 0x12DC + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); - Utils::Hook::Set(0x4F76FB, 0x12EC + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); + Utils::Hook::Set(0x4F766D, 0x12DC + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); + Utils::Hook::Set(0x4F76B7, 0x12DC + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); + Utils::Hook::Set(0x4F76FB, 0x12EC + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); // Move arg4 pointers - Utils::Hook::Set(0x4F7630, 0x12DC + (sizeof(bg_sharedAmmoCaps) - (1200 * 4))); - - - // Reallocate G_ModelIndex - Utils::Hook::Set(0x420654 + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x43BCE4 + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x44F27B + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x479087 + 1, G_ModelIndexReallocated); - Utils::Hook::Set(0x48069D + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x48F088 + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x4F457C + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x5FC762 + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x5FC7BE + 3, G_ModelIndexReallocated); - Utils::Hook::Set(0x44F256 + 2, G_MODELINDEX_LIMIT); - - GModelIndexHasBeenReallocated = true; + Utils::Hook::Set(0x4F7630, 0x12DC + (sizeof(bg_sharedAmmoCaps) - (BASEGAME_WEAPON_LIMIT * 4))); } void* Weapon::LoadNoneWeaponHook() @@ -641,7 +411,6 @@ namespace Components Weapon::Weapon() { PatchLimit(); - PatchConfigStrings(); // BG_LoadWEaponCompleteDef_FastFile Utils::Hook(0x57B650, LoadWeaponCompleteDef, HOOK_JUMP).install()->quick(); diff --git a/src/Components/Modules/Weapon.hpp b/src/Components/Modules/Weapon.hpp index 60c17c60..fb0a238b 100644 --- a/src/Components/Modules/Weapon.hpp +++ b/src/Components/Modules/Weapon.hpp @@ -1,14 +1,6 @@ #pragma once -// Increase the weapon limit -// Was 1200 before -#define WEAPON_LIMIT 2400 -#define MAX_CONFIGSTRINGS (4139 - 1200 + WEAPON_LIMIT) -// Double the limit to allow loading of some heavy-duty MW3 maps -#define ADDITIONAL_GMODELS 512 - -#define G_MODELINDEX_LIMIT (512 + WEAPON_LIMIT - 1200 + ADDITIONAL_GMODELS) namespace Components { @@ -16,9 +8,12 @@ namespace Components { public: Weapon(); - static Game::XModel* G_ModelIndexReallocated[G_MODELINDEX_LIMIT]; + static const int BASEGAME_WEAPON_LIMIT = 1200; + + // Increase the weapon limit + static const int WEAPON_LIMIT = 2400; - static bool GModelIndexHasBeenReallocated; + static const int ADDED_WEAPONS = WEAPON_LIMIT - BASEGAME_WEAPON_LIMIT; private: static const Game::dvar_t* BGWeaponOffHandFix; @@ -27,15 +22,9 @@ namespace Components static void PatchLimit(); static void* LoadNoneWeaponHook(); static void LoadNoneWeaponHookStub(); - static void PatchConfigStrings(); - static const char* GetWeaponConfigString(int index); static void SaveRegisteredWeapons(); - static void ParseConfigStrings(); - static int ParseWeaponConfigStrings(); - static int ClearConfigStrings(void* dest, int value, int size); - static void CG_UpdatePrimaryForAltModeWeapon_Stub(); static void CG_SelectWeaponIndex_Stub(); diff --git a/src/Components/Modules/ZoneBuilder.cpp b/src/Components/Modules/ZoneBuilder.cpp index b84fa205..56943fe4 100644 --- a/src/Components/Modules/ZoneBuilder.cpp +++ b/src/Components/Modules/ZoneBuilder.cpp @@ -7,12 +7,14 @@ #include #include "AssetInterfaces/ILocalizeEntry.hpp" + +#include "Events.hpp" #include "Branding.hpp" namespace Components { std::string ZoneBuilder::TraceZone; - std::vector> ZoneBuilder::TraceAssets; + std::vector ZoneBuilder::TraceAssets; bool ZoneBuilder::MainThreadInterrupted; DWORD ZoneBuilder::InterruptingThreadId; @@ -22,6 +24,8 @@ namespace Components iw4of::api ZoneBuilder::ExporterAPI(GetExporterAPIParams()); std::string ZoneBuilder::DumpingZone{}; + Dvar::Var ZoneBuilder::zb_sp_to_mp{}; + ZoneBuilder::Zone::Zone(const std::string& name, const std::string& sourceName, const std::string& destination) : indexStart(0), externalSize(0), // Reserve 100MB by default. @@ -40,7 +44,7 @@ namespace Components } - ZoneBuilder::Zone::Zone(const std::string& name) : ZoneBuilder::Zone::Zone(name, name, std::format("zone/english/{}.ff", name)) + ZoneBuilder::Zone::Zone(const std::string& name) : ZoneBuilder::Zone::Zone(name, name, std::format("zonebuilder_out/{}.ff", name)) { } @@ -115,7 +119,7 @@ namespace Components return &iw4ofApi; } - void ZoneBuilder::Zone::Zone::build() + void ZoneBuilder::Zone::build() { if (!this->dataMap.isValid()) { @@ -463,6 +467,10 @@ namespace Components outBuffer.append(zoneBuffer); + // Make sure directory exists + const auto directoryName = std::filesystem::path(destination).parent_path(); + Utils::IO::CreateDir(directoryName.string()); + Utils::IO::WriteFile(destination, outBuffer); Logger::Print("done writing {}\n", destination); @@ -730,11 +738,11 @@ namespace Components ZoneBuilder::TraceZone = zone; } - std::vector> ZoneBuilder::EndAssetTrace() + std::vector ZoneBuilder::EndAssetTrace() { ZoneBuilder::TraceZone.clear(); - std::vector> AssetTrace; + std::vector AssetTrace; Utils::Merge(&AssetTrace, ZoneBuilder::TraceAssets); ZoneBuilder::TraceAssets.clear(); @@ -1112,18 +1120,6 @@ namespace Components sound->info.data_ptr = allocatedSpace; } - Game::Sys_File ZoneBuilder::Sys_CreateFile_Stub(const char* dir, const char* filename) - { - auto file = Game::Sys_CreateFile(dir, filename); - - if (file.handle == INVALID_HANDLE_VALUE) - { - file = Game::Sys_CreateFile("zone\\zonebuilder\\", filename); - } - - return file; - } - iw4of::params_t ZoneBuilder::GetExporterAPIParams() { iw4of::params_t params{}; @@ -1175,7 +1171,212 @@ namespace Components return params; } - std::function ZoneBuilder::LoadZoneWithTrace(const std::string& zone, OUT std::vector>& assets) + void ZoneBuilder::DumpZone(const std::string& zone) + { + ZoneBuilder::DumpingZone = zone; + ZoneBuilder::RefreshExporterWorkDirectory(); + + std::vector assets{}; + const auto unload = ZoneBuilder::LoadZoneWithTrace(zone, assets); + + Logger::Print("Dumping zone '{}'...\n", zone); + + { + Utils::IO::CreateDir(GetDumpingZonePath()); + + // Order the CSV around + constexpr Game::XAssetType typeOrder[] = { + Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP, + Game::XAssetType::ASSET_TYPE_GAMEWORLD_SP, + Game::XAssetType::ASSET_TYPE_GFXWORLD, + Game::XAssetType::ASSET_TYPE_COMWORLD, + Game::XAssetType::ASSET_TYPE_FXWORLD, + Game::XAssetType::ASSET_TYPE_CLIPMAP_MP, + Game::XAssetType::ASSET_TYPE_CLIPMAP_SP, + Game::XAssetType::ASSET_TYPE_RAWFILE, + Game::XAssetType::ASSET_TYPE_VEHICLE, + Game::XAssetType::ASSET_TYPE_WEAPON, + Game::XAssetType::ASSET_TYPE_FX, + Game::XAssetType::ASSET_TYPE_TRACER, + Game::XAssetType::ASSET_TYPE_XMODEL, + Game::XAssetType::ASSET_TYPE_MATERIAL, + Game::XAssetType::ASSET_TYPE_TECHNIQUE_SET, + Game::XAssetType::ASSET_TYPE_PIXELSHADER, + Game::XAssetType::ASSET_TYPE_VERTEXSHADER, + Game::XAssetType::ASSET_TYPE_VERTEXDECL, + Game::XAssetType::ASSET_TYPE_LIGHT_DEF, + Game::XAssetType::ASSET_TYPE_IMAGE, + Game::XAssetType::ASSET_TYPE_SOUND, + Game::XAssetType::ASSET_TYPE_LOADED_SOUND, + Game::XAssetType::ASSET_TYPE_SOUND_CURVE, + Game::XAssetType::ASSET_TYPE_PHYSPRESET, + Game::XAssetType::ASSET_TYPE_LOCALIZE_ENTRY, + }; + + std::unordered_map typePriority{}; + for (auto i = 0; i < ARRAYSIZE(typeOrder); i++) + { + const auto type = typeOrder[i]; + typePriority.emplace(type, 1 + ARRAYSIZE(typeOrder) - i); + } + + enum AssetCategory + { + EXPLICIT, + IMPLICIT, + NOT_SUPPORTED, + DISAPPEARED, + + COUNT + }; + + std::vector assetsToList[AssetCategory::COUNT]{}; + + std::sort(assets.begin(), assets.end(), [&]( + const NamedAsset& a, + const NamedAsset& b + ) { + if (a.type == b.type) + { + + return a.name.compare(b.name) < 0; + } + else + { + const auto priorityA = typePriority[a.type]; + const auto priorityB = typePriority[b.type]; + + if (priorityA == priorityB) + { + return a.name.compare(b.name) < 0; + } + else + { + return priorityB < priorityA; + } + } + }); + + std::unordered_set assetsToSkip{}; + const std::function)> recursivelyAddChildren = + [&](std::unordered_set children) + { + for (const auto& k : children) + { + const auto type = static_cast(k.type); + Game::XAsset asset = { type, {k.data} }; + const auto insertionInfo = assetsToSkip.insert({ type, Game::DB_GetXAssetName(&asset) }); + + if (insertionInfo.second) + { + // True means it was inserted, so we might need to check children aswell + if (ExporterAPI.is_type_supported(k.type)) + { + const auto deps = ExporterAPI.get_children(k.type, k.data); + recursivelyAddChildren(deps); + } + } + } + }; + + Logger::Print("Filtering asset list for '{}.csv'...\n", zone); + std::vector explicitAssetsToFilter{}; + + // Filter implicit and assets that don't need dumping + for (const auto& asset : assets) + { + const auto type = asset.type; + const auto& name = asset.name; + + if (assetsToSkip.contains({ type, name.data() })) + { + assetsToList[AssetCategory::IMPLICIT].push_back(std::format("{},{}", Game::DB_GetXAssetTypeName(type), name)); + continue; + } + + if (ExporterAPI.is_type_supported(type) && name[0] != ',') + { + const auto assetHeader = Game::DB_FindXAssetHeader(type, name.data()); + if (assetHeader.data) + { + const auto children = ExporterAPI.get_children(type, assetHeader.data); + + recursivelyAddChildren(children); + explicitAssetsToFilter.push_back({ type, assetHeader }); + } + else + { + Logger::Warning(Game::conChannel_t::CON_CHANNEL_ERROR, "Asset {} has disappeared while dumping!\n", name); + assetsToList[AssetCategory::DISAPPEARED].push_back(std::format("{},{}", Game::DB_GetXAssetTypeName(type), name)); + } + } + else + { + assetsToList[AssetCategory::NOT_SUPPORTED].push_back(std::format("{},{}", Game::DB_GetXAssetTypeName(type), name)); + } + } + + // Write explicit assets + Logger::Print("Dumping remaining assets...\n"); + for (auto& asset : explicitAssetsToFilter) + { + const auto& name = Game::DB_GetXAssetName(&asset); + if (!assetsToSkip.contains({ asset.type, name })) + { + ExporterAPI.write(asset.type, asset.header.data); + Logger::Print("."); + assetsToList[AssetCategory::EXPLICIT].push_back(std::format("{},{}", Game::DB_GetXAssetTypeName(asset.type), name)); + } + } + + Logger::Print("\n"); + + // Write zone source + Logger::Print("Writing zone source...\n"); + std::ofstream csv(std::filesystem::path(GetDumpingZonePath()) / std::format("{}.csv", zone)); + csv + << std::format("### Zone '{}' dumped with Zonebuilder {}", zone, Components::Branding::GetVersionString()) + << "\n\n"; + + for (size_t i = 0; i < AssetCategory::COUNT; i++) + { + if (assetsToList[i].size() == 0) + { + continue; + } + + switch (static_cast(i)) + { + case AssetCategory::EXPLICIT: + break; + case AssetCategory::IMPLICIT: + csv << "\n### The following assets are implicitly built with previous assets:\n"; + break; + case AssetCategory::NOT_SUPPORTED: + csv << "\n### The following assets are not supported for dumping:\n"; + break; + case AssetCategory::DISAPPEARED: + csv << "\n### The following assets disappeared while dumping but are mentioned in the zone:\n"; + break; + } + + for (const auto& asset : assetsToList[i]) + { + csv << (i == AssetCategory::EXPLICIT ? "" : "#") << asset << "\n"; + } + } + + csv << std::format("\n### {} assets", assets.size()) << "\n"; + } + + unload(); + + Logger::Print("Zone '{}' dumped", ZoneBuilder::DumpingZone); + ZoneBuilder::DumpingZone = std::string(); + } + + + std::function ZoneBuilder::LoadZoneWithTrace(const std::string& zone, OUT std::vector& assets) { ZoneBuilder::BeginAssetTrace(zone); @@ -1216,8 +1417,6 @@ namespace Components // Prevent loading textures (preserves loaddef) //Utils::Hook::Set(Game::Load_Texture, 0xC3); - Utils::Hook(0x5BC832, Sys_CreateFile_Stub, HOOK_CALL).install()->quick(); - // Store the loaddef Utils::Hook(Game::Load_Texture, StoreTexture, HOOK_JUMP).install()->quick(); @@ -1311,6 +1510,8 @@ namespace Components // don't remap techsets Utils::Hook::Nop(0x5BC791, 5); + + ZoneBuilder::zb_sp_to_mp = Game::Dvar_RegisterBool("zb_sp_to_mp", false, Game::DVAR_ARCHIVE, "Attempt to convert singleplayer assets to multiplayer format whenever possible"); Utils::Hook::Set(0x5B97B6, 0xE9); @@ -1321,7 +1522,7 @@ namespace Components { if (!ZoneBuilder::TraceZone.empty() && ZoneBuilder::TraceZone == FastFiles::Current()) { - ZoneBuilder::TraceAssets.emplace_back(std::make_pair(type, name)); + ZoneBuilder::TraceAssets.push_back({ type, name }); } }); @@ -1333,186 +1534,7 @@ namespace Components std::string zone = params->get(1); - ZoneBuilder::DumpingZone = zone; - ZoneBuilder::RefreshExporterWorkDirectory(); - - std::vector> assets{}; - const auto unload = ZoneBuilder::LoadZoneWithTrace(zone, assets); - - Logger::Print("Dumping zone '{}'...\n", zone); - - { - Utils::IO::CreateDir(GetDumpingZonePath()); - std::ofstream csv(std::filesystem::path(GetDumpingZonePath()) / std::format("{}.csv", zone)); - csv - << std::format("### Zone '{}' dumped with Zonebuilder {}", zone, Components::Branding::GetVersionString()) - << "\n\n"; - - constexpr Game::XAssetType typeOrder[] = { - Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP, - Game::XAssetType::ASSET_TYPE_GAMEWORLD_SP, - Game::XAssetType::ASSET_TYPE_GFXWORLD, - Game::XAssetType::ASSET_TYPE_COMWORLD, - Game::XAssetType::ASSET_TYPE_FXWORLD, - Game::XAssetType::ASSET_TYPE_CLIPMAP_MP, - Game::XAssetType::ASSET_TYPE_CLIPMAP_SP, - Game::XAssetType::ASSET_TYPE_RAWFILE, - Game::XAssetType::ASSET_TYPE_VEHICLE, - Game::XAssetType::ASSET_TYPE_WEAPON, - Game::XAssetType::ASSET_TYPE_FX, - Game::XAssetType::ASSET_TYPE_TRACER, - Game::XAssetType::ASSET_TYPE_XMODEL, - Game::XAssetType::ASSET_TYPE_MATERIAL, - Game::XAssetType::ASSET_TYPE_TECHNIQUE_SET, - Game::XAssetType::ASSET_TYPE_PIXELSHADER, - Game::XAssetType::ASSET_TYPE_VERTEXSHADER, - Game::XAssetType::ASSET_TYPE_VERTEXDECL, - Game::XAssetType::ASSET_TYPE_IMAGE, - Game::XAssetType::ASSET_TYPE_SOUND, - Game::XAssetType::ASSET_TYPE_LOADED_SOUND, - Game::XAssetType::ASSET_TYPE_SOUND_CURVE, - Game::XAssetType::ASSET_TYPE_PHYSPRESET, - }; - - std::unordered_map typePriority{}; - for (auto i = 0; i < ARRAYSIZE(typeOrder); i++) - { - const auto type = typeOrder[i]; - typePriority.emplace(type, 1 + ARRAYSIZE(typeOrder) - i); - } - - std::map> invalidAssets{}; - - std::sort(assets.begin(), assets.end(), [&]( - const std::pair& a, - const std::pair& b - ) { - if (a.first == b.first) - { - - return a.second.compare(b.second) < 0; - } - else - { - const auto priorityA = typePriority[a.first]; - const auto priorityB = typePriority[b.first]; - - if (priorityA == priorityB) - { - return a.second.compare(b.second) < 0; - } - else - { - return priorityB < priorityA; - } - } - }); - - // Used to format the CSV - Game::XAssetType lastTypeEncountered{}; - - for (auto& asset : assets) - { - bool skip = false; - - switch (asset.first) - { - case Game::XAssetType::ASSET_TYPE_RAWFILE: - case Game::XAssetType::ASSET_TYPE_TECHNIQUE_SET: - case Game::XAssetType::ASSET_TYPE_MATERIAL: - case Game::XAssetType::ASSET_TYPE_PIXELSHADER: - case Game::XAssetType::ASSET_TYPE_VERTEXSHADER: - case Game::XAssetType::ASSET_TYPE_VERTEXDECL: - case Game::XAssetType::ASSET_TYPE_IMAGE: - case Game::XAssetType::ASSET_TYPE_XMODEL: - case Game::XAssetType::ASSET_TYPE_XANIMPARTS: - - break; - - default: - skip = true; - break; - } - - - Logger::Print("Dumping asset {} '{}'...\n", (int)asset.first, asset.second); - const auto type = asset.first; - const auto name = asset.second; - - if (ExporterAPI.is_type_supported(type) && !skip) - { - const auto assetHeader = Game::DB_FindXAssetHeader(type, name.data()); - - if (assetHeader.data) - { - // IW4OF only supports gameworldMP for now, fortunately the types are very similar - { - //if (asset.first == Game::XAssetType::ASSET_TYPE_GAMEWORLD_SP && assetHeader.gameWorldSp) - //{ - // asset.first = Game::XAssetType::ASSET_TYPE_GAMEWORLD_MP; - - // auto* newWorldMp = assetReallocator.allocate(); - // newWorldMp->name = assetHeader.gameWorldSp->name; - // newWorldMp->g_glassData = assetHeader.gameWorldSp->g_glassData; - - // assetHeader.gameWorldMp = newWorldMp; - //} - - if (asset.first == Game::XAssetType::ASSET_TYPE_IMAGE) - { - if (assetHeader.image->category == Game::ImageCategory::IMG_CATEGORY_UNKNOWN) - { - assetHeader.image->category = Game::ImageCategory::IMG_CATEGORY_LOAD_FROM_FILE; - } - } - - if (asset.first == Game::XAssetType::ASSET_TYPE_TECHNIQUE_SET && assetHeader.techniqueSet) - { - // fix for garbage PTRs hanging out in iw4 memory - assetHeader.techniqueSet->remappedTechniqueSet = nullptr; - } - } - - - ExporterAPI.write(type, assetHeader.data); - const auto typeName = Game::DB_GetXAssetTypeName(type); - - if (type != lastTypeEncountered) - { - csv << "\n### " << typeName << "\n"; - lastTypeEncountered = type; - } - - csv << typeName << "," << name << "\n"; - } - else - { - Logger::Warning(Game::conChannel_t::CON_CHANNEL_ERROR, "Asset {} has disappeared while dumping!\n", name); - invalidAssets["The following assets disappeared while dumping"].push_back(std::format("{},{}", Game::DB_GetXAssetTypeName(type), name)); - } - } - else - { - invalidAssets["The following assets are unsupported or not dumped as individual assets, but still present in the zone"].push_back(std::format("{},{}", Game::DB_GetXAssetTypeName(type), name)); - } - } - - for (const auto& kv : invalidAssets) - { - csv << "\n### " << kv.first << "\n"; - for (const auto& line : kv.second) - { - csv << "#" << line << "\n"; - } - } - - csv << std::format("\n### {} assets", assets.size()) << "\n"; - } - - unload(); - - Logger::Print("Zone '{}' dumped", ZoneBuilder::DumpingZone); - ZoneBuilder::DumpingZone = std::string(); + ZoneBuilder::DumpZone(zone); }); Command::Add("verifyzone", [](const Command::Params* params) @@ -1520,13 +1542,13 @@ namespace Components if (params->size() < 2) return; std::string zone = params->get(1); - std::vector> assets{}; + std::vector assets{}; const auto unload = ZoneBuilder::LoadZoneWithTrace(zone, assets); int count = 0; for (auto i = assets.begin(); i != assets.end(); ++i, ++count) { - Logger::Print(" {}: {}: {}\n", count, Game::DB_GetXAssetTypeName(i->first), i->second); + Logger::Print(" {}: {}: {}\n", count, Game::DB_GetXAssetTypeName(i->type), i->name); } Logger::Print("\n"); @@ -1547,18 +1569,20 @@ namespace Components { if (params->size() < 2) return; + Dvar::Var fs_game("fs_game"); + std::string modName = params->get(1); Logger::Print("Building zone for mod '{}'...\n", modName); - const std::string previousFsGame = Dvar::Var("fs_game").get(); + const std::string previousFsGame = fs_game.get(); const std::string dir = "mods/" + modName; Utils::IO::CreateDir(dir); - Dvar::Var("fs_game").set(dir); + fs_game.set(dir); Zone("mod", modName, dir + "/mod.ff").build(); - Dvar::Var("fs_game").set(previousFsGame); + fs_game.set(previousFsGame); }); Command::Add("buildall", []() @@ -1614,8 +1638,8 @@ namespace Components #endif } } - } - }); + } + }); Command::Add("listassets", [](const Command::Params* params) { @@ -1631,8 +1655,8 @@ namespace Components }, &type, false); } }); - } } +} ZoneBuilder::~ZoneBuilder() { diff --git a/src/Components/Modules/ZoneBuilder.hpp b/src/Components/Modules/ZoneBuilder.hpp index bc3affb5..dfa35924 100644 --- a/src/Components/Modules/ZoneBuilder.hpp +++ b/src/Components/Modules/ZoneBuilder.hpp @@ -32,7 +32,7 @@ namespace Components private: Zone* builder; }; - + Zone(const std::string& zoneName, const std::string& sourceName, const std::string& destination); Zone(const std::string& zoneName); ~Zone(); @@ -123,6 +123,22 @@ namespace Components size_t assetDepth; }; + struct NamedAsset + { + Game::XAssetType type; + std::string name; + + bool operator==(const NamedAsset& other) const { + return type == other.type && name == other.name; + }; + + struct Hash { + size_t operator()(const NamedAsset& k) const { + return static_cast(k.type) ^ std::hash{}(k.name); + } + }; + }; + ZoneBuilder(); ~ZoneBuilder(); @@ -130,10 +146,12 @@ namespace Components static bool IsDumpingZone() { return DumpingZone.length() > 0; }; static std::string TraceZone; - static std::vector> TraceAssets; + static std::vector TraceAssets; static void BeginAssetTrace(const std::string& zone); - static std::vector> EndAssetTrace(); + static std::vector EndAssetTrace(); + + static Dvar::Var zb_sp_to_mp; static Game::XAssetHeader GetEmptyAssetIfCommon(Game::XAssetType type, const std::string& name, Zone* builder); static std::string GetDumpingZonePath(); @@ -160,7 +178,9 @@ namespace Components static iw4of::params_t GetExporterAPIParams(); - static std::function LoadZoneWithTrace(const std::string& zone, OUT std::vector> &assets); + static void DumpZone(const std::string& zone); + + static std::function LoadZoneWithTrace(const std::string& zone, OUT std::vector& assets); static void Com_Quitf_t(); diff --git a/src/Game/FileSystem.cpp b/src/Game/FileSystem.cpp index 4486f405..d700607f 100644 --- a/src/Game/FileSystem.cpp +++ b/src/Game/FileSystem.cpp @@ -10,6 +10,7 @@ namespace Game FS_FOpenFileAppend_t FS_FOpenFileAppend = FS_FOpenFileAppend_t(0x410BB0); FS_FOpenFileWrite_t FS_FOpenFileWrite = FS_FOpenFileWrite_t(0x4BA530); FS_FOpenTextFileWrite_t FS_FOpenTextFileWrite = FS_FOpenTextFileWrite_t(0x43FD90); + FS_FileOpenReadText_t FS_FileOpenReadText = FS_FileOpenReadText_t(0x446B60); FS_FOpenFileRead_t FS_FOpenFileRead = FS_FOpenFileRead_t(0x46CBF0); FS_FOpenFileReadDatabase_t FS_FOpenFileReadDatabase = FS_FOpenFileReadDatabase_t(0x42ECA0); FS_FOpenFileReadForThread_t FS_FOpenFileReadForThread = FS_FOpenFileReadForThread_t(0x643270); diff --git a/src/Game/FileSystem.hpp b/src/Game/FileSystem.hpp index 41a0029e..74c2f793 100644 --- a/src/Game/FileSystem.hpp +++ b/src/Game/FileSystem.hpp @@ -26,6 +26,9 @@ namespace Game typedef int(*FS_FOpenFileRead_t)(const char* filename, int* file); extern FS_FOpenFileRead_t FS_FOpenFileRead; + typedef FILE*(*FS_FileOpenReadText_t)(const char* filename); + extern FS_FileOpenReadText_t FS_FileOpenReadText; + typedef int(*FS_FOpenFileReadDatabase_t)(const char* filename, int* file); extern FS_FOpenFileReadDatabase_t FS_FOpenFileReadDatabase; diff --git a/src/Game/Functions.cpp b/src/Game/Functions.cpp index 183084f2..0d3ee982 100644 --- a/src/Game/Functions.cpp +++ b/src/Game/Functions.cpp @@ -22,7 +22,7 @@ namespace Game CG_ScrollScoreboardUp_t CG_ScrollScoreboardUp = CG_ScrollScoreboardUp_t(0x47A5C0); CG_ScrollScoreboardDown_t CG_ScrollScoreboardDown = CG_ScrollScoreboardDown_t(0x493B50); CG_GetTeamName_t CG_GetTeamName = CG_GetTeamName_t(0x4B6210); - CG_SetupWeaponDef_t CG_SetupWeaponDef = CG_SetupWeaponDef_t(0x4BD520); + CG_SetupWeaponConfigString_t CG_SetupWeaponConfigString = CG_SetupWeaponConfigString_t(0x4BD520); Cmd_AddCommand_t Cmd_AddCommand = Cmd_AddCommand_t(0x470090); Cmd_AddServerCommand_t Cmd_AddServerCommand = Cmd_AddServerCommand_t(0x4DCE00); diff --git a/src/Game/Functions.hpp b/src/Game/Functions.hpp index d0481dfc..e613035b 100644 --- a/src/Game/Functions.hpp +++ b/src/Game/Functions.hpp @@ -51,8 +51,8 @@ namespace Game typedef const char*(*CG_GetTeamName_t)(team_t team); extern CG_GetTeamName_t CG_GetTeamName; - typedef void(*CG_SetupWeaponDef_t)(int localClientNum, unsigned int weapIndex); - extern CG_SetupWeaponDef_t CG_SetupWeaponDef; + typedef void(*CG_SetupWeaponConfigString_t)(int localClientNum, unsigned int weapIndex); + extern CG_SetupWeaponConfigString_t CG_SetupWeaponConfigString; typedef void(*Cmd_AddCommand_t)(const char* cmdName, void(*function), cmd_function_s* allocedCmd, int isKey); extern Cmd_AddCommand_t Cmd_AddCommand; diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 7e0ad53b..0b90782c 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -17,6 +17,12 @@ namespace Game G_DebugLineWithDuration_t G_DebugLineWithDuration = G_DebugLineWithDuration_t(0x4C3280); gentity_s* g_entities = reinterpret_cast(0x18835D8); + bool* g_quitRequested = reinterpret_cast(0x649FB61); + + NetField* clientStateFields = reinterpret_cast(0x741E40); + size_t clientStateFieldsCount = Utils::Hook::Get(0x7433C8); + + MssLocal* milesGlobal = reinterpret_cast(0x649A1A0); const char* origErrorMsg = reinterpret_cast(0x79B124); diff --git a/src/Game/Game.hpp b/src/Game/Game.hpp index b51e2538..12b3fe9c 100644 --- a/src/Game/Game.hpp +++ b/src/Game/Game.hpp @@ -52,6 +52,13 @@ namespace Game constexpr std::size_t MAX_GENTITIES = 2048; constexpr std::size_t ENTITYNUM_NONE = MAX_GENTITIES - 1; extern gentity_s* g_entities; + extern bool* g_quitRequested; + + // This does not belong anywhere else + extern NetField* clientStateFields; + extern size_t clientStateFieldsCount; + extern MssLocal* milesGlobal; + extern const char* origErrorMsg; diff --git a/src/Game/Structs.hpp b/src/Game/Structs.hpp index e3f80bb6..df639f09 100644 --- a/src/Game/Structs.hpp +++ b/src/Game/Structs.hpp @@ -1,6 +1,6 @@ #pragma once -#define PROTOCOL 0x96 +#define PROTOCOL 0x97 #define NUM_CUSTOM_CLASSES 15 #define FX_ELEM_FIELD_COUNT 90 @@ -527,8 +527,14 @@ namespace Game CS_VOTE_NO = 0x14, CS_VOTE_MAPNAME = 0x15, CS_VOTE_GAMETYPE = 0x16, + CS_MODELS = 0x465, // Models (confirmed) 1125 + // 1580<>1637 models not cached (something's going on, not sure what) + CS_MODELS_LAST = 0x664, // End of models CS_SHELLSHOCKS = 0x985, - CS_ITEMS = 0x102A, + CS_WEAPONFILES = 0xAF5, // 2805 Confirmed + CS_WEAPONFILES_LAST = 0xFA3, // Confirmed too // 4003 + CS_ITEMS = 4138, // Correct! CS_ITEMS is actually an item **COUNT** + MAX_CONFIGSTRINGS = 4139 }; // Incomplete enum conChannel_t @@ -1066,7 +1072,7 @@ namespace Game struct XSurfaceVertexInfo { - __int16 vertCount[4]; + unsigned __int16 vertCount[4]; unsigned __int16* vertsBlend; }; @@ -1133,11 +1139,11 @@ namespace Game unsigned __int16 triCount; XSurfaceCollisionTree* collisionTree; }; - + struct DObjSkelMat { - float axis[3][4]; - float origin[4]; + float axis[3][4]; + float origin[4]; }; struct XSurface @@ -1972,6 +1978,7 @@ namespace Game CMD_BUTTON_FRAG = 1 << 14, CMD_BUTTON_OFFHAND_SECONDARY = 1 << 15, CMD_BUTTON_THROW = 1 << 19, + CMD_BUTTON_REMOTE = 1 << 20, }; struct usercmd_s @@ -2419,7 +2426,7 @@ namespace Game float scale; unsigned int noScalePartBits[6]; unsigned __int16* boneNames; - unsigned char *parentList; + unsigned char* parentList; short* quats; float* trans; unsigned char* partClassification; @@ -4031,7 +4038,7 @@ namespace Game GfxSurfaceBounds* surfacesBounds; GfxStaticModelDrawInst* smodelDrawInsts; GfxDrawSurf* surfaceMaterials; - unsigned int* surfaceCastsSunShadow; + unsigned int* surfaceCastsSunShadow; volatile int usageCount; }; @@ -4042,7 +4049,7 @@ namespace Game unsigned __int16 materialSortedIndex : 12; unsigned __int16 visDataRefCountLessOne : 4; }; - + union GfxSModelSurfHeader { GfxSModelSurfHeaderFields fields; @@ -4961,6 +4968,14 @@ namespace Game float colors[5][4]; }; + struct NetField + { + char* name; + int offset; + int bits; + char changeHints; + }; + struct __declspec(align(4)) WeaponDef { const char* szOverlayName; @@ -5527,6 +5542,32 @@ namespace Game StructuredDataEnumEntry* entries; }; + enum LookupResultDataType + { + LOOKUP_RESULT_INT = 0x0, + LOOKUP_RESULT_BOOL = 0x1, + LOOKUP_RESULT_STRING = 0x2, + LOOKUP_RESULT_FLOAT = 0x3, + LOOKUP_RESULT_SHORT = 0x4, + }; + + enum LookupState + { + LOOKUP_IN_PROGRESS = 0x0, + LOOKUP_FINISHED = 0x1, + LOOKUP_ERROR = 0x2, + }; + + enum LookupError + { + LOOKUP_ERROR_NONE = 0x0, + LOOKUP_ERROR_WRONG_DATA_TYPE = 0x1, + LOOKUP_ERROR_INDEX_OUTSIDE_BOUNDS = 0x2, + LOOKUP_ERROR_INVALID_STRUCT_PROPERTY = 0x3, + LOOKUP_ERROR_INVALID_ENUM_VALUE = 0x4, + LOOKUP_ERROR_COUNT = 0x5, + }; + enum StructuredDataTypeCategory { DATA_INT = 0x0, @@ -5602,6 +5643,15 @@ namespace Game unsigned int size; }; + + struct StructuredDataLookup + { + StructuredDataDef* def; + StructuredDataType* type; + unsigned int offset; + LookupError error; + }; + struct StructuredDataDefSet { const char* name; @@ -7940,8 +7990,8 @@ namespace Game struct GfxCmdBufContext { - GfxCmdBufSourceState *source; - GfxCmdBufState *state; + GfxCmdBufSourceState* source; + GfxCmdBufState* state; }; struct GfxDrawGroupSetupFields @@ -8393,18 +8443,18 @@ namespace Game int timeStamp; DObjAnimMat* mat; }; - + struct bitarray { - int array[6]; + int array[6]; }; /* 1923 */ struct XAnimCalcAnimInfo { - DObjAnimMat rotTransArray[1152]; - bitarray animPartBits; - bitarray ignorePartBits; + DObjAnimMat rotTransArray[1152]; + bitarray animPartBits; + bitarray ignorePartBits; }; @@ -8741,7 +8791,7 @@ namespace Game char* skelMemoryStart; bool allowedAllocSkel; int serverId; - gameState_t gameState; + gameState_t cl_gameState; clSnapshot_t noDeltaSnapshot; int nextNoDeltaEntity; entityState_s noDeltaEntities[1024]; @@ -11102,6 +11152,166 @@ namespace Game huff_t compressDecompress; }; + enum FF_DIR + { + FFD_DEFAULT = 0x0, + FFD_MOD_DIR = 0x1, + FFD_USER_MAP = 0x2, + }; + + struct ASISTAGE + { + int(__stdcall* ASI_stream_open)(unsigned int, int(__stdcall*)(unsigned int, void*, int, int), unsigned int); + int(__stdcall* ASI_stream_process)(int, void*, int); + int(__stdcall* ASI_stream_seek)(int, int); + int(__stdcall* ASI_stream_close)(int); + int(__stdcall* ASI_stream_property)(int, unsigned int, void*, const void*, void*); + unsigned int INPUT_BIT_RATE; + unsigned int INPUT_SAMPLE_RATE; + unsigned int INPUT_BITS; + unsigned int INPUT_CHANNELS; + unsigned int OUTPUT_BIT_RATE; + unsigned int OUTPUT_SAMPLE_RATE; + unsigned int OUTPUT_BITS; + unsigned int OUTPUT_CHANNELS; + unsigned int OUTPUT_RESERVOIR; + unsigned int POSITION; + unsigned int PERCENT_DONE; + unsigned int MIN_INPUT_BLOCK_SIZE; + unsigned int RAW_RATE; + unsigned int RAW_BITS; + unsigned int RAW_CHANNELS; + unsigned int REQUESTED_RATE; + unsigned int REQUESTED_BITS; + unsigned int REQUESTED_CHANS; + unsigned int STREAM_SEEK_POS; + unsigned int DATA_START_OFFSET; + unsigned int DATA_LEN; + int stream; + }; + + struct _STREAM + { + int block_oriented; + int using_ASI; + ASISTAGE* ASI; + void* samp; + unsigned int fileh; + char* bufs[3]; + unsigned int bufsizes[3]; + int reset_ASI[3]; + int reset_seek_pos[3]; + int bufstart[3]; + void* asyncs[3]; + int loadedbufstart[2]; + int loadedorder[2]; + int loadorder; + int bufsize; + int readsize; + unsigned int buf1; + int size1; + unsigned int buf2; + int size2; + unsigned int buf3; + int size3; + unsigned int datarate; + int filerate; + int filetype; + unsigned int fileflags; + int totallen; + int substart; + int sublen; + int subpadding; + unsigned int blocksize; + int padding; + int padded; + int loadedsome; + unsigned int startpos; + unsigned int totalread; + unsigned int loopsleft; + unsigned int error; + int preload; + unsigned int preloadpos; + int noback; + int alldone; + int primeamount; + int readatleast; + int playcontrol; + void(__stdcall* callback)(_STREAM*); + int user_data[8]; + void* next; + int autostreaming; + int docallback; + }; + + enum SND_EQTYPE + { + SND_EQTYPE_FIRST = 0x0, + SND_EQTYPE_LOWPASS = 0x0, + SND_EQTYPE_HIGHPASS = 0x1, + SND_EQTYPE_LOWSHELF = 0x2, + SND_EQTYPE_HIGHSHELF = 0x3, + SND_EQTYPE_BELL = 0x4, + SND_EQTYPE_LAST = 0x4, + SND_EQTYPE_COUNT = 0x5, + SND_EQTYPE_INVALID = 0x5, + }; + + struct __declspec(align(4)) SndEqParams + { + SND_EQTYPE type; + float gain; + float freq; + float q; + bool enabled; + }; + + struct MssEqInfo + { + SndEqParams params[3][64]; + }; + + struct MssFileHandle + { + unsigned int id; + MssFileHandle* next; + int handle; + char fileName[128]; + unsigned int hashCode; + int offset; + int fileOffset; + int fileLength; + }; + + struct __declspec(align(4)) MssStreamReadInfo + { + char path[256]; + int timeshift; + float fraction; + int startDelay; + _STREAM* handle; + bool readError; + }; + + struct MssLocal + { + struct _DIG_DRIVER* driver; + struct _SAMPLE* handle_sample[40]; + _STREAM* handle_stream[12]; + bool voiceEqDisabled[52]; + MssEqInfo eq[2]; + float eqLerp; + unsigned int eqFilter; + int currentRoomtype; + MssFileHandle fileHandle[12]; + MssFileHandle* freeFileHandle; + bool isMultiChannel; + float realVolume[12]; + int playbackRate[52]; + MssStreamReadInfo streamReadInfo[12]; + }; + + #pragma endregion #ifndef IDA diff --git a/src/Game/System.cpp b/src/Game/System.cpp index 0571204a..5dabfe7c 100644 --- a/src/Game/System.cpp +++ b/src/Game/System.cpp @@ -56,4 +56,10 @@ namespace Game return TryEnterCriticalSection(&s_criticalSection[critSect]) != FALSE; } + + HANDLE Sys_OpenFileReliable(const char* filename) + { + return CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, nullptr); + } } diff --git a/src/Game/System.hpp b/src/Game/System.hpp index 84aff611..e98defec 100644 --- a/src/Game/System.hpp +++ b/src/Game/System.hpp @@ -84,6 +84,8 @@ namespace Game extern bool Sys_TryEnterCriticalSection(CriticalSection critSect); + extern HANDLE Sys_OpenFileReliable(const char* filename); + class Sys { public: diff --git a/src/STDInclude.hpp b/src/STDInclude.hpp index 03aad46b..56d3e7b1 100644 --- a/src/STDInclude.hpp +++ b/src/STDInclude.hpp @@ -56,6 +56,9 @@ #include #pragma comment (lib, "dwmapi.lib") +#include +#pragma comment (lib, "iphlpapi.lib") + // Ignore the warnings #pragma warning(push) #pragma warning(disable: 4100) diff --git a/src/Steam/Proxy.cpp b/src/Steam/Proxy.cpp index 248723ff..c4710b4a 100644 --- a/src/Steam/Proxy.cpp +++ b/src/Steam/Proxy.cpp @@ -276,8 +276,6 @@ namespace Steam void Proxy::RunFrame() { - return; - std::lock_guard _(Proxy::CallMutex); if (Proxy::SteamUtils) diff --git a/src/Utils/Cryptography.cpp b/src/Utils/Cryptography.cpp index d07525ff..06cbe1e9 100644 --- a/src/Utils/Cryptography.cpp +++ b/src/Utils/Cryptography.cpp @@ -8,7 +8,6 @@ namespace Utils { void Initialize() { - DES3::Initialize(); Rand::Initialize(); } @@ -28,6 +27,13 @@ namespace Utils return std::string{ buffer, static_cast(pos) }; } + std::uint64_t Rand::GenerateLong() + { + std::uint64_t number = 0; + fortuna_read(reinterpret_cast(&number), sizeof(number), &Rand::State); + return number; + } + std::uint32_t Rand::GenerateInt() { std::uint32_t number = 0; @@ -46,13 +52,44 @@ namespace Utils #pragma region ECC - ECC::Key ECC::GenerateKey(int bits) + ECC::Key ECC::GenerateKey(int bits, const std::string& entropy) { Key key; ltc_mp = ltm_desc; - register_prng(&sprng_desc); - ecc_make_key(nullptr, find_prng("sprng"), bits / 8, key.getKeyPtr()); + + if (entropy.empty()) + { + register_prng(&sprng_desc); + const auto result = ecc_make_key(nullptr, find_prng("sprng"), bits / 8, key.getKeyPtr()); + if (result != CRYPT_OK) + { + Components::Logger::PrintError(Game::conChannel_t::CON_CHANNEL_ERROR, "There was an issue generating a secured random key! Please contact support"); + } + } + else + { + int descriptorIndex = register_prng(&chacha20_prng_desc); + + // allocate state + prng_state* state = new prng_state(); + + chacha20_prng_start(state); + + chacha20_prng_add_entropy(reinterpret_cast(entropy.data()), entropy.size(), state); + + chacha20_prng_ready(state); + + const auto result = ecc_make_key(state, descriptorIndex, bits / 8, key.getKeyPtr()); + + if (result != CRYPT_OK) + { + Components::Logger::PrintError(Game::conChannel_t::CON_CHANNEL_ERROR, "There was an issue generating your unique player ID! Please contact support"); + } + + // Deallocate state + delete state; + } return key; } @@ -79,8 +116,8 @@ namespace Utils int result = 0; return (ecc_verify_hash(reinterpret_cast(signature.data()), signature.size(), - reinterpret_cast(message.data()), message.size(), - &result, key.getKeyPtr()) == CRYPT_OK && result != 0); + reinterpret_cast(message.data()), message.size(), + &result, key.getKeyPtr()) == CRYPT_OK && result != 0); } #pragma endregion @@ -115,7 +152,7 @@ namespace Utils ltc_mp = ltm_desc; rsa_sign_hash_ex(reinterpret_cast(hash.data()), hash.size(), - buffer, &length, LTC_PKCS_1_V1_5, nullptr, 0, hash_index, 0, key.getKeyPtr()); + buffer, &length, LTC_PKCS_1_V1_5, nullptr, 0, hash_index, 0, key.getKeyPtr()); return std::string{ reinterpret_cast(buffer), length }; } @@ -133,47 +170,8 @@ namespace Utils auto result = 0; return (rsa_verify_hash_ex(reinterpret_cast(signature.data()), signature.size(), - reinterpret_cast(hash.data()), hash.size(), LTC_PKCS_1_V1_5, - hash_index, 0, &result, key.getKeyPtr()) == CRYPT_OK && result != 0); - } - -#pragma endregion - -#pragma region DES3 - - void DES3::Initialize() - { - register_cipher(&des3_desc); - } - - std::string DES3::Encrypt(const std::string& text, const std::string& iv, const std::string& key) - { - std::string encData; - encData.resize(text.size()); - - symmetric_CBC cbc; - const auto des3 = find_cipher("3des"); - - cbc_start(des3, reinterpret_cast(iv.data()), reinterpret_cast(key.data()), static_cast(key.size()), 0, &cbc); - cbc_encrypt(reinterpret_cast(text.data()), reinterpret_cast(encData.data()), text.size(), &cbc); - cbc_done(&cbc); - - return encData; - } - - std::string DES3::Decrpyt(const std::string& data, const std::string& iv, const std::string& key) - { - std::string decData; - decData.resize(data.size()); - - symmetric_CBC cbc; - const auto des3 = find_cipher("3des"); - - cbc_start(des3, reinterpret_cast(iv.data()), reinterpret_cast(key.data()), static_cast(key.size()), 0, &cbc); - cbc_decrypt(reinterpret_cast(data.data()), reinterpret_cast(decData.data()), data.size(), &cbc); - cbc_done(&cbc); - - return decData; + reinterpret_cast(hash.data()), hash.size(), LTC_PKCS_1_V1_5, + hash_index, 0, &result, key.getKeyPtr()) == CRYPT_OK && result != 0); } #pragma endregion diff --git a/src/Utils/Cryptography.hpp b/src/Utils/Cryptography.hpp index 46ac5e14..67734f81 100644 --- a/src/Utils/Cryptography.hpp +++ b/src/Utils/Cryptography.hpp @@ -5,6 +5,7 @@ namespace Utils namespace Cryptography { void Initialize(); + std::string GetEntropy(); class Token { @@ -131,6 +132,7 @@ namespace Utils { public: static std::string GenerateChallenge(); + static std::uint64_t GenerateLong(); static std::uint32_t GenerateInt(); static void Initialize(); @@ -235,7 +237,7 @@ namespace Utils std::shared_ptr keyStorage; }; - static Key GenerateKey(int bits); + static Key GenerateKey(int bits, const std::string& entropy = {}); static std::string SignMessage(Key key, const std::string& message); static bool VerifyMessage(Key key, const std::string& message, const std::string& signature); }; @@ -327,14 +329,6 @@ namespace Utils static bool VerifyMessage(Key key, const std::string& message, const std::string& signature); }; - class DES3 - { - public: - static void Initialize(); - static std::string Encrypt(const std::string& text, const std::string& iv, const std::string& key); - static std::string Decrpyt(const std::string& text, const std::string& iv, const std::string& key); - }; - class Tiger { public: diff --git a/src/Utils/Library.cpp b/src/Utils/Library.cpp index 70d661de..d5220666 100644 --- a/src/Utils/Library.cpp +++ b/src/Utils/Library.cpp @@ -102,17 +102,17 @@ namespace Utils this->module_ = nullptr; } - void Library::LaunchProcess(const std::string& process, const std::string& commandLine, const std::string& currentDir) + void Library::LaunchProcess(const std::wstring& process, const std::wstring& commandLine, const std::filesystem::path& currentDir) { - STARTUPINFOA startupInfo; + STARTUPINFOW startupInfo; PROCESS_INFORMATION processInfo; ZeroMemory(&startupInfo, sizeof(startupInfo)); ZeroMemory(&processInfo, sizeof(processInfo)); startupInfo.cb = sizeof(startupInfo); - CreateProcessA(process.data(), const_cast(commandLine.data()), nullptr, - nullptr, false, NULL, nullptr, currentDir.data(), + CreateProcessW(process.data(), const_cast(commandLine.data()), nullptr, + nullptr, false, NULL, nullptr, currentDir.wstring().data(), &startupInfo, &processInfo); if (processInfo.hThread && processInfo.hThread != INVALID_HANDLE_VALUE) diff --git a/src/Utils/Library.hpp b/src/Utils/Library.hpp index 367d9d08..3ff72663 100644 --- a/src/Utils/Library.hpp +++ b/src/Utils/Library.hpp @@ -65,7 +65,7 @@ namespace Utils return T(); } - static void LaunchProcess(const std::string& process, const std::string& commandLine, const std::string& currentDir); + static void LaunchProcess(const std::wstring& process, const std::wstring& commandLine, const std::filesystem::path& currentDir); private: HMODULE module_; diff --git a/src/Utils/Utils.cpp b/src/Utils/Utils.cpp index a1066804..60e06a5f 100644 --- a/src/Utils/Utils.cpp +++ b/src/Utils/Utils.cpp @@ -25,8 +25,10 @@ namespace Utils void OutputDebugLastError() { +#ifdef DEBUG DWORD errorMessageID = ::GetLastError(); - OutputDebugStringA(Utils::String::VA("Last error code: 0x%08X (%s)\n", errorMessageID, GetLastWindowsError().data())); + OutputDebugStringA(String::VA("Last error code: 0x%08X (%s)\n", errorMessageID, GetLastWindowsError().data())); +#endif } std::string GetLastWindowsError() @@ -85,8 +87,7 @@ namespace Utils if (!ntdll) return nullptr; - static uint8_t ntQueryInformationThread[] = { 0xB1, 0x8B, 0xAE, 0x8A, 0x9A, 0x8D, 0x86, 0xB6, 0x91, 0x99, 0x90, 0x8D, 0x92, 0x9E, 0x8B, 0x96, 0x90, 0x91, 0xAB, 0x97, 0x8D, 0x9A, 0x9E, 0x9B }; // NtQueryInformationThread - NtQueryInformationThread_t NtQueryInformationThread = NtQueryInformationThread_t(GetProcAddress(ntdll, String::XOR(std::string(reinterpret_cast(ntQueryInformationThread), sizeof ntQueryInformationThread), -1).data())); + NtQueryInformationThread_t NtQueryInformationThread = NtQueryInformationThread_t(GetProcAddress(ntdll, "NtQueryInformationThread")); if (!NtQueryInformationThread) return nullptr; HANDLE dupHandle, currentProcess = GetCurrentProcess(); @@ -116,11 +117,15 @@ namespace Utils SetCurrentDirectoryW(binaryPath); } + /** + * IW4x_INSTALL should point to where the IW4x rawfiles/client files are + * or the current working dir + */ void SetEnvironment() { char* buffer{}; std::size_t size{}; - if (_dupenv_s(&buffer, &size, "MW2_INSTALL") != 0 || buffer == nullptr) + if (_dupenv_s(&buffer, &size, "IW4x_INSTALL") != 0 || buffer == nullptr) { SetLegacyEnvironment(); return; @@ -132,10 +137,57 @@ namespace Utils SetDllDirectoryA(buffer); } + /** + * Points to where the Modern Warfare 2 folder is + */ + std::filesystem::path GetBaseFilesLocation() + { + char* buffer{}; + std::size_t size{}; + if (_dupenv_s(&buffer, &size, "BASE_INSTALL") != 0 || buffer == nullptr) + { + return {}; + } + + const auto _0 = gsl::finally([&] { std::free(buffer); }); + + try + { + std::filesystem::path result = buffer; + return result; + } + catch (const std::exception& ex) + { + printf("Failed to convert '%s' to native file system path. Got error '%s'\n", buffer, ex.what()); + return {}; + } + } + + std::wstring GetLaunchParameters() + { + std::wstring args; + + int numArgs; + auto* const argv = CommandLineToArgvW(GetCommandLineW(), &numArgs); + + if (argv) + { + for (auto i = 1; i < numArgs; ++i) + { + std::wstring arg(argv[i]); + args.append(arg); + args.append(L" "); + } + + LocalFree(argv); + } + + return args; + } + HMODULE GetNTDLL() { - static uint8_t ntdll[] = { 0x91, 0x8B, 0x9B, 0x93, 0x93, 0xD1, 0x9B, 0x93, 0x93 }; // ntdll.dll - return GetModuleHandleA(Utils::String::XOR(std::string(reinterpret_cast(ntdll), sizeof ntdll), -1).data()); + return GetModuleHandleA("ntdll.dll"); } void SafeShellExecute(HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, INT nShowCmd) diff --git a/src/Utils/Utils.hpp b/src/Utils/Utils.hpp index eba34b59..9ec8664b 100644 --- a/src/Utils/Utils.hpp +++ b/src/Utils/Utils.hpp @@ -20,9 +20,12 @@ namespace Utils HMODULE GetNTDLL(); void SetEnvironment(); + std::filesystem::path GetBaseFilesLocation(); void OpenUrl(const std::string& url); + std::wstring GetLaunchParameters(); + bool HasIntersection(unsigned int base1, unsigned int len1, unsigned int base2, unsigned int len2); template