CS2-Kit
C++23 library for CS2 Metamod:Source plugin development
Loading...
Searching...
No Matches
GameData.cpp
Go to the documentation of this file.
1#include "Sdk/SigScanner.hpp"
2
3#include <CS2Kit/Core/Paths.hpp>
4#include <CS2Kit/Sdk/GameData.hpp>
5#include <CS2Kit/Utils/Log.hpp>
6#include <filesystem>
7#include <fstream>
8#include <nlohmann/json.hpp>
9
10namespace CS2Kit::Sdk
11{
12using namespace CS2Kit::Utils;
13
14bool GameData::Load(const std::string& path)
15{
16 try
17 {
18 auto fullPath = Core::ResolvePath(path);
19 std::ifstream file(fullPath);
20 if (!file.is_open())
21 {
22 Log::Warn("GameData file not found: {}", path);
23 return false;
24 }
25
26 auto json = nlohmann::json::parse(file,
27 /*cb=*/nullptr, /*allow_exceptions=*/true, /*ignore_comments=*/true);
28
29#ifdef _WIN32
30 constexpr const char* platform = "windows";
31#else
32 constexpr const char* platform = "linux";
33#endif
34
35 if (json.contains("offsets"))
36 {
37 for (auto& [name, entry] : json["offsets"].items())
38 {
39 if (entry.contains(platform))
40 _offsets[name] = entry[platform].get<int>();
41 }
42 }
43
44 if (json.contains("signatures"))
45 {
46 for (auto& [name, entry] : json["signatures"].items())
47 {
48 if (!entry.contains(platform))
49 continue;
50
51 auto& platEntry = entry[platform];
52 SignatureEntry sig;
53 sig.Library = entry.value("library", "server");
54 sig.Pattern = platEntry.value("pattern", "");
55 sig.Offset = platEntry.value("offset", 0);
56 _signatures[name] = std::move(sig);
57 }
58 }
59
60 Log::Info("GameData loaded: {} offsets, {} signatures.", _offsets.size(), _signatures.size());
61 return true;
62 }
63 catch (const std::exception& e)
64 {
65 Log::Warn("Failed to parse GameData: {}", e.what());
66 return false;
67 }
68}
69
70int GameData::GetOffset(const std::string& name) const
71{
72 auto it = _offsets.find(name);
73 return it != _offsets.end() ? it->second : -1;
74}
75
76void* GameData::FindSignature(const std::string& name) const
77{
78 auto it = _signatures.find(name);
79 if (it == _signatures.end())
80 return nullptr;
81
82 auto& sig = it->second;
83 return CS2Kit::Sdk::FindPattern(sig.Library.c_str(), sig.Pattern);
84}
85
86void* GameData::ResolveSignature(const std::string& name) const
87{
88 auto it = _signatures.find(name);
89 if (it == _signatures.end())
90 return nullptr;
91
92 auto& sig = it->second;
93 void* match = CS2Kit::Sdk::FindPattern(sig.Library.c_str(), sig.Pattern);
94 if (!match)
95 return nullptr;
96
97 if (sig.Offset == 0)
98 return match;
99
100 auto addr = reinterpret_cast<uintptr_t>(match) + sig.Offset;
101 addr = ResolveRelativeAddress(addr, 0, 4);
102 if (addr == 0)
103 return nullptr;
104 return reinterpret_cast<void*>(addr);
105}
106
107} // namespace CS2Kit::Sdk
std::filesystem::path ResolvePath(const std::string &relativePath)
Definition Paths.cpp:13
void * FindPattern(const char *moduleName, const std::string &pattern)
uintptr_t ResolveRelativeAddress(uintptr_t addr, int ripOffset, int ripSize)