id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,531,771
|
osc.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtinc/osc.hpp
|
#include<memory>
#ifndef OSC_H
namespace oscpkt {
class Message;
}
struct RecvMsg {
void *ar;
oscpkt::Message *msg;
RecvMsg(void *ar, oscpkt::Message *msg) : ar(ar), msg(msg) { }
~RecvMsg();
};
#endif
void _osc_send(const std::string &address, int port, double t, oscpkt::Message *msg);
oscpkt::Message *_osc_new_msg(const std::string& path);
void _osc_push(oscpkt::Message *m, int32_t v);
void _osc_push(oscpkt::Message *m, int64_t v);
void _osc_push(oscpkt::Message *m, float v);
void _osc_push(oscpkt::Message *m, double v);
void _osc_push(oscpkt::Message *m, const std::string &v);
void _osc_push_all(oscpkt::Message *) { }
template<typename T1, typename...T>
void _osc_push_all(oscpkt::Message *msg, T1 param1, T...params) {
_osc_push(msg, param1);
_osc_push_all(msg, params...);
}
template<typename...T>
void osc_send(const std::string &address, int port, double t, const std::string &path, T...params) {
oscpkt::Message *msg = _osc_new_msg(path);
_osc_push_all(msg, params...);
_osc_send(address, port, t, msg);
}
bool _osc_pop(RecvMsg &m, int32_t &v);
bool _osc_pop(RecvMsg &m, int64_t &v);
bool _osc_pop(RecvMsg &m, float &v);
bool _osc_pop(RecvMsg &m, double &v);
bool _osc_pop(RecvMsg &m, std::string &v);
bool osc_get(RecvMsg&) { return true; }
template<typename T1, typename...T>
bool osc_get(RecvMsg &msg, T1 &v1, T&... v) {
return _osc_pop(msg, v1) && osc_get(msg, v...);
}
std::vector<std::shared_ptr<RecvMsg>> osc_recv(int port, double t, const std::string &path);
| 1,529
|
C++
|
.h
| 42
| 34.285714
| 100
| 0.672507
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,772
|
connect.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtinc/connect.hpp
|
#define CONNECT_MIN 0
#define CONNECT_MAX 1
#define CONNECT_ALL 2
void connect(string a, string b, string filter_a="", string filter_b="", int mode=CONNECT_MAX);
void disconnect(string a, string b, string filter_a="", string filter_b="", int mode=CONNECT_MAX);
| 261
|
C++
|
.h
| 5
| 51.2
| 98
| 0.742188
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,773
|
pv.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtinc/pv.hpp
|
//PV = Phase Vocoder
struct PVBin {
double amp, freq;
PVBin() : amp(0), freq(0) { }
PVBin(double amp, double freq) : amp(amp), freq(freq) { }
};
using PVBuf = Buf<PVBin>;
namespace internals {
extern double hop;
}
struct PhaseVocoder {
PVBuf data;
Buf<double> last_phase;
Buf<double> phase_sum;
size_t size = 0;
size_t num_channels = 0;
FFTBuf fft;
bool global_hop;
double user_hop;
PhaseVocoder() { use_global_hop(); }
PhaseVocoder(size_t num_channels, size_t size) : PhaseVocoder() { resize(num_channels, size); }
void resize(size_t num_channels, size_t size) {
if (this->size*this->num_channels != size*num_channels) {
this->size = size;
this->num_channels = num_channels;
data.resize(num_channels, size);
last_phase.resize(num_channels, size);
phase_sum.resize(num_channels, size);
}
}
void reset(bool last=true, bool sum=true) {
if (last) last_phase.zero();
if (sum) phase_sum.zero();
}
void fill_from(PhaseVocoder &other) {
num_channels = other.num_channels;
size = other.size;
global_hop = other.global_hop;
user_hop = other.user_hop;
data.fill_from(other.data);
last_phase.fill_from(other.last_phase);
phase_sum.fill_from(other.phase_sum);
}
void use_global_hop() { global_hop = true; }
void set_hop(double new_hop) {
user_hop = new_hop;
global_hop = false;
}
double hop() {
if (global_hop) return internals::hop;
else return user_hop;
}
PVBin* operator[](int index) { return data[index]; }
void analyze(WaveBuf &other);
void synthesize(WaveBuf &other);
void analyze(FFTBuf &other);
void synthesize(FFTBuf &other);
double phase_to_frequency(size_t bin, double phase_diff);
double frequency_to_phase(double freq);
void shift(std::function<double(double)> fn);
void shift(std::function<void(WaveBuf&)> fn);
};
| 2,033
|
C++
|
.h
| 62
| 26.677419
| 99
| 0.621827
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,774
|
fft.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtinc/fft.hpp
|
#include <complex>
using cplx = std::complex<double>;
using FFTBuf = Buf<cplx>;
void frft(FFTBuf &in, FFTBuf &out, double exponent);
| 133
|
C++
|
.h
| 4
| 32.25
| 52
| 0.744186
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,775
|
root.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtlib/root.hpp
|
#include "osc.hpp"
#include "control.hpp"
#include "windowfn.hpp"
#include "fft.hpp"
#include "pv.hpp"
#include "connect.hpp"
| 126
|
C++
|
.h
| 6
| 20
| 23
| 0.75
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,776
|
control.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtlib/control.hpp
|
double current_time_secs();
using func_t = function<void(WaveBuf&, WaveBuf&, double)>;
namespace internals {
extern uint64_t window_size;
extern uint64_t new_window_size;
extern uint64_t hop_samples;
extern uint64_t hop_fract;
extern uint64_t computed_hop;
extern double hop;
extern deque<float> aqueue, atmp, ainqueue;
extern uint64_t time_samples;
extern uint64_t time_fract;
extern size_t nch_in, nch_out, new_nch_in, new_nch_out;
extern mutex data_mtx;
extern func_t fptr;
extern double rate;
extern vector<jack_port_t *> in_ports;
extern vector<jack_port_t *> out_ports;
extern jack_client_t *client;
}
void set_hop(double new_hop) {
if (new_hop < 0) cerr << "ignoring invalid hop: " << new_hop << endl;
else {
internals::hop = new_hop;
internals::hop_samples = new_hop;
internals::hop_fract = fmod(new_hop, 1.0)*double(uint64_t(-1));
}
}
void next_hop_samples(uint32_t n, double h) {
internals::new_window_size = n;
set_hop(h);
}
void next_hop_ratio(uint32_t n, double ratio) {
internals::new_window_size = n;
set_hop(n*ratio);
}
void next_hop_hz(uint32_t n, double hz) {
internals::new_window_size = n;
set_hop(internals::rate/hz);
}
void set_process_fn(func_t fn) {
internals::fptr = fn;
}
void set_time(double secs) {
if (secs < 0)
cerr << "negative time is not supported, ignoring call to set_time(" << secs << ")" << endl;
else {
base_time += current_time_secs() - secs;
internals::time_samples = uint64_t(secs*internals::rate);
internals::time_fract = fmod(secs*internals::rate, 1.0)*double(uint64_t(-1));
}
}
void set_num_channels(size_t in, size_t out) {
lock_guard<mutex> data_lk(internals::data_mtx);
internals::ainqueue.clear();
internals::aqueue.clear();
//TODO should probably clear atmp too
for (size_t i = in; i < internals::new_nch_in; i++) {
jack_port_unregister(internals::client, internals::in_ports.back());
internals::in_ports.pop_back();
}
for (size_t i = internals::new_nch_in; i < in; i++) {
string name = "in" + to_string(i);
internals::in_ports.push_back(jack_port_register(internals::client, name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
}
for (size_t i = out; i < internals::new_nch_out; i++) {
jack_port_unregister(internals::client, internals::out_ports.back());
internals::out_ports.pop_back();
}
for (size_t i = internals::new_nch_out; i < out; i++) {
string name = "out" + to_string(i);
internals::out_ports.push_back(jack_port_register(internals::client, name.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
}
internals::new_nch_in = in;
internals::new_nch_out = out;
}
void skip_to_now() {
lock_guard<mutex> data_lk(internals::data_mtx);
internals::ainqueue.resize(internals::nch_in*(internals::computed_hop+internals::window_size));
internals::aqueue.resize(0);
}
| 3,035
|
C++
|
.h
| 81
| 32.703704
| 138
| 0.651541
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,777
|
osc.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtlib/osc.hpp
|
#include<list>
#include<unordered_map>
#include"oscpkt/oscpkt.hh"
#include"oscpkt/udp.hh"
using namespace oscpkt;
using namespace std;
bool debug_osc = false;
#define OSC_H
// OSC stuff
// If this looks ridiculous it's because I had to work around a very odd cling bug.
// Eventually I will write my own OSC lib to avoid this mess.
unordered_map<string, UdpSocket> socks;
struct timeval init_time;
double base_time = 0;
uint64_t to_timestamp(double t) {
return ((init_time.tv_sec + 2208988800u + uint64_t(t + base_time)) << 32)
+ 4294.967296*(init_time.tv_usec + fmod(t + base_time, 1.0)*1000000);
}
void _osc_send(const string &address, int port, double t, Message *msg) {
auto res = socks.emplace(address+":"+to_string(port), UdpSocket());
UdpSocket &sock = res.first->second;
if (res.second) {
sock.connectTo(address, port);
if (!sock.isOk()) cerr << "Error connecting: " << sock.errorMessage() << endl;
else cerr << "Connect ok!" << endl;
}
uint64_t timestamp = to_timestamp(t);
PacketWriter pw;
pw.startBundle(TimeTag(timestamp)).addMessage(*msg).endBundle();
if (!sock.sendPacket(pw.packetData(), pw.packetSize()))
cerr << "Send error: " << sock.errorMessage() << endl;
delete msg;
}
Message *_osc_new_msg(const string &path) { return new oscpkt::Message(path); }
void _osc_push(Message *m, int32_t v) { m->pushInt32(v); }
void _osc_push(Message *m, int64_t v) { m->pushInt64(v); }
void _osc_push(Message *m, float v) { m->pushFloat(v); }
void _osc_push(Message *m, double v) { m->pushDouble(v); }
void _osc_push(Message *m, const string &v) { m->pushStr(v); }
RecvMsg::~RecvMsg() {
delete (Message::ArgReader*) ar;
delete msg;
}
bool _osc_pop(RecvMsg &m, int32_t &v) { return ((Message::ArgReader*)m.ar)->popInt32(v); }
bool _osc_pop(RecvMsg &m, int64_t &v) { return ((Message::ArgReader*)m.ar)->popInt64(v); }
bool _osc_pop(RecvMsg &m, float &v) { return ((Message::ArgReader*)m.ar)->popFloat(v); }
bool _osc_pop(RecvMsg &m, double &v) { return ((Message::ArgReader*)m.ar)->popDouble(v); }
bool _osc_pop(RecvMsg &m, string &v) { return ((Message::ArgReader*)m.ar)->popStr(v); }
struct Server {
UdpSocket sock;
list<Message> queue;
};
unordered_map<int, Server> servers;
vector<shared_ptr<RecvMsg>> osc_recv(int port, double t, const string &path) {
uint64_t timestamp = to_timestamp(t);
vector<shared_ptr<RecvMsg>> out;
auto res = servers.emplace(port, Server());
UdpSocket &sock = res.first->second.sock;
auto &queue = res.first->second.queue;
if (res.second) {
sock.bindTo(port);
if (!sock.isOk()) cerr << "Error binding: " << sock.errorMessage() << endl;
else cerr << "OSC Server started on port " << std::to_string(port) << endl;
}
PacketReader pr;
while (sock.receiveNextPacket(0)) {
pr.init(sock.packetData(), sock.packetSize());
oscpkt::Message *msg;
while (pr.isOk() && (msg = pr.popMessage()))
queue.emplace_back(*msg);
}
for (auto it = queue.begin(); it != queue.end();) {
Message &msg = *it;
if (debug_osc)
cout << msg << endl;
if (msg.match(path) && msg.timeTag() < timestamp) {
Message *copy = new Message;
*copy = msg;
auto ar = copy->match(path);
auto *arcopy = new Message::ArgReader(ar);
out.push_back(make_shared<RecvMsg>(arcopy, copy));
it = queue.erase(it);
}
else ++it;
}
return out;
}
| 3,550
|
C++
|
.h
| 87
| 35.954023
| 90
| 0.634393
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,778
|
connect.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtlib/connect.hpp
|
// TODO reorder args
namespace internals {
extern jack_client_t *client;
}
#define CONNECT_MIN 0
#define CONNECT_MAX 1
#define CONNECT_ALL 2
struct PortPattern {
string regex;
size_t idx_s, idx_t;
unsigned long flags;
};
size_t parse_int_or(string s, size_t otherwise) {
if (s.size() == 0)
return otherwise;
try { return stoi(s); }
catch (...) { cerr << "failed to parse \"" << s << "\" as integer" << endl; }
return otherwise;
}
PortPattern parse_port_pattern(string filter) {
PortPattern p;
p.regex = ":.*";
p.idx_s = 0;
p.idx_t = -1;
p.flags = JackPortIsOutput | JackPortIsInput;
if (filter.size() == 0);
else if (filter[0] == ':') {
p.regex = filter;
} else {
size_t range_idx = 1;
if (filter[0] == 'i')
p.flags = JackPortIsInput;
else if (filter[0] == 'o')
p.flags = JackPortIsOutput;
else
range_idx = 0;
p.regex = ":.*";
int idx = filter.find(',');
if (idx == -1) {
p.idx_s = parse_int_or(filter.substr(range_idx), 0);
p.idx_t = parse_int_or(filter.substr(range_idx), -2) + 1;
} else {
p.idx_s = parse_int_or(filter.substr(range_idx, idx), 0);
p.idx_t = parse_int_or(filter.substr(idx+1), -1);
}
}
return p;
}
void dis_connect_impl(bool con, string client_a, string client_b, string filter_a, string filter_b, int mode) {
const char* what = con ? "connect" : "disconnect";
auto fn = con ? jack_connect : jack_disconnect;
PortPattern a_ptn = parse_port_pattern(filter_a);
PortPattern b_ptn = parse_port_pattern(filter_b);
const char** ports_a_in = jack_get_ports(internals::client, (client_a + a_ptn.regex).c_str(),
JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput);
const char** ports_a_out = jack_get_ports(internals::client, (client_a + a_ptn.regex).c_str(),
JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput);
const char** ports_b_in = jack_get_ports(internals::client, (client_b + b_ptn.regex).c_str(),
JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput);
const char** ports_b_out = jack_get_ports(internals::client, (client_b + b_ptn.regex).c_str(),
JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput);
size_t ports_a_in_len = 0; for (int i = 0; ports_a_in && ports_a_in[i]; i++) ports_a_in_len++;
size_t ports_a_in_len_x = min(ports_a_in_len, a_ptn.idx_t-a_ptn.idx_s);
size_t ports_a_out_len = 0; for (int i = 0; ports_a_out && ports_a_out[i]; i++) ports_a_out_len++;
size_t ports_a_out_len_x = min(ports_a_out_len, a_ptn.idx_t-a_ptn.idx_s);
size_t ports_b_in_len = 0; for (int i = 0; ports_b_in && ports_b_in[i]; i++) ports_b_in_len++;
size_t ports_b_in_len_x = min(ports_b_in_len, b_ptn.idx_t-b_ptn.idx_s);
size_t ports_b_out_len = 0; for (int i = 0; ports_b_out && ports_b_out[i]; i++) ports_b_out_len++;
size_t ports_b_out_len_x = min(ports_b_out_len, b_ptn.idx_t-b_ptn.idx_s);
auto lenfn = [=](size_t a, size_t b) { return mode ? max(a, b) : min(a, b); };
int count = 0;
if ((a_ptn.flags & JackPortIsInput) && (b_ptn.flags & JackPortIsOutput)
&& ports_b_out_len_x && ports_a_in_len_x)
for (size_t i = 0; i < lenfn(ports_a_in_len_x, ports_b_out_len_x); i++) {
for (size_t j = i; j < i + (mode == CONNECT_ALL ? lenfn(ports_a_in_len_x, ports_b_out_len_x) : 1); j++) {
fn(internals::client, ports_b_out[(b_ptn.idx_s+i%ports_b_out_len_x)%ports_b_out_len],
ports_a_in[(a_ptn.idx_s+j%ports_a_in_len_x)%ports_a_in_len]);
cerr << what << " " << ports_b_out[(b_ptn.idx_s+i%ports_b_out_len_x)%ports_b_out_len]
<< " and " << ports_a_in[(a_ptn.idx_s+j%ports_a_in_len_x)%ports_a_in_len] << endl;
count++;
}
}
if ((a_ptn.flags & JackPortIsOutput) && (b_ptn.flags & JackPortIsInput)
&& ports_a_out_len_x && ports_b_in_len_x)
for (size_t i = 0; i < lenfn(ports_a_out_len_x, ports_b_in_len_x); i++) {
for (size_t j = i; j < i + (mode == CONNECT_ALL ? lenfn(ports_a_in_len_x, ports_b_out_len_x) : 1); j++) {
fn(internals::client, ports_a_out[(a_ptn.idx_s+i%ports_a_out_len_x)%ports_a_out_len],
ports_b_in[(b_ptn.idx_s+j%ports_b_in_len_x)%ports_b_in_len]);
cerr << what << " " << ports_a_out[(a_ptn.idx_s+i%ports_a_out_len_x)%ports_a_out_len]
<< " and " << ports_b_in[(b_ptn.idx_s+j%ports_b_in_len_x)%ports_b_in_len] << endl;
count++;
}
}
jack_free(ports_a_in); jack_free(ports_b_in); jack_free(ports_a_out); jack_free(ports_b_out);
if (count == 0)
cerr << what << ": no matching ports" << endl;
}
void disconnect(string client_a, string client_b, string filter_a, string filter_b, int mode) {
dis_connect_impl(false, client_a, client_b, filter_a, filter_b, mode);
}
void connect(string client_a, string client_b, string filter_a, string filter_b, int mode) {
dis_connect_impl(true, client_a, client_b, filter_a, filter_b, mode);
}
| 5,183
|
C++
|
.h
| 103
| 42.631068
| 117
| 0.573286
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,779
|
windowfn.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtlib/windowfn.hpp
|
void window_hann(WaveBuf &data) {
for (size_t i = 0; i < data.size; i++) {
double w = 0.5*(1-cos(2*M_PI*i/data.size)); // Hann
for (size_t j = 0; j < data.num_channels; j++)
data[j][i] *= w;
}
}
void window_sqrt_hann(WaveBuf &data) {
for (size_t i = 0; i < data.size; i++) {
double w = sqrt(0.5*(1-cos(2*M_PI*i/data.size))); // Hann
for (size_t j = 0; j < data.num_channels; j++)
data[j][i] *= w;
}
}
| 473
|
C++
|
.h
| 14
| 27.642857
| 65
| 0.492375
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,780
|
pv.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtlib/pv.hpp
|
namespace internals {
extern double hop;
}
void PhaseVocoder::analyze(WaveBuf &other) {
window_sqrt_hann(other);
fft.fill_from(other);
frft(fft, fft, 1);
analyze(fft);
}
void PhaseVocoder::synthesize(WaveBuf &other) {
other.resize(num_channels, size);
synthesize(fft);
frft(fft, fft, -1);
other.fill_from<cplx>(fft, [](cplx x){return x.real();});
window_sqrt_hann(other);
}
void PhaseVocoder::analyze(FFTBuf &other) {
resize(other.num_channels, other.size);
for (size_t i = 0; i < num_channels; i++) {
for (size_t j = 0; j < size; j++) {
double amp = abs(other[i][j]);
double phase = arg(other[i][j]);
double freq = phase_to_frequency(j, phase - last_phase[i][j]);
last_phase[i][j] = phase;
data[i][j] = PVBin(amp, freq);
}
}
}
void PhaseVocoder::synthesize(FFTBuf &other) {
other.resize(num_channels, size);
for (size_t i = 0; i < num_channels; i++) {
for (size_t j = 0; j < size; j++) {
double phase = frequency_to_phase(data[i][j].freq);
phase_sum[i][j] += phase;
other[i][j] = std::polar(data[i][j].amp, phase_sum[i][j]);
}
}
}
double PhaseVocoder::phase_to_frequency(size_t bin, double phase_diff) {
double delta = phase_diff - bin*2.0*M_PI*hop()/size;
int qpd = (int)(delta / M_PI);
if (qpd >= 0) qpd += qpd & 1;
else qpd -= qpd & 1;
return (bin + size/hop()*(delta - M_PI*qpd)/2.0/M_PI)*RATE/size;
}
double PhaseVocoder::frequency_to_phase(double freq) {
return 2.0*M_PI*freq/RATE*hop();
}
void PhaseVocoder::shift(std::function<double(double)> fn) {
shift([&](WaveBuf& buf) {
for (size_t i = 0; i < num_channels; i++)
for (size_t j = 0; j < size/2; j++)
buf[i][j] = fn(buf[i][j]);
});
}
void PhaseVocoder::shift(std::function<void(WaveBuf&)> fn) {
WaveBuf bins(num_channels, size/2);
WaveBuf freqs(num_channels, size/2);
for (size_t i = 0; i < num_channels; i++) {
for (size_t j = 0; j < size/2; j++) {
bins[i][j] = j/(double)size*RATE;
freqs[i][j] = data[i][j].freq;
}
}
fn(bins);
fn(freqs);
PVBuf tmp;
tmp.fill_from(data);
data.zero();
for (size_t i = 0; i < num_channels; i++) {
for (size_t j = 0; j < size/2; j++) {
int k = bins[i][j]/RATE*size;
if (k >= 0 && k < (int)size/2) {
data[i][k].amp += tmp[i][j].amp;
data[i][k].freq = freqs[i][j];
}
}
}
}
| 2,591
|
C++
|
.h
| 79
| 26.379747
| 74
| 0.539411
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,781
|
fft.hpp
|
nwoeanhinnogaehr_tinyspec-cling/rtlib/fft.hpp
|
// fast fractional fourier transform
// https://algassert.com/post/1710
void frft(FFTBuf &in, FFTBuf &out, double exponent) {
assert(in.size == out.size);
assert(in.num_channels == in.num_channels);
size_t num_channels = in.num_channels;
size_t fft_size = in.size;
if (num_channels*fft_size == 0)
return;
size_t data_size = sizeof(cplx)*num_channels*fft_size;
FFTBuf fft_tmp(num_channels, fft_size);
int size_arr[] = {(int) fft_size};
fftw_plan plan = fftw_plan_many_dft(1, size_arr, num_channels,
(fftw_complex*) in.data, nullptr, 1, fft_size,
(fftw_complex*) out.data, nullptr, 1, fft_size,
FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(plan);
fftw_destroy_plan(plan);
memcpy(fft_tmp.data, out.data, data_size);
cplx im(0, 1);
cplx im1 = pow(im, exponent);
cplx im2 = pow(im, exponent*2);
cplx im3 = pow(im, exponent*3);
double sqrtn = sqrt(fft_size);
for (size_t c = 0; c < num_channels; c++) {
for (size_t i = 0; i < fft_size; i++) {
int j = i ? fft_size-i : 0;
cplx f0 = in[c][i];
cplx f1 = fft_tmp[c][i]/sqrtn;
cplx f2 = in[c][j];
cplx f3 = fft_tmp[c][j]/sqrtn;
cplx b0 = f0 + f1 + f2 + f3;
cplx b1 = f0 + im*f1 - f2 - im*f3;
cplx b2 = f0 - f1 + f2 - f3;
cplx b3 = f0 - im*f1 - f2 + im*f3;
b1 *= im1;
b2 *= im2;
b3 *= im3;
out[c][i] = (b0 + b1 + b2 + b3) / 4.0;
}
}
}
| 1,564
|
C++
|
.h
| 42
| 29.261905
| 66
| 0.531887
|
nwoeanhinnogaehr/tinyspec-cling
| 34
| 1
| 3
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,786
|
sys_utils.cpp
|
SNMetamorph_goldsrc-monitor/sources/sys_utils.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "sys_utils.h"
#include <vector>
#include <cassert>
#include <algorithm>
#ifdef _WIN32
#include <Psapi.h>
#include <TlHelp32.h>
#endif
static ModuleHandle g_CurrentModuleHandle = 0;
bool ProcessHandle::Valid() const
{
return m_iHandle > 0;
}
bool ModuleHandle::Valid() const
{
return m_iHandle > 0;
}
void SysUtils::InitCurrentLibraryHandle(ModuleHandle handle)
{
static bool initialized = false;
if (!initialized) {
g_CurrentModuleHandle = handle;
initialized = true;
}
}
ModuleHandle SysUtils::GetCurrentLibraryHandle()
{
assert(g_CurrentModuleHandle != 0);
return g_CurrentModuleHandle;
}
#ifdef _WIN32
ProcessHandle::ProcessHandle(HANDLE handle)
{
m_iHandle = reinterpret_cast<int64_t>(handle);
}
ProcessHandle::operator HANDLE() const
{
return reinterpret_cast<HANDLE>(m_iHandle);
}
ModuleHandle::ModuleHandle(HMODULE handle)
{
m_iHandle = reinterpret_cast<int64_t>(handle);
}
ModuleHandle::operator HMODULE() const
{
return reinterpret_cast<HMODULE>(m_iHandle);
}
void SysUtils::Sleep(size_t timeMsec)
{
::Sleep(timeMsec);
}
float SysUtils::GetCurrentSysTime()
{
static LARGE_INTEGER perfFreq;
static LARGE_INTEGER clockStart;
LARGE_INTEGER currentTime;
LONGLONG timeDiff;
if (!perfFreq.QuadPart)
{
QueryPerformanceFrequency(&perfFreq);
QueryPerformanceCounter(&clockStart);
}
QueryPerformanceCounter(¤tTime);
timeDiff = currentTime.QuadPart - clockStart.QuadPart;
return (float)timeDiff / (float)perfFreq.QuadPart;
}
ModuleHandle SysUtils::GetCurrentProcessModule()
{
return GetModuleHandle(NULL);
}
ProcessHandle SysUtils::GetCurrentProcessHandle()
{
return GetCurrentProcess();
}
bool SysUtils::GetModuleDirectory(ModuleHandle moduleHandle, std::string &workingDir)
{
workingDir.resize(MAX_PATH);
GetModuleFileNameA(
moduleHandle,
workingDir.data(),
workingDir.capacity()
);
if (std::strlen(workingDir.c_str()) > 1)
{
// remove file name
workingDir.assign(workingDir.c_str());
workingDir.erase(workingDir.find_last_of("/\\") + 1);
workingDir.shrink_to_fit();
return true;
}
else {
return false;
}
}
bool SysUtils::GetModuleFilename(ModuleHandle moduleHandle, std::string &fileName)
{
fileName.resize(MAX_PATH);
if (GetModuleFileNameA(moduleHandle, fileName.data(), fileName.capacity()))
{
fileName.assign(fileName.c_str());
fileName.erase(0, fileName.find_last_of("/\\") + 1);
fileName.shrink_to_fit();
return true;
}
return false;
}
bool SysUtils::GetModuleInfo(ProcessHandle procHandle, ModuleHandle moduleHandle, SysUtils::ModuleInfo &moduleInfo)
{
MODULEINFO minfo;
if (GetModuleInformation(procHandle, moduleHandle, &minfo, sizeof(minfo)))
{
moduleInfo.baseAddress = (uint8_t *)minfo.lpBaseOfDll;
moduleInfo.imageSize = minfo.SizeOfImage;
moduleInfo.entryPointAddress = (uint8_t *)minfo.EntryPoint;
return true;
}
return false;
}
ModuleHandle SysUtils::FindModuleByExport(ProcessHandle procHandle, const char *exportName)
{
DWORD listSize;
size_t modulesCount;
std::vector<HMODULE> modulesList;
// retrieve modules count
listSize = 0;
EnumProcessModules(procHandle, NULL, 0, &listSize);
modulesCount = listSize / sizeof(HMODULE);
if (modulesCount > 0) {
modulesList.resize(modulesCount);
}
else {
return NULL;
}
if (!EnumProcessModules(procHandle, modulesList.data(), listSize, &listSize)) {
return NULL;
}
for (size_t i = 0; i < modulesCount; ++i)
{
uint8_t *moduleAddr;
uint32_t *nameOffsetList;
PIMAGE_DOS_HEADER dosHeader;
PIMAGE_NT_HEADERS peHeader;
PIMAGE_EXPORT_DIRECTORY dllExports;
moduleAddr = (uint8_t*)modulesList[i];
dosHeader = (PIMAGE_DOS_HEADER)moduleAddr;
peHeader = (PIMAGE_NT_HEADERS)(moduleAddr + dosHeader->e_lfanew);
dllExports = (PIMAGE_EXPORT_DIRECTORY)(moduleAddr +
peHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
if (!dllExports->AddressOfNames) {
continue;
}
nameOffsetList = (uint32_t*)(moduleAddr + dllExports->AddressOfNames);
for (size_t j = 0; j < dllExports->NumberOfNames; ++j)
{
const char *entryName = (const char *)(moduleAddr + nameOffsetList[j]);
if (strcmp(entryName, exportName) == 0)
return modulesList[i];
}
}
return NULL;
}
ModuleHandle SysUtils::FindModuleInProcess(ProcessHandle procHandle, const std::string &moduleName)
{
size_t modulesCount;
HMODULE moduleHandle;
std::string fileName;
std::vector<HMODULE> modulesList;
static char modulePath[MAX_PATH];
DWORD listSize = 0;
EnumProcessModules(procHandle, NULL, 0, &listSize);
moduleHandle = NULL;
modulesCount = listSize / sizeof(HMODULE);
if (modulesCount > 0) {
modulesList.resize(modulesCount);
}
else {
return NULL;
}
if (!EnumProcessModules(procHandle, modulesList.data(), listSize, &listSize)) {
return NULL;
}
for (size_t i = 0; i < modulesCount; ++i)
{
const size_t pathLength = sizeof(modulePath) / sizeof(modulePath[0]);
GetModuleFileNameExA(procHandle, modulesList[i], modulePath, pathLength);
fileName.assign(modulePath);
fileName.erase(0, fileName.find_last_of("/\\") + 1);
bool stringsEqual = true;
if (fileName.length() == moduleName.length())
{
for (size_t i = 0; i < fileName.length(); i++)
{
if (std::tolower(fileName[i]) != std::tolower(moduleName[i]))
{
stringsEqual = false;
break;
}
}
}
else {
stringsEqual = false;
}
if (stringsEqual)
{
moduleHandle = modulesList[i];
break;
}
}
return moduleHandle;
}
void SysUtils::FindProcessIdByName(const char *processName, std::vector<int32_t>& processIds)
{
#undef Process32First
#undef Process32Next
#undef PROCESSENTRY32
HANDLE processSnap;
PROCESSENTRY32 processEntry;
processIds.clear();
processEntry.dwSize = sizeof(processEntry);
processSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (processSnap != INVALID_HANDLE_VALUE)
{
if (Process32First(processSnap, &processEntry))
{
do {
if (std::strncmp(processName, processEntry.szExeFile, sizeof(processEntry.szExeFile)) == 0) {
processIds.push_back(processEntry.th32ProcessID);
}
} while (Process32Next(processSnap, &processEntry));
}
CloseHandle(processSnap);
}
}
void *SysUtils::GetModuleFunction(ModuleHandle moduleHandle, const char *funcName)
{
return GetProcAddress(moduleHandle, funcName);
}
#else
#pragma error "SysUtils functions not yet implemented for this platform!"
#endif
| 7,781
|
C++
|
.cpp
| 251
| 25.36255
| 115
| 0.675614
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,787
|
string_stack.cpp
|
SNMetamorph_goldsrc-monitor/sources/string_stack.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "string_stack.h"
#include <string>
#include <stdarg.h>
CStringStack::CStringStack(int stringLen)
{
m_stackIndex = 0;
m_stringLen = stringLen;
m_stringBuffer.clear();
}
void CStringStack::Push(const char *str)
{
AllocString();
char *stringAddr = &m_stringBuffer[m_stackIndex * m_stringLen];
strncpy(stringAddr, str, m_stringLen);
++m_stackIndex;
}
void CStringStack::PushPrintf(const char *format, ...)
{
va_list args;
AllocString();
char *stringAddr = &m_stringBuffer[m_stackIndex * m_stringLen];
va_start(args, format);
vsnprintf(stringAddr, m_stringLen, format, args);
va_end(args);
++m_stackIndex;
}
void CStringStack::Pop()
{
if (m_stackIndex > 0)
--m_stackIndex;
}
void CStringStack::Clear()
{
m_stackIndex = 0;
}
const char *CStringStack::StringAt(int index) const
{
if (index >= 0 && index < m_stackIndex)
return &m_stringBuffer[index * m_stringLen];
else
return nullptr;
}
void CStringStack::AllocString()
{
int currentSize = m_stringBuffer.size();
int desiredSize = m_stackIndex * m_stringLen + m_stringLen;
if (currentSize < desiredSize)
m_stringBuffer.resize(desiredSize);
}
| 1,736
|
C++
|
.cpp
| 60
| 25.833333
| 68
| 0.72509
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,788
|
exception.cpp
|
SNMetamorph_goldsrc-monitor/sources/exception.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "exception.h"
#include <cstdio>
#include <cstring>
#include <sstream>
CException::CException(
std::string description,
const char *funcName,
const char *fileName,
int lineNumber
)
{
m_funcName = funcName;
m_fileName = fileName;
m_description = description;
m_lineNumber = lineNumber;
m_message.clear();
}
const std::string &CException::GetFormattedMessage()
{
std::stringstream exMessage;
exMessage << m_funcName << "() [" << m_fileName << ":" << m_lineNumber << "]: " << m_description << "\n";
m_message = exMessage.str();
return m_message;
}
const std::string &CException::GetDescription() const
{
return m_description;
}
const std::string &CException::GetFunctionName() const
{
return m_funcName;
}
const std::string &CException::GetFileName() const
{
return m_fileName;
}
int CException::GetLineNumber() const
{
return m_lineNumber;
}
| 1,436
|
C++
|
.cpp
| 51
| 25.627451
| 109
| 0.741091
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,789
|
application.cpp
|
SNMetamorph_goldsrc-monitor/sources/loader/application.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "application.h"
#include "exception.h"
#include "app_info.h"
#include "sys_utils.h"
#include "win32_inject_strategy.h"
#include <iostream>
CApplication &CApplication::GetInstance()
{
static CApplication instance;
return instance;
}
int CApplication::Run(int argc, char *argv[])
{
ParseParameters(argc, argv);
InitInjectStrategy();
StartMainLoop();
std::cout << "Program will be closed 3 seconds later..." << std::endl;
SysUtils::Sleep(3000);
return 0;
}
void CApplication::ParseParameters(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
{
std::string parameter = argv[i];
if (parameter.compare("+process_name") == 0)
{
std::string argument = argv[++i];
m_processName = argument;
continue;
}
else if (parameter.compare("+library_name") == 0)
{
std::string argument = argv[++i];
m_libraryName = argument;
continue;
}
else if (parameter.compare("+inject_delay") == 0)
{
std::string argument = argv[++i];
m_injectDelay = std::stoi(argument);
continue;
}
}
}
void CApplication::StartMainLoop()
{
while (true)
{
PrintTitleText();
try
{
InjectStatus status = m_injectStrategy->Start(m_injectDelay, m_processName, m_libraryName);
if (status == InjectStatus::Success || status == InjectStatus::AlreadyInjected) {
break;
}
}
catch (CException &ex) {
ReportError(ex.GetDescription());
}
}
}
void CApplication::ReportError(const std::string &msg)
{
std::cout << "ERROR: " << msg << std::endl;
std::cout << "Press Enter to try again" << std::endl;
std::cin.get();
}
void CApplication::PrintTitleText()
{
#ifdef _WIN32
std::system("cls");
std::system("color 02");
#else
// TODO clear console, set desired color
#endif
std::printf(
"\n"
" %s - utility for mapping/scripting/researching games on GoldSrc engine\n"
" Version : %d.%d\n"
" Compiled : %s\n"
" Link : %s\n"
"\n"
" WARNING: This stuff is untested on VAC-secured\n"
" servers, therefore there is a risk to get VAC ban\n"
" while using it on VAC-secured servers.\n"
"\n", APP_TITLE_STR, APP_VERSION_MAJOR, APP_VERSION_MINOR, APP_BUILD_DATE, APP_GITHUB_LINK
);
}
void CApplication::InitInjectStrategy()
{
#ifdef _WIN32
m_injectStrategy = std::make_unique<CWin32InjectStrategy>();
#endif
}
| 3,154
|
C++
|
.cpp
| 106
| 24.198113
| 103
| 0.629898
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,791
|
win32_inject_strategy.cpp
|
SNMetamorph_goldsrc-monitor/sources/loader/win32_inject_strategy.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "win32_inject_strategy.h"
#include "exception.h"
#include "sys_utils.h"
#include "utils.h"
#include <vector>
#include <iostream>
#include <filesystem>
#include <windows.h>
namespace fs = std::filesystem;
class CWin32InjectStrategy::Impl
{
public:
bool IsLibraryInjected(HANDLE procHandle, const std::string &libraryName);
bool IsGameLoaded(HWND windowHandle, int timeout);
HWND FindGameWindow(HANDLE procHandle);
HANDLE OpenGameProcess(const std::string &processName);
char *WritePathString(HANDLE procHandle, const std::string &libPath);
void InjectLibrary(HANDLE procHandle, const std::string &libraryName);
int GetThreadExitCode(HANDLE threadHandle);
void GetProcessWindowList(DWORD processID, std::vector<HWND> &windowList);
};
CWin32InjectStrategy::CWin32InjectStrategy()
{
m_pImpl = std::make_unique<CWin32InjectStrategy::Impl>();
}
CWin32InjectStrategy::~CWin32InjectStrategy()
{
}
InjectStatus CWin32InjectStrategy::Start(size_t injectDelayMsec,
const std::string &processName, const std::string &libraryName)
{
HWND gameWindow;
HANDLE processHandle;
std::cout << "Target process name: " << processName.c_str() << std::endl;
std::cout << "Waiting for starting game..." << std::endl;
processHandle = m_pImpl->OpenGameProcess(processName);
std::cout << "Game process found. Waiting for game loading..." << std::endl;
// try to find game window ten times
for (size_t i = 0; i < 10; ++i)
{
gameWindow = m_pImpl->FindGameWindow(processHandle);
if (!gameWindow) {
Sleep(500);
}
else {
break;
}
}
if (gameWindow)
{
// wait until game being loaded
while (!m_pImpl->IsGameLoaded(gameWindow, 500));
}
else
{
std::cout << "Failed to find game window, waiting " << injectDelayMsec << " ms" << std::endl;
Sleep(injectDelayMsec);
}
if (!m_pImpl->IsLibraryInjected(processHandle, libraryName))
{
m_pImpl->InjectLibrary(processHandle, libraryName);
if (m_pImpl->IsLibraryInjected(processHandle, libraryName))
{
std::cout << "Library successfully injected: check game console for more info" << std::endl;
CloseHandle(processHandle);
return InjectStatus::Success;
}
else
{
CloseHandle(processHandle);
EXCEPT("library injection performed, but module not found");
}
}
else
{
CloseHandle(processHandle);
std::cout << "Library already injected into game process, restart game and try again" << std::endl;
return InjectStatus::AlreadyInjected;
}
}
bool CWin32InjectStrategy::Impl::IsLibraryInjected(HANDLE procHandle, const std::string &libraryName)
{
return SysUtils::FindModuleInProcess(procHandle, libraryName.c_str()) != NULL;
}
bool CWin32InjectStrategy::Impl::IsGameLoaded(HWND windowHandle, int timeout)
{
#ifdef APP_SUPPORT_64BIT // TODO instead check for WinSDK version
DWORD_PTR result;
#else
DWORD result;
#endif
return SendMessageTimeout(windowHandle, WM_NULL, NULL, NULL, SMTO_BLOCK, timeout, &result) != NULL;
}
HWND CWin32InjectStrategy::Impl::FindGameWindow(HANDLE procHandle)
{
std::vector<HWND> windowList;
int processID = GetProcessId(procHandle);
if (processID)
{
GetProcessWindowList(processID, windowList);
for (auto it = windowList.begin(); it != windowList.end();)
{
if (IsWindowEnabled(*it) && IsWindowVisible(*it)) {
++it;
}
else {
it = windowList.erase(it); // remove invisible windows
}
}
if (windowList.size() > 0) {
return windowList[0]; // just pick first window handle
}
}
return NULL;
}
HANDLE CWin32InjectStrategy::Impl::OpenGameProcess(const std::string &processName)
{
HANDLE processHandle;
std::vector<int> processIds;
const DWORD accessFlags = (
PROCESS_VM_READ |
PROCESS_VM_WRITE |
PROCESS_VM_OPERATION |
PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION
);
while (true)
{
SysUtils::FindProcessIdByName(processName.c_str(), processIds);
if (processIds.size() > 0)
{
int processID = processIds[0];
if (processIds.size() > 1)
{
size_t processNumber;
std::cout << "There are several processes with same name." << std::endl;
for (size_t i = 0; i < processIds.size(); ++i) {
std::cout << "(" << i + 1 << L") " << processName << " (PID: " << processIds[i] << ")" << std::endl;
}
std::cout << "Choose the required process: " << std::endl;
while (true) // repeat until valid value arrives
{
std::cin >> processNumber;
if (processNumber > 0 && processNumber <= processIds.size())
{
processID = processIds[processNumber - 1];
break;
}
}
}
processHandle = OpenProcess(accessFlags, false, processID);
if (processHandle)
return processHandle;
else
EXCEPT("unable to open game process");
}
Sleep(500);
}
}
char *CWin32InjectStrategy::Impl::WritePathString(HANDLE procHandle, const std::string &libPath)
{
size_t writtenBytes = 0;
char *pathRemoteAddr;
// allocating memory in game process for library path string
pathRemoteAddr = reinterpret_cast<char*>(VirtualAllocEx(
procHandle,
NULL,
libPath.capacity(),
MEM_RESERVE | MEM_COMMIT,
PAGE_READWRITE
));
if (!pathRemoteAddr) {
return nullptr;
}
// writing string to game process
WriteProcessMemory(
procHandle, pathRemoteAddr,
libPath.data(), libPath.capacity(),
(SIZE_T *)&writtenBytes
);
if (libPath.capacity() != writtenBytes)
return nullptr;
return pathRemoteAddr;
}
void CWin32InjectStrategy::Impl::InjectLibrary(HANDLE procHandle, const std::string &libraryName)
{
fs::path libraryPath;
char *pathStrRemote;
ModuleHandle k32LocalHandle;
ModuleHandle k32RemoteHandle;
HANDLE threadHandle;
size_t funcOffset;
uint8_t *funcRemote;
SysUtils::ModuleInfo k32Info;
if (!Utils::FindLibraryAbsolutePath(libraryName, libraryPath))
EXCEPT("library file not found, make sure that you unpacked program from archive");
pathStrRemote = WritePathString(procHandle, libraryPath.string());
if (!pathStrRemote)
EXCEPT("unable to write library path string in game process memory");
/*
getting address of LoadLibrary() in game process
it's simple method to get address of function in remote process
and it will work in most cases, if kernel32.dll from game process
isn't differ with same kernel32.dll from loader process
*/
k32LocalHandle = GetModuleHandleA("kernel32.dll");
k32RemoteHandle = SysUtils::FindModuleInProcess(procHandle, "kernel32.dll");
if (!k32RemoteHandle) {
EXCEPT("kernel32.dll remote handle not found");
}
if (!SysUtils::GetModuleInfo(procHandle, k32RemoteHandle, k32Info)) {
EXCEPT("GetModuleInfo() for remote kernel32.dll failed");
}
// creating thread in game process and invoking LoadLibrary()
std::cout << "Starting injection thread in remote process..." << std::endl;
funcOffset = Utils::GetFunctionOffset(k32LocalHandle, "LoadLibraryA");
funcRemote = k32Info.baseAddress + funcOffset;
threadHandle = CreateRemoteThread(procHandle,
0, 0,
(LPTHREAD_START_ROUTINE)funcRemote, pathStrRemote,
0, 0
);
if (!threadHandle) {
EXCEPT("unable to create remote thread");
}
// wait for thread in game process exits
if (WaitForSingleObject(threadHandle, 6000) == WAIT_TIMEOUT) {
EXCEPT("library injection thread timed out");
}
int exitCode = GetThreadExitCode(threadHandle);
if (exitCode && exitCode != 0xC0000005)
std::cout << "Injected library base address: 0x" << std::hex << exitCode << std::endl;
else
EXCEPT("remote thread failed to load library");
}
int CWin32InjectStrategy::Impl::GetThreadExitCode(HANDLE threadHandle)
{
DWORD exitCode;
GetExitCodeThread(threadHandle, &exitCode);
return exitCode;
}
void CWin32InjectStrategy::Impl::GetProcessWindowList(DWORD processID, std::vector<HWND> &windowList)
{
HWND window = NULL;
windowList.clear();
do {
DWORD checkProcessID;
window = FindWindowEx(NULL, window, NULL, NULL);
GetWindowThreadProcessId(window, &checkProcessID);
if (processID == checkProcessID) {
windowList.push_back(window);
}
}
while (window != NULL);
}
| 9,624
|
C++
|
.cpp
| 266
| 29.428571
| 120
| 0.654758
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,792
|
utils.cpp
|
SNMetamorph_goldsrc-monitor/sources/loader/utils.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "utils.h"
namespace fs = std::filesystem;
bool Utils::FindLibraryAbsolutePath(const std::string &libraryName, std::filesystem::path &libPath)
{
fs::path libraryRelativePath = libraryName;
if (fs::exists(libraryRelativePath)) {
libPath = fs::absolute(libraryRelativePath);
return true;
}
return false;
}
size_t Utils::GetFunctionOffset(ModuleHandle moduleHandle, const char *funcName)
{
SysUtils::ModuleInfo moduleInfo;
SysUtils::GetModuleInfo(SysUtils::GetCurrentProcessHandle(), moduleHandle, moduleInfo);
uint8_t *funcAddr = reinterpret_cast<uint8_t*>(SysUtils::GetModuleFunction(moduleHandle, funcName));
return (size_t)(funcAddr - moduleInfo.baseAddress);
}
| 1,235
|
C++
|
.cpp
| 29
| 39.724138
| 104
| 0.781667
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,793
|
displaymode_angletracking.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_angletracking.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "displaymode_angletracking.h"
#include "application.h"
#include "client_module.h"
#include "local_player.h"
CModeAngleTracking::CModeAngleTracking(const CLocalPlayer &playerRef)
: m_localPlayer(playerRef)
{
m_lastAngles = Vector(0.0f, 0.0f, 0.0f);
m_trackStartTime = 0.0f;
m_lastYawVelocity = 0.0f;
m_lastPitchVelocity = 0.0f;
}
void CModeAngleTracking::Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText)
{
if (!m_localPlayer.PredictionDataValid())
return;
const float threshold = 0.001f;
const vec3_t &currAngles = m_localPlayer.GetAngles();
float pitchVelocity = (currAngles.x - m_lastAngles.x) / frameTime;
float yawVelocity = (currAngles.y - m_lastAngles.y) / frameTime;
screenText.Clear();
screenText.PushPrintf(" up : %.2f deg/s", -pitchVelocity);
screenText.PushPrintf("right : %.2f deg/s", -yawVelocity);
const int stringWidth = Utils::GetStringWidth(screenText.StringAt(0));
const int marginDown = 35;
Utils::DrawStringStack(
(scrWidth / 2) + stringWidth / 2,
(scrHeight / 2) + marginDown,
screenText
);
// check for start
if (fabs(m_lastPitchVelocity) < threshold && fabs(pitchVelocity) > threshold) {
m_trackStartTime = g_pClientEngfuncs->GetClientTime();
}
if (fabs(pitchVelocity) > threshold)
{
g_pClientEngfuncs->Con_Printf("(%.5f; %.2f)\n",
(g_pClientEngfuncs->GetClientTime() - m_trackStartTime), -pitchVelocity
);
}
// check for end
if (fabs(pitchVelocity) < threshold && fabs(m_lastPitchVelocity) > threshold) {
g_pClientEngfuncs->Con_Printf("\n");
}
m_lastAngles = currAngles;
m_lastPitchVelocity = pitchVelocity;
m_lastYawVelocity = yawVelocity;
}
| 2,325
|
C++
|
.cpp
| 59
| 34.915254
| 105
| 0.713398
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,794
|
displaymode_full.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_full.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "displaymode_full.h"
#include "client_module.h"
#include "cvars.h"
#include "utils.h"
#include "local_player.h"
CModeFull::CModeFull(const CLocalPlayer &playerRef)
: m_localPlayer(playerRef)
{
m_frameTime = 0.0f;
m_lastFrameTime = 0.0f;
m_lastSysTime = 0.0f;
}
void CModeFull::Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText)
{
if (m_localPlayer.PredictionDataValid())
{
float timeDelta = GetSmoothSystemFrametime();
float velocityNum = m_localPlayer.GetVelocity().Length2D();
const vec3_t &origin = m_localPlayer.GetOrigin();
const vec3_t &velocity = m_localPlayer.GetVelocity();
const vec3_t &angles = m_localPlayer.GetAngles();
const vec3_t &baseVelocity = m_localPlayer.GetBaseVelocity();
const vec3_t &punchAngle = m_localPlayer.GetPunchAngles();
const vec3_t &viewOffset = m_localPlayer.GetViewOffset();
screenText.Clear();
screenText.PushPrintf("FPS: %.1f", 1.f / timeDelta);
screenText.PushPrintf("Time: %.2f seconds", g_pClientEngfuncs->GetClientTime());
screenText.PushPrintf("Frame Time: %.1f ms\n", timeDelta * 1000.f);
screenText.PushPrintf("Velocity: %.2f u/s (%.2f, %.2f, %.2f)", velocityNum, velocity.x, velocity.y, velocity.z);
screenText.PushPrintf("Origin: (%.2f, %.2f, %.2f)", origin.x, origin.y, origin.z);
screenText.PushPrintf("Angles: (%.2f, %.2f, %.2f)", angles.x, angles.y, angles.z);
screenText.PushPrintf("Base Velocity: (%.2f, %.2f, %.2f)", baseVelocity.x, baseVelocity.y, baseVelocity.z);
screenText.PushPrintf("Max Velocity: %.2f (client %.2f)", m_localPlayer.GetMaxSpeed(), m_localPlayer.GetClientMaxSpeed());
screenText.PushPrintf("Movetype: %s\n", Utils::GetMovetypeName(m_localPlayer.GetMovetype()));
screenText.PushPrintf("View Offset: (%.2f, %.2f, %.2f)", viewOffset.x, viewOffset.y, viewOffset.z);
screenText.PushPrintf("Punch Angle: (%.2f, %.2f, %.2f)", punchAngle.x, punchAngle.y, punchAngle.z);
screenText.PushPrintf("Duck Time: %.2f", m_localPlayer.GetDuckTime());
screenText.PushPrintf("In Duck Process: %s", m_localPlayer.IsDucking() ? "yes" : "no");
screenText.PushPrintf("Player Flags: %d", m_localPlayer.GetFlags());
screenText.PushPrintf("Hull Type: %d", m_localPlayer.GetHullType());
screenText.PushPrintf("Gravity: %.2f", m_localPlayer.GetGravity());
screenText.PushPrintf("Friction: %.2f", m_localPlayer.GetFriction());
screenText.PushPrintf("On Ground: %s", m_localPlayer.OnGround() ? "yes" : "no");
screenText.PushPrintf("fuserX: %.2f / %.2f / %.2f / %.2f",
m_localPlayer.GetFloatUserVar(1),
m_localPlayer.GetFloatUserVar(2),
m_localPlayer.GetFloatUserVar(3),
m_localPlayer.GetFloatUserVar(4)
);
screenText.PushPrintf("iuserX: %d / %d / %d / %d",
m_localPlayer.GetIntUserVar(1),
m_localPlayer.GetIntUserVar(2),
m_localPlayer.GetIntUserVar(3),
m_localPlayer.GetIntUserVar(4)
);
}
else
{
screenText.Clear();
screenText.Push("This mode unavailable when playing demo");
}
Utils::DrawStringStack(
static_cast<int>(ConVars::gsm_margin_right->value),
static_cast<int>(ConVars::gsm_margin_up->value),
screenText
);
}
float CModeFull::GetSmoothSystemFrametime()
{
const float smoothFactor = 0.24f;
const float diffThreshold = 0.13f;
float currSysTime = Utils::GetCurrentSysTime();
float timeDelta = currSysTime - m_lastSysTime;
if ((timeDelta - m_lastFrameTime) > diffThreshold)
timeDelta = m_lastFrameTime;
m_frameTime += (timeDelta - m_frameTime) * smoothFactor;
m_lastFrameTime = m_frameTime;
m_lastSysTime = currSysTime;
return m_frameTime;
}
| 4,469
|
C++
|
.cpp
| 91
| 42.747253
| 130
| 0.673614
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,795
|
displaymode_speedometer.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_speedometer.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "displaymode_speedometer.h"
#include "client_module.h"
#include "utils.h"
#include "local_player.h"
CModeSpeedometer::CModeSpeedometer(const CLocalPlayer &playerRef)
: m_localPlayer(playerRef)
{
}
void CModeSpeedometer::Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText)
{
const int centerX = scrWidth / 2;
const int centerY = scrHeight / 2;
const int speedometerMargin = 35;
const float speedUpdateInterval = 0.125f;
float currentTime = Utils::GetCurrentSysTime();
float updateTimeDelta = currentTime - m_lastUpdateTime;
if (updateTimeDelta >= speedUpdateInterval)
{
CalculateVelocity(frameTime);
m_lastUpdateTime = currentTime;
}
//DrawVelocityBar(centerX, centerY, m_flVelocity);
screenText.Clear();
screenText.PushPrintf("%3.1f", m_velocity);
int stringWidth = Utils::GetStringWidth(screenText.StringAt(0));
Utils::DrawStringStack(
centerX + stringWidth / 2,
centerY + speedometerMargin,
screenText
);
}
void CModeSpeedometer::DrawVelocityBar(int centerX, int centerY, float velocity) const
{
const int barHeight = 15;
const int barMargin = 60;
const int barWidth = 100.f / 600.f * velocity;
g_pClientEngfuncs->pfnFillRGBA(
centerX - (barWidth / 2),
centerY + barMargin,
barWidth,
barHeight,
0, 255, 0, 200
);
}
void CModeSpeedometer::CalculateVelocity(float frameTime)
{
if (m_localPlayer.IsSpectate()) {
m_velocity = GetEntityVelocityApprox(m_localPlayer.GetSpectateTargetIndex());
}
else {
m_velocity = (m_localPlayer.GetVelocity() + m_localPlayer.GetBaseVelocity()).Length2D();
}
}
float CModeSpeedometer::GetEntityVelocityApprox(int entityIndex) const
{
if (g_pClientEngfuncs->GetEntityByIndex(entityIndex)) {
return Utils::GetEntityVelocityApprox(entityIndex).Length2D();
}
return 0.0f;
}
| 2,487
|
C++
|
.cpp
| 71
| 30.661972
| 103
| 0.731393
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,796
|
hooks_impl.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/hooks_impl.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "hooks_impl.h"
#include "hooks_logger.h"
CFunctionHook<CHooks::Impl::pfnRedraw_t> CHooks::Impl::m_hookRedraw;
CFunctionHook<CHooks::Impl::pfnPlayerMove_t> CHooks::Impl::m_hookPlayerMove;
CFunctionHook<CHooks::Impl::pfnKeyEvent_t> CHooks::Impl::m_hookKeyEvent;
CFunctionHook<CHooks::Impl::pfnDrawTriangles_t> CHooks::Impl::m_hookDrawTriangles;
CFunctionHook<CHooks::Impl::pfnIsThirdPerson_t> CHooks::Impl::m_hookIsThirdPerson;
CFunctionHook<CHooks::Impl::pfnCameraOffset_t> CHooks::Impl::m_hookCameraOffset;
CFunctionHook<CHooks::Impl::pfnVidInit_t> CHooks::Impl::m_hookVidInit;
void CHooks::Impl::InitializeLogger()
{
m_pLogger = std::make_shared<CHooks::Logger>();
m_pLogger->setLogLevel(PLH::ErrorLevel::WARN);
PLH::Log::registerLogger(m_pLogger);
}
void CHooks::Impl::RevertHooks()
{
m_hookRedraw.Unhook();
m_hookPlayerMove.Unhook();
m_hookKeyEvent.Unhook();
m_hookDrawTriangles.Unhook();
m_hookIsThirdPerson.Unhook();
m_hookCameraOffset.Unhook();
m_hookVidInit.Unhook();
}
| 1,542
|
C++
|
.cpp
| 36
| 40.555556
| 82
| 0.782667
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,797
|
application.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/application.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "application.h"
#include "utils.h"
#include "hooks.h"
#include "cvars.h"
#include "app_info.h"
#include "exception.h"
#include "memory_pattern.h"
#include "engine_module.h"
#include "client_module.h"
#include "server_module.h"
#include "displaymode_full.h"
#include "displaymode_measurement.h"
#include "displaymode_speedometer.h"
#include "displaymode_entityreport.h"
#include "displaymode_angletracking.h"
#include "displaymode_facereport.h"
#include "opengl_primitives_renderer.h"
#include <stdint.h>
//#define FILTER_AVG_EXPONENTIAL
#define FILTER_AVG_SIMPLE
#define FILTER_SIZE 5
CApplication &g_Application = CApplication::GetInstance();
CApplication &CApplication::GetInstance()
{
static CApplication instance;
return instance;
}
CApplication::CApplication()
: m_clientModule(m_engineModule),
m_serverModule(m_engineModule),
m_hooks(m_clientModule),
m_stringStack(128)
{
InitializeDisplayModes();
InitializePrimitivesRenderer();
};
void CApplication::Run()
{
if (!m_engineModule.FindHandle())
EXCEPT("failed to get engine module handle");
if (!m_clientModule.FindHandle())
EXCEPT("failed to get client module handle");
SysUtils::ModuleInfo engineDLL;
SysUtils::GetModuleInfo(SysUtils::GetCurrentProcessHandle(), m_engineModule.GetHandle(), engineDLL);
m_buildInfo.Initialize(engineDLL);
m_clientModule.FindEngfuncs(m_buildInfo);
m_serverModule.FindEngfuncs(m_buildInfo);
m_serverModule.FindHandle();
InitializeConVars(engineDLL);
SetCurrentDisplayMode();
PrintTitleText();
m_hooks.Apply();
// load configuration file
g_pClientEngfuncs->pfnClientCmd("exec gsm_config.cfg");
}
void CApplication::InitializeDisplayModes()
{
m_displayModes.clear();
m_displayModes.push_back(std::make_shared<CModeFull>(m_localPlayer));
m_displayModes.push_back(std::make_shared<CModeSpeedometer>(m_localPlayer));
m_displayModes.push_back(std::make_shared<CModeEntityReport>(m_localPlayer, m_engineModule));
m_displayModes.push_back(std::make_shared<CModeMeasurement>(m_localPlayer));
m_displayModes.push_back(std::make_shared<CModeFaceReport>(m_localPlayer));
m_displayModes.push_back(std::make_shared<CModeAngleTracking>(m_localPlayer));
}
void CApplication::InitializePrimitivesRenderer()
{
m_primitivesRenderer = std::make_shared<COpenGLPrimitivesRenderer>();
}
void CApplication::HandleChangelevel()
{
for (auto &mode : m_displayModes) {
mode->HandleChangelevel();
}
}
void CApplication::FindTimescaleConVar(const SysUtils::ModuleInfo &engineLib)
{
uint8_t *probeAddr;
uint8_t *stringAddr;
uint8_t *scanStartAddr;
uint8_t *moduleStartAddr;
uint8_t *moduleEndAddr;
CMemoryPattern scanPattern("sys_timescale", 14);
const size_t pointerSize = sizeof(void *);
moduleStartAddr = engineLib.baseAddress;
moduleEndAddr = moduleStartAddr + engineLib.imageSize;
scanStartAddr = moduleStartAddr;
stringAddr = (uint8_t *)Utils::FindPatternAddress(
scanStartAddr, moduleEndAddr, scanPattern
);
if (!stringAddr)
return;
while (true)
{
probeAddr = (uint8_t *)Utils::FindMemoryPointer(
scanStartAddr, moduleEndAddr, stringAddr
);
if (!probeAddr || scanStartAddr >= moduleEndAddr)
return;
else
scanStartAddr = probeAddr + pointerSize;
if (probeAddr >= moduleStartAddr && probeAddr < moduleEndAddr)
{
cvar_t *probeCvar = (cvar_t *)probeAddr;
uint8_t *stringAddr = (uint8_t *)probeCvar->string;
if (stringAddr >= moduleStartAddr && stringAddr < moduleEndAddr)
{
if (strcmp(probeCvar->string, "1.0") == 0)
{
ConVars::sys_timescale = probeCvar;
return;
}
}
}
}
}
void CApplication::PrintTitleText()
{
const int verMajor = APP_VERSION_MAJOR;
const int verMinor = APP_VERSION_MINOR;
g_pClientEngfuncs->Con_Printf(
" \n"
" %s - utility for mapping/scripting/researching games on GoldSrc engine\n"
" Version : %d.%d\n"
" Compiled : %s\n"
" Link : %s\n"
" \n"
" WARNING: This stuff is untested on VAC-secured\n"
" servers, therefore there is a risk to get VAC ban\n"
" while using it on VAC-secured servers.\n"
" \n",
APP_TITLE_STR,
verMajor, verMinor,
APP_BUILD_DATE,
APP_GITHUB_LINK
);
g_pClientEngfuncs->pfnPlaySoundByName("buttons/blip2.wav", 0.6f);
}
static void CommandTimescale()
{
auto &serverModule = g_Application.GetServerModule();
if (!ConVars::sys_timescale)
{
g_pClientEngfuncs->Con_Printf("sys_timescale address not found");
return;
}
if (serverModule.IsInitialized() || serverModule.FindHandle())
{
if (g_pClientEngfuncs->Cmd_Argc() > 1)
{
float argument = static_cast<float>(std::atof(g_pClientEngfuncs->Cmd_Argv(1)));
if (argument > 0.f)
{
ConVars::sys_timescale->value = argument;
g_pClientEngfuncs->Con_Printf("sys_timescale value = %.1f\n", argument);
}
else
g_pClientEngfuncs->Con_Printf("Value should be greater than zero\n");
}
else
g_pClientEngfuncs->Con_Printf("Command using example: gsm_timescale 0.5\n");
}
else
{
g_pClientEngfuncs->Con_Printf(
"Server module not found! Start singleplayer "
"or listen server and execute command again\n"
);
}
}
void CApplication::InitializeConVars(const SysUtils::ModuleInfo &engineLib)
{
FindTimescaleConVar(engineLib);
g_pClientEngfuncs->pfnAddCommand("gsm_timescale", &CommandTimescale);
ConVars::gsm_color_r = Utils::RegisterConVar("gsm_color_r", "0", FCVAR_CLIENTDLL);
ConVars::gsm_color_g = Utils::RegisterConVar("gsm_color_g", "220", FCVAR_CLIENTDLL);
ConVars::gsm_color_b = Utils::RegisterConVar("gsm_color_b", "220", FCVAR_CLIENTDLL);
ConVars::gsm_margin_up = Utils::RegisterConVar("gsm_margin_up", "15", FCVAR_CLIENTDLL);
ConVars::gsm_margin_right = Utils::RegisterConVar("gsm_margin_right", "400", FCVAR_CLIENTDLL);
ConVars::gsm_mode = Utils::RegisterConVar("gsm_mode", "0", FCVAR_CLIENTDLL);
ConVars::gsm_debug = Utils::RegisterConVar("gsm_debug", "0", FCVAR_CLIENTDLL);
ConVars::gsm_thirdperson = Utils::RegisterConVar("gsm_thirdperson", "0", FCVAR_CLIENTDLL);
ConVars::gsm_thirdperson_dist = Utils::RegisterConVar("gsm_thirdperson_dist", "64", FCVAR_CLIENTDLL);
}
void CApplication::SetCurrentDisplayMode()
{
DisplayModeType displayMode = Utils::GetCurrentDisplayMode();
for (auto &mode : m_displayModes)
{
if (mode->GetModeIndex() == displayMode)
{
m_currentDisplayMode = mode;
return;
}
}
m_currentDisplayMode = m_displayModes[0];
}
void CApplication::UpdateScreenInfo()
{
m_screenInfo.iSize = sizeof(m_screenInfo);
g_pClientEngfuncs->pfnGetScreenInfo(&m_screenInfo);
}
// should be updated only once in frame
void CApplication::UpdateSmoothFrametime()
{
#ifdef FILTER_AVG_EXPONENTIAL
// exponential running average filter
// less k - more smooth result will be
const float k = 0.24f;
const float diffThreshold = 0.13f;
float currentTime = g_pClientEngfuncs->GetClientTime();
float timeDelta = currentTime - m_lastClientTime;
if ((timeDelta - m_lastFrameTime) > diffThreshold)
timeDelta = m_lastFrameTime;
m_frameTime += (timeDelta - m_frameTime) * k;
m_lastFrameTime = m_frameTime;
m_lastClientTime = currentTime;
#elif defined(FILTER_AVG_SIMPLE)
float currentTime = g_pClientEngfuncs->GetClientTime();
float timeDelta = currentTime - m_lastClientTime;
static float buffer[FILTER_SIZE];
double sum = 0.0;
for (int i = FILTER_SIZE - 2; i >= 0; --i) {
buffer[i + 1] = buffer[i];
}
buffer[0] = timeDelta;
for (int i = 0; i < 5; ++i) {
sum += buffer[i];
}
m_lastClientTime = currentTime;
m_frameTime = sum / (double)FILTER_SIZE;
#else
float currentTime = g_pClientEngfuncs->GetClientTime();
float timeDelta = currentTime - m_lastClientTime;
m_frameTime = timeDelta;
m_lastClientTime = currentTime;
#endif
}
void CApplication::DisplayModeRender2D()
{
SetCurrentDisplayMode();
UpdateSmoothFrametime();
UpdateScreenInfo();
m_currentDisplayMode->Render2D(m_frameTime, m_screenInfo.iWidth, m_screenInfo.iHeight, m_stringStack);
}
void CApplication::DisplayModeRender3D()
{
SetCurrentDisplayMode();
m_currentDisplayMode->Render3D();
}
bool CApplication::KeyInput(int keyDown, int keyCode, const char *bindName)
{
return m_currentDisplayMode->KeyInput(keyDown != 0, keyCode, bindName);
}
| 9,578
|
C++
|
.cpp
| 265
| 30.69434
| 106
| 0.685545
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,798
|
displaymode_measurement.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_measurement.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "displaymode_measurement.h"
#include "utils.h"
#include "client_module.h"
#include "cvars.h"
#include "local_player.h"
// HLSDK
#include "keydefs.h"
CModeMeasurement::CModeMeasurement(const CLocalPlayer &playerRef)
: m_localPlayer(playerRef)
{
const vec3_t zeroVector = { 0.0f, 0.0f, 0.0f };
m_pointA = zeroVector;
m_pointB = zeroVector;
m_lineSprite = 0;
m_snapMode = SnapMode::Free;
}
void CModeMeasurement::UpdatePointOrigin(vec3_t &linePoint, const vec3_t &targetPoint)
{
if (m_snapMode != SnapMode::AlongLine)
{
switch (m_snapMode)
{
case SnapMode::AxisX:
linePoint.x = targetPoint.x;
break;
case SnapMode::AxisY:
linePoint.y = targetPoint.y;
break;
case SnapMode::AxisZ:
linePoint.z = targetPoint.z;
break;
default:
linePoint = targetPoint;
break;
}
}
else
{
vec3_t lineVector = m_pointB - m_pointA;
if (lineVector.Length() > 0.0f)
{
vec3_t targVector = targetPoint - linePoint;
float projLen = DotProduct(lineVector, targVector) / lineVector.Length();
linePoint = linePoint + lineVector.Normalize() * projLen;
}
}
}
void CModeMeasurement::TraceAlongNormal(pmtrace_t &traceData, float traceLength)
{
vec3_t traceOrigin = traceData.endpos;
vec3_t planeNormal = traceData.plane.normal;
vec3_t *pointsList[2] = { &m_pointA, &m_pointB };
for (int i = 0; i < 2; ++i)
{
float directionSign = -1.0f + 2.0f * (i % 2);
vec3_t traceDir = planeNormal * directionSign;
Utils::TraceLine(traceOrigin, traceDir, traceLength, &traceData);
*pointsList[i] = traceData.endpos;
}
}
void CModeMeasurement::DrawVisualization(float frameTime, int screenWidth, int screenHeight)
{
float lifeTime = std::min(0.05f, frameTime);
DrawMeasurementLine(lifeTime);
DrawLineProjections(screenWidth, screenHeight, lifeTime);
PrintPointHints(screenWidth, screenHeight);
PrintLineLength(screenWidth, screenHeight, m_pointA, m_pointB);
if (m_snapMode != SnapMode::Free && m_snapMode != SnapMode::AlongLine) {
DrawSupportLines(lifeTime);
}
}
const vec3_t& CModeMeasurement::GetPointOriginA() const
{
return m_pointA;
}
const vec3_t& CModeMeasurement::GetPointOriginB() const
{
return m_pointB;
}
float CModeMeasurement::GetPointsDistance() const
{
return (m_pointB - m_pointA).Length();
}
bool CModeMeasurement::KeyInput(bool keyDown, int keyCode, const char *)
{
vec3_t viewDir;
vec3_t viewOrigin;
vec3_t viewAngles;
pmtrace_t traceData;
const float traceLen = 64000.f;
if (Utils::GetCurrentDisplayMode() != DisplayModeType::Measurement || !keyDown)
return true;
if (keyCode >= K_MOUSE1 && keyCode <= K_MOUSE3)
{
g_pClientEngfuncs->pfnPlaySoundByName("buttons/lightswitch2.wav", 1.0f);
g_pClientEngfuncs->GetViewAngles(viewAngles);
g_pClientEngfuncs->pfnAngleVectors(viewAngles, viewDir, nullptr, nullptr);
viewOrigin = m_localPlayer.GetViewOrigin();
Utils::TraceLine(viewOrigin, viewDir, traceLen, &traceData);
if (keyCode == K_MOUSE1)
UpdatePointOrigin(m_pointA, traceData.endpos);
else if (keyCode == K_MOUSE2)
UpdatePointOrigin(m_pointB, traceData.endpos);
else if (keyCode == K_MOUSE3)
TraceAlongNormal(traceData, traceLen);
return false;
}
else if (keyCode == 'v')
{
m_snapMode = static_cast<SnapMode>(static_cast<uint32_t>(m_snapMode) + 1);
if (m_snapMode == SnapMode::Count) {
m_snapMode = SnapMode::Free;
}
g_pClientEngfuncs->pfnPlaySoundByName("buttons/blip1.wav", 0.8f);
return false;
}
return true;
}
void CModeMeasurement::HandleChangelevel()
{
const vec3_t vecNull = vec3_t(0, 0, 0);
m_pointA = vecNull;
m_pointB = vecNull;
m_snapMode = SnapMode::Free;
m_lineSprite = 0;
}
void CModeMeasurement::DrawMeasurementLine(float lifeTime)
{
const float lineWidth = 0.7f;
const float lineBrightness = 1.0f;
const float lineSpeed = 5.0f;
const float lineColorR = 0.1f;
const float lineColorG = 1.0f;
const float lineColorB = 0.11f;
g_pClientEngfuncs->pEfxAPI->R_BeamPoints(
m_pointA, m_pointB, m_lineSprite,
lifeTime * 2.f, lineWidth, 0,
lineBrightness, lineSpeed, 0, 0,
lineColorR, lineColorG, lineColorB
);
}
void CModeMeasurement::PrintPointHints(int screenWidth, int screenHeight)
{
const int textColorR = 39;
const int textColorG = 227;
const int textColorB = 198;
Utils::DrawString3D(m_pointA, "A", textColorR, textColorG, textColorB);
Utils::DrawString3D(m_pointB, "B", textColorR, textColorG, textColorB);
}
void CModeMeasurement::PrintLineLength(int screenWidth, int screenHeight, vec3_t pointStart, vec3_t pointEnd)
{
std::string lengthStr;
vec3_t lineMiddle = (pointStart + pointEnd) / 2.f;
const int textColorR = 255;
const int textColorG = 255;
const int textColorB = 20;
float distance = (pointStart - pointEnd).Length();
if (distance > 0.0f)
{
vec3_t offset = vec3_t(0.0f, 0.0f, 1.0f) * std::powf(distance, 0.5f);
Utils::Snprintf(lengthStr, "%.2f", distance);
Utils::DrawString3D(lineMiddle + offset, lengthStr.c_str(), textColorR, textColorG, textColorB);
}
}
void CModeMeasurement::DrawSupportLines(float lifeTime)
{
vec3_t axisVector = { 0.f, 0.f, 0.f };
const vec3_t *pointsList[2] = { &m_pointA, &m_pointB };
const float lineWidth = 0.7f;
const float lineLenght = 24.0f;
const float lineSpeed = 5.0f;
const float lineColorR = 1.0f;
const float lineColorG = 0.0f;
const float lineColorB = 0.5f;
const float lineBrightness = 1.2f;
if (m_snapMode == SnapMode::AxisX)
axisVector.x = 1.f;
else if (m_snapMode == SnapMode::AxisY)
axisVector.y = 1.f;
else if (m_snapMode == SnapMode::AxisZ)
axisVector.z = 1.f;
for (int i = 0; i < 2; ++i)
{
g_pClientEngfuncs->pEfxAPI->R_BeamPoints(
*pointsList[i] + (axisVector * lineLenght),
*pointsList[i] - (axisVector * lineLenght),
m_lineSprite,
lifeTime * 2.0f, lineWidth, 0,
lineBrightness, lineSpeed, 0, 0,
lineColorR, lineColorG, lineColorB
);
}
}
void CModeMeasurement::DrawLineProjections(int screenWidth, int screenHeight, float lifeTime)
{
bool baseFound = false;
vec3_t basePoint = m_pointA;
const float lineWidth = 0.7f;
const float lineLenght = 24.0f;
const float lineSpeed = 5.0f;
const float lineColorR = 1.0f;
const float lineColorG = 0.08f;
const float lineColorB = 0.08f;
const float lineBrightness = 1.2f;
const vec3_t *pointsList[2] = { &m_pointA, &m_pointB };
for (int i = 0; i < 3; ++i)
{
if (std::fabsf(m_pointA[i] - m_pointB[i]) > 0.1f)
{
basePoint[i] = m_pointB[i];
baseFound = true;
break;
}
}
for (int i = 0; baseFound && i < 3; ++i)
{
vec3_t axisVector = { 0.f, 0.f, 0.f };
float diff = basePoint[i] - m_pointB[i];
if (std::fabsf(diff) < 0.001f) {
diff = basePoint[i] - m_pointA[i];
}
axisVector[i] = 1.0f - 2.0f * (diff > 0.0f);
vec3_t endPoint = basePoint + axisVector * std::fabsf(diff);
g_pClientEngfuncs->pEfxAPI->R_BeamPoints(
basePoint,
endPoint,
m_lineSprite,
lifeTime * 2.0f, lineWidth, 0,
lineBrightness, lineSpeed, 0, 0,
lineColorR, lineColorG, lineColorB
);
PrintLineLength(screenWidth, screenHeight, basePoint, endPoint);
}
}
void CModeMeasurement::LoadLineSprite()
{
if (m_lineSprite)
return;
const char *spritePath = "sprites/laserbeam.spr";
g_pClientEngfuncs->pfnSPR_Load(spritePath);
m_lineSprite = g_pClientEngfuncs->pEventAPI->EV_FindModelIndex(spritePath);
}
void CModeMeasurement::Render2D(float frameTime, int screenWidth, int screenHeight, CStringStack &screenText)
{
if (m_localPlayer.PredictionDataValid())
{
const vec3_t &originPointA = GetPointOriginA();
const vec3_t &originPointB = GetPointOriginB();
float pointsDistance = GetPointsDistance();
float elevationAngle = GetLineElevationAngle();
const char *snapModeName = GetSnapModeName();
const float roundThreshold = 0.08f;
float fractionalPart = fmodf(pointsDistance, 1.f);
if (fractionalPart >= (1.f - roundThreshold))
pointsDistance += (1.f - fractionalPart);
else if (fractionalPart <= roundThreshold)
pointsDistance -= fractionalPart;
screenText.Clear();
if (originPointA.Length() < 0.0001f)
screenText.Push("Point A not set");
else
screenText.PushPrintf("Point A origin: (%.2f, %.2f, %.2f)",
originPointA.x, originPointA.y, originPointA.z);
if (originPointB.Length() < 0.0001f)
screenText.Push("Point B not set");
else
screenText.PushPrintf("Point B origin: (%.2f, %.2f, %.2f)",
originPointB.x, originPointB.y, originPointB.z);
screenText.PushPrintf("Points Distance: %.1f (%.3f meters)",
pointsDistance, pointsDistance / 39.37f);
screenText.PushPrintf("Elevation Angle: %.2f deg", elevationAngle);
screenText.PushPrintf("Snap Mode: %s", snapModeName);
LoadLineSprite();
if (m_pointA.Length() > 0.0001f && m_pointB.Length() > 0.0001f) {
DrawVisualization(frameTime, screenWidth, screenHeight);
}
}
else
{
screenText.Clear();
screenText.Push("This mode unavailable when playing demo");
}
Utils::DrawStringStack(
static_cast<int>(ConVars::gsm_margin_right->value),
static_cast<int>(ConVars::gsm_margin_up->value),
screenText
);
}
const char *CModeMeasurement::GetSnapModeName() const
{
switch (m_snapMode)
{
case SnapMode::Free:
return "Free";
break;
case SnapMode::AxisX:
return "Axis X";
break;
case SnapMode::AxisY:
return "Axis Y";
break;
case SnapMode::AxisZ:
return "Axis Z";
break;
case SnapMode::AlongLine:
return "Along Line";
break;
}
return "";
}
float CModeMeasurement::GetLineElevationAngle() const
{
vec3_t lineDirection;
const vec3_t *highPoint;
const vec3_t *lowPoint;
if (m_pointA.z > m_pointB.z)
{
highPoint = &m_pointA;
lowPoint = &m_pointB;
}
else
{
highPoint = &m_pointB;
lowPoint = &m_pointA;
}
lineDirection = *highPoint - *lowPoint;
lineDirection = lineDirection.Normalize();
return asinf(lineDirection.z) * 180.0f / 3.14f;
}
| 11,757
|
C++
|
.cpp
| 340
| 28.194118
| 109
| 0.638579
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,799
|
memory_pattern.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/memory_pattern.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "memory_pattern.h"
#include "exception.h"
#include <exception>
#include <sstream>
#include <iterator>
CMemoryPattern::CMemoryPattern(const std::string &pattern)
{
InitFromString(pattern);
}
CMemoryPattern::CMemoryPattern(const char *pattern, int byteCount, uint8_t wildmark)
{
InitFromBytes((uint8_t*)pattern, byteCount, wildmark);
}
void CMemoryPattern::ReserveElements(size_t elemCount)
{
m_mask.reserve(elemCount);
m_signature.reserve(elemCount);
}
void CMemoryPattern::Reset()
{
m_mask.clear();
m_signature.clear();
}
void CMemoryPattern::AddByte(uint8_t value, bool shouldCheck)
{
m_mask.push_back(shouldCheck);
m_signature.push_back(value);
}
void CMemoryPattern::InitFromBytes(uint8_t *pattern, int byteCount, uint8_t wildmark)
{
Reset();
ReserveElements(byteCount);
for (int i = 0; i < byteCount; ++i)
{
uint8_t *currentByte = pattern + i;
if (currentByte[0] != wildmark)
{
m_signature.push_back(currentByte[0]);
m_mask.push_back(true);
}
else
{
m_signature.push_back(0x0);
m_mask.push_back(false);
}
}
}
// Parses string in format like "FF A5 B1 ?? ?? AA C5"
// Not so good at terms of perfomance but at least isn't complicated
void CMemoryPattern::InitFromString(const std::string &pattern)
{
std::stringstream pattern_stream(pattern);
std::vector<std::string> tokens(
std::istream_iterator<std::string, char>(pattern_stream),
{}
);
Reset();
ReserveElements(128); // pre-allocate some elements
try {
for (const std::string &token : tokens)
{
if (token.compare("??") != 0) {
AddByte(static_cast<uint8_t>(std::stoul(token, 0, 16)));
}
else {
AddByte(0x0, false);
}
}
m_mask.shrink_to_fit();
m_signature.shrink_to_fit();
}
catch (std::exception &ex)
{
EXCEPT(std::string("memory pattern parsing error: ") + ex.what());
}
}
bool CMemoryPattern::IsInitialized() const
{
if (m_mask.size() < 1 || m_signature.size() < 1) {
return false;
}
return true;
}
| 2,752
|
C++
|
.cpp
| 94
| 24.276596
| 85
| 0.66137
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,800
|
client_module.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/client_module.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "client_module.h"
#include "engine_module.h"
#include "build_info.h"
#include "build_info_entry.h"
#include "exception.h"
#include "utils.h"
#include "sys_utils.h"
cl_enginefunc_t *g_pClientEngfuncs;
CClientModule::CClientModule(const CEngineModule &moduleRef)
: m_engineModule(moduleRef)
{
m_moduleInfo.baseAddress = nullptr;
m_moduleInfo.entryPointAddress = nullptr;
m_moduleInfo.imageSize = 0;
}
bool CClientModule::FindHandle()
{
ProcessHandle currProcess = SysUtils::GetCurrentProcessHandle();
m_moduleHandle = SysUtils::FindModuleByExport(currProcess, "HUD_ProcessPlayerState");
SysUtils::GetModuleInfo(currProcess, m_moduleHandle, m_moduleInfo);
return m_moduleHandle.Valid();
}
bool CClientModule::FindEngfuncs(const CBuildInfo &buildInfo)
{
uint8_t *pfnSPR_Load;
uint8_t *pfnSPR_Frames;
uint8_t *moduleAddr = m_engineModule.GetAddress();
uint8_t *moduleEndAddr = moduleAddr + m_engineModule.GetSize();
const CBuildInfo::Entry *buildInfoEntry = buildInfo.GetInfoEntry();
if (!m_engineModule.GetFunctionsFromAPI(&pfnSPR_Load, &pfnSPR_Frames))
{
if (!buildInfoEntry) {
std::string errorMsg;
Utils::Snprintf(errorMsg, "build info parsing error: %s\n", buildInfo.GetInitErrorDescription().c_str());
EXCEPT(errorMsg);
}
// obtain address directly without searching
if (buildInfoEntry->HasClientEngfuncsOffset()) {
g_pClientEngfuncs = (cl_enginefunc_t *)(moduleAddr + buildInfoEntry->GetClientEngfuncsOffset());
return true;
}
pfnSPR_Load = static_cast<uint8_t *>(buildInfo.FindFunctionAddress(
CBuildInfo::FunctionType::SPR_Load, moduleAddr, moduleEndAddr
));
if (!pfnSPR_Load) {
EXCEPT("SPR_Load() address not found");
}
pfnSPR_Frames = static_cast<uint8_t *>(buildInfo.FindFunctionAddress(
CBuildInfo::FunctionType::SPR_Frames, moduleAddr, moduleEndAddr
));
if (!pfnSPR_Frames) {
EXCEPT("SPR_Frames() address not found");
}
}
cl_enginefunc_t *tableAddr = SearchEngfuncsTable(pfnSPR_Load, pfnSPR_Frames);
if (tableAddr) {
g_pClientEngfuncs = tableAddr;
return true;
}
EXCEPT("valid reference to SPR_Load() not found");
return false;
}
cl_enginefunc_t *CClientModule::SearchEngfuncsTable(uint8_t *pfnSPR_Load, uint8_t *pfnSPR_Frames)
{
bool fallbackMethod = false;
uint8_t *targetAddr = pfnSPR_Load;
uint8_t *moduleAddr = m_engineModule.GetAddress();
uint8_t *scanStartAddr = moduleAddr;
uint8_t *moduleEndAddr = moduleAddr + m_engineModule.GetSize();
constexpr size_t pointerSize = sizeof(void *);
while (true)
{
uint8_t *coincidenceAddr = (uint8_t *)Utils::FindMemoryPointer(
scanStartAddr,
moduleEndAddr,
targetAddr
);
if (!coincidenceAddr || scanStartAddr >= moduleEndAddr)
{
// try to use fallback method
targetAddr = (uint8_t *)Utils::FindJmpFromAddress(moduleAddr, moduleEndAddr, pfnSPR_Load);
if (!targetAddr || fallbackMethod) {
break;
}
else
{
fallbackMethod = true;
scanStartAddr = moduleAddr;
continue;
}
}
else {
scanStartAddr = coincidenceAddr + pointerSize;
}
// check for module range to avoid segfault
uint8_t *probeAddr = *(uint8_t **)(coincidenceAddr + pointerSize);
if (probeAddr >= moduleAddr && probeAddr < moduleEndAddr)
{
if (probeAddr == pfnSPR_Frames || (fallbackMethod && Utils::UnwrapJmp(probeAddr) == pfnSPR_Frames))
{
return reinterpret_cast<cl_enginefunc_t*>(coincidenceAddr);
}
}
}
return nullptr;
}
uint8_t* CClientModule::GetFuncAddress(const char *funcName) const
{
return reinterpret_cast<uint8_t*>(GetProcAddress(GetHandle(), funcName));
}
| 4,623
|
C++
|
.cpp
| 121
| 31.22314
| 117
| 0.667856
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,801
|
hooks.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/hooks.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "stdafx.h"
#include "hooks_impl.h"
#include "hooks.h"
#include "application.h"
#include "client_module.h"
#include "exception.h"
#include "local_player.h"
NOINLINE static int __cdecl HookRedraw(float time, int intermission)
{
// call original function
PLH::FnCast(CHooks::Impl::m_hookRedraw.GetTrampolineAddr(), CHooks::Impl::pfnRedraw_t())(time, intermission);
g_Application.DisplayModeRender2D();
return 1;
}
NOINLINE static void __cdecl HookPlayerMove(playermove_t *pmove, int server)
{
PLH::FnCast(CHooks::Impl::m_hookPlayerMove.GetTrampolineAddr(), CHooks::Impl::pfnPlayerMove_t())(pmove, server);
g_Application.GetLocalPlayer().UpdatePlayerMove(pmove);
}
NOINLINE static int __cdecl HookKeyEvent(int keyDown, int keyCode, const char *bindName)
{
int returnCode = PLH::FnCast(CHooks::Impl::m_hookKeyEvent.GetTrampolineAddr(), CHooks::Impl::pfnKeyEvent_t())(
keyDown, keyCode, bindName
);
return (returnCode && g_Application.KeyInput(keyDown, keyCode, bindName)) ? 1 : 0;
}
NOINLINE static void __cdecl HookDrawTriangles()
{
PLH::FnCast(CHooks::Impl::m_hookDrawTriangles.GetTrampolineAddr(), CHooks::Impl::pfnDrawTriangles_t())();
g_Application.DisplayModeRender3D();
}
NOINLINE static int __cdecl HookIsThirdPerson()
{
int returnCode = PLH::FnCast(CHooks::Impl::m_hookIsThirdPerson.GetTrampolineAddr(), CHooks::Impl::pfnIsThirdPerson_t())();
return (returnCode || g_Application.GetLocalPlayer().IsThirdPersonForced()) ? 1 : 0;
}
NOINLINE static void __cdecl HookCameraOffset(float *cameraOffset)
{
PLH::FnCast(CHooks::Impl::m_hookCameraOffset.GetTrampolineAddr(), CHooks::Impl::pfnCameraOffset_t())(cameraOffset);
if (g_Application.GetLocalPlayer().IsThirdPersonForced())
{
g_pClientEngfuncs->GetViewAngles(cameraOffset);
cameraOffset[2] = g_Application.GetLocalPlayer().GetThirdPersonCameraDist();
}
}
NOINLINE static int __cdecl HookVidInit()
{
int returnCode = PLH::FnCast(CHooks::Impl::m_hookVidInit.GetTrampolineAddr(), CHooks::Impl::pfnVidInit_t())();
g_Application.HandleChangelevel();
return returnCode;
}
CHooks::CHooks(const CClientModule &moduleRef)
: m_clientModule(moduleRef)
{
m_pImpl = std::make_unique<CHooks::Impl>();
}
CHooks::~CHooks()
{
}
void CHooks::Apply()
{
Impl::pfnRedraw_t pfnRedraw = (Impl::pfnRedraw_t)m_clientModule.GetFuncAddress("HUD_Redraw");
Impl::pfnPlayerMove_t pfnPlayerMove = (Impl::pfnPlayerMove_t)m_clientModule.GetFuncAddress("HUD_PlayerMove");
Impl::pfnKeyEvent_t pfnKeyEvent = (Impl::pfnKeyEvent_t)m_clientModule.GetFuncAddress("HUD_Key_Event");
Impl::pfnDrawTriangles_t pfnDrawTriangles = (Impl::pfnDrawTriangles_t)m_clientModule.GetFuncAddress("HUD_DrawTransparentTriangles");
Impl::pfnIsThirdPerson_t pfnIsThirdPerson = (Impl::pfnIsThirdPerson_t)m_clientModule.GetFuncAddress("CL_IsThirdPerson");
Impl::pfnCameraOffset_t pfnCameraOffset = (Impl::pfnCameraOffset_t)m_clientModule.GetFuncAddress("CL_CameraOffset");
Impl::pfnVidInit_t pfnVidInit = (Impl::pfnVidInit_t)m_clientModule.GetFuncAddress("HUD_VidInit");
m_pImpl->InitializeLogger();
Impl::m_hookRedraw.Hook(pfnRedraw, &HookRedraw);
Impl::m_hookPlayerMove.Hook(pfnPlayerMove, &HookPlayerMove);
Impl::m_hookKeyEvent.Hook(pfnKeyEvent, &HookKeyEvent);
Impl::m_hookDrawTriangles.Hook(pfnDrawTriangles, &HookDrawTriangles);
Impl::m_hookIsThirdPerson.Hook(pfnIsThirdPerson, &HookIsThirdPerson);
Impl::m_hookCameraOffset.Hook(pfnCameraOffset, &HookCameraOffset);
Impl::m_hookVidInit.Hook(pfnVidInit, &HookVidInit);
if (!Impl::m_hookKeyEvent.IsHooked())
{
g_pClientEngfuncs->Con_Printf(
"WARNING: KeyEvent() hooking failed: "
"measurement mode will not react to keys.\n"
);
}
if (!Impl::m_hookDrawTriangles.IsHooked())
{
pfnDrawTriangles = (Impl::pfnDrawTriangles_t)m_clientModule.GetFuncAddress("HUD_DrawNormalTriangles");
if (!Impl::m_hookDrawTriangles.Hook(pfnDrawTriangles, &HookDrawTriangles))
{
g_pClientEngfuncs->Con_Printf(
"WARNING: DrawTriangles() hooking failed: entity "
"report mode will not draw entity hull.\n"
);
}
}
if (!Impl::m_hookIsThirdPerson.IsHooked() || !Impl::m_hookCameraOffset.IsHooked())
{
Impl::m_hookIsThirdPerson.Unhook();
Impl::m_hookCameraOffset.Unhook();
g_pClientEngfuncs->Con_Printf(
"WARNING: IsThirdPerson() hooking failed: "
"command gsm_thirdperson will not work.\n"
);
}
bool isHookSuccessful = (
Impl::m_hookRedraw.IsHooked() &&
Impl::m_hookPlayerMove.IsHooked() &&
Impl::m_hookVidInit.IsHooked()
);
if (!isHookSuccessful)
{
m_pImpl->RevertHooks();
EXCEPT("unable to hook desired functions, check logs\n");
}
}
void CHooks::Remove()
{
// check for client.dll not already unloaded from process
if (GetModuleHandle("client.dll")) {
m_pImpl->RevertHooks();
}
}
| 5,611
|
C++
|
.cpp
| 132
| 37.780303
| 136
| 0.723443
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,802
|
entity_dictionary.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/entity_dictionary.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "entity_dictionary.h"
#include "utils.h"
#include "client_module.h"
// Should be initialized after every map change
void CEntityDictionary::Initialize()
{
Reset();
ParseEntityData();
BuildDescriptionsTree();
}
void CEntityDictionary::VisualizeTree(bool textRendering)
{
m_entityDescTree.Visualize(textRendering);
}
void CEntityDictionary::VisualizeDescriptions() const
{
for (int i = 0; i < m_entityDescList.size(); ++i)
{
const CEntityDescription &description = m_entityDescList[i];
Utils::DrawCuboid(
description.GetOrigin(),
vec3_t(0, 0, 0),
description.GetAngles(),
description.GetBoundingBox().GetSize(),
Color::GetRandom(i)
);
}
}
void CEntityDictionary::Reset()
{
m_entityDescList.clear();
m_associations.clear();
}
bool CEntityDictionary::FindDescription(int entityIndex, CEntityDescription &destDescription, int &iterCount)
{
int nodeIndex;
CBoundingBox entityBoundingBox;
Utils::GetEntityBoundingBox(entityIndex, entityBoundingBox);
if (m_associations.count(entityIndex) > 0)
{
int descIndex = m_associations[entityIndex];
destDescription = m_entityDescList[descIndex];
return true;
}
else if (m_entityDescTree.FindLeaf(entityBoundingBox, nodeIndex, iterCount))
{
const CBVHTreeNode &node = m_entityDescTree.GetNode(nodeIndex);
int descIndex = node.GetDescriptionIndex();
AssociateDescription(entityIndex, descIndex);
destDescription = m_entityDescList[descIndex];
return true;
}
return false;
}
CEntityDictionary::CEntityDictionary()
: m_entityDescTree(m_entityDescList)
{
}
void CEntityDictionary::AssociateDescription(int entityIndex, int descIndex)
{
CEntityDescription &entityDesc = m_entityDescList[descIndex];
entityDesc.AssociateEntity(entityIndex);
m_associations.insert({ entityIndex, descIndex });
}
void CEntityDictionary::BuildDescriptionsTree()
{
m_entityDescTree.Reset();
m_entityDescTree.Build();
}
void CEntityDictionary::ParseEntityData()
{
cl_entity_t *worldEntity = g_pClientEngfuncs->GetEntityByIndex(0);
model_t *worldModel = worldEntity->model;
char *entData = worldModel->entities;
std::vector<char> key;
std::vector<char> value;
std::vector<char> token;
const int bufferSize = 2048;
key.resize(bufferSize, '\0');
value.resize(bufferSize, '\0');
token.resize(bufferSize, '\0');
while (true)
{
if (!entData || entData[1] == '\0')
break;
entData = g_pClientEngfuncs->COM_ParseFile(entData, token.data());
if (strcmp(token.data(), "{") == 0)
{
CEntityDescription entityDesc;
while (true)
{
// unexpected ending of entity data
if (!entData || entData[0] == '\0')
break;
entData = g_pClientEngfuncs->COM_ParseFile(entData, token.data());
if (strcmp(token.data(), "}") == 0)
{
entityDesc.Initialize();
m_entityDescList.push_back(entityDesc);
break;
}
else
{
if (!entData || entData[0] == '\0')
break;
strncpy(key.data(), token.data(), sizeof(key) - 1);
entData = g_pClientEngfuncs->COM_ParseFile(entData, value.data());
entityDesc.AddKeyValue(std::string(key.data()), std::string(value.data()));
}
}
}
}
}
| 4,204
|
C++
|
.cpp
| 124
| 26.846774
| 109
| 0.647146
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,803
|
local_player.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/local_player.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "local_player.h"
#include "utils.h"
#include "client_module.h"
#include <assert.h>
void CLocalPlayer::UpdatePlayerMove(playermove_t *pmove)
{
m_pPlayerMove = pmove;
}
vec3_t CLocalPlayer::GetOrigin() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->origin;
}
else {
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
return localPlayer->origin;
}
}
vec3_t CLocalPlayer::GetAngles() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->angles;
}
else
{
vec3_t angles;
g_pClientEngfuncs->GetViewAngles(angles);
return angles;
}
}
vec3_t CLocalPlayer::GetPunchAngles() const
{
assert(PredictionDataValid());
return m_pPlayerMove->punchangle;
}
vec3_t CLocalPlayer::GetVelocity() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->velocity;
}
else {
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
return Utils::GetEntityVelocityApprox(localPlayer->index);
}
}
vec3_t CLocalPlayer::GetBaseVelocity() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->basevelocity;
}
else {
return vec3_t(0.f, 0.f, 0.f);
}
}
vec3_t CLocalPlayer::GetViewOffset() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->view_ofs;
}
else {
vec3_t viewOffset;
g_pClientEngfuncs->pEventAPI->EV_LocalPlayerViewheight(viewOffset);
return viewOffset;
}
}
vec3_t CLocalPlayer::GetViewOrigin() const
{
return GetOrigin() + GetViewOffset();
}
vec3_t CLocalPlayer::GetViewDirection() const
{
vec3_t viewAngles, viewDir;
g_pClientEngfuncs->GetViewAngles(viewAngles);
g_pClientEngfuncs->pfnAngleVectors(viewAngles, viewDir, nullptr, nullptr);
return viewDir;
}
float CLocalPlayer::GetMaxSpeed() const
{
assert(PredictionDataValid());
return m_pPlayerMove->maxspeed;
}
float CLocalPlayer::GetClientMaxSpeed() const
{
assert(PredictionDataValid());
return m_pPlayerMove->clientmaxspeed;
}
float CLocalPlayer::GetGravity() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->gravity;
}
else {
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
return localPlayer->curstate.gravity;
}
}
float CLocalPlayer::GetFriction() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->friction;
}
else {
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
return localPlayer->curstate.friction;
}
}
float CLocalPlayer::GetDuckTime() const
{
assert(PredictionDataValid());
return m_pPlayerMove->flDuckTime;
}
bool CLocalPlayer::IsDucking() const
{
assert(PredictionDataValid());
return m_pPlayerMove->bInDuck;
}
bool CLocalPlayer::OnGround() const
{
// TODO implement this for case when prediction data unavailable?
assert(PredictionDataValid());
return m_pPlayerMove->onground != -1;
}
int CLocalPlayer::GetMovetype() const
{
if (PredictionDataValid()) {
return m_pPlayerMove->movetype;
}
else {
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
return localPlayer->curstate.movetype;
}
}
int CLocalPlayer::GetFlags() const
{
assert(PredictionDataValid());
return m_pPlayerMove->flags;
}
int CLocalPlayer::GetHullType() const
{
assert(PredictionDataValid());
return m_pPlayerMove->usehull;
}
const physent_t *CLocalPlayer::GetPhysents() const
{
assert(PredictionDataValid());
return m_pPlayerMove->physents;
}
const physent_t *CLocalPlayer::GetVisents() const
{
assert(PredictionDataValid());
return m_pPlayerMove->visents;
}
const physent_t *CLocalPlayer::GetMoveents() const
{
assert(PredictionDataValid());
return m_pPlayerMove->moveents;
}
int CLocalPlayer::GetPhysentsCount() const
{
assert(PredictionDataValid());
return m_pPlayerMove->numphysent;
}
int CLocalPlayer::GetVisentsCount() const
{
assert(PredictionDataValid());
return m_pPlayerMove->numvisent;
}
int CLocalPlayer::GetMoveentsCount() const
{
assert(PredictionDataValid());
return m_pPlayerMove->nummoveent;
}
int CLocalPlayer::GetIntUserVar(size_t index) const
{
int *p;
assert(index >= 1 && index <= 4);
if (PredictionDataValid()) {
p = &m_pPlayerMove->iuser1;
}
else {
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
p = &localPlayer->curstate.iuser1;
}
return p[index - 1];
}
float CLocalPlayer::GetFloatUserVar(size_t index) const
{
float *p;
assert(index >= 1 && index <= 4);
if (PredictionDataValid()) {
p = &m_pPlayerMove->fuser1;
}
else {
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
p = &localPlayer->curstate.fuser1;
}
return p[index - 1];
}
bool CLocalPlayer::IsThirdPersonForced() const
{
bool playerDead = PredictionDataValid() ? m_pPlayerMove->dead : false;
return ConVars::gsm_thirdperson->value > 0.0f && playerDead;
}
float CLocalPlayer::GetThirdPersonCameraDist() const
{
pmtrace_t traceInfo;
vec3_t viewDir = GetViewDirection();
vec3_t viewOrigin = GetViewOrigin();
float maxDist = ConVars::gsm_thirdperson_dist->value;
Utils::TraceLine(viewOrigin, -viewDir, maxDist, &traceInfo);
return maxDist * traceInfo.fraction;
}
bool CLocalPlayer::PredictionDataValid() const
{
// we can't use prediction data when demo playing
bool demoPlaying = g_pClientEngfuncs->pDemoAPI->IsPlayingback() != 0;
return m_pPlayerMove != nullptr && !demoPlaying;
}
bool CLocalPlayer::IsSpectate() const
{
// assume that it's valid only for cs 1.6/hl1
// because other mods can use iuser variables for other purposes
int specMode, targetIndex;
if (PredictionDataValid())
{
specMode = m_pPlayerMove->iuser1;
targetIndex = m_pPlayerMove->iuser2;
}
else
{
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
specMode = localPlayer->curstate.iuser1;
targetIndex = localPlayer->curstate.iuser2;
}
return specMode != 0 && targetIndex != 0;
}
SpectatingMode CLocalPlayer::GetSpectatingMode() const
{
if (PredictionDataValid())
{
return static_cast<SpectatingMode>(m_pPlayerMove->iuser3);
}
else
{
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
return static_cast<SpectatingMode>(localPlayer->curstate.iuser3);
}
}
int CLocalPlayer::GetSpectateTargetIndex() const
{
if (IsSpectate())
{
if (PredictionDataValid()) {
return m_pPlayerMove->iuser2;
}
else
{
cl_entity_t *localPlayer = g_pClientEngfuncs->GetLocalPlayer();
return localPlayer->curstate.iuser2;
}
}
return -1;
}
| 7,453
|
C++
|
.cpp
| 274
| 22.99635
| 78
| 0.702926
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,804
|
cvars.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/cvars.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "cvars.h"
cvar_t *ConVars::gsm_color_r;
cvar_t *ConVars::gsm_color_g;
cvar_t *ConVars::gsm_color_b;
cvar_t *ConVars::gsm_margin_up;
cvar_t *ConVars::gsm_margin_right;
cvar_t *ConVars::gsm_mode;
cvar_t *ConVars::gsm_debug;
cvar_t *ConVars::gsm_thirdperson;
cvar_t *ConVars::gsm_thirdperson_dist;
cvar_t *ConVars::sys_timescale;
| 850
|
C++
|
.cpp
| 22
| 37.454545
| 68
| 0.791262
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,805
|
server_module.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/server_module.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "server_module.h"
#include "engine_module.h"
#include "build_info.h"
#include "build_info_entry.h"
#include "exception.h"
#include "sys_utils.h"
#include "utils.h"
enginefuncs_t *g_pServerEngfuncs;
CServerModule::CServerModule(const CEngineModule &moduleRef)
: m_engineModule(moduleRef)
{
m_moduleInfo.baseAddress = nullptr;
m_moduleInfo.entryPointAddress = nullptr;
m_moduleInfo.imageSize = 0;
}
bool CServerModule::FindHandle()
{
ProcessHandle currProcess = SysUtils::GetCurrentProcessHandle();
m_module = SysUtils::FindModuleByExport(GetCurrentProcess(), "GetEntityAPI");
SysUtils::GetModuleInfo(currProcess, m_module, m_moduleInfo);
return m_module.Valid();
}
bool CServerModule::FindEngfuncs(const CBuildInfo &buildInfo)
{
void *pfnPrecacheModel;
void *pfnPrecacheSound;
uint8_t *probeAddr;
uint8_t *coincidenceAddr;
uint8_t *scanStartAddr;
const size_t pointerSize = sizeof(void *);
uint8_t *moduleAddr = m_engineModule.GetAddress();
uint8_t *moduleEndAddr = moduleAddr + m_engineModule.GetSize();
const CBuildInfo::Entry *buildInfoEntry = buildInfo.GetInfoEntry();
if (!buildInfoEntry) {
return false;
}
if (buildInfoEntry->HasServerEngfuncsOffset()) {
g_pServerEngfuncs = (enginefuncs_t *)(moduleAddr + buildInfoEntry->GetServerEngfuncsOffset());
return true;
}
pfnPrecacheModel = buildInfo.FindFunctionAddress(
CBuildInfo::FunctionType::PrecacheModel,
moduleAddr,
moduleEndAddr
);
if (!pfnPrecacheModel)
{
// PrecacheModel() address not found
return false;
}
scanStartAddr = moduleAddr;
while (true)
{
coincidenceAddr = (uint8_t *)Utils::FindMemoryPointer(
scanStartAddr,
moduleEndAddr,
pfnPrecacheModel
);
if (!coincidenceAddr || scanStartAddr >= moduleEndAddr)
{
// valid pointer to PrecacheModel() not found
return false;
}
else
scanStartAddr = coincidenceAddr + pointerSize;
probeAddr = *(uint8_t **)(coincidenceAddr + pointerSize);
if (probeAddr >= moduleAddr && probeAddr < moduleEndAddr)
{
pfnPrecacheSound = buildInfo.FindFunctionAddress(
CBuildInfo::FunctionType::PrecacheSound, probeAddr
);
if (pfnPrecacheSound)
{
g_pServerEngfuncs = (enginefuncs_t *)coincidenceAddr;
return true;
}
}
}
return false;
}
uint8_t* CServerModule::GetFuncAddress(const char *funcName)
{
return reinterpret_cast<uint8_t*>(GetProcAddress(GetHandle(), funcName));
}
| 3,250
|
C++
|
.cpp
| 95
| 28.273684
| 102
| 0.692994
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,806
|
build_info_entry.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/build_info_entry.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "build_info.h"
#include "build_info_entry.h"
bool CBuildInfo::Entry::Validate() const
{
if (m_clientEngfuncsOffset > 0) {
return true;
}
for (size_t i = 0; i < static_cast<size_t>(FunctionType::PrecacheModel); ++i) // check only client-side functions
{
const CMemoryPattern &pattern = m_functionPatterns[i];
if (!pattern.IsInitialized()) {
return false;
}
}
return true;
}
| 965
|
C++
|
.cpp
| 27
| 32.037037
| 117
| 0.728832
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,807
|
entity_description.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/entity_description.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "entity_description.h"
#include "client_module.h"
#include "engine_module.h"
#include "studio.h"
#include <sstream>
CEntityDescription::CEntityDescription()
{
Reset();
}
void CEntityDescription::AddKeyValue(const std::string &key, const std::string &value)
{
m_EntityProps.insert({ key, value });
}
void CEntityDescription::Initialize()
{
ParseEntityData();
EstimateBoundingBox();
}
void CEntityDescription::GetPropertyString(int index, std::string &buffer) const
{
int currIndex = 0;
buffer.clear();
buffer.reserve(256);
for (auto it = m_EntityProps.begin(); it != m_EntityProps.end(); ++it)
{
const std::string &key = it->first;
const std::string &value = it->second;
if (currIndex == index)
{
buffer.append(key + " : " + value);
return;
}
++currIndex;
}
}
void CEntityDescription::AssociateEntity(int entityIndex)
{
m_iAssociatedEntity = entityIndex;
}
void CEntityDescription::Reset()
{
const vec3_t vecNull = vec3_t(0, 0, 0);
m_vecOrigin = vecNull;
m_vecAngles = vecNull;
m_szClassname.clear();
m_szTargetname.clear();
m_szModelName.clear();
m_boundingBox = CBoundingBox(vecNull);
m_iAssociatedEntity = -1;
}
void CEntityDescription::EstimateBoundingBox()
{
cl_entity_t *worldEntity = g_pClientEngfuncs->GetEntityByIndex(0);
model_t *worldModel = worldEntity->model;
if (m_szModelName[0] == '*') // brush model
{
int submodelIndex = std::atoi(&m_szModelName[1]);
if (submodelIndex < worldModel->numsubmodels)
{
dmodel_t *submodel = &worldModel->submodels[submodelIndex];
vec3_t submodelMaxs = submodel->maxs;
vec3_t submodelMins = submodel->mins;
vec3_t hullSize = submodelMaxs - submodelMins;
m_boundingBox = CBoundingBox(submodelMins, submodelMaxs);
m_vecOrigin = m_boundingBox.GetCenterPoint();
}
}
else if (m_vecOrigin.Length() > 0.01f) // is origin != (0, 0, 0)
{
// studio model entity
if (m_szModelName.length() >= 1 && m_szModelName.find(".mdl") != std::string::npos)
{
model_t *model = FindModelByName(m_szModelName.c_str());
if (model && model->type == mod_studio)
{
studiohdr_t *mdlHeader = (studiohdr_t *)model->cache.data;
if (mdlHeader)
{
mstudioseqdesc_t *seqDesc = (mstudioseqdesc_t *)((char *)mdlHeader + mdlHeader->seqindex);
m_boundingBox = CBoundingBox(seqDesc[0].bbmin, seqDesc[0].bbmax);
m_boundingBox.SetCenterToPoint(m_vecOrigin);
return;
}
}
}
// otherwise just use fixed-size hull for point entities
const vec3_t pointEntityHull = vec3_t(32, 32, 32);
m_boundingBox = CBoundingBox(pointEntityHull);
m_boundingBox.SetCenterToPoint(m_vecOrigin);
}
}
void CEntityDescription::ParseEntityData()
{
std::istringstream tokenStream;
for (auto it = m_EntityProps.begin(); it != m_EntityProps.end();)
{
const std::string &key = it->first;
const std::string &value = it->second;
if (key.compare("classname") == 0)
m_szClassname.assign(value);
else if (key.compare("targetname") == 0)
m_szTargetname.assign(value);
else if (key.compare("model") == 0)
m_szModelName.assign(value);
else if (key.compare("origin") == 0)
{
tokenStream.str(value);
tokenStream >> m_vecOrigin.x >> m_vecOrigin.y >> m_vecOrigin.z;
}
else if (key.compare("angles") == 0)
{
tokenStream.str(value);
tokenStream >> m_vecAngles.x >> m_vecAngles.y >> m_vecAngles.z;
}
else
{
// check if we should remove property
if (key.compare("renderamt") != 0 &&
key.compare("rendercolor") != 0 &&
key.compare("rendermode") != 0)
{
++it;
continue; // keep unhandled properties
}
};
// erase properties which already parsed
it = m_EntityProps.erase(it);
}
}
model_t *CEntityDescription::FindModelByName(const char *name)
{
int modelIndex = g_pClientEngfuncs->pEventAPI->EV_FindModelIndex(name);
if (modelIndex > 0) {
return g_pClientEngfuncs->hudGetModelByIndex(modelIndex);
}
return nullptr;
}
| 5,117
|
C++
|
.cpp
| 148
| 27.297297
| 110
| 0.619365
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,808
|
bvh_tree_node.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/bvh_tree_node.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "bvh_tree_node.h"
#include "exception.h"
CBVHTreeNode::CBVHTreeNode()
{
}
CBVHTreeNode::CBVHTreeNode(int index, const CBoundingBox &box)
{
m_index = index;
m_boundingBox = box;
}
CBVHTreeNode::CBVHTreeNode(int index, const CBoundingBox &box, CBVHTreeNode &parent)
{
m_index = index;
m_boundingBox = box;
m_parentNode = parent.GetIndex();
if (parent.GetLeftChild() < 0) {
parent.SetLeftChild(index);
}
else if (parent.GetRightChild() < 0) {
parent.SetRightChild(index);
}
else {
EXCEPT("trying to set node which already has child nodes");
}
}
| 1,135
|
C++
|
.cpp
| 36
| 28.472222
| 84
| 0.741995
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,809
|
build_info_impl.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/build_info_impl.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "build_info_impl.h"
#include "build_info_entry.h"
#include "utils.h"
#include "exception.h"
#include <string>
#include <fstream>
#include <filesystem>
std::optional<uint32_t> CBuildInfo::Impl::GetBuildNumber() const
{
if (m_pfnGetBuildNumber)
return m_pfnGetBuildNumber();
else if (m_buildNumber)
return m_buildNumber;
else
return std::nullopt;
}
int CBuildInfo::Impl::DateToBuildNumber(const char *date) const
{
int m = 0, d = 0, y = 0;
static int b = 0;
static int monthDaysCount[12] = {
31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31
};
static const char *monthNames[12] = {
"Jan", "Feb", "Mar",
"Apr", "May", "Jun",
"Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"
};
if (b != 0)
return b;
for (m = 0; m < 11; m++)
{
if (!strnicmp(&date[0], monthNames[m], 3))
break;
d += monthDaysCount[m];
}
d += atoi(&date[4]) - 1;
y = atoi(&date[7]) - 1900;
b = d + (int)((y - 1) * 365.25f);
if ((y % 4 == 0) && m > 1)
{
b += 1;
}
b -= 34995;
return b;
}
const char *CBuildInfo::Impl::FindDateString(uint8_t *startAddr, int maxLen) const
{
const int dateStringLen = 11;
maxLen -= dateStringLen;
for (int i = 0; i < maxLen; ++i)
{
int index = 0;
const char *text = reinterpret_cast<const char*>(startAddr + i);
if (Utils::IsSymbolAlpha(text[index++]) &&
Utils::IsSymbolAlpha(text[index++]) &&
Utils::IsSymbolAlpha(text[index++]) &&
Utils::IsSymbolSpace(text[index++]))
{
if (Utils::IsSymbolDigit(text[index]) || Utils::IsSymbolSpace(text[index]))
{
++index;
if (Utils::IsSymbolDigit(text[index++]) &&
Utils::IsSymbolSpace(text[index++]) &&
Utils::IsSymbolDigit(text[index++]) &&
Utils::IsSymbolDigit(text[index++]) &&
Utils::IsSymbolDigit(text[index++]))
return text;
}
}
}
return nullptr;
}
bool CBuildInfo::Impl::LoadBuildInfoFile(std::vector<uint8_t> &fileContents)
{
std::string libraryDirPath;
SysUtils::GetModuleDirectory(SysUtils::GetCurrentLibraryHandle(), libraryDirPath);
std::ifstream file(std::filesystem::path(libraryDirPath + "\\build_info.json"), std::ios::in | std::ios::binary);
fileContents.clear();
if (file.is_open())
{
#ifdef max
#undef max
file.ignore(std::numeric_limits<std::streamsize>::max());
#endif
size_t length = file.gcount();
file.clear();
file.seekg(0, std::ios_base::beg);
fileContents.reserve(length);
fileContents.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
fileContents.push_back('\0');
file.close();
return true;
}
else {
return false;
}
}
std::optional<std::string> CBuildInfo::Impl::ParseBuildInfo(std::vector<uint8_t> &fileContents)
{
rapidjson::Document doc;
doc.Parse(reinterpret_cast<const char *>(fileContents.data()));
if (!doc.IsObject()) {
return "JSON: build info document root is not object";
}
if (!doc.HasMember("build_number_signatures")) {
return "JSON: build info document hasn't member build_number_signatures";
}
if (!doc.HasMember("engine_builds_info")) {
return "JSON: build info document hasn't member engine_builds_info";
}
const rapidjson::Value &buildSignatures = doc["build_number_signatures"];
for (size_t i = 0; i < buildSignatures.Size(); ++i) {
m_BuildNumberSignatures.emplace_back(buildSignatures[i].GetString());
}
const rapidjson::Value &engineBuilds = doc["engine_builds_info"];
for (size_t i = 0; i < engineBuilds.Size(); ++i)
{
CBuildInfo::Entry infoEntry;
auto error = ParseBuildInfoEntry(infoEntry, engineBuilds[i]);
if (error.has_value()) {
return error;
}
m_EngineInfoEntries.push_back(infoEntry);
}
if (doc.HasMember("game_specific_builds_info"))
{
const rapidjson::Value &gameSpecificBuilds = doc["game_specific_builds_info"];
for (size_t i = 0; i < gameSpecificBuilds.Size(); ++i)
{
CBuildInfo::Entry infoEntry;
const rapidjson::Value &entryObject = gameSpecificBuilds[i];
if (entryObject.HasMember("process_name"))
{
auto error = ParseBuildInfoEntry(infoEntry, entryObject);
if (error.has_value()) {
return error;
}
infoEntry.SetGameProcessName(entryObject["process_name"].GetString());
m_GameInfoEntries.push_back(infoEntry);
}
else {
return "JSON: parsed game specific build info without process name";
}
}
}
return std::nullopt;
}
std::optional<std::string> CBuildInfo::Impl::ParseBuildInfoEntry(CBuildInfo::Entry &destEntry, const rapidjson::Value &jsonObject)
{
if (jsonObject.HasMember("number")) {
destEntry.SetBuildNumber(jsonObject["number"].GetInt());
}
if (jsonObject.HasMember("cl_engfuncs_offset")) {
destEntry.SetClientEngfuncsOffset(jsonObject["cl_engfuncs_offset"].GetUint64());
}
if (jsonObject.HasMember("sv_engfuncs_offset")) {
destEntry.SetServerEngfuncsOffset(jsonObject["sv_engfuncs_offset"].GetUint64());
}
if (jsonObject.HasMember("signatures"))
{
const rapidjson::Value &signatures = jsonObject["signatures"];
destEntry.SetFunctionPattern(CBuildInfo::FunctionType::SPR_Load, CMemoryPattern(signatures["SPR_Load"].GetString()));
destEntry.SetFunctionPattern(CBuildInfo::FunctionType::SPR_Frames, CMemoryPattern(signatures["SPR_Frames"].GetString()));
if (signatures.HasMember("PrecacheModel")) {
destEntry.SetFunctionPattern(CBuildInfo::FunctionType::PrecacheModel, CMemoryPattern(signatures["PrecacheModel"].GetString()));
}
if (signatures.HasMember("PrecacheSound")) {
destEntry.SetFunctionPattern(CBuildInfo::FunctionType::PrecacheSound, CMemoryPattern(signatures["PrecacheSound"].GetString()));
}
}
if (!destEntry.Validate()) {
return "JSON: parsed empty build info entry, check if signatures/offsets are set";
}
return std::nullopt;
}
bool CBuildInfo::Impl::ApproxBuildNumber(const SysUtils::ModuleInfo &engineModule)
{
CMemoryPattern datePattern("Jan", 4);
uint8_t *moduleStartAddr = engineModule.baseAddress;
uint8_t *moduleEndAddr = moduleStartAddr + engineModule.imageSize;
uint8_t *scanStartAddr = moduleStartAddr;
while (true)
{
uint8_t *stringAddr = (uint8_t *)Utils::FindPatternAddress(
scanStartAddr, moduleEndAddr, datePattern
);
if (stringAddr)
{
const int scanOffset = 64; // offset for finding date string
uint8_t *probeAddr = stringAddr - scanOffset;
const char *dateString = FindDateString(probeAddr, scanOffset);
if (dateString)
{
m_buildNumber = DateToBuildNumber(dateString);
return true;
}
else
{
scanStartAddr = stringAddr + 1;
continue;
}
}
else
return false;
}
}
bool CBuildInfo::Impl::FindBuildNumberFunc(const SysUtils::ModuleInfo &engineModule)
{
uint8_t *moduleStartAddr = engineModule.baseAddress;
uint8_t *moduleEndAddr = moduleStartAddr + engineModule.imageSize;
for (size_t i = 0; i < m_BuildNumberSignatures.size(); ++i)
{
m_pfnGetBuildNumber = (int(*)())Utils::FindPatternAddress(
moduleStartAddr,
moduleEndAddr,
m_BuildNumberSignatures[i]
);
if (m_pfnGetBuildNumber && m_pfnGetBuildNumber() > 0)
return true;
}
return false;
}
std::optional<size_t> CBuildInfo::Impl::FindActualInfoEntry()
{
auto buildNumberOpt = GetBuildNumber();
const size_t totalEntriesCount = m_EngineInfoEntries.size() + m_GameInfoEntries.size();
if (totalEntriesCount < 1 || !buildNumberOpt.has_value()) {
return std::nullopt;
}
else
{
// first check among game-specific builds
std::string processName;
SysUtils::GetModuleFilename(SysUtils::GetCurrentProcessModule(), processName);
for (size_t i = 0; i < m_GameInfoEntries.size(); ++i)
{
const CBuildInfo::Entry &buildInfo = m_GameInfoEntries[i];
const std::string &targetName = buildInfo.GetGameProcessName();
if (targetName.compare(processName) == 0) {
m_infoEntryGameSpecific = true;
return i;
}
}
// and then among engine builds
if (m_EngineInfoEntries.size() < 1) {
return std::nullopt;
}
uint32_t currBuildNumber = buildNumberOpt.value();
const size_t lastEntryIndex = m_EngineInfoEntries.size() - 1;
std::sort(m_EngineInfoEntries.begin(), m_EngineInfoEntries.end());
for (size_t i = 0; i < lastEntryIndex; ++i)
{
const CBuildInfo::Entry &buildInfo = m_EngineInfoEntries[i];
const CBuildInfo::Entry &nextBuildInfo = m_EngineInfoEntries[i + 1];
const uint32_t nextBuildNumber = nextBuildInfo.GetBuildNumber();
if (nextBuildNumber > currBuildNumber) { // valid only if build info entries sorted ascending
return i;
}
}
return lastEntryIndex; // if can't find something matching, then try just use latest available entry
}
}
| 10,429
|
C++
|
.cpp
| 277
| 29.801444
| 139
| 0.623345
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,810
|
dll_main.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/dll_main.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "stdafx.h"
#include "application.h"
#include "exception.h"
#include "hooks.h"
#include "sys_utils.h"
#include <Windows.h>
#include <stdint.h>
BOOLEAN WINAPI DllMain(HINSTANCE hDllHandle, DWORD nReason, LPVOID Reserved)
{
if (nReason == DLL_PROCESS_ATTACH)
{
try
{
SysUtils::InitCurrentLibraryHandle(hDllHandle);
g_Application.Run();
}
catch (const CException &ex)
{
std::string errorMsg(256, '\0');
std::snprintf(
errorMsg.data(),
errorMsg.capacity(),
"ERROR [%s:%d]: %s\nReport about error to the project page.\n"
"Link: github.com/SNMetamorph/goldsrc-monitor/issues/1",
ex.GetFileName().c_str(),
ex.GetLineNumber(),
ex.GetDescription().c_str()
);
MessageBox(NULL, errorMsg.c_str(), APP_TITLE_STR, MB_OK | MB_ICONWARNING);
return FALSE;
}
}
else if (nReason == DLL_PROCESS_DETACH)
{
}
return TRUE;
}
| 1,599
|
C++
|
.cpp
| 48
| 26.5
| 86
| 0.641424
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,811
|
bvh_tree.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/bvh_tree.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "bvh_tree.h"
#include "utils.h"
#include "client_module.h"
#include "cvars.h"
#include <cmath>
#include <array>
#include <cfloat>
#include <algorithm>
CBVHTree::CBVHTree(const std::vector<CEntityDescription> &descList)
: m_descList(descList)
{
}
void CBVHTree::Reset()
{
m_nodes.clear();
m_rootNodeIndex = -1;
}
void CBVHTree::Build()
{
BuildBottomUp();
if ((int)ConVars::gsm_debug->value == 2) {
PrintReport();
}
}
bool CBVHTree::FindLeaf(const CBoundingBox &box, int &nodeIndex, int &iterCount)
{
std::stack<int> nodesStack;
nodesStack.push(m_rootNodeIndex);
iterCount = 0;
while (!nodesStack.empty())
{
int currNode = nodesStack.top();
CBVHTreeNode &node = m_nodes[currNode];
const CBoundingBox &nodeBounds = node.GetBoundingBox();
nodesStack.pop();
if (nodeBounds.Contains(box))
{
if (node.IsLeaf() && node.GetDescriptionIndex() != -1)
{
const vec3_t difference = nodeBounds.GetCenterPoint() - box.GetCenterPoint();
const vec3_t diffMin = nodeBounds.GetMins() - box.GetMins();
const vec3_t diffMax = nodeBounds.GetMaxs() - box.GetMaxs();
if (diffMin.Length() < 0.2f && diffMax.Length() < 0.2f)
{
nodeIndex = currNode;
return true;
}
}
int leftChild = node.GetLeftChild();
int rightChild = node.GetRightChild();
if (leftChild >= 0) {
nodesStack.push(leftChild);
}
if (rightChild >= 0) {
nodesStack.push(rightChild);
}
}
++iterCount;
}
return false;
}
double CBVHTree::ComputeCost() const
{
double cost = 0.0;
for (size_t i = 0; i < m_nodes.size(); ++i)
{
const CBVHTreeNode &node = m_nodes[i];
if (!node.IsLeaf()) {
cost += node.GetBoundingBox().GetSurfaceArea();
}
}
return cost / 1000.0;
}
void CBVHTree::Visualize(bool textRendering)
{
if (m_nodes.size() < 1)
return;
std::stack<int> nodesStack;
nodesStack.push(m_rootNodeIndex);
while (!nodesStack.empty())
{
CBVHTreeNode &node = m_nodes[nodesStack.top()];
const CBoundingBox &nodeBounds = node.GetBoundingBox();
const int nodeIndex = node.GetIndex();
nodesStack.pop();
if (textRendering) {
Utils::DrawString3D(nodeBounds.GetCenterPoint(), std::to_string(nodeIndex).c_str(), 0, 255, 255);
}
else {
Utils::DrawCuboid(nodeBounds.GetCenterPoint(), vec3_t(0, 0, 0), vec3_t(0, 0, 0), nodeBounds.GetSize(), Color::GetRandom(nodeIndex));
}
if (node.GetLeftChild() >= 0) {
nodesStack.push(node.GetLeftChild());
}
if (node.GetRightChild() >= 0) {
nodesStack.push(node.GetRightChild());
}
}
}
std::string CBVHTree::GetGraphvisDescription() const
{
std::string treeDesc;
std::stack<int> nodesStack;
treeDesc += "digraph bvh_tree {\n";
// mark leaf nodes that has linked descriptions as red boxes
for (size_t i = 0; i < m_nodes.size(); ++i)
{
const CBVHTreeNode &node = m_nodes[i];
if (node.IsLeaf())
{
treeDesc += std::to_string(i) + " [shape=box]";
if (node.GetDescriptionIndex() != -1) {
treeDesc += " [color=red]";
}
treeDesc += '\n';
}
}
nodesStack.push(m_rootNodeIndex);
while (!nodesStack.empty())
{
const CBVHTreeNode &node = m_nodes[nodesStack.top()];
int leftChild = node.GetLeftChild();
int rightChild = node.GetRightChild();
nodesStack.pop();
if (leftChild >= 0) {
nodesStack.push(leftChild);
treeDesc += std::to_string(node.GetIndex()) + " -> " + std::to_string(leftChild) + "\n";
}
if (rightChild >= 0) {
nodesStack.push(rightChild);
treeDesc += std::to_string(node.GetIndex()) + " -> " + std::to_string(rightChild) + "\n";
}
}
treeDesc += "}\n";
return treeDesc;
}
void CBVHTree::BuildBottomUp()
{
std::vector<int> inputNodes;
std::vector<int> outputNodes;
std::vector<int> gameObjects = GetGameObjects();
// create and initialize leaf nodes
m_nodes.reserve(gameObjects.size());
for (int i : gameObjects)
{
const CEntityDescription &desc = m_descList.at(i);
int newNode = AppendNode(desc.GetBoundingBox());
NodeAt(newNode).SetDescriptionIndex(i);
inputNodes.push_back(newNode);
}
while (inputNodes.size() > 0)
{
if (inputNodes.size() == 1)
{
m_rootNodeIndex = inputNodes[0];
return;
}
MergeLevelNodes(inputNodes, outputNodes);
inputNodes = outputNodes;
}
}
void CBVHTree::MergeLevelNodes(const std::vector<int> &inputNodes, std::vector<int> &outputNodes)
{
outputNodes.clear();
for (size_t i = 0; i < inputNodes.size(); ++i)
{
int parentIndex;
CBVHTreeNode &node = NodeAt(inputNodes[i]);
if (node.GetParent() != -1)
continue;
// find best sibling
double minSurfaceArea = DBL_MAX;
int siblingIndex = -1;
for (size_t j = 0; j < inputNodes.size(); ++j)
{
CBVHTreeNode &siblingNode = NodeAt(inputNodes[j]);
if (i != j && siblingNode.GetParent() == -1)
{
const CBoundingBox &nodeBounds = node.GetBoundingBox();
const CBoundingBox &siblingBounds = siblingNode.GetBoundingBox();
double surfaceArea = nodeBounds.GetUnion(siblingBounds).GetSurfaceArea();
if (surfaceArea < minSurfaceArea)
{
minSurfaceArea = surfaceArea;
siblingIndex = j;
}
}
}
if (siblingIndex != -1)
{
int leftNodeIndex = inputNodes[i];
int rightNodeIndex = inputNodes[siblingIndex];
CBoundingBox leftNodeBounds = NodeAt(leftNodeIndex).GetBoundingBox();
CBoundingBox rightNodeBounds = NodeAt(rightNodeIndex).GetBoundingBox();
CBoundingBox parentNodeBounds = leftNodeBounds.GetUnion(rightNodeBounds);
parentIndex = AppendNode(parentNodeBounds);
NodeAt(parentIndex).SetLeftChild(leftNodeIndex);
NodeAt(parentIndex).SetRightChild(rightNodeIndex);
NodeAt(leftNodeIndex).SetParent(parentIndex);
NodeAt(rightNodeIndex).SetParent(parentIndex);
}
else
{
// if siblingIndex == -1 means that there is no free sibling nodes left, and we should
// create parent node only with current node sibling, because we haven't second sibling lol
// anyway this node will be merged somewhere on top levels
int leftNodeIndex = inputNodes[i];
parentIndex = AppendNode(NodeAt(leftNodeIndex).GetBoundingBox());
NodeAt(parentIndex).SetLeftChild(leftNodeIndex);
NodeAt(leftNodeIndex).SetParent(parentIndex);
}
outputNodes.push_back(parentIndex);
}
}
void CBVHTree::PrintReport()
{
std::string line;
std::string treeDesc = GetGraphvisDescription();
for (size_t offset = 0; offset < treeDesc.size(); offset += 500)
{
line.clear();
line.assign(treeDesc, offset, 500);
g_pClientEngfuncs->Con_Printf(line.c_str());
}
g_pClientEngfuncs->Con_Printf("BVH nodes: %d\nBVH tree cost: %f\n", m_nodes.size(), ComputeCost());
}
// Not suitable for game objects, tree doesn't covers all game objects with leaf nodes
void CBVHTree::BuildTopDown()
{
std::vector<int> rootNodeObjects = GetGameObjects();
int rootNode = AppendNode(CalcNodeBoundingBox(rootNodeObjects));
m_nodes.reserve(rootNodeObjects.size());
m_rootNodeIndex = rootNode;
m_nodesStack.push(m_rootNodeIndex);
m_objectListStack.push(rootNodeObjects);
while (!m_nodesStack.empty())
{
CBVHTreeNode &node = m_nodes[m_nodesStack.top()];
ObjectList nodeObjects = m_objectListStack.top();
m_nodesStack.pop();
m_objectListStack.pop();
SplitNode(node, nodeObjects);
}
}
void CBVHTree::SplitNode(CBVHTreeNode &node, ObjectList nodeObjects)
{
const int count = nodeObjects.size();
if (count == 1)
{
node.SetDescriptionIndex(nodeObjects[0]);
return;
}
int nodeIndex = node.GetIndex();
const CBoundingBox &nodeBounds = node.GetBoundingBox();
vec3_t nodeCenter = nodeBounds.GetCenterPoint();
static vec3_t axisLengths = nodeBounds.GetSize();
std::vector<int> leftNodeElements[3];
std::vector<int> rightNodeElements[3];
for (int i : nodeObjects)
{
const CEntityDescription &desc = m_descList.at(i);
vec3_t objectCenter = desc.GetBoundingBox().GetCenterPoint();
for (int j = 0; j < 3; ++j)
{
if (objectCenter[j] < nodeCenter[j]) {
leftNodeElements[j].push_back(i);
}
else {
rightNodeElements[j].push_back(i);
}
}
}
// check is it possible to split by any of axes
bool splitFailed[3] = { false };
for (int i = 0; i < 3; ++i) {
splitFailed[i] = (leftNodeElements[i].size() == 0) || (rightNodeElements[i].size() == 0);
}
// if it isn't possible, just stop because it'll cause infinite loop
if (splitFailed[0] && splitFailed[1] && splitFailed[2]) {
return;
}
// sort axes accoring to it lengths
std::array<int, 3> splitOrder = { 0, 1, 2 };
struct {
bool operator()(int a, int b) const { return axisLengths[a] > axisLengths[b]; }
} sortFunc;
std::sort(splitOrder.begin(), splitOrder.end(), sortFunc);
std::vector<int> *leftElements = nullptr;
std::vector<int> *rightElements = nullptr;
for (int i = 0; i < 3; ++i)
{
int j = splitOrder[i];
if (!splitFailed[j])
{
leftElements = &leftNodeElements[j];
rightElements = &rightNodeElements[j];
break;
}
}
int leftNode = AppendNode(CalcNodeBoundingBox(*leftElements), nodeIndex);
int rightNode = AppendNode(CalcNodeBoundingBox(*rightElements), nodeIndex);
m_nodesStack.push(leftNode);
m_nodesStack.push(rightNode);
m_objectListStack.push(*leftElements);
m_objectListStack.push(*rightElements);
}
// Returns appended node index
int CBVHTree::AppendNode(const CBoundingBox &nodeBounds, int parent)
{
if (parent >= 0) {
m_nodes.emplace_back(CBVHTreeNode(m_nodes.size(), nodeBounds, m_nodes[parent]));
}
else {
m_nodes.emplace_back(CBVHTreeNode(m_nodes.size(), nodeBounds));
}
return m_nodes.size() - 1;
}
CBoundingBox CBVHTree::CalcNodeBoundingBox(ObjectList nodeObjects, float epsilon)
{
CBoundingBox nodeBounds;
const vec3_t fudge = vec3_t(epsilon, epsilon, epsilon);
for (int i : nodeObjects)
{
const CEntityDescription &desc = m_descList.at(i);
nodeBounds.CombineWith(desc.GetBoundingBox());
}
return CBoundingBox(nodeBounds.GetMins() - fudge, nodeBounds.GetMaxs() + fudge);
}
std::vector<int> CBVHTree::GetGameObjects()
{
// skip worldspawn here
std::vector<int> objectList;
for (size_t i = 1; i < m_descList.size(); ++i) {
objectList.push_back(i);
}
return objectList;
}
| 12,184
|
C++
|
.cpp
| 348
| 27.603448
| 144
| 0.616337
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,812
|
displaymode_facereport.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_facereport.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "displaymode_facereport.h"
#include "client_module.h"
#include "utils.h"
#include "local_player.h"
#include <gl/GL.h>
#define PlaneDiff(point,plane) (((plane)->type < 3 ? (point)[(plane)->type] : DotProduct((point), (plane)->normal)) - (plane)->dist)
#define SURF_PLANEBACK 2
#define SURF_DRAWSKY 4
#define SURF_DRAWSPRITE 8
#define SURF_DRAWTURB 0x10
#define SURF_DRAWTILED 0x20
#define SURF_DRAWBACKGROUND 0x40
CModeFaceReport::CModeFaceReport(const CLocalPlayer &playerRef)
: m_localPlayer(playerRef)
{
m_colorProbe = { 0 };
m_currentModel = nullptr;
m_currentFace = nullptr;
m_boundPoints = {};
}
void CModeFaceReport::Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText)
{
const float lineLen = 11590.0f;
vec3_t intersectPoint;
vec3_t viewOrigin = m_localPlayer.GetViewOrigin();
vec3_t viewDir = m_localPlayer.GetViewDirection();
m_currentFace = TraceSurface(viewOrigin, viewDir, lineLen, intersectPoint);
screenText.Clear();
if (m_currentFace)
{
const mplane_t *plane = m_currentFace->plane;
const Engine::texture_t *texture = Engine::CastType(m_currentFace->texinfo->texture);
vec3_t planeCenter = plane->normal * plane->dist;
int32_t lightmapWidth = (m_currentFace->extents[0] >> 4) + 1;
int32_t lightmapHeight = (m_currentFace->extents[1] >> 4) + 1;
m_colorProbe = { 0 };
GetSurfaceBoundingBox(m_currentFace, m_currentFaceBounds);
const vec3_t &surfSize = m_currentFaceBounds.GetSize();
screenText.PushPrintf("Model Name: %s", m_currentModel->name);
screenText.PushPrintf("Texture Name: %s", texture->name);
screenText.PushPrintf("Texture Size: %d x %d", texture->width, texture->height);
screenText.PushPrintf("Lightmap Size: %d x %d", lightmapWidth, lightmapHeight);
screenText.PushPrintf("Edges: %d", m_currentFace->numedges);
screenText.PushPrintf("Surfaces: %d", m_currentModel->nummodelsurfaces);
screenText.PushPrintf("Bounds: (%.1f; %.1f; %.1f)", surfSize.x, surfSize.y, surfSize.z);
screenText.PushPrintf("Normal: (%.1f; %.1f; %.1f)", plane->normal.x, plane->normal.y, plane->normal.z);
screenText.PushPrintf("Intersect point: (%.1f; %.1f; %.1f)", intersectPoint.x, intersectPoint.y, intersectPoint.z);
if (GetLightmapProbe(m_currentFace, intersectPoint, m_colorProbe))
{
screenText.PushPrintf("Lightmap Color: %d %d %d",
m_colorProbe.r, m_colorProbe.g, m_colorProbe.b);
screenText.Push("Press V to print lightmap info");
}
}
else {
screenText.Push("Surface not found");
}
Utils::DrawStringStack(
static_cast<int>(ConVars::gsm_margin_right->value),
static_cast<int>(ConVars::gsm_margin_up->value),
screenText
);
}
void CModeFaceReport::Render3D()
{
if (m_currentFace && m_currentModel)
{
g_pClientEngfuncs->pTriAPI->RenderMode(kRenderTransColor);
g_pClientEngfuncs->pTriAPI->CullFace(TRI_NONE);
glDisable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
DrawFaceOutline(m_currentFace);
//DrawSurfaceBounds(m_pCurrentFace);
g_pClientEngfuncs->pTriAPI->RenderMode(kRenderNormal);
g_pClientEngfuncs->pTriAPI->CullFace(TRI_FRONT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
}
}
bool CModeFaceReport::KeyInput(bool keyDown, int keyNum, const char *bindName)
{
if (keyDown && keyNum == 'v')
{
if (m_currentFace)
{
const texture_t *texture = m_currentFace->texinfo->texture;
g_pClientEngfuncs->Con_Printf("%s %d %d %d\n",
texture->name, m_colorProbe.r, m_colorProbe.g, m_colorProbe.b);
g_pClientEngfuncs->pfnPlaySoundByName("buttons/blip1.wav", 0.8f);
return false;
}
}
return true;
}
void CModeFaceReport::HandleChangelevel()
{
m_currentModel = nullptr;
m_currentFace = nullptr;
}
int CModeFaceReport::TraceEntity(vec3_t origin, vec3_t dir, float distance, vec3_t &intersect)
{
pmtrace_t traceData;
int ignoredEnt = -1;
if (m_localPlayer.IsSpectate()) {
ignoredEnt = m_localPlayer.GetSpectateTargetIndex();
}
Utils::TraceLine(origin, dir, distance, &traceData, ignoredEnt);
intersect = origin + dir * distance * traceData.fraction;
if (traceData.fraction < 1.f)
{
if (traceData.ent > 0)
return g_pClientEngfuncs->pEventAPI->EV_IndexFromTrace(&traceData);
}
return 0;
}
void CModeFaceReport::GetSurfaceBoundingBox(Engine::msurface_t *surf, CBoundingBox &bbox)
{
bbox = CBoundingBox();
m_boundPoints.reserve(surf->numedges * 2);
m_boundPoints.clear();
for (int i = 0; i < surf->numedges; ++i)
{
int edgeIndex = m_currentModel->surfedges[surf->firstedge + i];
const medge_t *edge = m_currentModel->edges + (edgeIndex >= 0 ? edgeIndex : -edgeIndex);
const mvertex_t *vertex = m_currentModel->vertexes + (edgeIndex >= 0 ? edge->v[0] : edge->v[1]);
m_boundPoints.push_back(vertex->position);
}
if (m_boundPoints.size() > 0)
{
bbox.SetCenterToPoint(m_boundPoints[0]);
for (size_t i = 0; i < m_boundPoints.size(); ++i)
{
const vec3_t &vertex = m_boundPoints[i];
bbox.ExpandToPoint(vertex);
}
}
}
Engine::mleaf_t *CModeFaceReport::PointInLeaf(vec3_t point, Engine::mnode_t *node)
{
for (;;)
{
if (node->contents < 0)
return reinterpret_cast<Engine::mleaf_t *>(node);
node = node->children[PlaneDiff(point, node->plane) <= 0];
}
return NULL;
}
void CModeFaceReport::DrawFaceOutline(Engine::msurface_t *surf)
{
const Color lineColor = Color(0.f, 1.f, 1.f, 1.f);
g_pClientEngfuncs->pTriAPI->Begin(TRI_LINES);
g_pClientEngfuncs->pTriAPI->Color4f(lineColor.Red(), lineColor.Green(), lineColor.Blue(), lineColor.Alpha());
for (int i = 0; i < surf->numedges; ++i)
{
int edgeIndex = m_currentModel->surfedges[surf->firstedge + i];
const medge_t *edge = m_currentModel->edges + (edgeIndex >= 0 ? edgeIndex : -edgeIndex);
vec3_t &vertex1 = m_currentModel->vertexes[edge->v[0]].position;
vec3_t &vertex2 = m_currentModel->vertexes[edge->v[1]].position;
g_pClientEngfuncs->pTriAPI->Vertex3fv(vertex1);
g_pClientEngfuncs->pTriAPI->Vertex3fv(vertex2);
}
g_pClientEngfuncs->pTriAPI->End();
}
void CModeFaceReport::DrawSurfaceBounds(Engine::msurface_t *surf)
{
CBoundingBox bounds;
const vec3_t nullVec = vec3_t(0, 0, 0);
const Color boxColor = Color(1.f, 0.f, 0.f, 1.f);
GetSurfaceBoundingBox(surf, bounds);
Utils::DrawCuboid(
bounds.GetCenterPoint(),
nullVec,
nullVec,
bounds.GetSize(),
boxColor
);
}
bool CModeFaceReport::GetLightmapProbe(Engine::msurface_t *surf, const vec3_t &point, color24 &probe)
{
if (surf->flags & SURF_DRAWTILED)
return false; // no lightmaps
mtexinfo_t *tex = surf->texinfo;
int s = DotProduct(point, tex->vecs[0]) + tex->vecs[0][3];
int t = DotProduct(point, tex->vecs[1]) + tex->vecs[1][3];
if (s < surf->texturemins[0] || t < surf->texturemins[1])
return false;
int ds = s - surf->texturemins[0];
int dt = t - surf->texturemins[1];
if (ds > surf->extents[0] || dt > surf->extents[1])
return false;
if (!surf->samples)
return false;
ds >>= 4;
dt >>= 4;
color24 *lightmap = surf->samples;
int lw = (surf->extents[0] >> 4) + 1;
int lh = (surf->extents[1] >> 4) + 1;
if (lightmap)
{
// this code also should assume lightstyles but this info not available here
lightmap += dt * lw + ds;
probe.r = lightmap->r;
probe.g = lightmap->g;
probe.b = lightmap->b;
return true;
}
return false;
}
Engine::msurface_t *CModeFaceReport::TraceSurface(vec3_t origin, vec3_t dir, float distance, vec3_t &intersect)
{
int entityIndex = TraceEntity(origin, dir, distance, intersect);
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(entityIndex);
model_t *worldModel = g_pClientEngfuncs->hudGetModelByIndex(1);
Engine::mnode_t *firstNode = nullptr;
Engine::msurface_t *surf = nullptr;
if (entity)
{
if (entity->model->type != mod_brush) {
m_currentModel = worldModel;
}
else {
m_currentModel = entity->model;
}
firstNode = Engine::CastType(m_currentModel->nodes);
firstNode = m_currentModel->hulls[0].firstclipnode + firstNode;
vec3_t endPoint = origin + (dir * distance);
surf = SurfaceAtPoint(m_currentModel, firstNode, origin, endPoint, intersect);
if (surf) {
return surf;
}
}
m_currentModel = nullptr;
return nullptr;
}
Engine::msurface_t *CModeFaceReport::SurfaceAtPoint(model_t *pModel, Engine::mnode_t *node, vec3_t start, vec3_t end, vec3_t &intersect)
{
mplane_t *plane;
vec3_t mid;
mtexinfo_t *tex;
Engine::msurface_t *surf;
if (node->contents < 0) {
return nullptr;
}
plane = node->plane;
float front = DotProduct(start, plane->normal) - plane->dist;
float back = DotProduct(end, plane->normal) - plane->dist;
int side = front < 0;
if ((back < 0) == side) {
return SurfaceAtPoint(pModel, node->children[side], start, end, intersect);
}
float frac = front / (front - back);
mid[0] = start[0] + (end[0] - start[0]) * frac;
mid[1] = start[1] + (end[1] - start[1]) * frac;
mid[2] = start[2] + (end[2] - start[2]) * frac;
surf = SurfaceAtPoint(pModel, node->children[side], start, mid, intersect);
if (surf) {
return surf;
}
if ((back < 0) == side) {
return nullptr;
}
surf = Engine::CastType(pModel->surfaces) + node->firstsurface;
for (int i = 0; i < node->numsurfaces; i++, surf++)
{
tex = surf->texinfo;
int s = DotProduct(mid, tex->vecs[0]) + tex->vecs[0][3];
int t = DotProduct(mid, tex->vecs[1]) + tex->vecs[1][3];
if (s < surf->texturemins[0] || t < surf->texturemins[1]) {
continue;
}
int ds = s - surf->texturemins[0];
int dt = t - surf->texturemins[1];
if (ds > surf->extents[0] || dt > surf->extents[1]) {
continue;
}
intersect = mid;
return surf;
}
return SurfaceAtPoint(pModel, node->children[!side], mid, end, intersect);
}
| 11,209
|
C++
|
.cpp
| 291
| 32.360825
| 136
| 0.642515
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,813
|
build_info.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/build_info.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "build_info.h"
#include "build_info_entry.h"
#include "build_info_impl.h"
#include "exception.h"
#include "utils.h"
#include <vector>
CBuildInfo::CBuildInfo()
{
m_pImpl = std::make_unique<CBuildInfo::Impl>();
}
CBuildInfo::~CBuildInfo()
{
}
void CBuildInfo::Initialize(const SysUtils::ModuleInfo &engineModule)
{
std::vector<uint8_t> fileContents;
if (m_pImpl->LoadBuildInfoFile(fileContents))
{
auto error = m_pImpl->ParseBuildInfo(fileContents);
if (error.has_value()) {
m_pImpl->m_initErrorMessage = error.value();
return;
}
}
else {
m_pImpl->m_initErrorMessage = "failed to load build info file";
return;
}
if (!m_pImpl->FindBuildNumberFunc(engineModule))
{
if (!m_pImpl->ApproxBuildNumber(engineModule)) {
m_pImpl->m_initErrorMessage = "failed to approximate engine build number";
return;
}
}
auto entryIndex = m_pImpl->FindActualInfoEntry();
if (!entryIndex.has_value()) {
m_pImpl->m_initErrorMessage = "not found matching build info entry";
return;
}
m_pImpl->m_iActualEntryIndex = entryIndex;
}
void *CBuildInfo::FindFunctionAddress(CBuildInfo::FunctionType funcType, void *startAddr, void *endAddr) const
{
if (!m_pImpl->m_iActualEntryIndex.has_value()) {
return nullptr;
}
const CBuildInfo::Entry *entry;
if (m_pImpl->m_infoEntryGameSpecific) {
entry = m_pImpl->m_GameInfoEntries.data() + m_pImpl->m_iActualEntryIndex.value();
}
else {
entry = m_pImpl->m_EngineInfoEntries.data() + m_pImpl->m_iActualEntryIndex.value();
}
CMemoryPattern funcPattern = entry->GetFunctionPattern(funcType);
if (!endAddr)
endAddr = (uint8_t *)startAddr + funcPattern.GetLength();
return Utils::FindPatternAddress(
startAddr,
endAddr,
funcPattern
);
}
const std::string &CBuildInfo::GetInitErrorDescription() const
{
return m_pImpl->m_initErrorMessage;
}
const CBuildInfo::Entry *CBuildInfo::GetInfoEntry() const
{
if (!m_pImpl->m_iActualEntryIndex.has_value()) {
return nullptr;
}
if (m_pImpl->m_infoEntryGameSpecific) {
return m_pImpl->m_GameInfoEntries.data() + m_pImpl->m_iActualEntryIndex.value();
}
else {
return m_pImpl->m_EngineInfoEntries.data() + m_pImpl->m_iActualEntryIndex.value();
}
}
| 2,949
|
C++
|
.cpp
| 90
| 27.966667
| 110
| 0.691848
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,814
|
displaymode_entityreport.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_entityreport.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "displaymode_entityreport.h"
#include "cvars.h"
#include "utils.h"
#include "client_module.h"
#include "engine_module.h"
#include "studio.h"
#include "local_player.h"
#include "bounding_box.h"
#include <algorithm>
#include <iterator>
CModeEntityReport::CModeEntityReport(const CLocalPlayer &playerRef, const CEngineModule &moduleRef)
: m_localPlayer(playerRef), m_engineModule(moduleRef)
{
m_entityIndex = 0;
m_lockedEntityIndex = 0;
m_entityIndexList = {};
m_entityDistanceList = {};
}
void CModeEntityReport::Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText)
{
if (m_localPlayer.PredictionDataValid())
{
int debugMode = ConVars::gsm_debug->value;
if (!m_entityDictionary.IsInitialized())
m_entityDictionary.Initialize();
screenText.Clear();
m_entityIndex = TraceEntity();
if (!PrintEntityInfo(GetActualEntityIndex(), screenText))
{
// disable hull highlighting for this entity
m_entityIndex = 0;
}
if (debugMode == 2) {
m_entityDictionary.VisualizeTree(true);
}
}
else
{
screenText.Clear();
screenText.Push("This mode unavailable when playing demo");
}
Utils::DrawStringStack(
static_cast<int>(ConVars::gsm_margin_right->value),
static_cast<int>(ConVars::gsm_margin_up->value),
screenText
);
}
void CModeEntityReport::Render3D()
{
CBoundingBox entityBbox;
int debugMode = ConVars::gsm_debug->value;
int currentEntity = GetActualEntityIndex();
const Color colorGreen = Color(0.f, 1.f, 0.f, 1.f);
if (debugMode == 1) {
m_entityDictionary.VisualizeDescriptions();
}
else if (debugMode == 2) {
m_entityDictionary.VisualizeTree(false);
}
if (currentEntity > 0 && !m_engineModule.IsSoftwareRenderer())
{
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(currentEntity);
Utils::GetEntityBoundingBox(currentEntity, entityBbox);
vec3_t centerOffset = (entity->curstate.mins + entity->curstate.maxs) / 2.f;
Utils::DrawCuboid(entity->origin, centerOffset, entity->angles, entityBbox.GetSize(), colorGreen);
}
}
bool CModeEntityReport::KeyInput(bool keyDown, int keyCode, const char *bindName)
{
if (Utils::GetCurrentDisplayMode() != DisplayModeType::EntityReport || !keyDown) {
return true;
}
if (keyCode == 'v')
{
if (m_entityIndex > 0) {
if (m_entityIndex == m_lockedEntityIndex) {
m_lockedEntityIndex = 0;
}
else {
m_lockedEntityIndex = m_entityIndex;
}
}
else {
m_lockedEntityIndex = 0;
}
g_pClientEngfuncs->pfnPlaySoundByName("buttons/blip1.wav", 0.8f);
return false;
}
return true;
}
void CModeEntityReport::HandleChangelevel()
{
m_entityDictionary.Reset();
}
int CModeEntityReport::TraceEntity()
{
vec3_t viewDir;
vec3_t viewOrigin;
pmtrace_t traceData;
const float lineLen = 11590.0f;
float worldDistance = lineLen;
int ignoredEnt = -1;
m_entityIndexList.clear();
m_entityDistanceList.clear();
viewOrigin = m_localPlayer.GetViewOrigin();
viewDir = m_localPlayer.GetViewDirection();
if (m_localPlayer.IsSpectate())
ignoredEnt = m_localPlayer.GetSpectateTargetIndex();
Utils::TraceLine(viewOrigin, viewDir, lineLen, &traceData, ignoredEnt);
if (traceData.fraction < 1.f)
{
if (traceData.ent > 0)
return g_pClientEngfuncs->pEventAPI->EV_IndexFromTrace(&traceData);
else
worldDistance = lineLen * traceData.fraction;
}
const int listCount = 3;
const physent_t *physEntLists[listCount] = {
m_localPlayer.GetVisents(),
m_localPlayer.GetPhysents(),
m_localPlayer.GetMoveents()
};
int physEntListsLen[listCount] = {
m_localPlayer.GetVisentsCount(),
m_localPlayer.GetPhysentsCount(),
m_localPlayer.GetMoveentsCount()
};
for (int i = 0; i < listCount; ++i)
{
int physEntIndex = TracePhysEntList(physEntLists[i], physEntListsLen[i], viewOrigin, viewDir, lineLen);
if (physEntIndex)
{
m_entityIndexList.push_back(physEntIndex);
m_entityDistanceList.push_back(GetEntityDistance(physEntIndex));
}
}
// get nearest entity from all lists
// also add world for comparision
m_entityIndexList.push_back(0);
m_entityDistanceList.push_back(worldDistance);
auto &distanceList = m_entityDistanceList;
if (distanceList.size() > 1)
{
auto iterNearestEnt = std::min_element(std::begin(distanceList), std::end(distanceList));
if (std::end(distanceList) != iterNearestEnt)
return m_entityIndexList[std::distance(distanceList.begin(), iterNearestEnt)];
}
return 0;
}
float CModeEntityReport::TracePhysEnt(const physent_t &physEnt, vec3_t &viewOrigin, vec3_t &viewDir, float lineLen)
{
CBoundingBox entityBbox;
Utils::GetEntityBoundingBox(physEnt.info, entityBbox);
// skip studiomodel visents which is culled
vec3_t bboxMins = entityBbox.GetMins();
vec3_t bboxMaxs = entityBbox.GetMaxs();
if (!g_pClientEngfuncs->pTriAPI->BoxInPVS(bboxMins, bboxMaxs)) {
return 1.0f;
}
// check for intersection
vec3_t lineEnd = viewOrigin + (viewDir * lineLen);
return Utils::TraceBBoxLine(entityBbox, viewOrigin, lineEnd);
}
int CModeEntityReport::TracePhysEntList(const physent_t *list, int count, vec3_t &viewOrigin, vec3_t &viewDir, float lineLen)
{
int entIndex = 0;
float minFraction = 1.0f;
for (int i = 0; i < count; ++i)
{
const physent_t &visEnt = list[i];
float traceFraction = TracePhysEnt(visEnt, viewOrigin, viewDir, lineLen);
if (traceFraction < minFraction)
{
entIndex = visEnt.info;
minFraction = traceFraction;
}
}
return entIndex;
}
float CModeEntityReport::GetEntityDistance(int entityIndex)
{
vec3_t pointInBbox;
CBoundingBox entityBbox;
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(entityIndex);
if (entity)
{
model_t *entityModel = entity->model;
vec3_t viewOrigin = m_localPlayer.GetViewOrigin();
// get nearest bbox-to-player distance by point caged in bbox
Utils::GetEntityBoundingBox(entityIndex, entityBbox);
const vec3_t &bboxMins = entityBbox.GetMins();
const vec3_t &bboxMaxs = entityBbox.GetMaxs();
pointInBbox.x = std::max(std::min(viewOrigin.x, bboxMaxs.x), bboxMins.x);
pointInBbox.y = std::max(std::min(viewOrigin.y, bboxMaxs.y), bboxMins.y);
pointInBbox.z = std::max(std::min(viewOrigin.z, bboxMaxs.z), bboxMins.z);
return (pointInBbox - viewOrigin).Length();
}
return 0.0f;
}
bool CModeEntityReport::PrintEntityInfo(int entityIndex, CStringStack &screenText)
{
int debugMode = ConVars::gsm_debug->value;
if (entityIndex < 1)
{
std::string mapName = Utils::GetCurrentMapName();
screenText.Push("Entity not found");
screenText.PushPrintf("Map: %s", mapName.c_str());
screenText.PushPrintf("Entity descriptions: %d", m_entityDictionary.GetDescriptionsCount());
}
else if (Utils::IsGameDirEquals("cstrike") && m_localPlayer.IsSpectate() && m_localPlayer.GetSpectatingMode() != SpectatingMode::Roaming)
{
// disable print in non free-look spectating modes
screenText.Push("Print enabled only in free look mode");
return false;
}
else
{
int iterCount;
CEntityDescription entityDesc;
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(entityIndex);
bool descFound = m_entityDictionary.FindDescription(entityIndex, entityDesc, iterCount);
PrintEntityCommonInfo(entityIndex, screenText);
if (descFound)
{
const std::string &classname = entityDesc.GetClassname();
const std::string &targetname = entityDesc.GetTargetname();
screenText.PushPrintf("Classname: %s", classname.c_str());
if (targetname.length() > 0)
screenText.PushPrintf("Targetname: %s", targetname.c_str());
}
if (entity && entity->model && entity->model->type == mod_studio)
{
std::string modelName;
Utils::GetEntityModelName(entityIndex, modelName);
screenText.PushPrintf("Model Name: %s", modelName.c_str());
screenText.PushPrintf("Anim. Frame: %.1f", entity->curstate.frame);
screenText.PushPrintf("Anim. Sequence: %d", entity->curstate.sequence);
screenText.PushPrintf("Bodygroup Number: %d", entity->curstate.body);
screenText.PushPrintf("Skin Number: %d", entity->curstate.skin);
}
if (descFound)
{
if (debugMode == 2) {
screenText.PushPrintf("Search iteration count: %d", iterCount);
}
const int propsCount = entityDesc.GetPropertiesCount();
if (propsCount > 0)
{
std::string propsString;
screenText.Push("Entity Properties");
for (int i = 0; i < propsCount; ++i)
{
entityDesc.GetPropertyString(i, propsString);
screenText.PushPrintf(" %s", propsString.c_str());
}
}
else {
screenText.Push("No entity properties");
}
}
else {
screenText.Push("Entity properties not found");
}
if (!m_lockedEntityIndex) {
screenText.Push("Press V to hold on current entity");
}
}
return true;
}
void CModeEntityReport::PrintEntityCommonInfo(int entityIndex, CStringStack &screenText)
{
CBoundingBox entityBbox;
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(entityIndex);
if (entity)
{
vec3_t entityVelocity = Utils::GetEntityVelocityApprox(entityIndex);
vec3_t centerOffset = (entity->curstate.mins + entity->curstate.maxs) / 2.f;
vec3_t entityAngles = entity->curstate.angles;
vec3_t entityOrigin = entity->origin + centerOffset;
Utils::GetEntityBoundingBox(entityIndex, entityBbox);
screenText.PushPrintf("Entity Index: %d", entityIndex);
screenText.PushPrintf("Origin: (%.1f; %.1f; %.1f)",
entityOrigin.x, entityOrigin.y, entityOrigin.z);
screenText.PushPrintf("Distance: %.1f units",
GetEntityDistance(entityIndex));
screenText.PushPrintf("Velocity: %.2f u/s (%.1f; %.1f; %.1f)",
entityVelocity.Length2D(), entityVelocity.x, entityVelocity.y, entityVelocity.z);
screenText.PushPrintf("Angles: (%.1f; %.1f; %.1f)",
entityAngles.x, entityAngles.y, entityAngles.z);
screenText.PushPrintf("Hull Size: (%.1f; %.1f; %.1f)",
entityBbox.GetSize().x, entityBbox.GetSize().y, entityBbox.GetSize().z);
screenText.PushPrintf("Movetype: %s", Utils::GetMovetypeName(entity->curstate.movetype));
screenText.PushPrintf("Render Mode: %s", Utils::GetRenderModeName(entity->curstate.rendermode));
screenText.PushPrintf("Render FX: %s", Utils::GetRenderFxName(entity->curstate.renderfx));
screenText.PushPrintf("Render Amount: %d", entity->curstate.renderamt);
screenText.PushPrintf("Render Color: %d %d %d",
entity->curstate.rendercolor.r,
entity->curstate.rendercolor.g,
entity->curstate.rendercolor.b
);
}
}
int CModeEntityReport::GetActualEntityIndex()
{
if (m_lockedEntityIndex > 0) {
return m_lockedEntityIndex;
}
else {
return m_entityIndex;
}
}
| 12,506
|
C++
|
.cpp
| 322
| 31.515528
| 141
| 0.655411
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,815
|
engine_module.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/engine_module.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "engine_module.h"
#include "hlsdk.h"
bool CEngineModule::FindHandle()
{
m_moduleHandle = GetModuleHandle("hw.dll");
if (!m_moduleHandle)
{
m_moduleHandle = GetModuleHandle("sw.dll");
if (m_moduleHandle)
{
m_isSoftwareRenderer = true;
}
else
{
m_isXashEngine = true;
m_moduleHandle = GetModuleHandle("xash.dll");
}
}
return (m_moduleHandle != NULL) && SetupModuleInfo();
}
bool CEngineModule::GetFunctionsFromAPI(uint8_t **pfnSPR_Load, uint8_t **pfnSPR_Frames) const
{
if (m_isXashEngine)
{
pfnEngSrc_pfnSPR_Load_t pfnFunc1 = (pfnEngSrc_pfnSPR_Load_t)GetProcAddress(m_moduleHandle, "pfnSPR_Load");
if (pfnFunc1)
{
pfnEngSrc_pfnSPR_Frames_t pfnFunc2 = (pfnEngSrc_pfnSPR_Frames_t)GetProcAddress(m_moduleHandle, "pfnSPR_Frames");
if (pfnFunc2)
{
*pfnSPR_Load = reinterpret_cast<uint8*>(pfnFunc1);
*pfnSPR_Frames = reinterpret_cast<uint8 *>(pfnFunc2);
return true;
}
}
}
return false;
}
bool CEngineModule::SetupModuleInfo()
{
if (m_moduleHandle)
{
if (SysUtils::GetModuleInfo(GetCurrentProcess(), m_moduleHandle, m_moduleInfo)) {
return true;
}
}
return false;
}
| 1,886
|
C++
|
.cpp
| 59
| 25.745763
| 124
| 0.65788
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,816
|
hooks_logger.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/hooks_logger.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "hooks_logger.h"
#include "utils.h"
#ifdef _WIN32
#include <windows.h>
#endif
CHooks::Logger::~Logger()
{
}
void CHooks::Logger::log(const std::string &msg, PLH::ErrorLevel level)
{
if (level >= m_errorLevel)
{
switch (level)
{
case PLH::ErrorLevel::INFO:
Utils::Snprintf(m_outputText, "[goldsrc-monitor] INFO: %s\n", msg.c_str());
break;
case PLH::ErrorLevel::WARN:
Utils::Snprintf(m_outputText, "[goldsrc-monitor] WARN: %s\n", msg.c_str());
break;
case PLH::ErrorLevel::SEV:
Utils::Snprintf(m_outputText, "[goldsrc-monitor] ERROR: %s\n", msg.c_str());
break;
default:
Utils::Snprintf(m_outputText, "[goldsrc-monitor] Unsupported error message logged: %s\n", msg.c_str());
}
#ifdef _WIN32
OutputDebugStringA(m_outputText.c_str());
#else
#pragma warning "Logging is not implemented for this platform"
#endif
}
}
void CHooks::Logger::setLogLevel(PLH::ErrorLevel level)
{
m_errorLevel = level;
}
| 1,463
|
C++
|
.cpp
| 48
| 28.4375
| 106
| 0.745028
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,817
|
opengl_primitives_renderer.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/opengl_primitives_renderer.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "opengl_primitives_renderer.h"
#include "client_module.h"
#include <cassert>
#ifdef _WIN32
#include <gl/GL.h>
#endif
void COpenGLPrimitivesRenderer::Begin()
{
// disable textures & culling, enable alpha blending
g_pClientEngfuncs->pTriAPI->RenderMode(kRenderTransColor);
g_pClientEngfuncs->pTriAPI->CullFace(TRI_NONE);
glDisable(GL_TEXTURE_2D);
}
void COpenGLPrimitivesRenderer::End()
{
// restore original OpenGL state, now doing it wrong, but :)
g_pClientEngfuncs->pTriAPI->RenderMode(kRenderNormal);
g_pClientEngfuncs->pTriAPI->CullFace(TRI_FRONT);
glEnable(GL_TEXTURE_2D);
}
void COpenGLPrimitivesRenderer::ToggleDepthTest(bool state)
{
if (state) {
glEnable(GL_DEPTH_TEST);
}
else {
glDisable(GL_DEPTH_TEST);
}
}
void COpenGLPrimitivesRenderer::RenderPrimitives(PrimitiveType type,
const std::vector<vec3_t> &verticesBuffer,
const std::vector<Color> &colorBuffer)
{
assert(!verticesBuffer.empty() && !verticesBuffer.empty());
glBegin(GetGlPrimitiveEnum(type));
for (size_t i = 0; i < verticesBuffer.size(); ++i)
{
// TODO optimize it, avoid using immediate mode
const Color &vertexColor = colorBuffer[std::min(i, colorBuffer.size() - 1)];
glColor4f(vertexColor.Red(), vertexColor.Green(), vertexColor.Blue(), vertexColor.Alpha());
glVertex3fv(verticesBuffer[i]);
}
glEnd();
}
uint32_t COpenGLPrimitivesRenderer::GetGlPrimitiveEnum(PrimitiveType pt) const
{
switch (pt) {
case PrimitiveType::Quads: return GL_QUADS;
case PrimitiveType::LineLoop: return GL_LINE_LOOP;
default: return GL_NONE;
}
}
| 2,082
|
C++
|
.cpp
| 63
| 31.047619
| 93
| 0.776231
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,818
|
bounding_box.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/bounding_box.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "bounding_box.h"
#include <algorithm>
CBoundingBox::CBoundingBox(const vec3_t &size)
{
Initialize(-size / 2, size / 2);
}
CBoundingBox::CBoundingBox(const vec3_t &vecMins, const vec3_t &vecMaxs)
{
Initialize(vecMins, vecMaxs);
}
vec3_t CBoundingBox::GetCenterPoint() const
{
return m_mins + m_size / 2;
}
void CBoundingBox::SetCenterToPoint(const vec3_t &point)
{
Initialize(point - m_size / 2, point + m_size / 2);
}
CBoundingBox CBoundingBox::GetUnion(const CBoundingBox &operand) const
{
CBoundingBox currentBoxCopy(m_mins, m_maxs);
currentBoxCopy.CombineWith(operand);
return currentBoxCopy;
}
void CBoundingBox::CombineWith(const CBoundingBox &operand)
{
vec3_t unionMins;
vec3_t unionMaxs;
const vec3_t &currMins = m_mins;
const vec3_t &currMaxs = m_maxs;
const vec3_t &operandMins = operand.GetMins();
const vec3_t &operandMaxs = operand.GetMaxs();
unionMins.x = std::min(currMins.x, operandMins.x);
unionMins.y = std::min(currMins.y, operandMins.y);
unionMins.z = std::min(currMins.z, operandMins.z);
unionMaxs.x = std::max(currMaxs.x, operandMaxs.x);
unionMaxs.y = std::max(currMaxs.y, operandMaxs.y);
unionMaxs.z = std::max(currMaxs.z, operandMaxs.z);
Initialize(unionMins, unionMaxs);
}
void CBoundingBox::ExpandToPoint(const vec3_t &point)
{
if (point.x < m_mins.x)
m_mins.x = point.x;
if (point.y < m_mins.y)
m_mins.y = point.y;
if (point.z < m_mins.z)
m_mins.z = point.z;
if (point.x > m_maxs.x)
m_maxs.x = point.x;
if (point.y > m_maxs.y)
m_maxs.y = point.y;
if (point.z > m_maxs.z)
m_maxs.z = point.z;
Initialize(m_mins, m_maxs);
}
bool CBoundingBox::Contains(const CBoundingBox &operand) const
{
const vec3_t &mins = operand.GetMins();
const vec3_t &maxs = operand.GetMaxs();
if (mins.x < m_mins.x || mins.x > m_maxs.x)
return false;
if (mins.y < m_mins.y || mins.y > m_maxs.y)
return false;
if (mins.z < m_mins.z || mins.z > m_maxs.z)
return false;
if (maxs.x < m_mins.x || maxs.x > m_maxs.x)
return false;
if (maxs.y < m_mins.y || maxs.y > m_maxs.y)
return false;
if (maxs.z < m_mins.z || maxs.z > m_maxs.z)
return false;
return true;
}
bool CBoundingBox::ContainsPoint(const vec3_t &point) const
{
if (point.x < m_mins.x || point.x > m_maxs.x)
return false;
if (point.y < m_mins.y || point.y > m_maxs.y)
return false;
if (point.z < m_mins.z || point.z > m_maxs.z)
return false;
return true;
}
double CBoundingBox::GetSurfaceArea() const
{
return 2.0 * (m_size.x * m_size.y + m_size.y * m_size.z + m_size.x * m_size.z);
}
void CBoundingBox::Initialize(const vec3_t &vecMins, const vec3_t &vecMaxs)
{
m_mins = vecMins;
m_maxs = vecMaxs;
m_size = vecMaxs - vecMins;
}
| 3,422
|
C++
|
.cpp
| 105
| 28.561905
| 83
| 0.67132
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,819
|
utils.cpp
|
SNMetamorph_goldsrc-monitor/sources/library/utils.cpp
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "utils.h"
#include "client_module.h"
#include "studio.h"
#include "application.h"
#include "matrix.h"
#include "sys_utils.h"
#include <stdint.h>
#include <cstring>
#include <vector>
void *Utils::FindPatternAddress(void *startAddr, void *endAddr, const CMemoryPattern &pattern)
{
size_t patternLen = pattern.GetLength();
uint8_t *totalEndAddr = (uint8_t*)endAddr - patternLen;
const uint8_t *patternStart = pattern.GetSignatureAddress();
const int *maskStart = pattern.GetMaskAddress();
for (uint8_t *i = (uint8_t*)startAddr; i <= totalEndAddr; ++i)
{
bool isFailed = false;
for (size_t j = 0; j < patternLen; ++j)
{
const uint8_t scanByte = *(i + j);
const uint8_t patternByte = *(patternStart + j);
const bool shouldCheckByte = *(maskStart + j) != 0;
if (shouldCheckByte && patternByte != scanByte)
{
isFailed = true;
break;
}
}
if (!isFailed)
return i;
}
return nullptr;
}
void *Utils::FindJmpFromAddress(void *startAddr, void *endAddr, void *targetAddress)
{
#ifndef APP_SUPPORT_64BIT
size_t patternLen = 5; // jmp instuction is 5 bytes length on x86
uint8_t *totalEndAddr = (uint8_t *)endAddr - patternLen;
for (uint8_t *i = (uint8_t *)startAddr; i <= totalEndAddr; ++i)
{
// check for jmp opcode (x86)
if (i[0] == 0xE9)
{
uint8_t *destAddress = Utils::UnwrapJmp(i);
if (destAddress == reinterpret_cast<uint8_t*>(targetAddress)) {
return i;
}
}
}
return nullptr;
#else
// now this function works only on x86
return nullptr;
#endif
}
uint8_t *Utils::UnwrapJmp(uint8_t *opcodeAddr)
{
int32_t relativeOffset = *(int32_t *)(opcodeAddr + 1);
return reinterpret_cast<uint8_t*>(relativeOffset + opcodeAddr + 5);
}
int Utils::GetStringWidth(const char *str)
{
const SCREENINFO &screenInfo = g_Application.GetScreenInfo();
int totalWidth = 0;
for (char *i = (char *)str; *i; ++i)
totalWidth += screenInfo.charWidths[*i];
return totalWidth;
}
bool Utils::WorldToScreen(int w, int h, int &x, int &y, const vec3_t &origin)
{
vec3_t screenCoords;
if (!g_pClientEngfuncs->pTriAPI->WorldToScreen((float*)&origin.x, &screenCoords.x))
{
x = static_cast<int>((1.0f + screenCoords.x) * w * 0.5f);
y = static_cast<int>((1.0f - screenCoords.y) * h * 0.5f);
return true;
}
return false;
}
void *Utils::FindMemoryPointer(void *startAddr, void *endAddr, void *scanValue)
{
#ifdef APP_SUPPORT_64BIT
typedef uint64_t PointerSize;
#else
typedef uint32_t PointerSize;
#endif
void *valueAddr = nullptr;
void *totalEndAddr = (PointerSize *)endAddr - sizeof(scanValue);
for (PointerSize *i = (PointerSize *)startAddr; i <= totalEndAddr; ++i)
{
if (i[0] == (PointerSize)scanValue)
{
valueAddr = i;
break;
}
}
return valueAddr;
}
cvar_t *Utils::RegisterConVar(const char *name, const char *value, int flags)
{
cvar_t *probe = g_pClientEngfuncs->pfnGetCvarPointer(name);
if (probe)
return probe;
return g_pClientEngfuncs->pfnRegisterVariable(name, value, flags);
}
void Utils::DrawStringStack(int marginRight, int marginUp, const CStringStack &stringStack)
{
int linesSkipped = 0;
int maxStringWidth = 0;
int stringCount = stringStack.GetStringCount();
const int stringHeight = 15;
const SCREENINFO &screenInfo = g_Application.GetScreenInfo();
for (int i = 0; i < stringCount; ++i)
{
const char *textString = stringStack.StringAt(i);
int stringWidth = GetStringWidth(textString);
if (stringWidth > maxStringWidth)
maxStringWidth = stringWidth;
}
for (int i = 0; i < stringCount; ++i)
{
const char *textString = stringStack.StringAt(i);
g_pClientEngfuncs->pfnDrawString(
screenInfo.iWidth - std::max(marginRight, maxStringWidth + 5),
marginUp + (stringHeight * (i + linesSkipped)),
textString,
(int)ConVars::gsm_color_r->value,
(int)ConVars::gsm_color_g->value,
(int)ConVars::gsm_color_b->value
);
int lastCharIndex = strlen(textString) - 1;
if (textString[lastCharIndex] == '\n')
++linesSkipped;
}
}
void Utils::DrawCuboid(const vec3_t &origin, const vec3_t ¢erOffset, const vec3_t &angles, const vec3_t &size, Color color)
{
constexpr bool drawFaces = false;
constexpr bool drawEdges = true;
static std::vector<vec3_t> vertexBuffer;
static std::vector<Color> colorBuffer;
auto renderer = g_Application.GetRenderer();
// initialize buffers
color.Normalize();
vertexBuffer.clear();
colorBuffer.clear();
// assumed that point (0, 0, 0) located in center of bbox
const vec3_t bboxMin = vec3_t(0, 0, 0) - size / 2;
vec3_t boxVertices[8] = {
{bboxMin.x, bboxMin.y, bboxMin.z},
{bboxMin.x + size.x, bboxMin.y, bboxMin.z},
{bboxMin.x + size.x, bboxMin.y, bboxMin.z + size.z},
{bboxMin.x + size.x, bboxMin.y + size.y, bboxMin.z + size.z},
{bboxMin.x + size.x, bboxMin.y + size.y, bboxMin.z},
{bboxMin.x, bboxMin.y + size.y, bboxMin.z},
{bboxMin.x, bboxMin.y + size.y, bboxMin.z + size.z},
{bboxMin.x, bboxMin.y, bboxMin.z + size.z}
};
// transform all vertices
Matrix4x4<vec_t> transformMat = Matrix4x4<vec_t>::CreateTranslate(centerOffset.x, centerOffset.y, centerOffset.z);
if (angles.Length() >= 0.001f) // just little optimization
{
transformMat = Matrix4x4<vec_t>::CreateRotateX(angles[2]) * transformMat; // roll
transformMat = Matrix4x4<vec_t>::CreateRotateY(-angles[0]) * transformMat; // pitch (inverted because of stupid quake bug)
transformMat = Matrix4x4<vec_t>::CreateRotateZ(angles[1]) * transformMat; // yaw
}
transformMat = Matrix4x4<vec_t>::CreateTranslate(origin.x, origin.y, origin.z) * transformMat;
for (int i = 0; i < 8; ++i) {
boxVertices[i] = transformMat.MultiplyVector(boxVertices[i]);
}
renderer->Begin();
if (drawFaces)
{
constexpr int faceIndices[] = {
7, 2, 1, 0, // 1 face
0, 5, 6, 7, // 2 face
5, 4, 3, 6, // 3 face
2, 3, 4, 1, // 4 face
7, 6, 3, 2, // 5 face
1, 4, 5, 0 // 6 face
};
colorBuffer.emplace_back(color.Red(), color.Green(), color.Blue(), 0.3f);
for (size_t i = 0; i < sizeof(faceIndices) / sizeof(faceIndices[0]); ++i) {
vertexBuffer.push_back(boxVertices[faceIndices[i]]);
}
renderer->RenderPrimitives(IPrimitivesRenderer::PrimitiveType::Quads, vertexBuffer, colorBuffer);
vertexBuffer.clear();
colorBuffer.clear();
}
if (drawEdges)
{
constexpr int edgeIndices[] = {
0, 1, 2, 3, 4, 5, 6, 7,
0, 7, 2, 1, 4, 3, 6, 5
};
colorBuffer.emplace_back(color.Red(), color.Green(), color.Blue(), 1.0f);
for (size_t i = 0; i < sizeof(edgeIndices) / sizeof(edgeIndices[0]); ++i) {
vertexBuffer.push_back(boxVertices[edgeIndices[i]]);
}
renderer->ToggleDepthTest(false);
renderer->RenderPrimitives(IPrimitivesRenderer::PrimitiveType::LineLoop, vertexBuffer, colorBuffer);
renderer->ToggleDepthTest(true);
}
renderer->End();
}
int Utils::DrawString3D(const vec3_t &origin, const char *text, int r, int g, int b)
{
int screenX, screenY;
const SCREENINFO &screenInfo = g_Application.GetScreenInfo();
if (Utils::WorldToScreen(screenInfo.iWidth, screenInfo.iHeight, screenX, screenY, origin))
{
// center-align text relative to point on screen
int stringWidth = Utils::GetStringWidth(text);
int textX = screenX - stringWidth * 0.5f;
return g_pClientEngfuncs->pfnDrawString(textX, screenY, text, r, g, b);
}
return 0;
}
void Utils::GetEntityModelName(int entityIndex, std::string &modelName)
{
const int maxClients = g_pClientEngfuncs->GetMaxClients();
if (entityIndex > 0 && entityIndex <= maxClients) // is entity player
{
hud_player_info_t playerInfo;
g_pClientEngfuncs->pfnGetPlayerInfo(entityIndex, &playerInfo);
modelName = "models/player/" + std::string(playerInfo.model) + ".mdl";
}
else
{
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(entityIndex);
modelName = entity->model->name;
}
}
std::string Utils::GetCurrentMapName()
{
std::string mapName = g_pClientEngfuncs->pfnGetLevelName();
mapName.erase(0, mapName.find_last_of("/\\") + 1);
mapName.erase(mapName.find_last_of("."));
return mapName;
}
const char *Utils::GetMovetypeName(int moveType)
{
switch (moveType)
{
case MOVETYPE_BOUNCE: return "Bounce";
case MOVETYPE_BOUNCEMISSILE: return "Bounce-missle";
case MOVETYPE_FLY: return "Fly";
case MOVETYPE_FLYMISSILE: return "Fly-missle";
case MOVETYPE_FOLLOW: return "Follow";
case MOVETYPE_NOCLIP: return "Noclip";
case MOVETYPE_NONE: return "None";
case MOVETYPE_PUSH: return "Push";
case MOVETYPE_PUSHSTEP: return "Push-step";
case MOVETYPE_STEP: return "Step";
case MOVETYPE_TOSS: return "Toss";
case MOVETYPE_WALK: return "Walk";
default: return "Unknown";
}
}
const char *Utils::GetRenderModeName(int renderMode)
{
switch (renderMode)
{
case kRenderNormal: return "Normal";
case kRenderTransColor: return "Trans. color";
case kRenderTransTexture: return "Trans. texture";
case kRenderGlow: return "Glow";
case kRenderTransAlpha: return "Trans. alpha";
case kRenderTransAdd: return "Trans. additive";
default: return "Unknown";
}
}
const char *Utils::GetRenderFxName(int renderFx)
{
switch (renderFx)
{
case kRenderFxNone: return "None";
case kRenderFxPulseSlow: return "Pulse (slow)";
case kRenderFxPulseFast: return "Pulse (fast)";
case kRenderFxPulseSlowWide: return "Pulse (slow wide)";
case kRenderFxPulseFastWide: return "Pulse (fast wide)";
case kRenderFxFadeSlow: return "Fade (slow)";
case kRenderFxFadeFast: return "Fade (fast)";
case kRenderFxSolidSlow: return "Solid (slow)";
case kRenderFxSolidFast: return "Solid (fast)";
case kRenderFxStrobeSlow: return "Strobe (slow)";
case kRenderFxStrobeFast: return "Strobe (fast)";
case kRenderFxStrobeFaster: return "Strobe (faster)";
case kRenderFxFlickerSlow: return "Flicker (slow)";
case kRenderFxFlickerFast: return "Flicker (fast)";
case kRenderFxNoDissipation: return "No dissipation";
case kRenderFxDistort: return "Distort";
case kRenderFxHologram: return "Hologram";
case kRenderFxDeadPlayer: return "Dead player";
case kRenderFxExplode: return "Explode";
case kRenderFxGlowShell: return "Glow shell";
case kRenderFxClampMinScale: return "Clamp min. scale";
case kRenderFxLightMultiplier: return "Light multiplier";
default: return "Unknown";
}
}
bool Utils::IsGameDirEquals(const char *gameDir)
{
const char *gameDirReal = g_pClientEngfuncs->pfnGetGameDirectory();
return strcmp(gameDirReal, gameDir) == 0;
}
void Utils::Snprintf(std::string &result, const char *format, ...)
{
va_list args;
va_start(args, format);
int stringSize = std::vsnprintf(nullptr, 0, format, args);
result.assign(stringSize + 2, '\0');
std::vsnprintf(result.data(), stringSize + 1, format, args);
result.assign(result.data());
va_end(args);
}
void Utils::TraceLine(vec3_t &origin, vec3_t &dir, float lineLen, pmtrace_t *traceData, int ignoredEnt)
{
vec3_t lineStart;
vec3_t lineEnd;
cl_entity_t *localPlayer;
lineStart = origin;
lineEnd = lineStart + (dir * lineLen);
localPlayer = g_pClientEngfuncs->GetLocalPlayer();
if (ignoredEnt < 0)
ignoredEnt = localPlayer->index;
g_pClientEngfuncs->pEventAPI->EV_SetUpPlayerPrediction(false, true);
g_pClientEngfuncs->pEventAPI->EV_PushPMStates();
g_pClientEngfuncs->pEventAPI->EV_SetSolidPlayers(localPlayer->index - 1);
g_pClientEngfuncs->pEventAPI->EV_SetTraceHull(2);
g_pClientEngfuncs->pEventAPI->EV_PlayerTrace(
lineStart, lineEnd, PM_NORMAL,
ignoredEnt, traceData
);
g_pClientEngfuncs->pEventAPI->EV_PopPMStates();
}
float Utils::TraceBBoxLine(const CBoundingBox &bbox, const vec3_t &lineStart, const vec3_t &lineEnd)
{
vec3_t invertedDir;
vec3_t rayDirection;
vec3_t fractionMin;
vec3_t fractionMax;
vec3_t fractionNear;
vec3_t fractionFar;
float nearDotFract;
float farDotFract;
const vec3_t &bboxMaxs = bbox.GetMaxs();
const vec3_t &bboxMins = bbox.GetMins();
// ray equation
// vector O + vector D * t
// O - ray origin
// D - ray direction
// t - fraction
// https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection
const vec3_t &rayOrigin = lineStart;
rayDirection = (lineEnd - lineStart);
const float lineLength = rayDirection.Length();
rayDirection = rayDirection.Normalize();
invertedDir.x = 1.f / rayDirection.x;
invertedDir.y = 1.f / rayDirection.y;
invertedDir.z = 1.f / rayDirection.z;
fractionMin.x = (bboxMins.x - rayOrigin.x) * invertedDir.x;
fractionMin.y = (bboxMins.y - rayOrigin.y) * invertedDir.y;
fractionMax.x = (bboxMaxs.x - rayOrigin.x) * invertedDir.x;
fractionMax.y = (bboxMaxs.y - rayOrigin.y) * invertedDir.y;
fractionNear.x = std::min(fractionMin.x, fractionMax.x);
fractionNear.y = std::min(fractionMin.y, fractionMax.y);
fractionFar.x = std::max(fractionMin.x, fractionMax.x);
fractionFar.y = std::max(fractionMin.y, fractionMax.y);
farDotFract = fractionFar.x;
nearDotFract = fractionNear.x;
// handle case when ray misses the box
if (nearDotFract > fractionFar.y || fractionNear.y > farDotFract)
return 1.f;
if (fractionNear.y > nearDotFract)
nearDotFract = fractionNear.y;
if (fractionFar.y < farDotFract)
farDotFract = fractionFar.y;
fractionMin.z = (bboxMins.z - rayOrigin.z) * invertedDir.z;
fractionMax.z = (bboxMaxs.z - rayOrigin.z) * invertedDir.z;
fractionFar.z = std::max(fractionMin.z, fractionMax.z);
fractionNear.z = std::min(fractionMin.z, fractionMax.z);
// another one
if (nearDotFract > fractionFar.z || fractionNear.z > farDotFract)
return 1.f;
if (fractionNear.z > nearDotFract)
nearDotFract = fractionNear.z;
if (fractionFar.z < farDotFract)
farDotFract = fractionFar.z;
if (nearDotFract < 0.f)
return 1.f;
return nearDotFract / lineLength;
}
vec3_t Utils::GetEntityVelocityApprox(int entityIndex, int approxStep)
{
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(entityIndex);
if (entity)
{
const int currIndex = entity->current_position;
position_history_t &currState = entity->ph[currIndex & HISTORY_MASK];
position_history_t &prevState = entity->ph[(currIndex - approxStep) & HISTORY_MASK];
float timeDelta = currState.animtime - prevState.animtime;
if (fabs(timeDelta) > 0.0f)
{
vec3_t originDelta = currState.origin - prevState.origin;
return originDelta / timeDelta;
}
}
return vec3_t(0, 0, 0);
}
void Utils::GetEntityBoundingBox(int entityIndex, CBoundingBox &bbox)
{
int seqIndex;
vec3_t hullSize;
studiohdr_t *mdlHeader;
mstudioseqdesc_t *seqDesc;
cl_entity_t *entity = g_pClientEngfuncs->GetEntityByIndex(entityIndex);
if (!entity)
{
bbox = CBoundingBox(vec3_t(0, 0, 0));
return;
}
else
{
const vec3_t centerOffset = (entity->curstate.mins + entity->curstate.maxs) / 2.f;
const vec3_t entityOrigin = entity->origin + centerOffset;
if (entity->model && entity->model->type == mod_studio)
{
mdlHeader = (studiohdr_t *)entity->model->cache.data;
seqDesc = (mstudioseqdesc_t *)((char *)mdlHeader + mdlHeader->seqindex);
seqIndex = entity->curstate.sequence;
hullSize = seqDesc[seqIndex].bbmax - seqDesc[seqIndex].bbmin;
}
else {
hullSize = entity->curstate.maxs - entity->curstate.mins;
}
bbox = CBoundingBox(hullSize);
bbox.SetCenterToPoint(entityOrigin);
}
}
float Utils::GetCurrentSysTime()
{
return SysUtils::GetCurrentSysTime();
}
DisplayModeType Utils::GetCurrentDisplayMode()
{
return static_cast<DisplayModeType>(ConVars::gsm_mode->value);
}
| 18,007
|
C++
|
.cpp
| 460
| 32.930435
| 130
| 0.643057
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,820
|
sys_utils.h
|
SNMetamorph_goldsrc-monitor/sources/sys_utils.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include <string>
#include <vector>
#include <stdint.h>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#endif
class ProcessHandle
{
public:
#ifdef _WIN32
ProcessHandle(HANDLE handle);
operator HANDLE() const;
#endif
bool Valid() const;
private:
int64_t m_iHandle = -1;
};
class ModuleHandle
{
public:
#ifdef _WIN32
ModuleHandle(HMODULE handle);
operator HMODULE() const;
#endif
ModuleHandle() {};
bool Valid() const;
private:
int64_t m_iHandle = -1;
};
namespace SysUtils
{
struct ModuleInfo
{
size_t imageSize;
uint8_t *baseAddress;
uint8_t *entryPointAddress;
};
void Sleep(size_t timeMsec);
float GetCurrentSysTime();
void InitCurrentLibraryHandle(ModuleHandle handle);
ModuleHandle GetCurrentLibraryHandle();
ModuleHandle GetCurrentProcessModule();
ProcessHandle GetCurrentProcessHandle();
bool GetModuleDirectory(ModuleHandle moduleHandle, std::string &workingDir);
bool GetModuleFilename(ModuleHandle moduleHandle, std::string &fileName);
bool GetModuleInfo(ProcessHandle procHandle, ModuleHandle moduleHandle, ModuleInfo &moduleInfo);
ModuleHandle FindModuleByExport(ProcessHandle procHandle, const char *exportName);
ModuleHandle FindModuleInProcess(ProcessHandle procHandle, const std::string &moduleName);
void FindProcessIdByName(const char *processName, std::vector<int32_t> &processIds);
void *GetModuleFunction(ModuleHandle moduleHandle, const char *funcName);
}
| 1,946
|
C++
|
.h
| 64
| 28.765625
| 97
| 0.815171
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,821
|
string_stack.h
|
SNMetamorph_goldsrc-monitor/sources/string_stack.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include <stdio.h>
#include <vector>
class CStringStack
{
public:
CStringStack(int stringLen);
void Pop();
void Clear();
void Push(const char *str);
void PushPrintf(const char *format, ...);
inline int GetStringLength() const { return m_stringLen; };
inline int GetStringCount() const { return m_stackIndex; };
inline int GetBufferSize() const { return m_stringBuffer.capacity(); };
const char *StringAt(int index) const;
private:
void AllocString();
int m_stackIndex = 0;
int m_stringLen = 0;
std::vector<char> m_stringBuffer;
};
| 1,138
|
C++
|
.h
| 32
| 32.53125
| 82
| 0.738335
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,822
|
app_info.h
|
SNMetamorph_goldsrc-monitor/sources/app_info.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#define MACRO_TO_STRING2(s) #s
#define MACRO_TO_STRING(s) MACRO_TO_STRING2(s)
#define DEFAULT_LIBRARY_NAME "gsm-library.dll"
#define DEFAULT_PROCESS_NAME "hl.exe";
#define APP_TITLE_STR "GoldSrc Monitor"
#define APP_GITHUB_LINK "https://github.com/SNMetamorph/goldsrc-monitor"
#define APP_BUILD_DATE (__DATE__ " " __TIME__)
#define APP_VERSION_MAJOR 3
#define APP_VERSION_MINOR 0
#define APP_VERSION_STRING MACRO_TO_STRING(APP_VERSION_MAJOR) \
"." MACRO_TO_STRING(APP_VERSION_MINOR) \
"\0"
| 1,147
|
C++
|
.h
| 24
| 43.916667
| 80
| 0.69678
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,823
|
color.h
|
SNMetamorph_goldsrc-monitor/sources/color.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include <stdint.h>
#include <random>
class Color
{
public:
Color()
{
Setup(1.f, 1.f, 1.f, 1.f);
};
Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255)
{
Setup(r, g, b, a);
};
Color(float r, float g, float b, float a = 1.0f)
{
Setup(r, g, b, a);
};
inline void Initialize(uint32_t color)
{
uint8_t r = (color >> 24) & 0xFF;
uint8_t g = (color >> 16) & 0xFF;
uint8_t b = (color >> 8) & 0xFF;
uint8_t a = color & 0xFF;
Setup(r, g, b, a);
}
inline void Initialize(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
{
Setup(r, g, b, a);
}
inline void Normalize()
{
float maxValue = m_Components[0];
for (int i = 0; i < 4; ++i)
{
if (m_Components[i] > maxValue) {
maxValue = m_Components[i];
}
}
m_flRed /= maxValue;
m_flGreen /= maxValue;
m_flBlue /= maxValue;
m_flAlpha /= maxValue;
}
inline Color GetNormalized() const
{
Color result = *this;
result.Normalize();
return result;
}
inline uint32_t GetUint32() const
{
uint8_t r = static_cast<uint8_t>(m_flRed * 255);
uint8_t g = static_cast<uint8_t>(m_flGreen * 255);
uint8_t b = static_cast<uint8_t>(m_flBlue * 255);
uint8_t a = static_cast<uint8_t>(m_flAlpha * 255);
return (r << 24) | (g << 16) | (b << 8) | a;
}
inline float Red() const { return m_flRed; }
inline float Green() const { return m_flGreen; }
inline float Blue() const { return m_flBlue; }
inline float Alpha() const { return m_flAlpha; }
inline void SetRed(float v) { m_flRed = v; }
inline void SetGreen(float v) { m_flGreen = v; }
inline void SetBlue(float v) { m_flBlue = v; }
inline void SetAlpha(float v) { m_flAlpha = v; }
static inline Color GetRandom(int seed, float minBound = 0.2f, float maxBound = 1.f)
{
std::default_random_engine gen;
std::uniform_real_distribution<float> dist(minBound, maxBound);
gen.seed(seed);
return Color(dist(gen), dist(gen), dist(gen));
}
Color& operator=(const Color &operand)
{
m_flRed = operand.Red();
m_flGreen = operand.Green();
m_flBlue = operand.Blue();
m_flAlpha = operand.Alpha();
return *this;
}
private:
inline void Setup(float r, float g, float b, float a)
{
m_flRed = r;
m_flGreen = g;
m_flBlue = b;
m_flAlpha = a;
}
union {
struct {
float m_flRed;
float m_flGreen;
float m_flBlue;
float m_flAlpha;
};
float m_Components[4];
};
};
| 3,343
|
C++
|
.h
| 110
| 23.845455
| 88
| 0.575654
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,824
|
exception.h
|
SNMetamorph_goldsrc-monitor/sources/exception.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include <string>
#include <string_view>
#define EXCEPT(msg) (throw CException((msg), __FUNCTION__, CException::TruncFilePath(__FILE__), __LINE__))
class CException
{
public:
CException(
std::string description,
const char *funcName,
const char *fileName,
int lineNumber
);
const std::string &CException::GetFormattedMessage();
const std::string &GetDescription() const;
const std::string &GetFunctionName() const;
const std::string &GetFileName() const;
int GetLineNumber() const;
static constexpr const char *TruncFilePath(const char *filePath)
{
std::string_view sv = filePath;
return filePath + sv.find_last_of("/\\") + 1;
};
private:
int m_lineNumber;
std::string m_description;
std::string m_funcName;
std::string m_fileName;
std::string m_message;
};
| 1,398
|
C++
|
.h
| 41
| 30.243902
| 106
| 0.725519
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,825
|
utils.h
|
SNMetamorph_goldsrc-monitor/sources/loader/utils.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "sys_utils.h"
#include <string>
#include <stdint.h>
#include <filesystem>
namespace Utils
{
bool FindLibraryAbsolutePath(const std::string &libName, std::filesystem::path &libPath);
size_t GetFunctionOffset(ModuleHandle moduleHandle, const char *funcName);
}
| 803
|
C++
|
.h
| 21
| 36.666667
| 93
| 0.805913
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,826
|
inject_strategy.h
|
SNMetamorph_goldsrc-monitor/sources/loader/inject_strategy.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include <stdint.h>
#include <string>
enum class InjectStatus
{
Success,
Failed,
AlreadyInjected,
};
class IInjectStrategy
{
public:
virtual ~IInjectStrategy() {};
virtual InjectStatus Start(size_t injectDelayMsec,
const std::string &processName, const std::string &libraryName) = 0;
};
| 823
|
C++
|
.h
| 27
| 29
| 70
| 0.80531
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,827
|
win32_inject_strategy.h
|
SNMetamorph_goldsrc-monitor/sources/loader/win32_inject_strategy.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "inject_strategy.h"
#include <memory>
class CWin32InjectStrategy : public IInjectStrategy
{
public:
CWin32InjectStrategy();
~CWin32InjectStrategy() override;
InjectStatus Start(size_t injectDelayMsec,
const std::string &processName, const std::string &libraryName) override;
class Impl;
private:
std::unique_ptr<Impl> m_pImpl;
};
| 875
|
C++
|
.h
| 25
| 33.48
| 75
| 0.811834
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,829
|
application.h
|
SNMetamorph_goldsrc-monitor/sources/loader/application.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "app_info.h"
#include "inject_strategy.h"
#include <stdint.h>
#include <string>
#include <memory>
class CApplication
{
public:
static CApplication &GetInstance();
int Run(int argc, char *argv[]);
private:
CApplication() {};
~CApplication() {};
void ParseParameters(int argc, char *argv[]);
void StartMainLoop();
void ReportError(const std::string &msg);
void PrintTitleText();
void InitInjectStrategy();
size_t m_injectDelay = 3000;
std::unique_ptr<IInjectStrategy> m_injectStrategy;
std::string m_processName = DEFAULT_PROCESS_NAME;
std::string m_libraryName = DEFAULT_LIBRARY_NAME;
};
| 1,178
|
C++
|
.h
| 35
| 30.971429
| 68
| 0.759683
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,830
|
build_info.h
|
SNMetamorph_goldsrc-monitor/sources/library/build_info.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "sys_utils.h"
#include <memory>
#include <string>
class CBuildInfo
{
public:
class Entry;
enum class FunctionType
{
// client-side
SPR_Load,
SPR_Frames,
// server-side
PrecacheModel,
PrecacheSound,
Count, // keep this last
};
static const size_t k_functionsCount = static_cast<size_t>(FunctionType::Count);
CBuildInfo();
~CBuildInfo();
void Initialize(const SysUtils::ModuleInfo &engineModule);
void *FindFunctionAddress(FunctionType funcType, void *startAddr, void *endAddr = nullptr) const;
const std::string &GetInitErrorDescription() const;
const Entry *GetInfoEntry() const;
private:
class Impl;
std::unique_ptr<Impl> m_pImpl;
};
| 1,281
|
C++
|
.h
| 40
| 28.175
| 101
| 0.736032
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,831
|
primitives_renderer.h
|
SNMetamorph_goldsrc-monitor/sources/library/primitives_renderer.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
#include "color.h"
#include <vector>
class IPrimitivesRenderer
{
public:
enum class PrimitiveType {
Quads,
LineLoop
};
virtual void Begin() = 0;
virtual void End() = 0;
virtual void ToggleDepthTest(bool state) = 0;
virtual void RenderPrimitives(PrimitiveType type,
const std::vector<vec3_t> &verticesBuffer,
const std::vector<Color> &colorBuffer) = 0;
};
| 918
|
C++
|
.h
| 29
| 29.931034
| 68
| 0.789593
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,832
|
bounding_box.h
|
SNMetamorph_goldsrc-monitor/sources/library/bounding_box.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
class CBoundingBox
{
public:
CBoundingBox() {};
CBoundingBox(const vec3_t &size);
CBoundingBox(const vec3_t &vecMins, const vec3_t &vecMaxs);
double GetSurfaceArea() const;
vec3_t GetCenterPoint() const;
void SetCenterToPoint(const vec3_t &point);
CBoundingBox GetUnion(const CBoundingBox &operand) const;
void CombineWith(const CBoundingBox &operand);
void ExpandToPoint(const vec3_t &point);
bool Contains(const CBoundingBox &operand) const;
bool ContainsPoint(const vec3_t &point) const;
const vec3_t &GetSize() const { return m_size; };
const vec3_t &GetMins() const { return m_mins; };
const vec3_t &GetMaxs() const { return m_maxs; };
private:
void Initialize(const vec3_t &vecMins, const vec3_t &vecMaxs);
vec3_t m_mins = vec3_t(0, 0, 0);
vec3_t m_maxs = vec3_t(0, 0, 0);
vec3_t m_size = vec3_t(0, 0, 0);
};
| 1,437
|
C++
|
.h
| 36
| 36.694444
| 68
| 0.737976
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,833
|
hooks.h
|
SNMetamorph_goldsrc-monitor/sources/library/hooks.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "client_module.h"
#include <memory>
class CHooks
{
public:
class Impl;
class Logger;
CHooks(const CClientModule &moduleRef);
~CHooks();
void Apply();
void Remove();
private:
const CClientModule &m_clientModule;
std::unique_ptr<Impl> m_pImpl;
};
| 815
|
C++
|
.h
| 27
| 27.777778
| 68
| 0.774936
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,834
|
memory_pattern.h
|
SNMetamorph_goldsrc-monitor/sources/library/memory_pattern.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include <stdint.h>
#include <vector>
#include <string>
class CMemoryPattern
{
public:
CMemoryPattern() {};
CMemoryPattern(const std::string &pattern);
CMemoryPattern(const char *pattern, int byteCount, uint8_t wildmark = 0xCC);
void AddByte(uint8_t value, bool shouldCheck = true);
void InitFromBytes(uint8_t *pattern, int byteCount, uint8_t wildmark = 0xCC);
void InitFromString(const std::string &pattern);
bool IsInitialized() const;
int GetLength() const { return m_signature.size(); };
uint8_t GetByteAt(int offset) const { return m_signature[offset]; };
bool ShouldCheckByteAt(int offset) const { return m_mask[offset]; };
// To provide an optimal way to finding pattern address
const int *GetMaskAddress() const { return m_mask.data(); };
const uint8_t *GetSignatureAddress() const { return m_signature.data(); };
private:
void ReserveElements(size_t elemCount);
void Reset();
std::vector<int> m_mask;
std::vector<uint8_t> m_signature;
};
| 1,549
|
C++
|
.h
| 37
| 38.72973
| 81
| 0.750167
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,835
|
displaymode_angletracking.h
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_angletracking.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "display_mode.h"
#include "local_player.h"
#include "hlsdk.h"
class CModeAngleTracking : public IDisplayMode
{
public:
CModeAngleTracking(const CLocalPlayer &playerRef);
virtual ~CModeAngleTracking() {};
void Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText) override;
void Render3D() override {};
bool KeyInput(bool, int, const char *) override { return true; };
void HandleChangelevel() override {};
DisplayModeType GetModeIndex() override { return DisplayModeType::AngleTracking; };
private:
vec3_t m_lastAngles;
float m_trackStartTime;
float m_lastYawVelocity;
float m_lastPitchVelocity;
const CLocalPlayer &m_localPlayer;
};
| 1,249
|
C++
|
.h
| 32
| 36.28125
| 99
| 0.779521
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,836
|
utils.h
|
SNMetamorph_goldsrc-monitor/sources/library/utils.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "string_stack.h"
#include "memory_pattern.h"
#include "bounding_box.h"
#include "display_mode.h"
#include "color.h"
#include "stdafx.h"
#include <stdint.h>
#include <string>
namespace Utils
{
inline bool IsSymbolAlpha(char symbol) { return (symbol >= 'A' && symbol <= 'Z') || (symbol >= 'a' && symbol <= 'z'); };
inline bool IsSymbolDigit(char symbol) { return (symbol >= '0' && symbol <= '9'); };
inline bool IsSymbolSpace(char symbol) { return (symbol == ' '); };
void *FindMemoryPointer(void *startAddr, void *endAddr, void *scanValue);
void *FindPatternAddress(void *startAddr, void *endAddr, const CMemoryPattern &pattern);
void *FindJmpFromAddress(void *startAddr, void *endAddr, void *targetAddress);
uint8_t *UnwrapJmp(uint8_t *opcodeAddr);
float GetCurrentSysTime();
DisplayModeType GetCurrentDisplayMode();
cvar_t *RegisterConVar(const char *name, const char *value, int flags);
int GetStringWidth(const char *str);
bool WorldToScreen(int w, int h, int &x, int &y, const vec3_t &origin);
void DrawStringStack(int marginRight, int marginUp, const CStringStack &stringStack);
void DrawCuboid(const vec3_t &origin, const vec3_t ¢erOffset, const vec3_t &angles, const vec3_t &size, Color color);
int DrawString3D(const vec3_t &origin, const char *text, int r, int g, int b);
void GetEntityModelName(int entityIndex, std::string &modelName);
std::string GetCurrentMapName();
const char *GetMovetypeName(int moveType);
const char *GetRenderModeName(int renderMode);
const char *GetRenderFxName(int renderFx);
bool IsGameDirEquals(const char *gameDir);
void Snprintf(std::string &result, const char *format, ...);
vec3_t GetEntityVelocityApprox(int entityIndex, int approxStep = 22);
void GetEntityBoundingBox(int entityIndex, CBoundingBox &bbox);
void TraceLine(vec3_t &origin, vec3_t &dir, float lineLen, pmtrace_t *traceData, int ignoredEnt = -1);
float TraceBBoxLine(const CBoundingBox &bbox, const vec3_t &lineStart, const vec3_t &lineEnd);
};
| 2,600
|
C++
|
.h
| 49
| 49.77551
| 125
| 0.743217
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,837
|
entity_dictionary.h
|
SNMetamorph_goldsrc-monitor/sources/library/entity_dictionary.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "entity_description.h"
#include "bvh_tree.h"
#include "hlsdk.h"
#include <vector>
#include <map>
class CEntityDictionary
{
public:
CEntityDictionary();
void Reset();
void Initialize();
void VisualizeTree(bool textRendering);
void VisualizeDescriptions() const;
bool FindDescription(int entityIndex, CEntityDescription &destDescription, int &iterCount);
int GetDescriptionsCount() const { return m_entityDescList.size(); }
bool IsInitialized() const { return m_entityDescList.size() > 0; }
private:
void AssociateDescription(int entityIndex, int descIndex);
void BuildDescriptionsTree();
void ParseEntityData();
std::map<int, int> m_associations;
std::vector<CEntityDescription> m_entityDescList;
CBVHTree m_entityDescTree;
};
| 1,327
|
C++
|
.h
| 36
| 33.972222
| 95
| 0.778733
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,838
|
cvars.h
|
SNMetamorph_goldsrc-monitor/sources/library/cvars.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
class ConVars
{
public:
static cvar_t *gsm_color_r;
static cvar_t *gsm_color_g;
static cvar_t *gsm_color_b;
static cvar_t *gsm_margin_up;
static cvar_t *gsm_margin_right;
static cvar_t *gsm_mode;
static cvar_t *gsm_debug;
static cvar_t *gsm_thirdperson;
static cvar_t *gsm_thirdperson_dist;
static cvar_t *sys_timescale;
};
| 910
|
C++
|
.h
| 27
| 31.074074
| 68
| 0.76223
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,839
|
engine_types.h
|
SNMetamorph_goldsrc-monitor/sources/library/engine_types.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
/*
* For structures mnode_t, mleaf_t, msurface_t, texture_t there is two
* incompatible versions: for software and hardware renderers.
* In this header presented only hardware renderer structures (they also present in Xash3D)
* By default in HLSDK presented only software renderer structures.
* To prevent collision with HLSDK these structures located in separate "Engine" namespace.
*/
namespace Engine
{
struct mnode_t
{
// common with leaf
int contents; // 0, to differentiate from leafs
int visframe; // node needs to be traversed if current
float minmaxs[6]; // for bounding box culling. HW.
mnode_t *parent;
// node specific
mplane_t *plane;
mnode_t *children[2];
unsigned short firstsurface;
unsigned short numsurfaces;
};
struct mleaf_t
{
// common with node
int contents; // wil be a negative contents number
int visframe; // node needs to be traversed if current
float minmaxs[6]; // for bounding box culling HW
mnode_t *parent;
// leaf specific
byte *compressed_vis;
struct efrag_s *efrags;
msurface_t **firstmarksurface;
int nummarksurfaces;
int key; // BSP sequence number for leaf's contents
byte ambient_sound_level[NUM_AMBIENTS];
};
struct msurface_t
{
int visframe; // should be drawn when node is crossed
mplane_t *plane;
int flags;
int firstedge; // look up in model->surfedges[], negative numbers
int numedges; // are backwards edges
short texturemins[2];
short extents[2];
int light_s, light_t; // gl lightmap coordinates
struct glpoly_t *polys; // multiple if warped
struct msurface_t *texturechain;
mtexinfo_t *texinfo;
// lighting info
int dlightframe;
int dlightbits;
int lightmaptexturenum;
byte styles[MAXLIGHTMAPS];
int cached_light[MAXLIGHTMAPS]; // values currently used in lightmap
qboolean cached_dlight; // true if dynamic light in cache
// byte *samples; // [numstyles*surfsize]
color24 *samples; // note: this is the actual lightmap data for this surface
decal_t *pdecals;
};
struct texture_t
{
char name[16];
unsigned width, height;
int gl_texturenum;
struct msurface_s *texturechain; // for gl_texsort drawing
int anim_total; // total tenths in sequence ( 0 = no)
int anim_min, anim_max; // time for this frame min <=time< max
struct texture_s *anim_next; // in the animation sequence
struct texture_s *alternate_anims; // bmodels in frmae 1 use these
unsigned offsets[MIPLEVELS]; // four mip maps stored
};
inline Engine::mnode_t *CastType(::mnode_t *origType) { return reinterpret_cast<Engine::mnode_t *>(origType); }
inline Engine::mleaf_t *CastType(::mleaf_t *origType) { return reinterpret_cast<Engine::mleaf_t *>(origType); }
inline Engine::msurface_t *CastType(::msurface_t *origType) { return reinterpret_cast<Engine::msurface_t *>(origType); }
inline Engine::texture_t *CastType(::texture_t *origType) { return reinterpret_cast<Engine::texture_t *>(origType); }
};
| 3,823
|
C++
|
.h
| 91
| 39.505495
| 121
| 0.684976
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,840
|
displaymode_speedometer.h
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_speedometer.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "display_mode.h"
#include "local_player.h"
#include "hlsdk.h"
class CModeSpeedometer : public IDisplayMode
{
public:
CModeSpeedometer(const CLocalPlayer &playerRef);
virtual ~CModeSpeedometer() {};
void Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText) override;
void Render3D() override {};
bool KeyInput(bool, int, const char *) override { return true; };
void HandleChangelevel() override {};
DisplayModeType GetModeIndex() override { return DisplayModeType::Speedometer; };
private:
void CalculateVelocity(float frameTime);
float GetEntityVelocityApprox(int entityIndex) const;
void DrawVelocityBar(int scrWidth, int scrHeight, float velocity) const;
float m_velocity;
float m_lastUpdateTime;
const CLocalPlayer &m_localPlayer;
};
| 1,358
|
C++
|
.h
| 33
| 38.333333
| 99
| 0.783005
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,841
|
build_info_entry.h
|
SNMetamorph_goldsrc-monitor/sources/library/build_info_entry.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "build_info.h"
#include "memory_pattern.h"
#include <string>
#include <stdint.h>
class CBuildInfo::Entry
{
public:
Entry() {};
bool Validate() const;
uint32_t GetBuildNumber() const { return m_buildNumber; }
void SetBuildNumber(uint32_t value) { m_buildNumber = value; }
bool HasClientEngfuncsOffset() const { return m_clientEngfuncsOffset != 0; }
bool HasServerEngfuncsOffset() const { return m_serverEngfuncsOffset != 0; }
uint64_t GetClientEngfuncsOffset() const { return m_clientEngfuncsOffset; }
uint64_t GetServerEngfuncsOffset() const { return m_serverEngfuncsOffset; }
void SetClientEngfuncsOffset(uint64_t offset) { m_clientEngfuncsOffset = offset; }
void SetServerEngfuncsOffset(uint64_t offset) { m_serverEngfuncsOffset = offset; }
const std::string &GetGameProcessName() const { return m_gameProcessName; }
void SetGameProcessName(const char *value) { m_gameProcessName.assign(value); }
void SetFunctionPattern(CBuildInfo::FunctionType type, CMemoryPattern pattern) {
m_functionPatterns[static_cast<size_t>(type)] = pattern;
}
const CMemoryPattern &GetFunctionPattern(CBuildInfo::FunctionType type) const {
return m_functionPatterns[static_cast<size_t>(type)];
}
bool operator<(const Entry &operand) const {
return m_buildNumber < operand.GetBuildNumber();
}
private:
uint32_t m_buildNumber = 0;
std::string m_gameProcessName;
uint64_t m_clientEngfuncsOffset = 0x0;
uint64_t m_serverEngfuncsOffset = 0x0;
CMemoryPattern m_functionPatterns[CBuildInfo::k_functionsCount];
};
| 2,145
|
C++
|
.h
| 47
| 41.914894
| 86
| 0.760057
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,842
|
hooks_logger.h
|
SNMetamorph_goldsrc-monitor/sources/library/hooks_logger.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hooks.h"
#include <polyhook2/Enums.hpp>
#include <polyhook2/ErrorLog.hpp>
#include <string>
class CHooks::Logger : public PLH::Logger
{
public:
~Logger() override;
void log(const std::string &msg, PLH::ErrorLevel level) override;
void setLogLevel(PLH::ErrorLevel level);
private:
std::string m_outputText;
PLH::ErrorLevel m_errorLevel = PLH::ErrorLevel::NONE;
};
| 907
|
C++
|
.h
| 26
| 33.461538
| 68
| 0.796804
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,843
|
local_player.h
|
SNMetamorph_goldsrc-monitor/sources/library/local_player.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "cvars.h"
#include "hlsdk.h"
enum class SpectatingMode
{
None,
ChaseLocked,
ChaseFree,
Roaming, // Free Look
InEye, // First Person
MapFree, // Free Map Overview
MapChase, // Chase Map Overview
};
class CLocalPlayer
{
public:
CLocalPlayer() {};
~CLocalPlayer() = default;
void UpdatePlayerMove(playermove_t *pmove);
bool PredictionDataValid() const;
vec3_t GetOrigin() const;
vec3_t GetAngles() const;
vec3_t GetPunchAngles() const;
vec3_t GetVelocity() const;
vec3_t GetBaseVelocity() const;
vec3_t GetViewOffset() const;
vec3_t GetViewOrigin() const;
vec3_t GetViewDirection() const;
float GetMaxSpeed() const;
float GetClientMaxSpeed() const;
float GetGravity() const;
float GetFriction() const;
float GetDuckTime() const;
bool IsDucking() const;
bool OnGround() const;
int GetMovetype() const;
int GetFlags() const;
int GetHullType() const;
const physent_t *GetPhysents() const;
const physent_t *GetVisents() const;
const physent_t *GetMoveents() const;
int GetPhysentsCount() const;
int GetVisentsCount() const;
int GetMoveentsCount() const;
int GetIntUserVar(size_t index) const;
float GetFloatUserVar(size_t index) const;
bool IsSpectate() const;
SpectatingMode GetSpectatingMode() const;
int GetSpectateTargetIndex() const;
bool IsThirdPersonForced() const;
float GetThirdPersonCameraDist() const;
private:
playermove_t *m_pPlayerMove = nullptr;
};
| 2,086
|
C++
|
.h
| 65
| 28.261538
| 68
| 0.732338
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,844
|
bvh_tree_node.h
|
SNMetamorph_goldsrc-monitor/sources/library/bvh_tree_node.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "bounding_box.h"
class CBVHTreeNode
{
public:
CBVHTreeNode();
CBVHTreeNode(int index, const CBoundingBox &box);
CBVHTreeNode(int index, const CBoundingBox &box, CBVHTreeNode &parent);
void SetParent(int index) { m_parentNode = index; };
void SetLeftChild(int index) { m_leftChildNode = index; };
void SetRightChild(int index) { m_rightChildNode = index; };
void SetBoundingBox(const CBoundingBox &box) { m_boundingBox = box; };
void SetDescriptionIndex(int value) { m_descriptionIndex = value; };
int GetIndex() const { return m_index; };
int GetParent() const { return m_parentNode; }
int GetLeftChild() const { return m_leftChildNode; };
int GetRightChild() const { return m_rightChildNode; };
int GetDescriptionIndex() const { return m_descriptionIndex; }
const CBoundingBox &GetBoundingBox() const { return m_boundingBox; };
const vec3_t &GetSize() const { return m_boundingBox.GetSize(); };
bool IsLeaf() const { return m_leftChildNode < 0 && m_rightChildNode < 0; };
private:
int m_index = 0;
int m_parentNode = -1;
int m_leftChildNode = -1;
int m_rightChildNode = -1;
int m_descriptionIndex = -1;
CBoundingBox m_boundingBox;
};
| 2,012
|
C++
|
.h
| 40
| 46.975
| 109
| 0.641586
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,845
|
displaymode_measurement.h
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_measurement.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "stdafx.h"
#include "display_mode.h"
#include "local_player.h"
class CModeMeasurement : public IDisplayMode
{
public:
enum class SnapMode
{
Free,
AxisX,
AxisY,
AxisZ,
AlongLine,
Count,
};
public:
CModeMeasurement(const CLocalPlayer &playerRef);
virtual ~CModeMeasurement() {};
void Render2D(float frameTime, int screenWidth, int screenHeight, CStringStack &screenText) override;
void Render3D() override {};
bool KeyInput(bool keyDown, int keyCode, const char *) override;
void HandleChangelevel() override;
DisplayModeType GetModeIndex() override { return DisplayModeType::Measurement; };
private:
const vec3_t &GetPointOriginA() const;
const vec3_t &GetPointOriginB() const;
const char *GetSnapModeName() const;
float GetPointsDistance() const;
float GetLineElevationAngle() const;
void UpdatePointOrigin(vec3_t &linePoint, const vec3_t &targetPoint);
void TraceAlongNormal(pmtrace_t &traceData, float traceLength);
void DrawVisualization(float frameTime, int screenWidth, int screenHeight);
void DrawMeasurementLine(float lifeTime);
void PrintPointHints(int screenWidth, int screenHeight);
void PrintLineLength(int screenWidth, int screenHeight, vec3_t pointStart, vec3_t pointEnd);
void DrawSupportLines(float lifeTime);
void DrawLineProjections(int screenWidth, int screenHeight, float lifeTime);
void LoadLineSprite();
vec3_t m_pointA;
vec3_t m_pointB;
HLSPRITE m_lineSprite;
SnapMode m_snapMode;
const CLocalPlayer &m_localPlayer;
};
| 2,166
|
C++
|
.h
| 56
| 34.589286
| 105
| 0.751547
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,846
|
hlsdk.h
|
SNMetamorph_goldsrc-monitor/sources/library/hlsdk.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
// HLSDK
#include <wrect.h>
#include <cl_dll.h>
#include <in_defs.h>
#include <cdll_int.h>
#include <cl_entity.h>
#include <com_model.h>
#include <cvardef.h>
#include <entity_state.h>
#include <entity_types.h>
#include <event_args.h>
#include <net_api.h>
#include <r_studioint.h>
#include <pm_defs.h>
#include <r_efx.h>
#include <com_model.h>
#include <ref_params.h>
#include <studio_event.h>
#include <event_api.h>
#include <screenfade.h>
#include <demo_api.h>
#include <triangleapi.h>
#include <ivoicetweak.h>
#include <con_nprint.h>
#undef ARRAYSIZE
#include <eiface.h>
| 1,101
|
C++
|
.h
| 38
| 27.842105
| 68
| 0.776204
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,847
|
engine_module.h
|
SNMetamorph_goldsrc-monitor/sources/library/engine_module.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "sys_utils.h"
#include <stdint.h>
class CEngineModule
{
public:
bool FindHandle();
bool GetFunctionsFromAPI(uint8_t **pfnSPR_Load, uint8_t **pfnSPR_Frames) const;
bool IsXashEngine() const { return m_isXashEngine; }
bool IsSoftwareRenderer() const { return m_isSoftwareRenderer; };
ModuleHandle GetHandle() const { return m_moduleHandle; };
uint8_t* GetAddress() const { return m_moduleInfo.baseAddress; };
size_t GetSize() const { return m_moduleInfo.imageSize; }
private:
bool SetupModuleInfo();
ModuleHandle m_moduleHandle = NULL;
SysUtils::ModuleInfo m_moduleInfo;
bool m_isXashEngine = false;
bool m_isSoftwareRenderer = false;
};
| 1,248
|
C++
|
.h
| 31
| 37.483871
| 83
| 0.752271
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,848
|
entity_description.h
|
SNMetamorph_goldsrc-monitor/sources/library/entity_description.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
#include "bounding_box.h"
#include <string>
#include <map>
class CEntityDescription
{
public:
CEntityDescription();
void AddKeyValue(const std::string &key, const std::string &value);
void Initialize();
void GetPropertyString(int index, std::string &buffer) const;
void AssociateEntity(int entityIndex);
int GetPropertiesCount() const { return m_EntityProps.size(); }
int GetAssocEntityIndex() const { return m_iAssociatedEntity; }
const std::string& GetClassname() const { return m_szClassname; }
const std::string& GetTargetname() const { return m_szTargetname; }
const std::string& GetModelName() const { return m_szModelName; }
const vec3_t &GetOrigin() const { return m_vecOrigin; }
const vec3_t &GetAngles() const { return m_vecAngles; }
const CBoundingBox &GetBoundingBox() const { return m_boundingBox; }
private:
void Reset();
void EstimateBoundingBox();
void ParseEntityData();
model_t *FindModelByName(const char *name);
std::string m_szClassname;
std::string m_szTargetname;
std::string m_szModelName;
vec3_t m_vecAngles;
vec3_t m_vecOrigin;
int m_iAssociatedEntity;
CBoundingBox m_boundingBox;
std::map<std::string, std::string> m_EntityProps;
};
| 1,811
|
C++
|
.h
| 46
| 36.043478
| 72
| 0.748578
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,849
|
hooks_impl.h
|
SNMetamorph_goldsrc-monitor/sources/library/hooks_impl.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hooks.h"
#include "hlsdk.h"
#include "function_hook.h"
class CHooks::Impl
{
public:
typedef int(__cdecl *pfnRedraw_t)(float, int);
typedef void(__cdecl *pfnPlayerMove_t)(playermove_t *, int);
typedef int(__cdecl *pfnKeyEvent_t)(int, int, const char *);
typedef void(__cdecl *pfnDrawTriangles_t)();
typedef int(__cdecl *pfnIsThirdPerson_t)();
typedef void(__cdecl *pfnCameraOffset_t)(float *);
typedef int(__cdecl *pfnVidInit_t)();
void InitializeLogger();
void RevertHooks();
std::shared_ptr<CHooks::Logger> m_pLogger;
static CFunctionHook<pfnRedraw_t> m_hookRedraw;
static CFunctionHook<pfnPlayerMove_t> m_hookPlayerMove;
static CFunctionHook<pfnKeyEvent_t> m_hookKeyEvent;
static CFunctionHook<pfnDrawTriangles_t> m_hookDrawTriangles;
static CFunctionHook<pfnIsThirdPerson_t> m_hookIsThirdPerson;
static CFunctionHook<pfnCameraOffset_t> m_hookCameraOffset;
static CFunctionHook<pfnVidInit_t> m_hookVidInit;
};
| 1,489
|
C++
|
.h
| 36
| 39.138889
| 68
| 0.782999
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,850
|
opengl_primitives_renderer.h
|
SNMetamorph_goldsrc-monitor/sources/library/opengl_primitives_renderer.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "primitives_renderer.h"
#include <stdint.h>
class COpenGLPrimitivesRenderer : public IPrimitivesRenderer
{
public:
virtual void Begin() override;
virtual void End() override;
virtual void ToggleDepthTest(bool state) override;
virtual void RenderPrimitives(PrimitiveType type,
const std::vector<vec3_t>& verticesBuffer,
const std::vector<Color>& colorBuffer) override;
private:
uint32_t GetGlPrimitiveEnum(PrimitiveType pt) const;
};
| 981
|
C++
|
.h
| 26
| 36.115385
| 68
| 0.815789
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,851
|
matrix.h
|
SNMetamorph_goldsrc-monitor/sources/library/matrix.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
#include <assert.h>
template<class T> class Matrix4x4
{
public:
Matrix4x4() {};
void Assign(Matrix4x4 &src)
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
m_Elements[i][j] = src[i][j];
}
}
Matrix4x4 Add(Matrix4x4 &operand) const
{
Matrix4x4 result;
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
result[i][j] = m_Elements[i][j] + operand[i][j];
}
return result;
}
Matrix4x4 Sub(Matrix4x4 &operand) const
{
Matrix4x4 result;
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
result[i][j] = m_Elements[i][j] - operand[i][j];
}
return result;
}
Matrix4x4 Multiply(Matrix4x4 &operand) const
{
Matrix4x4 result;
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
for (int k = 0; k < 4; ++k)
result[i][j] += m_Elements[i][k] * operand[k][j];
}
}
return result;
}
Matrix4x4 Product(T x) const
{
Matrix4x4 result;
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
result[i][j] *= x;
}
return result;
}
Matrix4x4 Power(int power) const
{
assert(power > 1);
Matrix4x4 thisMatrix = *this;
Matrix4x4 result = thisMatrix;
for (int i = 1; i < power; ++i) {
result.Assign(result.Multiply(thisMatrix));
}
return result;
}
static Matrix4x4 CreateIdentity()
{
Matrix4x4 result;
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
if (i == j)
result[i][j] = 1;
else
result[i][j] = 0;
}
}
return result;
}
static Matrix4x4 CreateTranslate(float x, float y, float z)
{
Matrix4x4 result = CreateIdentity();
result[0][3] = x;
result[1][3] = y;
result[2][3] = z;
return result;
}
static Matrix4x4 CreateRotateX(float angle)
{
Matrix4x4 result = CreateIdentity();
const float pi = 3.141592f;
const float radAngle = angle * (pi * 2 / 360);
result[1][1] = cosf(radAngle);
result[2][1] = sinf(radAngle);
result[1][2] = -sinf(radAngle);
result[2][2] = cosf(radAngle);
return result;
}
static Matrix4x4 CreateRotateY(float angle)
{
Matrix4x4 result = CreateIdentity();
const float pi = 3.141592f;
const float radAngle = angle * (pi * 2 / 360);
result[0][0] = cosf(radAngle);
result[0][2] = sinf(radAngle);
result[2][0] = -sinf(radAngle);
result[2][2] = cosf(radAngle);
return result;
}
static Matrix4x4 CreateRotateZ(float angle)
{
Matrix4x4 result = CreateIdentity();
const float pi = 3.141592f;
const float radAngle = angle * (pi * 2 / 360);
result[0][0] = cosf(radAngle);
result[0][1] = -sinf(radAngle);
result[1][0] = sinf(radAngle);
result[1][1] = cosf(radAngle);
return result;
}
// HLSDK stuff
vec3_t MultiplyVector(const vec3_t &operand, float w = 1.f)
{
Matrix4x4 &mat = *this;
return vec3_t(
mat[0][0] * operand[0] + mat[0][1] * operand[1] + mat[0][2] * operand[2] + mat[0][3] * w,
mat[1][0] * operand[0] + mat[1][1] * operand[1] + mat[1][2] * operand[2] + mat[1][3] * w,
mat[2][0] * operand[0] + mat[2][1] * operand[1] + mat[2][2] * operand[2] + mat[2][3] * w
);
}
// operators
Matrix4x4 operator+(Matrix4x4 &operand) const { return Add(operand); }
Matrix4x4 operator-(Matrix4x4 &operand) const { return Sub(operand); }
Matrix4x4 operator*(Matrix4x4 &operand) const { return Multiply(operand); }
Matrix4x4 operator*(const T &operand) const { return Product(operand); }
T *operator[](const int index) { return m_Elements[index]; }
void operator=(Matrix4x4 &operand) { Assign(operand); }
private:
T m_Elements[4][4] = { 0 };
};
| 4,884
|
C++
|
.h
| 155
| 23.606452
| 101
| 0.534706
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,852
|
displaymode_full.h
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_full.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "display_mode.h"
#include "local_player.h"
class CModeFull : public IDisplayMode
{
public:
CModeFull(const CLocalPlayer &playerRef);
virtual ~CModeFull() {};
void Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText) override;
void Render3D() override {};
bool KeyInput(bool, int, const char *) override { return true; };
void HandleChangelevel() override {};
DisplayModeType GetModeIndex() override { return DisplayModeType::Full; };
private:
float GetSmoothSystemFrametime();
float m_frameTime;
float m_lastFrameTime;
float m_lastSysTime;
const CLocalPlayer &m_localPlayer;
};
| 1,194
|
C++
|
.h
| 31
| 35.709677
| 99
| 0.774221
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,853
|
bvh_tree.h
|
SNMetamorph_goldsrc-monitor/sources/library/bvh_tree.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "bounding_box.h"
#include "bvh_tree_node.h"
#include "entity_description.h"
#include <vector>
#include <stack>
#include <string>
class CBVHTree
{
public:
CBVHTree(const std::vector<CEntityDescription> &descList);
void Reset();
void Build();
double ComputeCost() const;
bool FindLeaf(const CBoundingBox &box, int &nodeIndex, int &iterCount);
void Visualize(bool textRendering);
const CBVHTreeNode &GetNode(int index) const { return m_nodes[index]; }
private:
typedef std::vector<int> ObjectList;
CBVHTreeNode &NodeAt(int index) { return m_nodes[index]; }
void PrintReport();
void BuildTopDown();
void BuildBottomUp();
void MergeLevelNodes(const std::vector<int> &inputNodes, std::vector<int> &outputNodes);
void SplitNode(CBVHTreeNode &node, ObjectList nodeObjects);
int AppendNode(const CBoundingBox &nodeBounds, int parent = -1);
CBoundingBox CalcNodeBoundingBox(ObjectList, float epsilon = 0.001f);
std::string GetGraphvisDescription() const;
std::vector<int> GetGameObjects();
int m_rootNodeIndex = -1;
std::stack<int> m_nodesStack;
std::stack<ObjectList> m_objectListStack;
std::vector<CBVHTreeNode> m_nodes;
const std::vector<CEntityDescription> &m_descList;
};
| 1,833
|
C++
|
.h
| 46
| 36.695652
| 92
| 0.74382
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,854
|
server_module.h
|
SNMetamorph_goldsrc-monitor/sources/library/server_module.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
#include "sys_utils.h"
#include "build_info.h"
#include "engine_module.h"
#include <stdint.h>
class CServerModule
{
public:
CServerModule(const CEngineModule &moduleRef);
bool FindHandle();
bool FindEngfuncs(const CBuildInfo &buildInfo);
uint8_t *GetFuncAddress(const char *funcName);
ModuleHandle GetHandle() const { return m_module; }
uint8_t *GetBaseAddress() const { return m_moduleInfo.baseAddress; }
uint8_t *GetEntryPoint() const { return m_moduleInfo.entryPointAddress; }
size_t GetSize() const { return m_moduleInfo.imageSize; }
bool IsInitialized() const { return m_module != NULL; }
private:
ModuleHandle m_module = NULL;
SysUtils::ModuleInfo m_moduleInfo;
const CEngineModule &m_engineModule;
};
extern enginefuncs_t *g_pServerEngfuncs;
| 1,368
|
C++
|
.h
| 35
| 36.485714
| 79
| 0.760935
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,855
|
client_module.h
|
SNMetamorph_goldsrc-monitor/sources/library/client_module.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "hlsdk.h"
#include "sys_utils.h"
#include "build_info.h"
#include "engine_module.h"
#include <stdint.h>
class CClientModule
{
public:
CClientModule(const CEngineModule &moduleRef);
bool FindHandle();
bool FindEngfuncs(const CBuildInfo &buildInfo);
uint8_t *GetFuncAddress(const char *funcName) const;
ModuleHandle GetHandle() const { return m_moduleHandle; }
uint8_t *GetBaseAddress() const { return m_moduleInfo.baseAddress; }
uint8_t *GetEntryPoint() const { return m_moduleInfo.entryPointAddress; }
size_t GetSize() const { return m_moduleInfo.imageSize; }
private:
cl_enginefunc_t* SearchEngfuncsTable(uint8_t *pfnSPR_Load, uint8_t *pfnSPR_Frames);
ModuleHandle m_moduleHandle = NULL;
SysUtils::ModuleInfo m_moduleInfo;
const CEngineModule &m_engineModule;
};
extern cl_enginefunc_t *g_pClientEngfuncs;
| 1,412
|
C++
|
.h
| 35
| 37.714286
| 87
| 0.769905
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,856
|
build_info_impl.h
|
SNMetamorph_goldsrc-monitor/sources/library/build_info_impl.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "build_info.h"
#include "memory_pattern.h"
#include <rapidjson/rapidjson.h>
#include <rapidjson/document.h>
#include <string>
#include <vector>
#include <optional>
class CBuildInfo::Impl
{
public:
typedef int(__cdecl *pfnGetBuildNumber_t)();
std::optional<uint32_t> GetBuildNumber() const;
int DateToBuildNumber(const char *date) const;
const char *FindDateString(uint8_t *startAddr, int maxLen) const;
bool LoadBuildInfoFile(std::vector<uint8_t> &fileContents);
std::optional<std::string> ParseBuildInfo(std::vector<uint8_t> &fileContents);
std::optional<std::string> ParseBuildInfoEntry(CBuildInfo::Entry &destEntry, const rapidjson::Value &jsonObject);
bool ApproxBuildNumber(const SysUtils::ModuleInfo &engineModule);
bool FindBuildNumberFunc(const SysUtils::ModuleInfo &engineModule);
std::optional<size_t> FindActualInfoEntry();
uint32_t m_buildNumber = -1;
bool m_infoEntryGameSpecific = false;
pfnGetBuildNumber_t m_pfnGetBuildNumber = nullptr;
std::string m_initErrorMessage;
std::optional<size_t> m_iActualEntryIndex = std::nullopt;
std::vector<CBuildInfo::Entry> m_GameInfoEntries;
std::vector<CBuildInfo::Entry> m_EngineInfoEntries;
std::vector<CMemoryPattern> m_BuildNumberSignatures;
};
| 1,809
|
C++
|
.h
| 41
| 41.268293
| 117
| 0.780239
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,858
|
application.h
|
SNMetamorph_goldsrc-monitor/sources/library/application.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "utils.h"
#include "hooks.h"
#include "cvars.h"
#include "sys_utils.h"
#include "app_info.h"
#include "exception.h"
#include "build_info.h"
#include "engine_module.h"
#include "client_module.h"
#include "server_module.h"
#include "local_player.h"
#include "display_mode.h"
#include "primitives_renderer.h"
#include "string_stack.h"
#include <vector>
#include <memory>
#include <stdint.h>
class CApplication
{
public:
static CApplication &GetInstance();
void Run();
void DisplayModeRender2D();
void DisplayModeRender3D();
void HandleChangelevel();
bool KeyInput(int keyDown, int keyCode, const char *bindName);
const SCREENINFO& GetScreenInfo() const { return m_screenInfo; };
auto GetRenderer() const { return m_primitivesRenderer; };
auto &GetServerModule() { return m_serverModule; }
auto &GetLocalPlayer() { return m_localPlayer; }
private:
CApplication();
~CApplication() {};
void InitializeDisplayModes();
void InitializePrimitivesRenderer();
void FindTimescaleConVar(const SysUtils::ModuleInfo &engineLib);
void PrintTitleText();
void InitializeConVars(const SysUtils::ModuleInfo &engineLib);
void SetCurrentDisplayMode();
void UpdateScreenInfo();
void UpdateSmoothFrametime();
float m_frameTime;
float m_lastFrameTime;
float m_lastClientTime;
CBuildInfo m_buildInfo;
CEngineModule m_engineModule;
CClientModule m_clientModule;
CServerModule m_serverModule;
CHooks m_hooks;
SCREENINFO m_screenInfo = { 0 };
CStringStack m_stringStack;
CLocalPlayer m_localPlayer;
std::shared_ptr<IDisplayMode> m_currentDisplayMode = nullptr;
std::shared_ptr<IPrimitivesRenderer> m_primitivesRenderer = nullptr;
std::vector<std::shared_ptr<IDisplayMode>> m_displayModes;
};
extern CApplication &g_Application;
| 2,374
|
C++
|
.h
| 69
| 31.318841
| 72
| 0.762299
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,859
|
function_hook.h
|
SNMetamorph_goldsrc-monitor/sources/library/function_hook.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include <polyhook2/ZydisDisassembler.hpp>
#include <polyhook2/Detour/NatDetour.hpp>
template <class T> class CFunctionHook
{
public:
CFunctionHook() {};
~CFunctionHook() {};
inline uint64_t GetTrampolineAddr() const { return m_pfnTrampoline; }
inline bool IsHooked() const { return m_isHooked; }
bool Hook(T origFunc, T callbackFunc)
{
m_pDetour = new PLH::NatDetour(
reinterpret_cast<uint64_t>(origFunc),
reinterpret_cast<uint64_t>(callbackFunc),
&m_pfnTrampoline
);
m_isHooked = m_pDetour->hook();
return m_isHooked;
};
bool Unhook()
{
if (m_pDetour && m_isHooked)
{
bool isUnhooked = m_pDetour->unHook();
if (isUnhooked)
{
m_isHooked = false;
delete m_pDetour;
m_pDetour = nullptr;
}
return isUnhooked;
}
return false;
};
private:
bool m_isHooked = false;
uint64_t m_pfnTrampoline = 0;
PLH::NatDetour *m_pDetour = nullptr;
};
| 1,625
|
C++
|
.h
| 51
| 25.529412
| 73
| 0.65621
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,860
|
display_mode.h
|
SNMetamorph_goldsrc-monitor/sources/library/display_mode.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "string_stack.h"
enum class DisplayModeType
{
Full,
Speedometer,
EntityReport,
Measurement,
FaceReport,
AngleTracking
};
class IDisplayMode
{
public:
virtual ~IDisplayMode() {};
virtual void Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText) = 0;
virtual void Render3D() = 0;
virtual bool KeyInput(bool keyDown, int keyCode, const char *bindName) = 0;
virtual void HandleChangelevel() = 0;
virtual DisplayModeType GetModeIndex() = 0;
};
| 1,053
|
C++
|
.h
| 32
| 30.21875
| 102
| 0.772638
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,861
|
displaymode_facereport.h
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_facereport.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "display_mode.h"
#include "hlsdk.h"
#include "engine_types.h"
#include "bounding_box.h"
#include "local_player.h"
#include <vector>
class CModeFaceReport : public IDisplayMode
{
public:
CModeFaceReport(const CLocalPlayer &playerRef);
virtual ~CModeFaceReport() {};
void Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText) override;
void Render3D() override;
bool KeyInput(bool keyDown, int keyCode, const char *bindName) override;
void HandleChangelevel() override;
DisplayModeType GetModeIndex() override { return DisplayModeType::FaceReport; };
private:
int TraceEntity(vec3_t origin, vec3_t dir, float distance, vec3_t &intersect);
void GetSurfaceBoundingBox(Engine::msurface_t *surf, CBoundingBox &bbox);
void DrawFaceOutline(Engine::msurface_t *surf);
void DrawSurfaceBounds(Engine::msurface_t *surf);
bool GetLightmapProbe(Engine::msurface_t *surf, const vec3_t &point, color24 &probe);
Engine::mleaf_t *PointInLeaf(vec3_t point, Engine::mnode_t *node);
Engine::msurface_t *TraceSurface(vec3_t origin, vec3_t dir, float distance, vec3_t &intersect);
Engine::msurface_t *SurfaceAtPoint(model_t *pModel, Engine::mnode_t *node, vec3_t start, vec3_t end, vec3_t &intersect);
color24 m_colorProbe;
model_t *m_currentModel;
Engine::msurface_t *m_currentFace;
CBoundingBox m_currentFaceBounds;
std::vector<vec3_t> m_boundPoints;
const CLocalPlayer &m_localPlayer;
};
| 2,019
|
C++
|
.h
| 44
| 42.795455
| 124
| 0.767276
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,862
|
displaymode_entityreport.h
|
SNMetamorph_goldsrc-monitor/sources/library/displaymode_entityreport.h
|
/*
Copyright (C) 2023 SNMetamorph
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#pragma once
#include "stdafx.h"
#include "display_mode.h"
#include "engine_module.h"
#include "local_player.h"
#include "entity_dictionary.h"
#include <vector>
class CModeEntityReport : public IDisplayMode
{
public:
CModeEntityReport(const CLocalPlayer &playerRef, const CEngineModule &moduleRef);
virtual ~CModeEntityReport() {};
void Render2D(float frameTime, int scrWidth, int scrHeight, CStringStack &screenText) override;
void Render3D() override;
bool KeyInput(bool keyDown, int keyCode, const char *bindName) override;
void HandleChangelevel() override;
DisplayModeType GetModeIndex() override { return DisplayModeType::EntityReport; };
private:
int TraceEntity();
float TracePhysEnt(const physent_t &physEnt, vec3_t &viewOrigin, vec3_t &viewDir, float lineLen);
int TracePhysEntList(const physent_t *list, int count, vec3_t &viewOrigin, vec3_t &viewDir, float lineLen);
float GetEntityDistance(int entityIndex);
bool PrintEntityInfo(int entityIndex, CStringStack &screenText);
void PrintEntityCommonInfo(int entityIndex, CStringStack &screenText);
int GetActualEntityIndex();
int m_entityIndex;
int m_lockedEntityIndex;
std::vector<int> m_entityIndexList;
std::vector<float> m_entityDistanceList;
CEntityDictionary m_entityDictionary;
const CLocalPlayer &m_localPlayer;
const CEngineModule &m_engineModule;
};
| 1,921
|
C++
|
.h
| 44
| 40.568182
| 111
| 0.784492
|
SNMetamorph/goldsrc-monitor
| 34
| 5
| 4
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,863
|
Test07-BeliefPropagation.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test07-BeliefPropagation.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "ModelLibrary.h"
#include "Utils.h"
#include <EasyFactorGraph/model/Graph.h>
namespace EFG::test {
using namespace model;
using namespace strct;
using namespace categoric;
using namespace factor;
using namespace library;
using ClusterInfo = PropagationResult::ClusterInfo;
namespace {
template <typename ModelT> class TestModels : public ModelT {
public:
TestModels() = default;
// check all messages were computed after propagation
bool areAllMessagesComputed() const {
for (const auto &cluster : this->state().clusters) {
for (const auto *node : cluster.nodes) {
for (const auto &[connected_node, connection] :
node->active_connections) {
if (connection.message == nullptr) {
return false;
}
}
}
}
return true;
};
bool checkMarginals(const std::string &var_name,
const std::vector<float> &expected,
float threshold = 0.01f) {
return almost_equal_it(make_prob_distr(expected),
this->getMarginalDistribution(var_name), threshold);
}
};
bool are_equal(const ClusterInfo &a, const ClusterInfo &b) {
return (a.size == b.size) && (a.tree_or_loopy_graph == b.tree_or_loopy_graph);
}
bool are_equal(const std::vector<ClusterInfo> &a,
const std::vector<ClusterInfo> &b) {
if (a.size() != b.size()) {
return false;
}
for (const auto &a_element : a) {
if (std::find_if(b.begin(), b.end(),
[&a_element](const ClusterInfo &b_element) {
return are_equal(a_element, b_element);
}) == b.end()) {
return false;
}
}
return true;
}
bool are_equal(const PropagationResult &a, const PropagationResult &b) {
return (a.propagation_kind_done == b.propagation_kind_done) &&
(a.was_completed == b.was_completed) &&
are_equal(a.structures, b.structures);
}
} // namespace
TEST_CASE("trivial graph propagation", "[propagation][trivial]") {
TestModels<Graph> model;
auto w = GENERATE(1.f, 1.5f, 2.f);
const float exp_w = expf(w);
model.addConstFactor(
make_corr_expfactor_ptr(make_variable(2, "A"), make_variable(2, "B"), w));
// B = 0
model.setEvidence(model.findVariable("B"), 0);
CHECK(model.checkMarginals("A", {exp_w, 1.f}));
// B = 1
model.setEvidence(model.findVariable("B"), 1);
CHECK(model.checkMarginals("A", {1.f, exp_w}));
model.removeAllEvidences();
// A = 0
model.setEvidence(model.findVariable("A"), 0);
CHECK(model.checkMarginals("B", {exp_w, 1.f}));
// A = 1
model.setEvidence(model.findVariable("A"), 1);
CHECK(model.checkMarginals("B", {1.f, exp_w}));
}
TEST_CASE("simple poly tree belief propagation", "[propagation][tree]") {
TestModels<SimpleTree> model;
REQUIRE_FALSE(model.hasPropagationResult());
const float a = expf(SimpleTree::alfa);
const float b = expf(SimpleTree::beta);
const float g = expf(SimpleTree::gamma);
const float e = expf(SimpleTree::eps);
// E=1
model.setEvidence(model.findVariable("E"), 1);
CHECK(model.checkMarginals(
"A", {(a * (g + e) + (1 + g * e)), ((g + e) + a * (1 + g * e))}));
REQUIRE(model.hasPropagationResult());
{
const auto &propagation_result = model.getLastPropagationResult();
strct::PropagationResult propagation_expected;
propagation_expected.propagation_kind_done = PropagationKind::SUM;
propagation_expected.was_completed = true;
propagation_expected.structures =
std::vector<ClusterInfo>{ClusterInfo{true, 4}};
REQUIRE(are_equal(propagation_expected, propagation_result));
}
REQUIRE(model.areAllMessagesComputed());
CHECK(model.checkMarginals("B", {(g + e), (1 + g * e)}));
CHECK(model.checkMarginals(
"C", {(b * (g + e) + (1 + g * e)), ((g + e) + b * (1 + g * e))}));
CHECK(model.checkMarginals("D", {1.f, e}));
model.removeAllEvidences();
REQUIRE_FALSE(model.hasPropagationResult());
// D=1
model.setEvidence(model.findVariable("D"), 1);
CHECK(model.checkMarginals("A", {a + g, 1.f + a * g}));
{
const auto &propagation_result = model.getLastPropagationResult();
strct::PropagationResult propagation_expected;
propagation_expected.propagation_kind_done = PropagationKind::SUM;
propagation_expected.was_completed = true;
propagation_expected.structures =
std::vector<ClusterInfo>{ClusterInfo{true, 3}, ClusterInfo{true, 1}};
REQUIRE(are_equal(propagation_expected, propagation_result));
}
REQUIRE(model.areAllMessagesComputed());
CHECK(model.checkMarginals("B", {1.f, g}));
CHECK(model.checkMarginals("C", {b + g, 1.f + b * g}));
CHECK(model.checkMarginals("E", {1.f, e}));
}
TEST_CASE("complex poly tree belief propagation", "[propagation][tree]") {
TestModels<ComplexTree> model;
model.setEvidence(model.findVariable("v1"), 1);
model.setEvidence(model.findVariable("v2"), 1);
model.setEvidence(model.findVariable("v3"), 1);
auto threads = GENERATE(1, 2, 4);
{
auto prob = model.getMarginalDistribution("v10", threads);
CHECK(prob[0] < prob[1]);
}
{
auto prob = model.getMarginalDistribution("v11", threads);
CHECK(prob[0] < prob[1]);
}
{
auto prob = model.getMarginalDistribution("v13", threads);
CHECK(prob[0] < prob[1]);
}
CHECK(model.areAllMessagesComputed());
}
TEST_CASE("simple loopy graph belief propagation", "[propagation][loopy]") {
TestModels<SimpleLoopy> model;
float M = expf(SimpleLoopy::w);
float M_alfa = powf(M, 3) + M + 2.f * powf(M, 2);
float M_beta = powf(M, 4) + 2.f * M + powf(M, 2);
// E=1
model.setEvidence(model.findVariable("E"), 1);
CHECK(model.checkMarginals(
"D", {3.f * M + powf(M, 3), powf(M, 4) + 3.f * powf(M, 2)}, 0.045f));
REQUIRE(model.hasPropagationResult());
{
const auto &propagation_result = model.getLastPropagationResult();
strct::PropagationResult propagation_expected;
propagation_expected.propagation_kind_done = PropagationKind::SUM;
propagation_expected.was_completed = true;
propagation_expected.structures =
std::vector<ClusterInfo>{ClusterInfo{false, 4}};
REQUIRE(are_equal(propagation_expected, propagation_result));
}
REQUIRE(model.areAllMessagesComputed());
CHECK(model.checkMarginals("C", {M_alfa, M_beta}, 0.045f));
CHECK(model.checkMarginals("B", {M_alfa, M_beta}, 0.045f));
CHECK(model.checkMarginals("A", {M * M_alfa + M_beta, M_alfa + M * M_beta},
0.045f));
}
TEST_CASE("complex loopy graph belief propagation", "[propagation][loopy]") {
TestModels<ComplexLoopy> model;
model.setEvidence(model.findVariable("v1"), 1);
auto threads = GENERATE(1, 2, 4);
auto prob = model.getMarginalDistribution("v8", threads);
CHECK(prob[0] < prob[1]);
CHECK(model.areAllMessagesComputed());
}
#include <sstream>
TEST_CASE("big loopy graph", "[propagation][loopy]") {
std::vector<std::vector<VariablePtr>> vars;
auto make_name = [](std::size_t r, std::size_t c) {
std::stringstream stream;
stream << "V_" << std::to_string(r) << std::to_string(c);
return stream.str();
};
const std::size_t size = 10;
vars.reserve(size);
for (std::size_t r = 0; r < size; ++r) {
auto &row = vars.emplace_back();
row.reserve(size);
for (std::size_t c = 0; c < size; ++c) {
row.push_back(make_variable(2, make_name(r, c)));
}
}
Graph model;
using Coord = std::pair<std::size_t, std::size_t>;
auto add_factor = [&](const Coord &first, const Coord &second) {
model.addConstFactor(
make_corr_expfactor_ptr(vars[first.first][first.second],
vars[second.first][second.second], 0.1f));
};
for (std::size_t r = 0; r < size; ++r) {
for (std::size_t c = 0; c < size; ++c) {
if (0 < r) {
add_factor(Coord{r, c}, Coord{r - 1, c});
}
if (0 < c) {
add_factor(Coord{r, c}, Coord{r, c - 1});
}
if ((0 < r) && (0 < c)) {
add_factor(Coord{r, c}, Coord{r - 1, c - 1});
}
}
}
auto threads = GENERATE(1, 2, 4);
model.getMarginalDistribution(make_name(0, 0), threads);
}
#include <EasyFactorGraph/structure/SpecialFactors.h>
namespace {
model::Graph make_chain_model(float wXY, float wYY) {
categoric::VariablesSoup Y = {make_variable(2, "Y0"), make_variable(2, "Y1"),
make_variable(2, "Y2"), make_variable(2, "Y3")};
categoric::VariablesSoup X = {make_variable(2, "X0"), make_variable(2, "X1"),
make_variable(2, "X2"), make_variable(2, "X3")};
model::Graph model;
auto connect = [&model](const VariablePtr &a, const VariablePtr &b, float w) {
model.addConstFactor(make_corr_expfactor_ptr(a, b, w));
};
connect(X[0], Y[0], wXY);
connect(X[1], Y[1], wXY);
connect(X[2], Y[2], wXY);
connect(X[3], Y[3], wXY);
connect(Y[0], Y[1], wYY);
connect(Y[1], Y[2], wYY);
connect(Y[2], Y[3], wYY);
model.copyConstFactor(
factor::FactorExponential(factor::Indicator{Y[0], 1}, wYY));
model.setEvidence(X[0], 0);
model.setEvidence(X[1], 1);
model.setEvidence(X[2], 0);
model.setEvidence(X[3], 1);
return model;
};
} // namespace
TEST_CASE("MAPTest", "[propagation][MAP]") {
SECTION("strong weight between hidden") {
auto model = make_chain_model(0.1f, 1.f);
std::vector<std::size_t> mapExpected = {1, 1, 1, 1};
CHECK(mapExpected == model.getHiddenSetMAP());
CHECK(model.getLastPropagationResult().propagation_kind_done ==
PropagationKind::MAP);
}
SECTION("strong weight for evidences") {
auto model = make_chain_model(1.0f, 0.1f);
auto get_expected_MAP_val = [](const std::string &var_name) {
if (var_name == "Y0") {
return 0;
}
if (var_name == "Y1") {
return 1;
}
if (var_name == "Y2") {
return 0;
}
return 1;
};
std::vector<std::size_t> mapExpected;
mapExpected.reserve(4);
for (const auto &var : model.getHiddenVariables()) {
mapExpected.push_back(get_expected_MAP_val(var->name()));
}
CHECK(mapExpected == model.getHiddenSetMAP());
}
}
TEST_CASE("Sub graph distribution", "[propagation][subgraph]") {
VariablePtr A = make_variable(2, "A");
VariablePtr B = make_variable(2, "B");
VariablePtr C = make_variable(2, "C");
VariablePtr D = make_variable(2, "D");
float alfa = 0.5f, beta = 1.5f;
// build the chain
model::Graph graph;
graph.addConstFactor(make_corr_expfactor_ptr(A, B, alfa));
graph.addConstFactor(make_corr_expfactor_ptr(B, C, alfa));
graph.addConstFactor(make_corr_expfactor_ptr(C, D, alfa));
// joint distribution of A B C
CHECK(almost_equal_it(
make_prob_distr({expf(alfa) * expf(beta), expf(alfa), 1.f, expf(beta),
expf(beta), 1.f, expf(alfa), expf(alfa) * expf(beta)}),
graph.getJointMarginalDistribution({"A", "B", "C"}).getProbabilities(),
0.15f));
// joint distribution of A B
CHECK(almost_equal_it(
make_prob_distr({expf(alfa), 1.f, 1.f, expf(alfa)}),
graph.getJointMarginalDistribution({"A", "B"}).getProbabilities(),
0.01f));
}
TEST_CASE("Belief propagation with Pool efficiency",
"[propagation][performance][!mayfail]") {
auto depth = GENERATE(8, 10);
auto loopy = GENERATE(false, true);
ScalableModel model(depth, 7, loopy);
auto measure_time = [&](std::size_t threads) -> std::chrono::nanoseconds {
model.removeAllEvidences();
model.setEvidence(model.root(), 0);
return test::measure_time(
[&]() { model.getMarginalDistribution(model.nonRoot(), threads); });
};
auto single_thread_time = measure_time(1);
auto multi_thread_time = measure_time(2);
CHECK(static_cast<double>(multi_thread_time.count()) <
static_cast<double>(single_thread_time.count()));
}
} // namespace EFG::test
| 11,986
|
C++
|
.cpp
| 316
| 32.971519
| 80
| 0.644131
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,864
|
Test02-Function-a.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test02-Function-a.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <EasyFactorGraph/factor/Function.h>
#include "Utils.h"
#include <cmath>
namespace EFG::test {
using Hasher = factor::Function::CombinationHasher;
using Combination = std::vector<std::size_t>;
TEST_CASE("Combination hasher", "[function]") {
using Case = std::pair<Combination, std::size_t>;
SECTION("single variable") {
auto info = factor::make_info(make_group(std::vector<std::size_t>{4}));
Hasher hasher{info};
for (std::size_t k = 0; k < 4; ++k) {
std::size_t index = hasher(std::vector<std::size_t>{k});
CHECK(index == k);
}
}
SECTION("multi variables") {
auto info =
factor::make_info(make_group(std::vector<std::size_t>{2, 4, 2}));
Hasher hasher{info};
std::vector<Case> cases;
cases.emplace_back(std::make_pair(std::vector<std::size_t>{0, 0, 0}, 0));
cases.emplace_back(std::make_pair(std::vector<std::size_t>{1, 3, 1},
info->totCombinations - 1));
cases.emplace_back(std::make_pair(std::vector<std::size_t>{0, 2, 0}, 4));
cases.emplace_back(std::make_pair(std::vector<std::size_t>{0, 2, 1}, 5));
cases.emplace_back(std::make_pair(std::vector<std::size_t>{1, 0, 0}, 8));
cases.emplace_back(std::make_pair(std::vector<std::size_t>{1, 3, 0}, 14));
cases.emplace_back(std::make_pair(std::vector<std::size_t>{1, 1, 1}, 11));
for (const auto &[comb, index_expected] : cases) {
std::size_t index = hasher(comb);
CHECK(index == index_expected);
}
}
}
namespace {
enum class Case { NONE, SPARSE, DENSE };
class FunctionTestable : public factor::Function {
public:
FunctionTestable()
: factor::Function{make_group(std::vector<std::size_t>{2, 4, 2})} {}
Case getCase() const {
Case res = Case::NONE;
VisitorConst<SparseContainer, DenseContainer>{
[&res](const SparseContainer &c) { res = Case::SPARSE; },
[&res](const DenseContainer &c) { res = Case::DENSE; }}
.visit(data_);
return res;
}
std::size_t size() const {
std::size_t res;
VisitorConst<SparseContainer, DenseContainer>{
[&res](const SparseContainer &c) { res = c.size(); },
[&res](const DenseContainer &c) { res = c.size(); }}
.visit(data_);
return res;
}
std::vector<float> getDenseImages() const {
std::vector<float> res;
VisitorConst<SparseContainer, DenseContainer>{
[&res](const SparseContainer &c) {},
[&res](const DenseContainer &c) { res = c; }}
.visit(data_);
return res;
}
};
void addBelowCritical(FunctionTestable &subject) {
subject.set(std::vector<std::size_t>{0, 1, 0}, 1.f);
subject.set(std::vector<std::size_t>{1, 3, 0}, 2.f);
subject.set(std::vector<std::size_t>{0, 2, 1}, 3.f);
}
void addAboveCritical(FunctionTestable &subject) {
subject.set(std::vector<std::size_t>{0, 0, 0}, 1.f);
subject.set(std::vector<std::size_t>{0, 0, 1}, 1.f);
subject.set(std::vector<std::size_t>{0, 2, 0}, 1.f);
subject.set(std::vector<std::size_t>{0, 2, 1}, 1.f);
subject.set(std::vector<std::size_t>{1, 0, 0}, 1.f);
subject.set(std::vector<std::size_t>{1, 0, 1}, 1.f);
subject.set(std::vector<std::size_t>{1, 2, 0}, 1.f);
subject.set(std::vector<std::size_t>{1, 2, 1}, 1.f);
subject.set(std::vector<std::size_t>{1, 3, 1}, 1.f);
}
} // namespace
TEST_CASE("Function set method", "[function]") {
FunctionTestable fnct;
SECTION("empty after construction") {
CHECK(fnct.size() == 0);
CHECK(fnct.getCase() == Case::SPARSE);
}
SECTION("add remaining under critical") {
addBelowCritical(fnct);
CHECK(fnct.size() == 3);
CHECK(fnct.getCase() == Case::SPARSE);
}
SECTION("add above critical") {
addAboveCritical(fnct);
CHECK(fnct.size() == 16);
CHECK(fnct.getCase() == Case::DENSE);
const auto images = fnct.getDenseImages();
CHECK(images == std::vector<float>{1.f, 1.f, 0, 0, 1.f, 1.f, 0, 0, 1.f, 1.f,
0, 0, 1.f, 1.f, 0, 1.f});
}
}
TEST_CASE("Function find method", "[function]") {
FunctionTestable fnct;
fnct.set(std::vector<std::size_t>{0, 0, 0}, 1.f);
fnct.set(std::vector<std::size_t>{1, 3, 0}, 1.f);
auto comb = std::vector<std::size_t>{0, 2, 1};
SECTION("set than find") {
fnct.set(comb, 2.f);
float img = fnct.findImage(comb);
CHECK(img == 2.f);
}
SECTION("override value") {
fnct.set(comb, 2.f);
float img = fnct.findImage(comb);
CHECK(img == 2.f);
fnct.set(comb, 1.5f);
img = fnct.findImage(comb);
CHECK(img == 1.5f);
}
}
namespace {
class FunctionWithTransform : public factor::Function {
public:
template <typename Trsf>
FunctionWithTransform(Trsf &&trsf)
: factor::Function{make_group(std::vector<std::size_t>{2, 4, 2})},
trsfm_{std::forward<Trsf>(trsf)} {}
protected:
float transform(float input) const override { return trsfm_(input); }
private:
std::function<float(float)> trsfm_;
};
} // namespace
TEST_CASE("Function transform", "[function]") {
FunctionWithTransform fnct{[](float val) { return 2 * val; }};
const auto comb = std::vector<std::size_t>{1, 3, 0};
fnct.set(comb, 1.5f);
CHECK(std::abs(fnct.findImage(comb) - 1.5f) < 0.001f);
CHECK(std::abs(fnct.findTransformed(comb) - 3.f) < 0.001f);
}
TEST_CASE("Function for each method", "[function]") {
FunctionTestable fnct;
SECTION("iterate dense ") {
SECTION("empty") {
std::vector<float> images;
fnct.forEachCombination<false>(
[&images](const Combination &, float img) { images.push_back(img); });
CHECK(images ==
std::vector<float>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
}
SECTION("with some values") {
addBelowCritical(fnct);
std::vector<float> images;
fnct.forEachCombination<false>(
[&images](const Combination &, float img) { images.push_back(img); });
CHECK(images == std::vector<float>{0, 0, 1.f, 0, 0, 3.f, 0, 0, 0, 0, 0, 0,
0, 0, 2.f, 0});
}
}
SECTION("iterate dense ") {
addAboveCritical(fnct);
std::vector<float> images;
fnct.forEachCombination<false>(
[&images](const Combination &, float img) { images.push_back(img); });
CHECK(images == std::vector<float>{1.f, 1.f, 0, 0, 1.f, 1.f, 0, 0, 1.f, 1.f,
0, 0, 1.f, 1.f, 0, 1.f});
}
}
} // namespace EFG::test
| 6,519
|
C++
|
.cpp
| 173
| 32.50289
| 80
| 0.612698
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,865
|
Test04-Insertions.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test04-Insertions.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "Utils.h"
#include <EasyFactorGraph/structure/FactorsConstManager.h>
#include <EasyFactorGraph/trainable/FactorsTunableManager.h>
namespace EFG::test {
using namespace categoric;
using namespace factor;
using namespace strct;
using namespace train;
using namespace test;
namespace {
class Checker : virtual public FactorsAware {
public:
void checkPostInsertion() {
if (hasPropagationResult()) {
throw Error{"Expected to not have propagation result"};
}
const auto &state = this->state();
if (!state.evidences.empty()) {
throw Error{"Expected to have no evidences"};
}
if (state.nodes.size() != state.variables.size()) {
throw Error{
"number of nodes expected to be equal to number of variables"};
}
std::size_t hidden_nodes_numb = 0;
for (const auto &cluster : state.clusters) {
hidden_nodes_numb += cluster.nodes.size();
}
if (hidden_nodes_numb != state.nodes.size()) {
throw Error{"number of hidden nodes expected to be equal to total number "
"of nodes"};
}
};
void checkVariables(const VariablesSet &vars) {
VariablesSet vars_this;
for (const auto &node : state().nodes) {
vars_this.emplace(node.first);
}
if (vars_this != vars) {
throw Error{"Variables mismatch"};
}
}
protected:
Checker() = default;
};
class FactorsManagerTest : public Checker, public FactorsConstInserter {
public:
FactorsManagerTest() = default;
};
} // namespace
TEST_CASE("const factors insertion", "[insertion]") {
auto A = make_variable(2, "A");
auto B = make_variable(2, "B");
FactorsManagerTest model;
SECTION("by copy") {
auto to_insert = make_corr_factor(A, B);
model.copyConstFactor(to_insert);
model.checkPostInsertion();
model.checkVariables(to_insert.function().vars().getVariablesSet());
CHECK(model.getAllFactors().size() == 1);
CHECK(model.getConstFactors().size() == 1);
CHECK(test::almost_equal_fnct(
model.getAllFactors().begin()->get()->function(),
to_insert.function()));
CHECK(test::almost_equal_fnct(
model.getConstFactors().begin()->get()->function(),
to_insert.function()));
}
SECTION("by sharing") {
auto to_insert = make_corr_factor_ptr(A, B);
model.addConstFactor(to_insert);
model.checkPostInsertion();
model.checkVariables(to_insert->function().vars().getVariablesSet());
CHECK(model.getAllFactors().size() == 1);
CHECK(model.getConstFactors().size() == 1);
CHECK(*model.getAllFactors().begin() == to_insert);
CHECK(*model.getConstFactors().begin() == to_insert);
}
}
namespace {
class FactorsTunableManagerTest : public Checker,
public FactorsConstInserter,
public FactorsTunableInserter {
public:
FactorsTunableManagerTest() = default;
virtual std::vector<float>
getWeightsGradient_(const TrainSet::Iterator &train_set_combinations) final {
return {};
}
const Tuners &getTuners() const { return tuners; }
using StateAware::state;
};
} // namespace
TEST_CASE("tunable factors insertion", "[insertion]") {
auto A = make_variable(2, "A");
auto B = make_variable(2, "B");
FactorsTunableManagerTest model;
SECTION("by copy") {
auto to_insert = make_corr_expfactor(A, B, 1.f);
model.copyTunableFactor(to_insert);
model.checkPostInsertion();
model.checkVariables(to_insert.function().vars().getVariablesSet());
CHECK(model.getAllFactors().size() == 1);
CHECK(model.getConstFactors().size() == 0);
CHECK(model.getTunableFactors().size() == 1);
CHECK(model.getTuners().size() == 1);
CHECK(test::almost_equal_fnct(
model.getAllFactors().begin()->get()->function(),
to_insert.function()));
CHECK(test::almost_equal_fnct(
model.getTunableFactors().begin()->get()->function(),
to_insert.function()));
}
SECTION("by sharing") {
auto to_insert = make_corr_expfactor_ptr(A, B, 1.f);
model.addTunableFactor(to_insert);
model.checkPostInsertion();
model.checkVariables(to_insert->function().vars().getVariablesSet());
CHECK(model.getAllFactors().size() == 1);
CHECK(model.getConstFactors().size() == 0);
CHECK(model.getTunableFactors().size() == 1);
CHECK(model.getTuners().size() == 1);
CHECK(*model.getAllFactors().begin() == to_insert);
CHECK(*model.getTunableFactors().begin() == to_insert);
SECTION("add factor sharing the weight") {
auto C = make_variable(2, "C");
auto to_insert2 = make_corr_expfactor_ptr(A, C, 1.f);
model.addTunableFactor(to_insert2,
to_insert->function().vars().getVariablesSet());
model.checkPostInsertion();
model.checkVariables(VariablesSet{A, B, C});
CHECK(model.getAllFactors().size() == 2);
CHECK(model.getConstFactors().size() == 0);
CHECK(model.getTunableFactors().size() == 2);
const auto clusters = model.getTunableClusters();
CHECK(model.getTuners().size() == 1);
CHECK(clusters.size() == 1);
VisitorConst<train::FactorExponentialPtr, train::TunableClusters>(
[](const train::FactorExponentialPtr &) {
throw std::runtime_error{"TunableClusters was expected"};
},
[](const train::TunableClusters &cl) { CHECK(cl.size() == 2); })
.visit(clusters.front());
}
}
}
TEST_CASE("tunable factors multiple insertions", "[insertion]") {
auto A = make_variable(2, "A");
auto B = make_variable(2, "B");
auto C = make_variable(2, "C");
auto D = make_variable(2, "D");
FactorsTunableManagerTest model;
auto factor_AB = make_corr_expfactor(A, B, 1.f);
auto factor_BC = make_corr_expfactor(B, C, 1.f);
factor::FactorExponential factor_D(factor::Factor{Group{VariablesSoup{D}}});
model.copyTunableFactor(factor_AB);
model.copyConstFactor(factor_BC);
model.copyTunableFactor(factor_D);
model.checkVariables(VariablesSet{A, B, C, D});
CHECK(model.getAllFactors().size() == 3);
CHECK(model.getConstFactors().size() == 1);
CHECK(model.getTunableFactors().size() == 2);
CHECK(model.getTuners().size() == 2);
const auto &state = model.state();
CHECK(state.clusters.size() == 2);
CHECK((state.clusters.front().nodes.size() == 3 ||
state.clusters.back().nodes.size() == 3));
CHECK((state.clusters.front().nodes.size() == 1 ||
state.clusters.back().nodes.size() == 1));
}
TEST_CASE("check bad factor insertions are refused", "[insertion]") {
auto A = make_variable(2, "A");
auto B = make_variable(2, "B");
FactorsTunableManagerTest model;
auto to_insert1 = make_corr_factor_ptr(A, B);
model.addConstFactor(to_insert1);
SECTION("factor connecting same variables") {
auto to_insert2 = make_corr_factor_ptr(A, B);
CHECK_THROWS_AS(model.addConstFactor(to_insert2), Error);
}
SECTION("factor referring to a bad variable") {
auto A_bis = make_variable(2, "A");
SECTION("bad unary factor") {
auto to_insert2 = std::make_shared<Factor>(Group{VariablesSoup{A_bis}});
CHECK_THROWS_AS(model.addConstFactor(to_insert2), Error);
}
SECTION("bad binary factor") {
auto C = make_variable(2, "C");
auto to_insert2 = make_corr_factor_ptr(A_bis, C);
CHECK_THROWS_AS(model.addConstFactor(to_insert2), Error);
}
}
}
} // namespace EFG::test
| 7,535
|
C++
|
.cpp
| 196
| 33.280612
| 80
| 0.666026
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,866
|
Test03-Factor.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test03-Factor.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <EasyFactorGraph/Error.h>
#include <EasyFactorGraph/factor/Factor.h>
#include <EasyFactorGraph/factor/FactorExponential.h>
#include "../src/src/io/Utils.h"
#include "Utils.h"
#include <fstream>
#include <math.h>
namespace EFG::test {
using namespace categoric;
using namespace factor;
using namespace train;
namespace {
bool set_image(factor::Factor &subject, const std::vector<std::size_t> &to_add,
float value) {
subject.set(to_add, value);
return subject.function().findImage(to_add) == value;
}
} // namespace
TEST_CASE("operations on factor", "[factor]") {
Factor factor(Group{
{make_variable(3, "A"), make_variable(4, "B"), make_variable(2, "C")}});
CHECK(set_image(factor, {1, 2, 1}, 2.f));
CHECK(set_image(factor, {0, 0, 0}, 3.5f));
CHECK(set_image(factor, {2, 3, 0}, 1.f));
CHECK(set_image(factor, {1, 1, 1}, 0.5f));
CHECK_THROWS_AS(set_image(factor, {1, 0, 1}, -2.5f), Error);
}
TEST_CASE("import from file", "[factor]") {
const std::string file_name = "factor_description";
{
std::ofstream stream(file_name);
if (!stream.is_open()) {
throw Error::make(file_name, " is an invalid filename");
}
stream << "0 1 1 2.0\n";
stream << "0 0 0 3.0\n";
stream << "1 1 3 2.5\n";
stream << "1 0 2 1.4";
}
// 2,2,4
factor::Factor factor(test::make_group(std::vector<std::size_t>{2, 2, 4}));
io::import_values(factor, file_name);
CHECK(test::almost_equal(
factor.function().findImage(std::vector<std::size_t>{0, 1, 1}), 2.f,
0.01f));
CHECK(test::almost_equal(
factor.function().findImage(std::vector<std::size_t>{0, 0, 0}), 3.f,
0.01f));
CHECK(test::almost_equal(
factor.function().findImage(std::vector<std::size_t>{1, 1, 3}), 2.5f,
0.01f));
CHECK(test::almost_equal(
factor.function().findImage(std::vector<std::size_t>{1, 0, 2}), 1.4f,
0.01f));
}
#include <EasyFactorGraph/categoric/GroupRange.h>
namespace {
bool all_equals_values(const std::vector<std::size_t> &comb) {
return std::all_of(comb.begin() + 1, comb.end(),
[val = comb.front()](auto el) { return val == el; });
}
} // namespace
TEST_CASE("correlating factors", "[factor]") {
auto sizes = std::vector<std::size_t>{4, 4, 4};
SECTION("correlating factor") {
Factor factor(test::make_group(sizes),
factor::Factor::SimplyCorrelatedTag{});
categoric::GroupRange range(factor.function().vars());
for_each_combination(range,
[&function = factor.function()](const auto &comb) {
if (all_equals_values(comb)) {
CHECK(1.f == function.findImage(comb));
} else {
CHECK(0 == function.findImage(comb));
}
});
}
SECTION("anti correlating factor") {
Factor factor(test::make_group(sizes),
factor::Factor::SimplyAntiCorrelatedTag{});
categoric::GroupRange range(factor.function().vars());
for_each_combination(range,
[&function = factor.function()](const auto &comb) {
if (all_equals_values(comb)) {
CHECK(0 == function.findImage(comb));
} else {
CHECK(1.f == function.findImage(comb));
}
});
}
}
TEST_CASE("merge factors", "[factor]") {
const float val1 = 1.5f;
const float val2 = 3.2f;
auto varA = make_variable(2, "A");
auto varB = make_variable(2, "B");
auto varC = make_variable(2, "C");
factor::Factor distrAC(Group{{varA, varC}});
test::setAllImages(distrAC, val1);
factor::Factor distrBC(Group{{varB, varC}});
test::setAllImages(distrBC, val2);
factor::Factor distrABC(std::vector<const Immutable *>{&distrAC, &distrBC});
REQUIRE(3 == distrABC.function().vars().getVariables().size());
const auto &distrABC_group = distrABC.function().vars().getVariablesSet();
REQUIRE(distrABC_group.find(make_variable(2, "A")) != distrABC_group.end());
REQUIRE(distrABC_group.find(make_variable(2, "B")) != distrABC_group.end());
REQUIRE(distrABC_group.find(make_variable(2, "C")) != distrABC_group.end());
GroupRange range(distrABC.function().vars());
REQUIRE(distrABC.function().vars().size() == 2 * 2 * 2);
for_each_combination(range, [&](const auto &comb) {
CHECK(distrABC.function().findImage(comb) == val1 * val2);
});
}
TEST_CASE("Factor copy c'tor", "[factor]") {
Group group(VariablesSoup{make_variable(4, "A"), make_variable(4, "B"),
make_variable(4, "C")});
Factor factor(test::make_group(std::vector<std::size_t>{4, 4, 4}),
factor::Factor::SimplyCorrelatedTag{});
SECTION("Factor") {
Factor copy(factor);
CHECK(test::almost_equal_fnct(factor.function(), copy.function()));
}
SECTION("FactorExponential") {
const float w = 1.3f;
FactorExponential factor_exp(factor, w);
FactorExponential copy(factor_exp);
CHECK(test::almost_equal_fnct(factor_exp.function(), copy.function()));
}
SECTION("Factor from FactorExponential") {
const float w = 1.3f;
FactorExponential factor_exp(factor, w);
Factor copy(factor_exp, factor::Factor::CloneTrasformedImagesTag{});
CHECK(test::almost_equal_fnct(factor_exp.function(), copy.function()));
}
}
TEST_CASE("Variables order change in factor", "[factor]") {
auto A = make_variable(3, "A");
auto B = make_variable(3, "B");
auto C = make_variable(3, "C");
Group initial_group(VariablesSoup{A, B, C});
Factor initial_order(initial_group);
initial_order.set(std::vector<std::size_t>{0, 1, 2}, 1.f);
initial_order.set(std::vector<std::size_t>{0, 2, 0}, 2.f);
initial_order.set(std::vector<std::size_t>{1, 0, 1}, 3.f);
Group different_group(VariablesSoup{B, C, A});
auto different_order = initial_order.cloneWithPermutedGroup(different_group);
REQUIRE(different_order.function().vars() == different_group);
CHECK(different_order.function().findImage(
std::vector<std::size_t>{1, 2, 0}) == 1.f);
CHECK(different_order.function().findImage(
std::vector<std::size_t>{2, 0, 0}) == 2.f);
CHECK(different_order.function().findImage(
std::vector<std::size_t>{0, 1, 1}) == 3.f);
}
} // namespace EFG::test
| 6,520
|
C++
|
.cpp
| 157
| 35.133758
| 79
| 0.619551
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,867
|
Test09-Gradient.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test09-Gradient.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "Utils.h"
#include <EasyFactorGraph/categoric/GroupRange.h>
#include <EasyFactorGraph/model/RandomField.h>
#include <EasyFactorGraph/structure/GibbsSampler.h>
#include <EasyFactorGraph/trainable/tuners/BaseTuner.h>
namespace EFG::test {
using namespace categoric;
using namespace train;
using namespace strct;
using namespace model;
namespace {
float exp_over_exp_plus_one(float val) {
float exp_val = expf(val);
return exp_val / (1.f + exp_val);
}
class TunableModelTest : public RandomField {
public:
TunableModelTest() = default;
TrainSet makeGoodTrainset(std::size_t samples) const {
return make_good_trainset(*this, samples);
}
bool checkGradient(const std::vector<float> &for_samples_generation,
const std::vector<float> &for_gradient_computation) {
setWeights(for_samples_generation);
auto samples = makeGoodTrainset(1000);
setWeights(for_gradient_computation);
propagateBelief(PropagationKind::SUM);
auto samples_it = samples.makeIterator();
for (std::size_t t = 0; t < tuners.size(); ++t) {
const auto &tuner = tuners[t];
float alfa_part = tuner->getGradientAlpha(samples_it);
float alfa_expected = exp_over_exp_plus_one(for_samples_generation[t]);
float beta_part = tuner->getGradientBeta();
float beta_expected = exp_over_exp_plus_one(tuner->getWeight());
if (!almost_equal(alfa_part, alfa_expected, 0.05f)) {
return false;
}
if (!almost_equal(beta_part, beta_expected, 0.05f)) {
return false;
}
}
return true;
}
};
} // namespace
TEST_CASE("Gradient evaluation on binary factor", "[gradient]") {
TunableModelTest model;
const float w = 1.f;
model.addTunableFactor(
make_corr_expfactor_ptr(make_variable(2, "A"), make_variable(2, "B"), w));
auto grad_w = GENERATE(0.5f, 2.f);
CHECK(model.checkGradient(std::vector<float>{w}, std::vector<float>{grad_w}));
}
TEST_CASE("Gradient evaluation on chain models", "[gradient]") {
TunableModelTest model;
auto A = make_variable(2, "A");
auto B = make_variable(2, "B");
auto C = make_variable(2, "C");
const float alfa = 1.f;
model.addTunableFactor(make_corr_expfactor_ptr(A, B, alfa));
const float beta = 0.5f;
model.addTunableFactor(make_corr_expfactor_ptr(B, C, beta));
{
const std::vector<float> reference_w = {alfa, beta};
auto modified_w =
GENERATE(std::vector<float>{1.f, 1.f}, std::vector<float>{0.5f, 0.5f},
std::vector<float>{2.f, 2.f});
CHECK(model.checkGradient(std::vector<float>{reference_w}, modified_w));
}
auto D = make_variable(2, "D");
const float gamma = 2.f;
model.addTunableFactor(make_corr_expfactor_ptr(C, D, gamma));
{
const std::vector<float> reference_w = {alfa, beta, gamma};
auto modified_w = GENERATE(std::vector<float>{1.f, 1.f, 1.f},
std::vector<float>{0.5f, 0.5f, 0.5f},
std::vector<float>{2.f, 2.f, 2.f});
CHECK(model.checkGradient(std::vector<float>{reference_w}, modified_w));
}
}
} // namespace EFG::test
| 3,212
|
C++
|
.cpp
| 83
| 33.843373
| 80
| 0.677181
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,868
|
Test07-Pool.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test07-Pool.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <EasyFactorGraph/structure/bases/PoolAware.h>
#include "Utils.h"
namespace EFG::test {
using namespace strct;
TEST_CASE("testing Pool", "[pool]") {
auto threads = GENERATE(1, 2, 4);
SECTION("parallel for balance") {
for (std::size_t k = 0; k < 5; ++k) {
Pool pool(threads);
std::vector<std::size_t> counters;
for (std::size_t k = 0; k < threads; ++k) {
counters.push_back(0);
}
const std::size_t times_x_thread = 5;
Tasks tasks;
const std::size_t tasks_size = times_x_thread * threads;
tasks.reserve(tasks_size);
for (std::size_t k = 0; k < tasks_size; ++k) {
tasks.emplace_back(
[&counters](const std::size_t th_id) { ++counters[th_id]; });
}
pool.parallelFor(tasks);
for (const auto counter : counters) {
CHECK(counter == times_x_thread);
}
}
}
SECTION("pool reset") {
class PoolContainerTest : public PoolAware {
public:
PoolContainerTest() = default;
void setReset(const std::size_t threads) {
setPoolSize(threads);
resetPool();
}
};
PoolContainerTest pool;
for (std::size_t k = 0; k < 3; ++k) {
pool.setReset(threads);
}
}
}
TEST_CASE("testing Pool efficiency", "[pool]") {
const std::size_t tasks_size = 20;
Tasks tasks;
for (std::size_t k = 0; k < tasks_size; ++k) {
tasks.emplace_back([](const std::size_t) {
std::this_thread::sleep_for(std::chrono::milliseconds{20});
});
}
const std::size_t cycles = 5;
auto measure_time =
[&](const std::size_t threads) -> std::chrono::nanoseconds {
Pool pool(threads);
return test::measure_time([&]() {
for (std::size_t k = 0; k < cycles; ++k) {
pool.parallelFor(tasks);
}
});
};
auto single_thread_time = measure_time(1);
auto multi_thread_time = measure_time(2);
CHECK(static_cast<double>(multi_thread_time.count()) <
static_cast<double>(0.7 * single_thread_time.count()));
}
} // namespace EFG::test
| 2,138
|
C++
|
.cpp
| 68
| 26.161765
| 73
| 0.608273
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,869
|
Test06-IO.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test06-IO.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "Utils.h"
#include <EasyFactorGraph/model/Graph.h>
#include <EasyFactorGraph/model/RandomField.h>
#include <EasyFactorGraph/trainable/tuners/TunerVisitor.h>
#include <EasyFactorGraph/io/json/Exporter.h>
#include <EasyFactorGraph/io/json/Importer.h>
#include <EasyFactorGraph/io/xml/Exporter.h>
#include <EasyFactorGraph/io/xml/Importer.h>
#include <algorithm>
#include <set>
namespace EFG::test {
using namespace categoric;
using namespace strct;
using namespace train;
using namespace model;
using namespace factor;
using namespace test;
namespace {
using VarNames = std::set<std::string>;
VarNames vars_names(const Group &subject) {
VarNames res;
for (const auto &var : subject.getVariables()) {
res.emplace(var->name());
}
return res;
}
void sort_set(std::vector<VarNames> &subject) {
auto convert = [](const VarNames &s) {
return *s.begin() + " " + *s.rbegin();
};
std::sort(subject.begin(), subject.end(),
[&convert](const VarNames &a, const VarNames &b) {
return convert(a) < convert(b);
});
}
template <typename ModelT> class TestModelBase : public ModelT {
public:
TestModelBase() = default;
bool checkVariables() {
std::vector<std::string> vars;
for (const auto &var : this->ModelT::getAllVariables()) {
vars.push_back(var->name());
}
std::sort(vars.begin(), vars.end());
std::vector<std::string> expected_vars = {"V0", "V1", "V2", "V3", "O"};
std::sort(expected_vars.begin(), expected_vars.end());
return vars == expected_vars;
}
bool checkEvidences() {
std::map<std::string, std::size_t> ev, expected;
for (const auto &[var, val] : this->ModelT::state().evidences) {
ev[var->name()] = val;
}
expected.emplace("O", 1);
return ev == expected;
}
};
class TestModel : public TestModelBase<RandomField> {
public:
static const inline float alfa = 0.5f;
static const inline float beta = 0.7f;
static const inline float gamma = 1.2f;
TestModel() = default;
struct FillTag {};
TestModel(FillTag tag) {
auto V0 = make_variable(3, "V0");
auto V1 = make_variable(3, "V1");
auto V2 = make_variable(3, "V2");
auto V3 = make_variable(3, "V3");
auto O = make_variable(3, "O");
addConstFactor(make_corr_factor_ptr(V0, O));
addConstFactor(make_corr_factor_ptr(V1, O));
addConstFactor(make_corr_factor_ptr(V2, O));
addConstFactor(make_corr_factor_ptr(V3, O));
addTunableFactor(make_corr_expfactor_ptr(V0, V1, alfa));
addTunableFactor(make_corr_expfactor_ptr(V1, V2, beta));
addTunableFactor(make_corr_expfactor_ptr(V2, V3, gamma));
addTunableFactor(make_corr_expfactor_ptr(V3, V0, gamma),
VariablesSet{V2, V3});
setEvidence(O, 1);
}
VariablesSet makeVars(const std::string &first,
const std::string &second) const {
return VariablesSet{findVariable(first), findVariable(second)};
}
bool checkConstFactors() {
std::vector<std::set<std::string>> groups, expected;
for (const auto &factor : const_factors) {
groups.emplace_back(vars_names(factor->function().vars()));
}
expected = std::vector<VarNames>{
{"V0", "O"}, {"V1", "O"}, {"V2", "O"}, {"V3", "O"}};
sort_set(groups);
sort_set(expected);
return groups == expected;
}
bool checkTunablefactors() {
auto sort_map = [](std::map<float, std::vector<VarNames>> &subject) {
for (auto &[_, group] : subject) {
sort_set(group);
}
};
std::map<float, std::vector<VarNames>> groups, expected;
for (const auto &tuner : tuners) {
train::visitTuner(
tuner.get(),
[&groups](const train::BaseTuner &b) {
groups[b.getWeight()].emplace_back(
vars_names(b.getFactor().function().vars()));
},
[&groups](const train::CompositeTuner &c) {
auto &collection = groups[c.getWeight()];
for (const auto &f : c.getElements()) {
collection.emplace_back(
vars_names(static_cast<const train::BaseTuner &>(*f)
.getFactor()
.function()
.vars()));
}
});
}
expected = std::map<float, std::vector<VarNames>>{
{alfa, std::vector<VarNames>{{"V0", "V1"}}},
{beta, std::vector<VarNames>{{"V1", "V2"}}},
{gamma, std::vector<VarNames>{{"V2", "V3"}, {"V3", "V0"}}}};
sort_map(groups);
sort_map(expected);
return groups == expected;
}
};
} // namespace
TEST_CASE("xml managing", "[io][xml]") {
TestModel model{TestModel::FillTag{}};
const std::string temp_file = "./temp.xml";
io::xml::Exporter::exportToFile(model,
EFG::io::xml::ExportInfo{temp_file, "Model"});
SECTION("tunable model") {
TestModel model_imported;
EFG::io::xml::Importer::importFromFile(model_imported, temp_file);
CHECK(model_imported.checkVariables());
CHECK(model_imported.checkEvidences());
CHECK(model_imported.checkConstFactors());
CHECK(model_imported.checkTunablefactors());
}
SECTION("constant model") {
TestModelBase<Graph> model_imported;
EFG::io::xml::Importer::importFromFile(model_imported, temp_file);
CHECK(model_imported.checkVariables());
CHECK(model_imported.checkEvidences());
CHECK(model_imported.getConstFactors().size() == 8);
CHECK(model_imported.getAllFactors().size() == 8);
}
}
TEST_CASE("json managing", "[io][json]") {
TestModel model{TestModel::FillTag{}};
const std::string temp_file = "./temp.json";
EFG::io::json::Exporter::exportToFile(model, temp_file);
SECTION("tunable model") {
TestModel model_imported;
EFG::io::json::Importer::importFromFile(model_imported, temp_file);
CHECK(model_imported.checkVariables());
CHECK(model_imported.checkEvidences());
CHECK(model_imported.checkConstFactors());
CHECK(model_imported.checkTunablefactors());
}
SECTION("constant model") {
TestModelBase<Graph> model_imported;
EFG::io::json::Importer::importFromFile(model_imported, temp_file);
CHECK(model_imported.checkVariables());
CHECK(model_imported.checkEvidences());
CHECK(model_imported.getConstFactors().size() == 8);
CHECK(model_imported.getAllFactors().size() == 8);
}
}
} // namespace EFG::test
| 6,519
|
C++
|
.cpp
| 177
| 31.158192
| 80
| 0.644205
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,870
|
Utils.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Utils.cpp
|
#include "Utils.h"
#include <EasyFactorGraph/categoric/GroupRange.h>
#include <EasyFactorGraph/structure/GibbsSampler.h>
#include <math.h>
#include <sstream>
namespace EFG::test {
bool almost_equal_fnct(const factor::Function &a, const factor::Function &b) {
bool res = true;
a.forEachCombination<true>([&b, &res](const auto &comb, float img) {
if (!almost_equal(img, b.findTransformed(comb), 0.001f)) {
res = false;
}
});
return res;
}
categoric::Group make_group(const std::vector<std::size_t> &sizes) {
if (sizes.empty()) {
throw Error{"empty sizes"};
}
categoric::Group group{categoric::make_variable(sizes.front(), "V0")};
std::size_t count = 1;
std::for_each(sizes.begin() + 1, sizes.end(), [&group, &count](auto size) {
group.add(categoric::make_variable(size, "V" + std::to_string(count++)));
});
return group;
}
factor::Factor make_corr_factor(const categoric::VariablePtr &first,
const categoric::VariablePtr &second) {
return factor::Factor(categoric::Group{first, second},
factor::Factor::SimplyCorrelatedTag{});
}
std::shared_ptr<factor::Factor>
make_corr_factor_ptr(const categoric::VariablePtr &first,
const categoric::VariablePtr &second) {
return std::make_shared<factor::Factor>(
categoric::Group{first, second}, factor::Factor::SimplyCorrelatedTag{});
}
factor::FactorExponential
make_corr_expfactor(const categoric::VariablePtr &first,
const categoric::VariablePtr &second, float w) {
auto factor = make_corr_factor(first, second);
return factor::FactorExponential(factor, w);
}
std::shared_ptr<factor::FactorExponential>
make_corr_expfactor_ptr(const categoric::VariablePtr &first,
const categoric::VariablePtr &second, float w) {
auto factor = make_corr_factor(first, second);
return std::make_shared<factor::FactorExponential>(factor, w);
}
std::vector<float> make_prob_distr(const std::vector<float> &values) {
float coeff = 0;
for (const auto &val : values) {
coeff += val;
}
coeff = 1.f / coeff;
std::vector<float> result = values;
for (auto &val : result) {
val *= coeff;
}
return result;
}
void setAllImages(factor::Factor &subject, float img) {
categoric::GroupRange range{subject.function().vars()};
categoric::for_each_combination(
range, [&](const auto &comb) { subject.set(comb, img); });
}
CombinationsAndProbabilities
compute_combinations_and_probs(const strct::FactorsAware &model) {
categoric::Group all_vars(model.getAllVariables());
CombinationsAndProbabilities result;
std::vector<const factor::Immutable *> factors;
for (const auto &factor : model.getAllFactors()) {
factors.push_back(factor.get());
}
factor::Factor merged_sorted =
factor::Factor{factors}.cloneWithPermutedGroup(all_vars);
result.probs = merged_sorted.getProbabilities();
result.combinations.reserve(all_vars.size());
categoric::GroupRange range(all_vars);
categoric::for_each_combination(
range, [&combinations = result.combinations](const auto &comb) {
combinations.emplace_back(comb);
});
return result;
}
train::TrainSet make_good_trainset(const strct::FactorsAware &model,
std::size_t samples) {
auto &&[probs, combinations] = compute_combinations_and_probs(model);
std::vector<std::vector<std::size_t>> sampled;
sampled.reserve(samples);
strct::UniformSampler sampler;
sampler.resetSeed(0);
while (sampled.size() != samples) {
auto pos = sampler.sampleFromDiscrete(probs);
sampled.emplace_back(combinations[pos]);
}
return train::TrainSet{sampled};
}
LikelihoodGetter::LikelihoodGetter(const strct::FactorsAware &model)
: vars{model.getAllVariables()} {
const auto &factors = model.getAllFactors();
finders.reserve(factors.size());
for (const auto &factor : factors) {
finders.emplace_back(factor->makeFinder(vars.getVariables()));
}
};
float LikelihoodGetter::getLogActivation(
const std::vector<std::size_t> &c) const {
float res = 0.f;
for (const auto &finder : finders) {
res += logf(finder.findTransformed(c));
}
return res;
};
float LikelihoodGetter::getLogLikeliHood(
const EFG::train::TrainSet::Iterator &combinations) {
float Z = 0.f;
{
categoric::GroupRange range(categoric::Group{vars});
for_each_combination(range, [this, &Z](const auto &comb) {
Z += this->getLogActivation(comb);
});
}
float lkl = 0.f, coeff = 1.f / static_cast<float>(combinations.size());
combinations.forEachSample([this, &lkl, &coeff](const auto &comb) {
lkl += coeff * this->getLogActivation(comb);
});
return lkl - Z;
}
} // namespace EFG::test
| 4,761
|
C++
|
.cpp
| 130
| 32.430769
| 78
| 0.695624
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,871
|
ModelLibrary.cpp
|
andreacasalino_Easy-Factor-Graph/tests/ModelLibrary.cpp
|
#include "ModelLibrary.h"
#include "Utils.h"
namespace EFG::test::library {
const float SimpleTree::alfa = 1.f;
const float SimpleTree::beta = 2.f;
const float SimpleTree::gamma = 1.f;
const float SimpleTree::eps = 1.5f;
SimpleTree::SimpleTree() {
auto A = categoric::make_variable(2, "A");
auto B = categoric::make_variable(2, "B");
auto C = categoric::make_variable(2, "C");
auto D = categoric::make_variable(2, "D");
auto E = categoric::make_variable(2, "E");
addTunableFactor(make_corr_expfactor_ptr(A, B, alfa));
addTunableFactor(make_corr_expfactor_ptr(B, C, beta));
addTunableFactor(make_corr_expfactor_ptr(B, D, gamma));
addTunableFactor(make_corr_expfactor_ptr(D, E, eps));
}
ComplexTree::ComplexTree() {
categoric::VariablesSoup vars;
vars.push_back(nullptr);
for (std::size_t k = 1; k <= 13; ++k) {
vars.push_back(categoric::make_variable(2, "v" + std::to_string(k)));
}
const float w = 1.f;
addTunableFactor(make_corr_expfactor_ptr(vars[1], vars[4], w));
addTunableFactor(make_corr_expfactor_ptr(vars[2], vars[4], w));
addTunableFactor(make_corr_expfactor_ptr(vars[3], vars[5], w));
addTunableFactor(make_corr_expfactor_ptr(vars[4], vars[6], w));
addTunableFactor(make_corr_expfactor_ptr(vars[4], vars[7], w));
addTunableFactor(make_corr_expfactor_ptr(vars[5], vars[7], w));
addTunableFactor(make_corr_expfactor_ptr(vars[5], vars[8], w));
addTunableFactor(make_corr_expfactor_ptr(vars[6], vars[9], w));
addTunableFactor(make_corr_expfactor_ptr(vars[6], vars[10], w));
addTunableFactor(make_corr_expfactor_ptr(vars[7], vars[11], w));
addTunableFactor(make_corr_expfactor_ptr(vars[8], vars[12], w));
addTunableFactor(make_corr_expfactor_ptr(vars[8], vars[13], w));
}
const float SimpleLoopy::w = 1.f;
SimpleLoopy::SimpleLoopy() {
auto A = categoric::make_variable(2, "A");
auto B = categoric::make_variable(2, "B");
auto C = categoric::make_variable(2, "C");
auto D = categoric::make_variable(2, "D");
auto E = categoric::make_variable(2, "E");
addTunableFactor(make_corr_expfactor_ptr(A, B, w));
addTunableFactor(make_corr_expfactor_ptr(B, C, w));
addTunableFactor(make_corr_expfactor_ptr(B, D, w));
addTunableFactor(make_corr_expfactor_ptr(C, D, w));
addTunableFactor(make_corr_expfactor_ptr(E, D, w));
}
ComplexLoopy::ComplexLoopy() {
categoric::VariablesSoup vars;
vars.push_back(nullptr);
for (std::size_t k = 1; k <= 8; ++k) {
vars.push_back(categoric::make_variable(2, "v" + std::to_string(k)));
}
const float w = 1.f;
addTunableFactor(make_corr_expfactor_ptr(vars[1], vars[2], w));
addTunableFactor(make_corr_expfactor_ptr(vars[2], vars[4], w));
addTunableFactor(make_corr_expfactor_ptr(vars[2], vars[3], w));
addTunableFactor(make_corr_expfactor_ptr(vars[3], vars[4], w));
addTunableFactor(make_corr_expfactor_ptr(vars[4], vars[5], w));
addTunableFactor(make_corr_expfactor_ptr(vars[3], vars[5], w));
addTunableFactor(make_corr_expfactor_ptr(vars[4], vars[6], w));
addTunableFactor(make_corr_expfactor_ptr(vars[5], vars[7], w));
addTunableFactor(make_corr_expfactor_ptr(vars[6], vars[7], w));
addTunableFactor(make_corr_expfactor_ptr(vars[7], vars[8], w));
}
namespace {
std::string make_scalable_var_name(std::size_t counter) {
return "var_" + std::to_string(counter);
}
struct BinaryTreeContext {
model::RandomField &subject;
std::size_t var_size;
float w;
bool loopy;
};
void fill_scalable_model(const BinaryTreeContext &ctxt,
std::size_t remaining_levels, std::size_t parent,
std::size_t &counter) {
if (0 == remaining_levels) {
return;
}
categoric::VariablePtr parent_var;
if (0 == counter) {
++counter;
parent = counter;
parent_var =
categoric::make_variable(ctxt.var_size, make_scalable_var_name(parent));
} else {
parent_var = ctxt.subject.findVariable(make_scalable_var_name(parent));
}
auto add_child = [&]() {
++counter;
const auto new_var_id = counter;
auto new_var = categoric::make_variable(ctxt.var_size,
make_scalable_var_name(new_var_id));
ctxt.subject.addTunableFactor(
make_corr_expfactor_ptr(parent_var, new_var, ctxt.w));
fill_scalable_model(ctxt, remaining_levels - 1, new_var_id, counter);
return new_var;
};
auto left_var = add_child();
auto right_var = add_child();
if (ctxt.loopy) {
ctxt.subject.addTunableFactor(
make_corr_expfactor_ptr(left_var, right_var, ctxt.w));
}
}
} // namespace
ScalableModel::ScalableModel(std::size_t size, std::size_t var_size,
const bool loopy) {
if (0 == size) {
throw Error{"Invalid depth"};
}
std::size_t counter = 0;
fill_scalable_model(BinaryTreeContext{*this, var_size, 1.f, loopy}, size, 0,
counter);
}
categoric::VariablePtr ScalableModel::root() const {
return findVariable(make_scalable_var_name(1));
}
categoric::VariablePtr ScalableModel::nonRoot() const {
return findVariable(make_scalable_var_name(2));
}
} // namespace EFG::test::library
| 5,126
|
C++
|
.cpp
| 128
| 35.9375
| 80
| 0.681535
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,872
|
Test01-Range.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test01-Range.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <EasyFactorGraph/categoric/GroupRange.h>
#include <algorithm>
namespace EFG::test {
using namespace categoric;
TEST_CASE("testing for_each", "[range]") {
VariablePtr A = make_variable(2, "A");
VariablePtr B = make_variable(2, "B");
std::vector<std::vector<std::size_t>> expected = {
{0, 0}, {0, 1}, {1, 0}, {1, 1}};
std::vector<std::vector<std::size_t>> got;
std::for_each(GroupRange{{A, B}}, RANGE_END,
[&got](const auto &comb) { got.emplace_back(comb); });
CHECK(got == expected);
}
namespace {
std::vector<std::vector<std::size_t>>
all_combinations_in_range(GroupRange &range) {
std::vector<std::vector<std::size_t>> got;
for_each_combination(range,
[&got](const auto &comb) { got.emplace_back(comb); });
return got;
}
} // namespace
TEST_CASE("testing for_each_combination", "[range]") {
SECTION("small binary group") {
GroupRange rangeAB({make_variable(2, "A"), make_variable(2, "B")});
CHECK(
all_combinations_in_range(rangeAB) ==
std::vector<std::vector<std::size_t>>{{0, 0}, {0, 1}, {1, 0}, {1, 1}});
}
SECTION("big binary group") {
GroupRange rangeAB({make_variable(3, "A"), make_variable(4, "B")});
CHECK(all_combinations_in_range(rangeAB) ==
std::vector<std::vector<std::size_t>>{{0, 0},
{0, 1},
{0, 2},
{0, 3},
{1, 0},
{1, 1},
{1, 2},
{1, 3},
{2, 0},
{2, 1},
{2, 2},
{2, 3}});
}
SECTION("ternary group") {
GroupRange rangeAB(
{make_variable(3, "A"), make_variable(4, "B"), make_variable(2, "C")});
CHECK(all_combinations_in_range(rangeAB) ==
std::vector<std::vector<std::size_t>>{
{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 2, 0},
{0, 2, 1}, {0, 3, 0}, {0, 3, 1}, {1, 0, 0}, {1, 0, 1},
{1, 1, 0}, {1, 1, 1}, {1, 2, 0}, {1, 2, 1}, {1, 3, 0},
{1, 3, 1}, {2, 0, 0}, {2, 0, 1}, {2, 1, 0}, {2, 1, 1},
{2, 2, 0}, {2, 2, 1}, {2, 3, 0}, {2, 3, 1}});
}
}
} // namespace EFG::test
| 2,638
|
C++
|
.cpp
| 61
| 29.934426
| 79
| 0.438255
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,873
|
Test05-Evidences.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test05-Evidences.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <algorithm>
#include <sstream>
#include "Utils.h"
#include <EasyFactorGraph/structure/EvidenceManager.h>
#include <EasyFactorGraph/structure/FactorsConstManager.h>
namespace EFG::test {
using namespace categoric;
using namespace factor;
using namespace strct;
using namespace test;
namespace {
class EvidenceTest : public EvidenceSetter,
public EvidenceRemover,
protected FactorsConstInserter {
public:
VariablesSoup uVars;
VariablesSoup mVars;
VariablesSoup lVars;
EvidenceTest() {
auto connect = [this](const VariablePtr &a, const VariablePtr &b) {
addConstFactor(make_corr_factor_ptr(a, b));
};
auto createVariable = [](const std::string &name, std::size_t id) {
std::stringstream s;
s << name << id;
return make_variable(2, s.str());
};
this->uVars.reserve(3);
this->mVars.reserve(4);
this->lVars.reserve(3);
this->uVars.push_back(createVariable("A", 0));
this->mVars.push_back(createVariable("M", 0));
this->lVars.push_back(createVariable("L", 0));
connect(this->uVars.back(), this->mVars.back());
connect(this->lVars.back(), this->mVars.back());
for (std::size_t k = 1; k < 3; ++k) {
std::size_t s = this->mVars.size();
this->uVars.push_back(createVariable("A", k));
this->mVars.push_back(createVariable("M", k));
this->lVars.push_back(createVariable("L", k));
connect(this->uVars.back(), this->mVars.back());
connect(this->lVars.back(), this->mVars.back());
connect(this->uVars[s - 1], this->mVars.back());
connect(this->lVars[s - 1], this->mVars.back());
}
};
void clusterExists(const VariablesSet &vars) {
auto convert = [](const std::unordered_set<Node *> &nodes) {
VariablesSet res;
for (auto *node : nodes) {
res.emplace(node->variable);
}
return res;
};
const auto &clusters = state().clusters;
auto it =
std::find_if(clusters.begin(), clusters.end(),
[&](const auto &cl) { return convert(cl.nodes) == vars; });
if (it == clusters.end()) {
std::stringstream stream;
stream << "Hidden cluster: <";
for (const auto &var : vars) {
stream << ' ' << var->name();
}
stream << '>';
stream << " was not found";
throw Error{stream.str()};
}
};
};
} // namespace
TEST_CASE("testing evidence managing", "[evidence]") {
EvidenceTest model;
model.clusterExists(VariablesSet{model.getAllVariables().begin(),
model.getAllVariables().end()});
CHECK(model.getEvidences().empty());
model.setEvidence(model.mVars[1], 0);
model.clusterExists(
VariablesSet{model.uVars[0], model.mVars[0], model.lVars[0]});
model.clusterExists(VariablesSet{model.uVars[2], model.mVars[2],
model.lVars[2], model.uVars[1],
model.lVars[1]});
{
Evidences expected;
expected.emplace(model.mVars[1], 0);
CHECK(model.getEvidences() == expected);
}
model.setEvidence(model.mVars[2], 1);
model.clusterExists(
VariablesSet{model.uVars[0], model.mVars[0], model.lVars[0]});
model.clusterExists(VariablesSet{model.uVars[1]});
model.clusterExists(VariablesSet{model.uVars[2]});
model.clusterExists(VariablesSet{model.lVars[1]});
model.clusterExists(VariablesSet{model.lVars[2]});
{
Evidences expected;
expected.emplace(model.mVars[1], 0);
expected.emplace(model.mVars[2], 1);
CHECK(model.getEvidences() == expected);
}
}
TEST_CASE("evidence individual reset", "[evidence]") {
EvidenceTest model;
model.setEvidence(model.mVars[1], 0);
model.setEvidence(model.mVars[2], 0);
model.removeEvidence(model.mVars[2]);
model.clusterExists(
VariablesSet{model.uVars[0], model.mVars[0], model.lVars[0]});
model.clusterExists(VariablesSet{model.uVars[1], model.uVars[2],
model.lVars[1], model.lVars[2],
model.mVars[2]});
{
Evidences expected;
expected.emplace(model.mVars[1], 0);
CHECK(model.getEvidences() == expected);
}
model.removeEvidence(model.mVars[1]);
model.clusterExists(VariablesSet{model.getAllVariables().begin(),
model.getAllVariables().end()});
CHECK(model.getEvidences().empty());
}
TEST_CASE("evidence group reset", "[evidence]") {
EvidenceTest model;
model.setEvidence(model.mVars[1], 0);
model.setEvidence(model.mVars[2], 0);
model.removeEvidences(VariablesSet{model.mVars[1], model.mVars[2]});
model.clusterExists(VariablesSet{model.getAllVariables().begin(),
model.getAllVariables().end()});
CHECK(model.getEvidences().empty());
}
TEST_CASE("evidence total reset", "[evidence]") {
EvidenceTest model;
model.setEvidence(model.mVars[1], 0);
model.setEvidence(model.mVars[2], 0);
model.removeAllEvidences();
model.clusterExists(VariablesSet{model.getAllVariables().begin(),
model.getAllVariables().end()});
CHECK(model.getEvidences().empty());
CHECK_THROWS_AS(model.removeEvidence(model.mVars[2]), Error);
}
} // namespace EFG::test
| 5,361
|
C++
|
.cpp
| 143
| 31.167832
| 80
| 0.644012
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,874
|
Test02-Function-b.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test02-Function-b.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <math.h>
#include <EasyFactorGraph/Error.h>
#include <EasyFactorGraph/categoric/GroupRange.h>
#include <EasyFactorGraph/factor/Factor.h>
#include <EasyFactorGraph/factor/FactorExponential.h>
#include "Utils.h"
namespace EFG::test {
using namespace categoric;
using namespace factor;
namespace {
using CombinationsMap = std::vector<std::pair<std::vector<std::size_t>, float>>;
Factor make_factor(const VariablesSoup &vars, const CombinationsMap &map) {
Factor result(Group{vars});
for (const auto &[comb, img] : map) {
result.set(comb, img);
}
return result;
}
} // namespace
TEST_CASE("operations on distribution", "[function]") {
const VariablePtr A = make_variable(3, "A");
SECTION("unary factor") {
auto factor = make_factor({A}, {{std::vector<std::size_t>{0}, 1.f},
{std::vector<std::size_t>{1}, 2.f}});
CHECK(factor.function().findImage(std::vector<std::size_t>{0}) == 1.f);
CHECK(factor.function().findImage(std::vector<std::size_t>{1}) == 2.f);
CHECK(factor.function().findImage(std::vector<std::size_t>{2}) == 0);
}
const VariablePtr B = make_variable(4, "B");
SECTION("binary factor") {
auto factor = make_factor({A, B}, {{std::vector<std::size_t>{0, 1}, 1.f},
{std::vector<std::size_t>{1, 1}, 2.f},
{std::vector<std::size_t>{1, 3}, 0.5f},
{std::vector<std::size_t>{1, 2}, 0.7f}});
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 1}) == 1.f);
CHECK(factor.function().findImage(std::vector<std::size_t>{1, 1}) == 2.f);
CHECK(factor.function().findImage(std::vector<std::size_t>{1, 3}) == 0.5f);
CHECK(factor.function().findImage(std::vector<std::size_t>{1, 2}) == 0.7f);
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 2}) == 0);
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 3}) == 0);
}
const VariablePtr C = make_variable(2, "C");
SECTION("ternary factor") {
auto factor =
make_factor({A, B, C}, {{std::vector<std::size_t>{0, 1, 0}, 1.f},
{std::vector<std::size_t>{1, 1, 1}, 2.f},
{std::vector<std::size_t>{1, 3, 0}, 0.5f},
{std::vector<std::size_t>{1, 2, 1}, 0.7f}});
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 1, 0}) ==
1.f);
CHECK(factor.function().findImage(std::vector<std::size_t>{1, 1, 1}) ==
2.f);
CHECK(factor.function().findImage(std::vector<std::size_t>{1, 3, 0}) ==
0.5f);
CHECK(factor.function().findImage(std::vector<std::size_t>{1, 2, 1}) ==
0.7f);
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 2, 0}) == 0);
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 2, 1}) == 0);
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 3, 0}) == 0);
CHECK(factor.function().findImage(std::vector<std::size_t>{0, 3, 1}) == 0);
SECTION("variables substitution") {
const VariablesSoup new_vars =
VariablesSoup{make_variable(3, "A2"), make_variable(4, "B2"),
make_variable(2, "C2")};
factor.replaceVariables(new_vars);
const auto &vars = factor.function().vars().getVariables();
CHECK(vars[0]->name() == "A2");
CHECK(vars[1]->name() == "B2");
CHECK(vars[2]->name() == "C2");
const VariablesSoup new_vars_bad =
VariablesSoup{make_variable(5, "A2"), make_variable(2, "B2"),
make_variable(2, "C2")};
CHECK_THROWS_AS(factor.replaceVariables(new_vars_bad), Error);
}
SECTION("exponential wrap evaluation") {
const float w = 1.5f;
FactorExponential factor_exp(factor, w);
CHECK(factor_exp.function().findTransformed(
std::vector<std::size_t>{0, 1, 0}) == expf(w * 1.f));
CHECK(factor_exp.function().findTransformed(
std::vector<std::size_t>{1, 1, 1}) == expf(w * 2.f));
}
}
}
TEST_CASE("probabilties computation", "[function]") {
auto factor =
make_factor(VariablesSoup{make_variable(2, "A"), make_variable(2, "B")},
{{std::vector<std::size_t>{0, 0}, 1.f},
{std::vector<std::size_t>{0, 1}, 0.f},
{std::vector<std::size_t>{1, 0}, 0.f},
{std::vector<std::size_t>{1, 1}, 1.f}});
SECTION("probabilities") {
CHECK(test::almost_equal_it(factor.getProbabilities(),
std::vector<float>{0.5f, 0, 0, 0.5f}, 0.001f));
}
SECTION("exponential wrap probabilities") {
const float w = 1.5f;
FactorExponential factor_exp(factor, w);
const float big = expf(w);
const float small = 1.f;
const float cumul = 2.f * (small + big);
CHECK(test::almost_equal_it(factor_exp.getProbabilities(),
std::vector<float>{big / cumul, small / cumul,
small / cumul, big / cumul},
0.001f));
}
}
#include <EasyFactorGraph/factor/ImageFinder.h>
namespace {
std::vector<std::size_t> make_combination(std::size_t size, std::size_t val) {
std::vector<std::size_t> result;
result.reserve(size);
for (std::size_t k = 0; k < size; ++k) {
result.push_back(val);
}
return result;
}
} // namespace
TEST_CASE("bigger combination finder", "[function]") {
auto group_size = GENERATE(1, 2, 3);
VariablesSoup group;
for (int k = 0; k < group_size; ++k) {
group.push_back(make_variable(4, "V" + std::to_string(k)));
}
Factor factor(Group{group});
for (std::size_t k = 0; k < 2; ++k) {
factor.set(make_combination(group_size, k), 1.f);
}
VariablesSoup bigger_group;
for (int k = 0; k < group_size; ++k) {
bigger_group.push_back(group[k]);
bigger_group.push_back(make_variable(4, "V" + std::to_string(k) + "_bis"));
}
auto factor_finder = factor.makeFinder(bigger_group);
// 0, ... ,0
CHECK(factor_finder.findImage(make_combination(bigger_group.size(), 0)) ==
1.f);
// 1, ... ,1
CHECK(factor_finder.findImage(make_combination(bigger_group.size(), 1)) ==
1.f);
// 2, ... ,2
CHECK(factor_finder.findImage(make_combination(bigger_group.size(), 2)) == 0);
// 3, ... ,3
CHECK(factor_finder.findImage(make_combination(bigger_group.size(), 3)) == 0);
}
TEST_CASE("bigger combination finder again", "[function]") {
auto A = make_variable(3, "A");
auto B = make_variable(3, "B");
auto C = make_variable(3, "C");
auto D = make_variable(3, "D");
VariablesSoup bigger_group = {A, B, C, D};
Factor factor(Group{VariablesSoup{B, D}});
factor.set(std::vector<std::size_t>{0, 1}, 1.f);
factor.set(std::vector<std::size_t>{2, 1}, 2.f);
factor.set(std::vector<std::size_t>{1, 1}, 3.f);
auto finder = factor.makeFinder(bigger_group);
CHECK(finder.findImage(std::vector<std::size_t>{0, 0, 2, 1}) == 1.f);
CHECK(finder.findImage(std::vector<std::size_t>{2, 2, 0, 1}) == 2.f);
CHECK(finder.findImage(std::vector<std::size_t>{2, 1, 2, 1}) == 3.f);
}
} // namespace EFG::test
| 7,307
|
C++
|
.cpp
| 163
| 37.650307
| 80
| 0.588351
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,875
|
Test08-Gibbs.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test08-Gibbs.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <EasyFactorGraph/model/Graph.h>
#include "ModelLibrary.h"
#include "Utils.h"
#include <algorithm>
namespace EFG::test {
using namespace categoric;
using namespace model;
using namespace strct;
using namespace library;
namespace {
bool are_samples_valid(const std::vector<std::vector<std::size_t>> &samples,
const VariablesSoup &group) {
if (samples.empty()) {
return false;
}
auto bad_comb = [&group](const std::vector<std::size_t> &comb) {
if (comb.size() != group.size()) {
return true;
}
for (std::size_t k = 0; k < comb.size(); ++k) {
if (group[k]->size() <= comb[k]) {
return true;
}
}
return false;
};
return std::find_if(samples.begin(), samples.end(), bad_comb) ==
samples.end();
}
// frequency of var = 1 is returned
float getFrequency1(const std::vector<std::vector<std::size_t>> &samples,
const VariablesSoup &group, const VariablePtr &var) {
std::size_t varPos;
if (auto it = std::find(group.begin(), group.end(), var); it != group.end()) {
varPos = std::distance(group.begin(), it);
} else {
throw Error::make("Unable to find variable ", var->name());
}
std::size_t instances = 0;
for (const auto &sample : samples) {
if (sample[varPos] == 1) {
++instances;
}
}
return static_cast<float>(instances) / static_cast<float>(samples.size());
};
float getFrequency(const std::vector<std::vector<std::size_t>> &samples,
const std::vector<std::size_t> &comb_to_search) {
std::size_t result = 0;
for (const auto &sample : samples) {
if (sample == comb_to_search) {
++result;
}
}
float result2 =
static_cast<float>(result) / static_cast<float>(samples.size());
return result2;
}
bool check_second_prob(float expected_value_0, float expected_value_1,
float freq_1, float threshold = 0.05f) {
return almost_equal(make_prob_distr({expected_value_0, expected_value_1})[1],
freq_1, threshold);
}
} // namespace
TEST_CASE("binary factor gibbs sampling", "[gibbs_sampling]") {
Graph model;
auto w = GENERATE(0.5f, 1.f, 2.f);
model.addConstFactor(
make_corr_expfactor_ptr(make_variable(2, "A"), make_variable(2, "B"), w));
SECTION("combinations involving all variables") {
auto samples =
model.makeSamples(GibbsSampler::SamplesGenerationContext{500, 50, 0});
model.removeAllEvidences();
const float exp_w = expf(w);
const float Z = 2.f * (1.f + exp_w);
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 0}),
exp_w / Z, 0.075f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 1}),
1.f / Z, 0.075f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 0}),
1.f / Z, 0.075f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 1}),
exp_w / Z, 0.075f));
}
SECTION("specific variable frequency") {
model.setEvidence(model.findVariable("A"), 1);
auto samples =
model.makeSamples(GibbsSampler::SamplesGenerationContext{500, 50, 0});
REQUIRE(are_samples_valid(samples, model.getAllVariables()));
CHECK(check_second_prob(1.f, expf(w),
getFrequency1(samples, model.getAllVariables(),
model.findVariable("B"))));
}
}
namespace {
float getFrequency(const std::vector<std::vector<std::size_t>> &samples,
const std::vector<std::size_t> &comb_to_search,
const std::vector<std::size_t> &pos_to_search) {
std::size_t result = 0;
for (const auto &sample : samples) {
std::vector<std::size_t> sub_part;
sub_part.reserve(pos_to_search.size());
for (const auto &pos : pos_to_search) {
sub_part.push_back(sample.data()[pos]);
}
if (sub_part == comb_to_search) {
++result;
}
}
float result2 =
static_cast<float>(result) / static_cast<float>(samples.size());
return result2;
}
} // namespace
TEST_CASE("2 binary factors gibbs sampling", "[gibbs_sampling]") {
Graph model;
auto A = make_variable(2, "A");
auto B = make_variable(2, "B");
auto C = make_variable(2, "C");
float alfa = 0.3f;
model.addConstFactor(make_corr_expfactor_ptr(A, B, alfa));
float beta = 1.3f;
model.addConstFactor(make_corr_expfactor_ptr(B, C, beta));
auto samples =
model.makeSamples(GibbsSampler::SamplesGenerationContext{1000, 50, 0});
const float exp_alfa = expf(alfa);
const float exp_beta = expf(beta);
{
const float Z = 2.f * (1.f + exp_alfa);
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 0},
std::vector<std::size_t>{0, 1}),
exp_alfa / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 1},
std::vector<std::size_t>{0, 1}),
exp_alfa / Z, 0.05f));
}
{
const float Z = 2.f * (1.f + exp_beta);
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 0},
std::vector<std::size_t>{1, 2}),
exp_beta / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 1},
std::vector<std::size_t>{1, 2}),
exp_beta / Z, 0.05f));
}
{
const float Z = 2.f * (1.f + exp_alfa + exp_beta + exp_alfa * exp_beta);
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 0, 0}),
exp_alfa * exp_beta / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 0, 1}),
exp_alfa / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 1, 0}),
1.f / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{0, 1, 1}),
exp_beta / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 0, 0}),
exp_beta / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 0, 1}),
1.f / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 1, 0}),
exp_alfa / Z, 0.05f));
CHECK(almost_equal(getFrequency(samples, std::vector<std::size_t>{1, 1, 1}),
exp_alfa * exp_beta / Z, 0.05f));
}
}
TEST_CASE("polyTree gibbs sampling", "[gibbs_sampling]") {
SimpleTree model;
const float a = expf(SimpleTree::alfa);
const float b = expf(SimpleTree::beta);
const float g = expf(SimpleTree::gamma);
const float e = expf(SimpleTree::eps);
auto threads = GENERATE(1, 2);
float toll = (threads > 1) ? 0.1f : 0.06f;
// E=1
model.setEvidence(model.findVariable("E"), 1);
auto samples = model.makeSamples(
GibbsSampler::SamplesGenerationContext{1500, 50, 0}, threads);
REQUIRE(are_samples_valid(samples, model.getAllVariables()));
CHECK(check_second_prob(
(a * (g + e) + (1 + g * e)), ((g + e) + a * (1 + g * e)),
getFrequency1(samples, model.getAllVariables(), model.findVariable("A")),
toll));
CHECK(check_second_prob(
(g + e), (1 + g * e),
getFrequency1(samples, model.getAllVariables(), model.findVariable("B")),
toll));
CHECK(check_second_prob(
(b * (g + e) + (1 + g * e)), ((g + e) + b * (1 + g * e)),
getFrequency1(samples, model.getAllVariables(), model.findVariable("C")),
toll));
CHECK(check_second_prob(
1.f, e,
getFrequency1(samples, model.getAllVariables(), model.findVariable("D")),
toll));
}
TEST_CASE("loopy model gibbs sampling", "[gibbs_sampling]") {
SimpleLoopy model;
float M = expf(SimpleLoopy::w);
float M_alfa = powf(M, 3) + M + 2.f * powf(M, 2);
float M_beta = powf(M, 4) + 2.f * M + powf(M, 2);
auto threads = GENERATE(1, 2);
float toll = (threads > 1) ? 0.1f : 0.06f;
// E=1
model.setEvidence(model.findVariable("E"), 1);
auto samples = model.makeSamples(
GibbsSampler::SamplesGenerationContext{1500, 50, 0}, threads);
REQUIRE(are_samples_valid(samples, model.getAllVariables()));
CHECK(check_second_prob(
3.f * M + powf(M, 3), powf(M, 4) + 3.f * powf(M, 2),
getFrequency1(samples, model.getAllVariables(), model.findVariable("D")),
toll));
CHECK(check_second_prob(
M_alfa, M_beta,
getFrequency1(samples, model.getAllVariables(), model.findVariable("C")),
toll));
CHECK(check_second_prob(
M_alfa, M_beta,
getFrequency1(samples, model.getAllVariables(), model.findVariable("B")),
toll));
CHECK(check_second_prob(
M * M_alfa + M_beta, M_alfa + M * M_beta,
getFrequency1(samples, model.getAllVariables(), model.findVariable("A")),
toll));
}
} // namespace EFG::test
| 9,162
|
C++
|
.cpp
| 227
| 33.39207
| 80
| 0.601844
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,876
|
Test10-Learning.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test10-Learning.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include "Utils.h"
#include <EasyFactorGraph/categoric/GroupRange.h>
#include <EasyFactorGraph/factor/ImageFinder.h>
#include <EasyFactorGraph/model/ConditionalRandomField.h>
#include <EasyFactorGraph/model/RandomField.h>
#include <EasyFactorGraph/structure/QueryManager.h>
#include <EasyFactorGraph/structure/SpecialFactors.h>
#include <EasyFactorGraph/trainable/FactorsTunableManager.h>
#include <EasyFactorGraph/trainable/ModelTrainer.h>
#include <TrainingTools/iterative/solvers/GradientDescend.h>
#include <TrainingTools/iterative/solvers/GradientDescendConjugate.h>
#include <TrainingTools/iterative/solvers/QuasiNewton.h>
#include <algorithm>
#include <functional>
#include <limits>
#include <math.h>
#include "ModelLibrary.h"
namespace EFG::test {
using namespace categoric;
using namespace model;
using namespace train;
using namespace strct;
using namespace library;
namespace {
template <typename ModelT> class LearningTest {
public:
template <typename MakeModelPred> LearningTest(MakeModelPred &&pred) {
to_train = pred();
reference = pred();
}
LearningTest &threads(std::size_t threads) {
threads_ = threads;
return *this;
}
template <typename MakeSamplesPred>
LearningTest &samplesMaker(MakeSamplesPred &&pred) {
samplesMaker_ = std::forward<std::function<TrainSet(ModelT &)>>(pred);
return *this;
}
template <typename InitTrainerPred>
LearningTest &trainerInitialization(InitTrainerPred &&init) {
initTrainer =
std::forward<std::function<void(::train::IterativeTrainer &)>>(init);
return *this;
}
LearningTest &maxIterations(std::size_t iter) {
max_iterations = iter;
return *this;
}
LearningTest &stochGradPecentage(float val) {
stoch_percentage = val;
return *this;
}
LearningTest &checkWeightToll(float val) {
check_weights_toll = val;
return *this;
}
LearningTest &checkLikelihoodToll(float val) {
check_likelihood_trend_toll = val;
return *this;
}
LearningTest &checkMarginalsToll(float val) {
check_marginal_toll = val;
return *this;
}
template <typename TrainerT> bool train() {
set_ones(*to_train);
std::vector<std::vector<float>> wStory;
wStory.reserve(max_iterations);
TrainerWithStory<TrainerT> trainer{wStory};
trainer.setMaxIterations(max_iterations);
if (initTrainer) {
initTrainer(trainer);
}
TrainInfo info;
info.stochastic_percentage = stoch_percentage;
info.threads = threads_;
TrainSet samples = samplesMaker_(*reference);
train_model(*to_train, trainer, samples, info);
/////////////////// checks ///////////////////
return almost_equal_it(reference->getWeights(), to_train->getWeights(),
check_weights_toll) &&
checkLikelihoodTrend(wStory, samples.makeIterator()) &&
checkMarginals();
}
protected:
bool checkLikelihoodTrend(const std::vector<std::vector<float>> &wStory,
const TrainSet::Iterator &train_set) {
if (check_likelihood_trend_toll == std::numeric_limits<float>::max()) {
return true;
}
const auto final_w = to_train->getWeights();
LikelihoodGetter likelihood_aware(*to_train);
float prev_likelihood = -std::numeric_limits<float>::max();
for (const auto &w : wStory) {
to_train->setWeights(w);
float att_likelihood = likelihood_aware.getLogLikeliHood(train_set);
const bool ok =
(-check_likelihood_trend_toll) < (att_likelihood - prev_likelihood);
if (!ok) {
return false;
}
prev_likelihood = att_likelihood;
}
to_train->setWeights(final_w);
return true;
}
bool checkMarginals() {
if constexpr (!std::is_same<ConditionalRandomField, ModelT>::value) {
if (check_marginal_toll == std::numeric_limits<float>::max()) {
return true;
}
VariablesSoup hidden_vars;
{
const auto &hidden_set = to_train->getHiddenVariables();
hidden_vars = VariablesSoup{hidden_set.begin(), hidden_set.end()};
}
auto var_getter = [&reference =
*this->reference](const std::string &name) {
return reference.findVariable(name);
};
dynamic_cast<EvidenceSetter *>(to_train.get())
->setEvidence(hidden_vars.back(), 0);
dynamic_cast<EvidenceSetter *>(reference.get())
->setEvidence(var_getter(hidden_vars.back()->name()), 0);
for (std::size_t k = 0; k < (hidden_vars.size() - 1); ++k) {
auto marginals_trained =
dynamic_cast<QueryManager *>(to_train.get())
->getMarginalDistribution(hidden_vars[k]->name());
auto marginals_reference =
dynamic_cast<QueryManager *>(reference.get())
->getMarginalDistribution(hidden_vars[k]->name());
if (!almost_equal_it(marginals_trained, marginals_reference,
check_marginal_toll)) {
return false;
}
}
}
return true;
}
std::unique_ptr<ModelT> reference;
std::unique_ptr<ModelT> to_train;
std::size_t threads_ = 1;
std::function<TrainSet(ModelT &)> samplesMaker_;
std::size_t max_iterations = 30;
std::function<void(::train::IterativeTrainer &)> initTrainer;
float stoch_percentage = 1.f;
float check_weights_toll = 0.5f;
float check_likelihood_trend_toll = 5.f;
float check_marginal_toll = 0.15f;
template <typename TrainerBase> class TrainerWithStory : public TrainerBase {
public:
TrainerWithStory(std::vector<std::vector<float>> &wStory)
: wStory{wStory} {};
protected:
void updateDirection() override {
Eigen::VectorXd par = this->getParameters();
std::vector<float> w;
w.reserve(par.size());
for (Eigen::Index i = 0; i < par.size(); ++i) {
w.push_back(par(i));
}
this->wStory.emplace_back(std::move(w));
this->TrainerBase::updateDirection();
};
private:
std::vector<std::vector<float>> &wStory;
};
};
} // namespace
TEST_CASE("Small random field tuning", "[train]") {
LearningTest<RandomField> info([]() {
VariablePtr A = make_variable(3, "A");
VariablePtr B = make_variable(3, "B");
VariablePtr C = make_variable(3, "C");
std::unique_ptr<RandomField> subject = std::make_unique<RandomField>();
subject->copyConstFactor(
factor::FactorExponential{factor::Indicator{A, 0}, 1.f});
subject->addTunableFactor(make_corr_expfactor_ptr(A, B, 2.f));
subject->addTunableFactor(make_corr_expfactor_ptr(A, C, 0.5f));
return subject;
});
info.samplesMaker([](RandomField &reference) {
return make_good_trainset(reference, 500);
});
SECTION("Gradient Descend Fixed") {
info.trainerInitialization([](::train::IterativeTrainer &trainer) {
static_cast<::train::GradientDescendFixed &>(trainer).setOptimizationStep(
0.5f);
});
CHECK(info.train<::train::GradientDescendFixed>());
}
info.checkLikelihoodToll(std::numeric_limits<float>::max());
SECTION("Gradient Descend Adaptive") {
CHECK(info.train<::train::GradientDescend<::train::YundaSearcher>>());
}
SECTION("Gradient Descend Conjugate") {
CHECK(info.train<
::train::GradientDescendConjugate<::train::YundaSearcher>>());
}
SECTION("Quasi Newton") {
CHECK(info.train<
::train::QuasiNewton<::train::YundaSearcher, ::train::BFGS>>());
}
}
TEST_CASE("Medium random field tuning", "[train]") {
LearningTest<RandomField> info([]() {
VariablePtr A = make_variable(3, "A");
VariablePtr B = make_variable(3, "B");
VariablePtr C = make_variable(3, "C");
VariablePtr D = make_variable(3, "D");
VariablePtr E = make_variable(3, "E");
std::unique_ptr<RandomField> subject = std::make_unique<RandomField>();
subject->copyConstFactor(
factor::FactorExponential{factor::Indicator{A, 0}, 1.f});
subject->addTunableFactor(make_corr_expfactor_ptr(A, B, 2.f));
subject->addTunableFactor(make_corr_expfactor_ptr(A, C, 0.5f));
subject->addTunableFactor(make_corr_expfactor_ptr(A, D, 2.f));
subject->addTunableFactor(make_corr_expfactor_ptr(A, E, 0.5f));
return subject;
});
SECTION("Full training set") {
info.samplesMaker([](RandomField &reference) {
return make_good_trainset(reference, 1000);
});
SECTION("Gradient Descend Fixed") {
info.trainerInitialization([](::train::IterativeTrainer &trainer) {
static_cast<::train::GradientDescendFixed &>(trainer)
.setOptimizationStep(0.2f);
});
auto threads = GENERATE(1, 2, 4);
info.threads(threads);
CHECK(info.train<::train::GradientDescendFixed>());
}
info.checkLikelihoodToll(std::numeric_limits<float>::max());
SECTION("Gradient Descend Adaptive") {
CHECK(info.train<::train::GradientDescend<::train::YundaSearcher>>());
}
SECTION("Gradient Descend Conjugate") {
CHECK(info.train<
::train::GradientDescendConjugate<::train::YundaSearcher>>());
}
SECTION("Quasi Newton") {
CHECK(info.train<
::train::QuasiNewton<::train::YundaSearcher, ::train::BFGS>>());
}
}
SECTION("Stochastic training set") {
info.samplesMaker([](RandomField &reference) {
return make_good_trainset(reference, 5000);
})
.checkLikelihoodToll(std::numeric_limits<float>::max())
.stochGradPecentage(0.2f);
SECTION("Gradient Descend Fixed") {
info.trainerInitialization([](::train::IterativeTrainer &trainer) {
static_cast<::train::GradientDescendFixed &>(trainer)
.setOptimizationStep(0.2f);
});
CHECK(info.train<::train::GradientDescendFixed>());
}
///////////////// temporarely disabled /////////////////
// SECTION("Gradient Descend Adaptive") {
// CHECK(info.train<::train::GradientDescend<::train::YundaSearcher>>());
// }
// SECTION("Gradient Descend Conjugate") {
// CHECK(info.train<
// ::train::GradientDescendConjugate<::train::YundaSearcher>>());
// }
// SECTION("Quasi Newton") {
// CHECK(info.train<
// ::train::QuasiNewton<::train::YundaSearcher, ::train::BFGS>>());
// }
}
}
TEST_CASE("Small conditional random field tuning", "[train]") {
LearningTest<ConditionalRandomField> info([]() {
VariablePtr A = make_variable(3, "A");
VariablePtr B = make_variable(3, "B");
VariablePtr C = make_variable(3, "C");
RandomField reference_model_temp;
reference_model_temp.copyConstFactor(
factor::FactorExponential{factor::Indicator{A, 0}, 1.f});
reference_model_temp.addTunableFactor(make_corr_expfactor_ptr(A, B, 2.f));
reference_model_temp.addTunableFactor(make_corr_expfactor_ptr(A, C, 0.5f));
reference_model_temp.setEvidence(B, 0);
reference_model_temp.setEvidence(C, 0);
return std::make_unique<ConditionalRandomField>(reference_model_temp,
false);
});
info.samplesMaker([](ConditionalRandomField &reference) {
return make_good_trainset(reference, 1000);
})
.checkMarginalsToll(std::numeric_limits<float>::max());
SECTION("Gradient Descend Fixed") {
info.trainerInitialization([](::train::IterativeTrainer &trainer) {
static_cast<::train::GradientDescendFixed &>(trainer).setOptimizationStep(
0.2f);
});
CHECK(info.train<::train::GradientDescendFixed>());
}
info.checkLikelihoodToll(std::numeric_limits<float>::max());
SECTION("Gradient Descend Adaptive") {
CHECK(info.train<::train::GradientDescend<::train::YundaSearcher>>());
}
SECTION("Gradient Descend Conjugate") {
CHECK(info.train<
::train::GradientDescendConjugate<::train::YundaSearcher>>());
}
SECTION("Quasi Newton") {
CHECK(info.train<
::train::QuasiNewton<::train::YundaSearcher, ::train::BFGS>>());
}
}
#include <sstream>
namespace {
void make_shared_w_chain(RandomField &model, std::size_t size, float alfa,
float beta) {
auto make_var_name = [](char name, std::size_t pos) {
std::stringstream stream;
stream << name << std::to_string(pos);
return stream.str();
};
auto make_vars_set = [&model](const std::vector<std::string> &names) {
VariablesSet result;
for (const auto &name : names) {
result.emplace(model.findVariable(name));
}
return result;
};
for (std::size_t k = 0; k < size; ++k) {
auto Y = make_variable(3, make_var_name('Y', k));
auto X = make_variable(3, make_var_name('X', k));
auto pot_XY = make_corr_expfactor_ptr(X, Y, beta);
if (0 == k) {
model.addTunableFactor(pot_XY);
} else {
model.addTunableFactor(pot_XY, make_vars_set({"X0", "Y0"}));
auto pot_YY = make_corr_expfactor_ptr(
Y, model.findVariable(make_var_name('Y', k - 1)), alfa);
if (1 == k) {
model.addTunableFactor(pot_YY);
} else {
model.addTunableFactor(pot_YY, make_vars_set({"Y0", "Y1"}));
}
}
}
}
} // namespace
TEST_CASE("Shared weights tuning", "[train]") {
auto chain_size = GENERATE(3, 6);
LearningTest<RandomField> info([size = chain_size]() {
auto subject = std::make_unique<RandomField>();
make_shared_w_chain(*subject, size, 0.7f, 1.2f);
return subject;
});
info.samplesMaker([](RandomField &reference) {
return make_good_trainset(reference, 1000);
})
.checkLikelihoodToll(std::numeric_limits<float>::max())
.checkMarginalsToll(std::numeric_limits<float>::max());
SECTION("Gradient Descend Fixed") {
info.trainerInitialization([](::train::IterativeTrainer &trainer) {
static_cast<::train::GradientDescendFixed &>(trainer).setOptimizationStep(
0.5f);
});
CHECK(info.train<::train::GradientDescendFixed>());
}
SECTION("Quasi Newton") {
CHECK(info.train<
::train::QuasiNewton<::train::YundaSearcher, ::train::BFGS>>());
}
}
/*
namespace {
std::vector<std::size_t> make_ones(std::size_t size) {
std::vector<std::size_t> result;
result.resize(size);
for (auto &val : result) {
val = 0;
}
return result;
}
} // namespace
TEST_CASE("Train with Pool efficiency", "[train][!mayfail]") {
auto depth = GENERATE(8, 10);
ScalableModel model{static_cast<std::size_t>(depth), 3, false};
std::unique_ptr<TrainSet> train_set;
{
const std::size_t train_set_size = 500;
std::vector<std::vector<std::size_t>> samples;
samples.reserve(train_set_size);
for (std::size_t k = 0; k < train_set_size; ++k) {
samples.emplace_back(make_ones(model.getAllVariables().size()));
}
train_set = std::make_unique<TrainSet>(samples);
}
auto measure_time =
[&](std::size_t threads,
FactorsTunableGetter &subject) -> std::chrono::nanoseconds {
::train::GradientDescendFixed trainer;
trainer.setMaxIterations(20);
trainer.setOptimizationStep(static_cast<float>(1e-5));
return test::measure_time([&]() {
train_model(subject, trainer, *train_set,
EFG::train::TrainInfo{threads, 1.f});
});
};
auto single_thread_time = measure_time(1, model);
auto multi_thread_time = measure_time(2, model);
CHECK(static_cast<double>(multi_thread_time.count()) <
static_cast<double>(single_thread_time.count()));
SECTION("conditional model") {
model.setEvidence(model.root(), 0);
ConditionalRandomField as_conditional_random_field(model, false);
single_thread_time = measure_time(1, as_conditional_random_field);
multi_thread_time = measure_time(2, as_conditional_random_field);
CHECK(static_cast<double>(multi_thread_time.count()) <
static_cast<double>(single_thread_time.count()));
}
}
*/
} // namespace EFG::test
| 15,922
|
C++
|
.cpp
| 424
| 32.066038
| 80
| 0.660215
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,531,877
|
Test03-SpecialFactor.cpp
|
andreacasalino_Easy-Factor-Graph/tests/Test03-SpecialFactor.cpp
|
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <EasyFactorGraph/factor/FactorExponential.h>
#include <EasyFactorGraph/structure/SpecialFactors.h>
#include "Utils.h"
namespace EFG::test {
using namespace categoric;
using namespace factor;
TEST_CASE("Unary factor ones at init", "[factor-special]") {
auto var = make_variable(3, "A");
MergedUnaries factor(var);
REQUIRE(factor.function().vars().getVariables() == VariablesSoup{var});
std::vector<float> imgs;
factor.function().forEachCombination<false>(
[&imgs](const auto &, float img) { imgs.push_back(img); });
CHECK(imgs == std::vector<float>{1.f, 1.f, 1.f});
}
TEST_CASE("Unary factor merge factors", "[factor-special]") {
auto var = make_variable(3, "A");
Factor distr_1(Group{var});
test::setAllImages(distr_1, 1.f);
distr_1.set(std::vector<std::size_t>{0}, 0.1f);
Factor distr_2(Group{var});
test::setAllImages(distr_2, 1.f);
distr_1.set(std::vector<std::size_t>{1}, 0.2f);
Factor distr_3(Group{var});
test::setAllImages(distr_3, 1.f);
distr_1.set(std::vector<std::size_t>{2}, 0.3f);
MergedUnaries factor(
std::vector<const Immutable *>{&distr_1, &distr_2, &distr_3});
REQUIRE(factor.function().vars().getVariables() == VariablesSoup{var});
factor::Function expected_distr{Group{var}};
expected_distr.set(std::vector<std::size_t>{0}, 0.1f / 0.3f);
expected_distr.set(std::vector<std::size_t>{1}, 0.2f / 0.3f);
expected_distr.set(std::vector<std::size_t>{2}, 0.3f / 0.3f);
CHECK(test::almost_equal_fnct(factor.function(), expected_distr));
}
TEST_CASE("Indicator", "[factor-special]") {
auto var = make_variable(3, "A");
Indicator factor(var, 1);
factor::Function expected_distr{Group{var}};
expected_distr.set(std::vector<std::size_t>{0}, 0);
expected_distr.set(std::vector<std::size_t>{1}, 1.f);
expected_distr.set(std::vector<std::size_t>{2}, 0);
CHECK(test::almost_equal_fnct(factor.function(), expected_distr));
}
namespace {
auto make_exp_test_group() {
return test::make_group(std::vector<std::size_t>{
2,
2,
});
}
FactorExponential make_exp_test_factor(float w) {
return FactorExponential{
Factor{make_exp_test_group(), Factor::SimplyCorrelatedTag{}}, w};
}
} // namespace
TEST_CASE("Evidence", "[factor-special]") {
const float w = 1.3f;
auto factor = make_exp_test_factor(w);
Evidence evidence(factor, factor.function().vars().getVariables()[0], 1);
CHECK(evidence.function().vars().getVariables().front() ==
factor.function().vars().getVariables()[1]);
factor::Function expected_distr{ Group{make_variable(2, "A")}};
expected_distr.set(std::vector<std::size_t>{0}, 1.f);
expected_distr.set(std::vector<std::size_t>{1}, exp(w));
CHECK(test::almost_equal_fnct(evidence.function(), expected_distr));
}
TEST_CASE("Message", "[factor-special]") {
const float w = 1.3f;
const float g = 0.6f;
auto factor_AB = make_exp_test_factor(w);
auto A = factor_AB.function().vars().getVariables().front();
auto B = factor_AB.function().vars().getVariables().back();
Factor shape_A(Group{A});
shape_A.set(std::vector<std::size_t>{0}, 0.5f);
shape_A.set(std::vector<std::size_t>{1}, 1.f);
FactorExponential factor_A(shape_A, g);
UnaryFactor factor_A_normalized =
MergedUnaries{std::vector<const Immutable *>{&factor_A}};
std::vector<float> values;
factor_A_normalized.function().forEachCombination<true>(
[&values](const auto &, float img) { values.push_back(img); });
SECTION("SUM") {
MessageSUM message(factor_A_normalized, factor_AB);
factor::Function expected_distr{Group{B}};
expected_distr.set(std::vector<std::size_t>{0},
exp(w) * values.front() + values.back());
expected_distr.set(std::vector<std::size_t>{1},
values.front() + exp(w) * values.back());
CHECK(test::almost_equal_fnct(message.function(), expected_distr));
}
SECTION("MAP") {
MessageMAP message(factor_A_normalized, factor_AB);
factor::Function expected_distr{Group{B}};
expected_distr.set(std::vector<std::size_t>{0},
std::max<float>(exp(w) * values.front(), values.back()));
expected_distr.set(std::vector<std::size_t>{1},
std::max<float>(values.front(), exp(w) * values.back()));
CHECK(test::almost_equal_fnct(message.function(), expected_distr));
}
}
} // namespace EFG::test
| 4,474
|
C++
|
.cpp
| 104
| 38.913462
| 80
| 0.673037
|
andreacasalino/Easy-Factor-Graph
| 32
| 4
| 1
|
GPL-3.0
|
9/20/2024, 10:43:29 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.