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,532,922
|
FTmodulatorI.cpp
|
essej_freqtweak/src/FTmodulatorI.cpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "FTmodulatorI.hpp"
#include <algorithm>
using namespace std;
using namespace PBD;
FTmodulatorI::FTmodulatorI(string confname, string name, nframes_t samplerate, unsigned int fftn)
: _inited(false), _name(name), _confname(confname), _userName("Unnamed"), _bypassed(false),
_sampleRate(samplerate), _fftN(fftn)
{
}
FTmodulatorI::~FTmodulatorI()
{
clearSpecMods();
GoingAway(this); // emit
}
void FTmodulatorI::goingAway(FTspectrumModifier * ft)
{
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
_specMods.remove (ft);
}
void FTmodulatorI::addSpecMod (FTspectrumModifier * specmod)
{
if (!specmod) return;
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
if (find(_specMods.begin(), _specMods.end(), specmod) == _specMods.end())
{
specmod->registerListener(this);
_specMods.push_back (specmod);
}
}
void FTmodulatorI::removeSpecMod (FTspectrumModifier * specmod)
{
if (!specmod) return;
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
_specMods.remove (specmod);
specmod->unregisterListener(this);
specmod->setDirty(false);
}
void FTmodulatorI::clearSpecMods ()
{
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
for (SpecModList::iterator iter = _specMods.begin(); iter != _specMods.end(); ++iter)
{
(*iter)->unregisterListener(this);
(*iter)->setDirty(false);
}
_specMods.clear();
}
void FTmodulatorI::getSpecMods (SpecModList & mods)
{
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
mods.insert (mods.begin(), _specMods.begin(), _specMods.end());
}
bool FTmodulatorI::hasSpecMod (FTspectrumModifier *specmod)
{
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
return (find(_specMods.begin(), _specMods.end(), specmod) != _specMods.end());
}
| 2,573
|
C++
|
.cpp
| 78
| 31.217949
| 97
| 0.736077
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,923
|
FTprocCompressor.cpp
|
essej_freqtweak/src/FTprocCompressor.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTprocCompressor.hpp"
#include "FTutils.hpp"
#include <cmath>
using namespace std;
#include <stdlib.h>
/**
* the following taken from SWH plugins utility functions
* we'll wrap it up later
*/
#define A_TBL 256
static inline float rms_env_process(rms_env *r, float x);
inline static float rms_env_process(rms_env *r, const float x)
{
r->sum -= r->buffer[r->pos];
r->sum += x;
r->buffer[r->pos] = x;
r->pos = (r->pos + 1) & (RMS_BUF_SIZE - 1);
return FTutils::fast_square_root(r->sum / (float)RMS_BUF_SIZE);
}
static void rms_env_reset(rms_env *r)
{
unsigned int i;
for (i=0; i<RMS_BUF_SIZE; i++) {
r->buffer[i] = 0.0f;
}
r->pos = 0;
r->sum = 0.0f;
}
static rms_env *rms_env_new()
{
rms_env *nenv = new rms_env;
rms_env_reset(nenv);
return nenv;
}
static void rms_env_free(rms_env *r)
{
delete r;
}
static inline int f_round(float f) {
ls_pcast32 p;
p.f = f;
p.f += (3<<22);
return p.i - 0x4b400000;
}
FTprocCompressor::FTprocCompressor (nframes_t samprate, unsigned int fftn)
: FTprocI("Compressor", samprate, fftn)
, _dbAdjust(12.0)
{
_confname = "Compressor";
}
FTprocCompressor::FTprocCompressor (const FTprocCompressor & other)
: FTprocI (other._name, other._sampleRate, other._fftN)
, _dbAdjust(12.0)
{
_confname = "Compressor";
}
void FTprocCompressor::initialize()
{
// create filter
_thresh_filter = new FTspectrumModifier("Comp Thresh", "compressor_thresh", 0, FTspectrumModifier::DB_MODIFIER, COMPRESS_SPECMOD, _fftN/2, 0.0);
_thresh_filter->setRange(-60.0, 0.0);
_filterlist.push_back (_thresh_filter);
_ratio_filter = new FTspectrumModifier("Comp Ratio", "compressor_ratio", 1, FTspectrumModifier::RATIO_MODIFIER, COMPRESS_SPECMOD, _fftN/2, 1.0);
_ratio_filter->setRange(1.0, 20.0);
_filterlist.push_back (_ratio_filter);
_release_filter = new FTspectrumModifier("Comp A/R", "compressor_release", 2, FTspectrumModifier::TIME_MODIFIER, COMPRESS_SPECMOD, _fftN/2, 0.2);
_release_filter->setRange(0.0, 1.0);
_filterlist.push_back (_release_filter);
_attack_filter = new FTspectrumModifier("Comp A/R", "compressor_attack", 2, FTspectrumModifier::TIME_MODIFIER, COMPRESS_SPECMOD, _fftN/2, 0.1);
_attack_filter->setRange(0.0, 1.0);
_filterlist.push_back (_attack_filter);
_makeup_filter = new FTspectrumModifier("Comp Makeup", "compressor_makeup", 3, FTspectrumModifier::DB_MODIFIER, COMPRESS_SPECMOD, _fftN/2, 0.0);
_makeup_filter->setRange(0.0, 32.0);
_filterlist.push_back (_makeup_filter);
// state
unsigned int nbins = _fftN >> 1;
_rms = new rms_env*[nbins];
_sum = new float[nbins];
_amp = new float[nbins];
_gain = new float[nbins];
_gain_t = new float[nbins];
_env = new float[nbins];
_count = new unsigned int[nbins];
for (unsigned int n=0; n < nbins; ++n)
{
_rms[n] = rms_env_new();
}
memset(_sum, 0, nbins * sizeof(float));
memset(_amp, 0, nbins * sizeof(float));
memset(_gain, 0, nbins * sizeof(float));
memset(_gain_t, 0, nbins * sizeof(float));
memset(_env, 0, nbins * sizeof(float));
memset(_count, 0, nbins * sizeof(unsigned int));
_as = new float[A_TBL];
_as[0] = 1.0f;
for (unsigned int i=1; i<A_TBL; i++) {
_as[i] = expf(-1.0f / ((_sampleRate/(_oversamp*(float)_fftN)) * (float)i / (float)A_TBL));
}
_inited = true;
}
void FTprocCompressor::setOversamp (int osamp)
{
FTprocI::setOversamp(osamp);
for (unsigned int i=1; i<A_TBL; i++) {
_as[i] = expf(-1.0f / ((_sampleRate/(_oversamp*(float)_fftN)) * (float)i / (float)A_TBL));
}
}
void FTprocCompressor::setFFTsize (unsigned int fftn)
{
// This must be called when we are not active, don't worry
unsigned int orignbins = _fftN >> 1;
FTprocI::setFFTsize(fftn);
// reallocate all state arrays
for (unsigned int n=0; n < orignbins; ++n)
{
rms_env_free(_rms[n]);
}
delete [] _rms;
delete [] _sum;
delete [] _amp;
delete [] _gain;
delete [] _gain_t;
delete [] _env;
delete [] _count;
unsigned int nbins = _fftN >> 1;
_rms = new rms_env*[nbins];
_sum = new float[nbins];
_amp = new float[nbins];
_gain = new float[nbins];
_gain_t = new float[nbins];
_env = new float[nbins];
_count = new unsigned int [nbins];
for (unsigned int n=0; n < nbins; ++n)
{
_rms[n] = rms_env_new();
}
memset(_sum, 0, nbins * sizeof(float));
memset(_amp, 0, nbins * sizeof(float));
memset(_gain, 0, nbins * sizeof(float));
memset(_gain_t, 0, nbins * sizeof(float));
memset(_env, 0, nbins * sizeof(float));
memset(_count, 0, nbins * sizeof(unsigned int));
_as[0] = 1.0f;
for (unsigned int i=1; i<A_TBL; i++) {
_as[i] = expf(-1.0f / ((_sampleRate/((float)4*_fftN)) * (float)i / (float)A_TBL));
}
}
FTprocCompressor::~FTprocCompressor()
{
if (!_inited) return;
_filterlist.clear();
delete _thresh_filter;
delete _ratio_filter;
delete _attack_filter;
delete _release_filter;
delete _makeup_filter;
}
void FTprocCompressor::process (fft_data *data, unsigned int fftn)
{
if (!_inited || _thresh_filter->getBypassed()) {
return;
}
float *threshold = _thresh_filter->getValues();
float *ratio = _ratio_filter->getValues();
float *attack = _attack_filter->getValues();
float *release = _release_filter->getValues();
float *makeup = _makeup_filter->getValues();
const float knee = 5.0;
float ga;
float gr;
float rs;
float mug;
float knee_min;
float knee_max;
float ef_a;
float ef_ai;
float thresh;
float rat;
float att, rel;
int fftN2 = (fftn+1) >> 1;
for (int i = 0; i < fftN2-1; i++)
{
// if (filter[i] > max) filt = max;
// else if (filter[i] < min) filt = min;
// else filt = filter[i];
// power = (data[i] * data[i]) + (data[fftn-i] * data[fftn-i]);
// db = FTutils::powerLogScale (power, 0.0000000) + _dbAdjust; // total fudge factors
thresh = LIMIT(threshold[i], -60.0f, 0.0f) + _dbAdjust;
rat = LIMIT(ratio[i], 1.0f, 80.0f);
att = LIMIT(attack[i], 0.002f, 1.0f);
rel = LIMIT(release[i], att, 1.0f);
ga = _as[f_round(att * (float)(A_TBL-1))];
gr = _as[f_round(rel * (float)(A_TBL-1))];
rs = (rat - 1.0f) / rat;
mug = db2lin(LIMIT(makeup[i], 0.0f, 32.0f));
knee_min = db2lin(thresh - knee);
knee_max = db2lin(thresh + knee);
ef_a = ga * 0.25f;
ef_ai = 1.0f - ef_a;
//_sum[i] += FTutils::fast_square_root((data[i] * data[i]) + (data[fftn-i] * data[fftn-i]));
if (i == 0) {
_sum[i] += (data[i] * data[i]);
}
else {
_sum[i] += (data[i] * data[i]) + (data[fftn-i] * data[fftn-i]);
}
// _sum[i] = FLUSH_TO_ZERO(_sum[i]);
// _env[i] = FLUSH_TO_ZERO(_env[i]);
// _amp[i] = FLUSH_TO_ZERO(_amp[i]);
// _rms[i]->sum = FLUSH_TO_ZERO(_rms[i]->sum);
// _gain[i] = FLUSH_TO_ZERO(_gain[i]);
if (_amp[i] > _env[i]) {
_env[i] = _env[i] * ga + _amp[i] * (1.0f - ga);
}
else {
_env[i] = _env[i] * gr + _amp[i] * (1.0f - gr);
}
if (_count[i]++ % 4 == 3)
{
_amp[i] = rms_env_process(_rms[i], _sum[i] * 0.25f);
_sum[i] = 0.0f;
if (_env[i] <= knee_min) {
_gain_t[i] = 1.0f;
} else if (_env[i] < knee_max) {
const float x = -(thresh - knee - lin2db(_env[i])) / knee;
_gain_t[i] = db2lin(-knee * rs * x * x * 0.25f);
} else {
_gain_t[i] = db2lin((thresh - lin2db(_env[i])) * rs);
}
}
_gain[i] = _gain[i] * ef_a + _gain_t[i] * ef_ai;
data[i] *= _gain[i] * mug;
if (i > 0) {
data[fftn-i] *= _gain[i] * mug;
}
}
}
| 8,113
|
C++
|
.cpp
| 255
| 29.356863
| 146
| 0.6459
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,924
|
FTconfigManager.cpp
|
essej_freqtweak/src/FTconfigManager.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <cstdio>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <climits>
#include <wx/wx.h>
#include <wx/dir.h>
#include <wx/textfile.h>
#include <wx/filename.h>
#include "FTconfigManager.hpp"
#include "FTspectrumModifier.hpp"
#include "FTspectralEngine.hpp"
#include "FTioSupport.hpp"
#include "FTprocessPath.hpp"
#include "FTdspManager.hpp"
#include "FTmodulatorManager.hpp"
#include "FTprocI.hpp"
#include "FTmodulatorI.hpp"
#include "version.h"
#include "xml++.hpp"
using namespace std;
FTconfigManager::FTconfigManager(const std::string & basedir)
: _basedir (basedir)
{
if (_basedir.empty()) {
_basedir = (wxGetHomeDir() + wxFileName::GetPathSeparator() + wxT(".freqtweak")).fn_str();
}
// try to create basedir if it doesn't exist
//wxDir bdir(_basedir);
if ( ! wxDir::Exists(wxString::FromAscii (_basedir.c_str())) ) {
if (mkdir ( _basedir.c_str(), 0755 )) {
fprintf (stderr, "Error creating %s\n", _basedir.c_str());
}
else {
fprintf(stderr, "Created settings directory: %s\n", _basedir.c_str());
}
}
else {
//printf ("config dir exists\n");
}
// make basedir/presets dir
wxString predir (wxString::FromAscii (_basedir.c_str()) + wxFileName::GetPathSeparator() + wxT("presets"));
if ( ! wxDir::Exists(predir) ) {
if (mkdir (predir.fn_str(), 0755 )) {
fprintf (stderr, "Error creating %s\n", static_cast<const char *> (predir.mb_str()));
}
else {
fprintf(stderr, "Created presets directory: %s\n", static_cast<const char *> (predir.mb_str()));
}
}
else {
//printf ("config_presets dir exists\n");
}
}
FTconfigManager::~FTconfigManager()
{
}
bool FTconfigManager::storeSettings (const std::string &name, bool uselast)
{
if (!uselast && (name == "")) {
return false;
}
wxString dirname (wxString::FromAscii (_basedir.c_str()) + wxFileName::GetPathSeparator());
// directory to store settings
if (uselast)
{
dirname += wxT("last_setting");
}
else
{
dirname += (wxString (wxT("presets"))
+ wxFileName::GetPathSeparator()
+ wxString::FromAscii(name.c_str()));
}
std::cout<< "storing setting '"
<< (name.empty() ? "(last setting)" : name)
<< "' to directory '"
<< static_cast<const char *> (dirname.mb_str())
<< "'"
<< std::endl;
if ( ! wxDir::Exists(dirname) ) {
if (mkdir ( dirname.fn_str(), 0755 )) {
printf ("Error creating %s\n", static_cast<const char *> (dirname.mb_str()));
return false;
}
}
FTioSupport * iosup = FTioSupport::instance();
// remove all of our files
wxDir dir(dirname);
if ( !dir.IsOpened() )
{
return false;
}
wxString filename;
bool cont = dir.GetFirst(&filename);
while ( cont )
{
//printf ("%s\n", filename.c_str());
unlink ( (dirname + wxFileName::GetPathSeparator() + filename).fn_str() );
cont = dir.GetNext(&filename);
}
// make xmltree
XMLTree configdoc;
XMLNode * rootNode = new XMLNode("Preset");
rootNode->add_property("version", freqtweak_version);
configdoc.set_root (rootNode);
// Params node has global dsp settings
XMLNode * paramsNode = rootNode->add_child ("Params");
XMLNode * channelsNode = rootNode->add_child ("Channels");
for (int i=0; i < iosup->getActivePathCount(); i++)
{
FTprocessPath * procpath = iosup->getProcessPath(i);
if (!procpath) continue; // shouldnt happen
FTspectralEngine *engine = procpath->getSpectralEngine();
if (i==0)
{
// pull global params from first procpath
paramsNode->add_property ("fft_size", static_cast<const char *> (wxString::Format(wxT("%d"), engine->getFFTsize()).mb_str()));
paramsNode->add_property ("windowing", static_cast<const char *> (wxString::Format(wxT("%d"), engine->getWindowing()).mb_str()));
paramsNode->add_property ("update_speed", static_cast<const char *> (wxString::Format(wxT("%d"), engine->getUpdateSpeed()).mb_str()));
paramsNode->add_property ("oversamp", static_cast<const char *> (wxString::Format(wxT("%d"), engine->getOversamp()).mb_str()));
paramsNode->add_property ("tempo", static_cast<const char *> (wxString::Format(wxT("%d"), engine->getTempo()).mb_str()));
paramsNode->add_property ("max_delay", static_cast<const char *> (wxString::Format(wxT("%.10g"), engine->getMaxDelay()).mb_str()));
}
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
XMLNode * chanNode = channelsNode->add_child ("Channel");
chanNode->add_property ("pos", static_cast<const char *> (wxString::Format(wxT("%d"), i).mb_str()));
chanNode->add_property ("input_gain", static_cast<const char *> (wxString::Format(wxT("%.10g"), engine->getInputGain()).mb_str()));
chanNode->add_property ("mix_ratio", static_cast<const char *> (wxString::Format(wxT("%.10g"), engine->getMixRatio()).mb_str()));
chanNode->add_property ("bypassed", static_cast<const char *> (wxString::Format(wxT("%d"), engine->getBypassed() ? 1: 0).mb_str()));
chanNode->add_property ("muted", static_cast<const char *> (wxString::Format(wxT("%d"), engine->getMuted() ? 1 : 0).mb_str()));
// now for the filter sections
XMLNode * procmodsNode = chanNode->add_child ("ProcMods");
for (unsigned int n=0; n < procmods.size(); ++n)
{
FTprocI *pm = procmods[n];
vector<FTspectrumModifier *> filts;
pm->getFilters (filts);
XMLNode * pmNode = procmodsNode->add_child ("ProcMod");
pmNode->add_property ("pos", static_cast<const char *> (wxString::Format(wxT("%d"), n).mb_str()));
pmNode->add_property ("name", pm->getConfName());
for (unsigned int m=0; m < filts.size(); ++m)
{
XMLNode * filtNode = pmNode->add_child ("Filter");
filtNode->add_property ("pos", static_cast<const char *> (wxString::Format(wxT("%d"), m).mb_str()));
filtNode->add_property ("name", filts[m]->getConfigName().c_str());
filtNode->add_property ("linked", static_cast<const char *> (
wxString::Format(wxT("%d"),
filts[m]->getLink() ?
filts[m]->getLink()->getId() : -1).mb_str()));
filtNode->add_property ("bypassed", static_cast<const char *> (
wxString::Format(wxT("%d"),
filts[m]->getBypassed() ? 1 : 0).mb_str()));
std::string filtfname ( (wxString::Format(wxT("%d_%d_"), i, n)
+ wxString::FromAscii (filts[m]->getConfigName().c_str())
+ wxT(".filter")).fn_str() );
filtNode->add_property ("file", filtfname);
// write out filter file
wxTextFile filtfile (dirname +
wxFileName::GetPathSeparator() +
wxString::FromAscii (filtfname.c_str()));
if (filtfile.Exists()) {
// remove it
unlink (wxString (filtfile.GetName()).fn_str ());
}
filtfile.Create ();
writeFilter (filts[m], filtfile);
filtfile.Write();
filtfile.Close();
// write Extra node
XMLNode * extran = filts[m]->getExtraNode();
filtNode->add_child_copy (*extran);
}
}
// port connections
XMLNode * inputsNode = chanNode->add_child ("Inputs");
const char ** inports = iosup->getConnectedInputPorts(i);
if (inports) {
for (int n=0; inports[n]; n++) {
XMLNode * portNode = inputsNode->add_child ("Port");
portNode->add_property ("name", inports[n]);
}
free(inports);
}
XMLNode * outputsNode = chanNode->add_child ("Outputs");
const char ** outports = iosup->getConnectedOutputPorts(i);
if (outports) {
for (int n=0; outports[n]; n++) {
XMLNode * portNode = outputsNode->add_child ("Port");
portNode->add_property ("name", outports[n]);
}
free(outports);
}
}
// modulations
XMLNode * modulationsNode = rootNode->add_child ("Modulators");
/* <Modulators>
<Modulator name="" user_name="" bypassed="" channel="">
<Controls>
<Control type="" name="" units="" lower_bound="" upper_bound="" enumlist="assd,asdsd" value="" />
...
</Controls>
<Filters>
<Filter chan="" modpos="" filtpos="" />
...
</Filters>
</Modulator>
<Modulators>
*/
for (int i=0; i < iosup->getActivePathCount(); i++)
{
FTprocessPath * procpath = iosup->getProcessPath(i);
if (!procpath) continue; // shouldnt happen
FTspectralEngine *engine = procpath->getSpectralEngine();
vector<FTmodulatorI *> mods;
engine->getModulators (mods);
for (vector<FTmodulatorI*>::iterator miter = mods.begin(); miter != mods.end(); ++miter)
{
XMLNode *modNode = modulationsNode->add_child ("Modulator");
XMLNode *controlsNode = modNode->add_child ("Controls");
XMLNode *filtersNode = modNode->add_child ("Filters");
FTmodulatorI * mod = (*miter);
modNode->add_property ("name", mod->getConfName().c_str());
modNode->add_property ("user_name", mod->getUserName().c_str());
modNode->add_property ("bypassed", static_cast<const char *> (wxString::Format(wxT("%d"), mod->getBypassed() ? 1 : 0).mb_str()));
modNode->add_property ("channel", static_cast<const char *> (wxString::Format(wxT("%d"), i).mb_str()));
// do the filters
FTmodulatorI::SpecModList filters;
mod->getSpecMods (filters);
for (FTmodulatorI::SpecModList::iterator filtiter = filters.begin(); filtiter != filters.end(); ++filtiter)
{
int chan=0, modpos=0, filtpos=0;
if (lookupFilterLocation ((*filtiter), chan, modpos, filtpos)) {
XMLNode * filtNode = filtersNode->add_child ("Filter");
filtNode->add_property ("channel", static_cast<const char *> (wxString::Format(wxT("%d"), chan).mb_str()));
filtNode->add_property ("modpos", static_cast<const char *> (wxString::Format(wxT("%d"), modpos).mb_str()));
filtNode->add_property ("filtpos", static_cast<const char *> (wxString::Format(wxT("%d"), filtpos).mb_str()));
}
}
// do the controls
FTmodulatorI::ControlList controls;
mod->getControls (controls);
for (FTmodulatorI::ControlList::iterator ctrliter = controls.begin(); ctrliter != controls.end(); ++ctrliter)
{
FTmodulatorI::Control * ctrl = (*ctrliter);
XMLNode * ctrlNode = controlsNode->add_child ("Control");
ctrlNode->add_property ("name", ctrl->getConfName().c_str());
//ctrlNode->add_property ("type", static_cast<const char *> (wxString::Format(wxT("%d"), (int) ctrl->getType()).mb_str()));
//ctrlNode->add_property ("units", ctrl->getUnits().c_str());
if (ctrl->getType() == FTmodulatorI::Control::IntegerType) {
int lb,ub,val;
ctrl->getBounds (lb, ub);
ctrl->getValue (val);
//ctrlNode->add_property ("lower_bound", static_cast<const char *> (wxString::Format(wxT("%d"), lb).mb_str()));
//ctrlNode->add_property ("upper_bound", static_cast<const char *> (wxString::Format(wxT("%d"), ub).mb_str()));
ctrlNode->add_property ("value", static_cast<const char *> (wxString::Format(wxT("%d"), val).mb_str()));
}
else if (ctrl->getType() == FTmodulatorI::Control::FloatType) {
float lb,ub,val;
ctrl->getBounds (lb, ub);
ctrl->getValue (val);
//ctrlNode->add_property ("lower_bound", static_cast<const char *> (wxString::Format(wxT("%.10g"), lb).mb_str()));
//ctrlNode->add_property ("upper_bound", static_cast<const char *> (wxString::Format(wxT("%.10g"), ub).mb_str()));
ctrlNode->add_property ("value", static_cast<const char *> (wxString::Format(wxT("%.10g"), val).mb_str()));
}
else if (ctrl->getType() == FTmodulatorI::Control::BooleanType) {
bool val;
ctrl->getValue (val);
modNode->add_property ("value", static_cast<const char *> (wxString::Format(wxT("%d"), val ? 1 : 0).mb_str()));
}
else if (ctrl->getType() == FTmodulatorI::Control::StringType) {
string val;
ctrl->getValue (val);
ctrlNode->add_property ("value", val.c_str());
}
else if (ctrl->getType() == FTmodulatorI::Control::EnumType) {
string val;
list<string> enumlist;
ctrl->getValue (val);
ctrl->getEnumStrings(enumlist);
ctrlNode->add_property ("value", val.c_str());
// string enumstr;
// for (list<string>::iterator eiter=enumlist.begin(); eiter != enumlist.end(); ++eiter) {
// if (eiter != enumlist.begin()) {
// enumstr += ",";
// }
// enumstr += (*eiter);
// }
// ctrlNode->add_property ("enumlist", enumstr.c_str());
}
}
}
}
// write doc to file
if (configdoc.write (static_cast<const char *> ((dirname + wxFileName::GetPathSeparator() + wxT("config.xml")).fn_str())))
{
fprintf (stderr, "Stored settings into %s\n", static_cast<const char *> (dirname.fn_str()));
return true;
}
else {
fprintf (stderr, "Failed to store settings into %s\n", static_cast<const char *> (dirname.fn_str()));
return false;
}
}
bool FTconfigManager::loadSettings (const std::string &name, bool restore_ports, bool uselast)
{
vector<vector <FTprocI *> > tmpvec;
return loadSettings(name, restore_ports, false, tmpvec, uselast);
}
bool FTconfigManager::loadSettings (const std::string &name, bool restore_ports, bool ignore_iosup, vector< vector<FTprocI *> > & procvec, bool uselast)
{
if (!uselast && (name == "")) {
return false;
}
wxString dirname (wxString::FromAscii (_basedir.c_str()) + wxFileName::GetPathSeparator());
if (uselast) {
dirname += wxT("last_setting");
}
else {
dirname += (wxString (wxT("presets")) + wxFileName::GetPathSeparator() + wxString::FromAscii (name.c_str()));
}
if ( ! wxDir::Exists(dirname) ) {
printf ("Settings %s does not exist!\n", static_cast<const char *> (dirname.fn_str()));
return false;
}
FTioSupport * iosup = 0;
if (!ignore_iosup) {
iosup = FTioSupport::instance();
}
// open file
string configfname(static_cast<const char *> ((dirname + wxFileName::GetPathSeparator() + wxT("config.xml")).fn_str() ));
XMLTree configdoc (configfname);
if (!configdoc.initialized()) {
fprintf (stderr, "Error loading config at %s!\n", configfname.c_str());
return false;
}
XMLNode * rootNode = configdoc.root();
if (!rootNode || rootNode->name() != "Preset") {
fprintf (stderr, "Preset root node not found in %s!\n", configfname.c_str());
return false;
}
// get channels
XMLNode * channelsNode = find_named_node (rootNode, "Channels");
if (!channelsNode ) {
fprintf (stderr, "Preset Channels node not found in %s!\n", configfname.c_str());
return false;
}
XMLNodeList chanlist = channelsNode->children();
if (chanlist.size() < 1) {
fprintf (stderr, "No channels found in %s!\n", configfname.c_str());
return false;
}
if (!ignore_iosup)
{
unsigned int i;
for (i=0; i < chanlist.size() && i < FT_MAXPATHS; i++)
{
iosup->setProcessPathActive(i, true);
}
// set all remaining paths inactive
for ( ; i < FT_MAXPATHS; i++) {
iosup->setProcessPathActive(i, false);
}
}
else {
// set up procvec with its channels
for (unsigned int i=0; i < chanlist.size() && i < FT_MAXPATHS; i++)
{
procvec.push_back(vector<FTprocI *>());
}
}
// get global params
unsigned long fft_size = 1024;
unsigned long windowing = 0;
unsigned long update_speed = 2;
unsigned long oversamp = 4;
unsigned long tempo = 120;
double max_delay = 2.5;
XMLNode * paramsNode = find_named_node (rootNode, "Params");
if (paramsNode)
{
XMLPropertyConstIterator propiter;
XMLPropertyList proplist = paramsNode->properties();
for (propiter=proplist.begin(); propiter != proplist.end(); ++propiter)
{
string key = (*propiter)->name();
wxString value (wxString::FromAscii ((*propiter)->value().c_str()));
if (key == "fft_size") {
value.ToULong(&fft_size);
}
else if (key == "windowing") {
value.ToULong(&windowing);
}
else if (key == "update_speed") {
value.ToULong(&update_speed);
}
else if (key == "oversamp") {
value.ToULong(&oversamp);
}
else if (key == "tempo") {
value.ToULong(&tempo);
}
else if (key == "max_delay") {
value.ToDouble(&max_delay);
}
}
}
_linkCache.clear();
// clear all procpaths
XMLNodeConstIterator chaniter;
XMLNode * chanNode;
double fval;
unsigned long uval;
for (chaniter=chanlist.begin(); chaniter != chanlist.end(); ++chaniter)
{
chanNode = *chaniter;
XMLProperty * prop;
if (!(prop = chanNode->property ("pos"))) {
fprintf (stderr, "pos missing in channel!\n");
continue;
}
unsigned long chan_pos;
wxString tmpstr (wxString::FromAscii (prop->value().c_str()));
if (!tmpstr.ToULong (&chan_pos) || chan_pos >= FT_MAXPATHS) {
fprintf (stderr, "invalid pos in channel!\n");
continue;
}
FTspectralEngine * engine = 0;
if (!ignore_iosup) {
FTprocessPath * procpath = iosup->getProcessPath((int) chan_pos);
if (!procpath) continue; // shouldnt happen
engine = procpath->getSpectralEngine();
// apply some of the global settings now
engine->setOversamp ((int) oversamp);
engine->setTempo ((int) tempo);
engine->setMaxDelay ((float) max_delay);
// get channel settings
XMLPropertyConstIterator propiter;
XMLPropertyList proplist = chanNode->properties();
for (propiter=proplist.begin(); propiter != proplist.end(); ++propiter)
{
string key = (*propiter)->name();
wxString value (wxString::FromAscii ((*propiter)->value().c_str()));
if (key == "input_gain") {
if (value.ToDouble(&fval)) {
engine->setInputGain ((float) fval);
}
}
else if (key == "mix_ratio") {
if (value.ToDouble(&fval)) {
engine->setMixRatio ((float) fval);
}
}
else if (key == "bypassed") {
if (value.ToULong(&uval)) {
engine->setBypassed (uval==1 ? true: false);
}
}
else if (key == "muted") {
if (value.ToULong(&uval)) {
engine->setMuted (uval==1 ? true: false);
}
}
}
// clear existing procmods
engine->clearProcessorModules();
}
// get procmods node
XMLNode * procmodsNode = find_named_node (chanNode, "ProcMods");
if ( !procmodsNode ) {
fprintf (stderr, "Preset ProcMods node not found in %s!\n", configfname.c_str());
return false;
}
XMLNodeList pmlist = procmodsNode->children();
XMLNodeConstIterator pmiter;
XMLNode * pmNode;
for (pmiter=pmlist.begin(); pmiter != pmlist.end(); ++pmiter)
{
pmNode = *pmiter;
if (pmNode->name() != "ProcMod") continue;
if (!(prop = pmNode->property ("pos"))) {
fprintf (stderr, "pos missing in procmod!\n");
continue;
}
unsigned long ppos;
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToULong (&ppos)) {
fprintf (stderr, "invalid pos in procmod!\n");
continue;
}
if (!(prop = pmNode->property ("name"))) {
fprintf (stderr, "name missing in procmod!\n");
continue;
}
string pmname = prop->value();
// construct new procmod
FTprocI * procmod = FTdspManager::instance()->getModuleByConfigName(pmname);
if (!procmod) {
fprintf (stderr, "no proc module '%s' supported\n", pmname.c_str());
continue;
}
procmod = procmod->clone();
// must call this before initialization
procmod->setMaxDelay ((float)max_delay);
procmod->initialize();
if (!ignore_iosup) {
procmod->setSampleRate (iosup->getSampleRate());
}
procmod->setOversamp ((int)oversamp);
// load up the filters in the procmod
XMLNodeList filtlist = pmNode->children();
XMLNodeConstIterator filtiter;
XMLNode * filtNode;
for (filtiter=filtlist.begin(); filtiter != filtlist.end(); ++filtiter)
{
filtNode = *filtiter;
if (filtNode->name() != "Filter")
{
continue;
}
if (!(prop =filtNode->property ("pos"))) {
fprintf (stderr, "pos missing in filter!\n");
continue;
}
unsigned long fpos;
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToULong (&fpos)) {
fprintf (stderr, "invalid filter pos in channel!\n");
continue;
}
if (!(prop = filtNode->property ("file"))) {
fprintf (stderr, "filter filename missing in procmod!\n");
continue;
}
std::string filtfname = prop->value();
FTspectrumModifier * specmod = procmod->getFilter (fpos);
if (!specmod) {
fprintf (stderr, "no filter at index %lu in procmod!\n", fpos);
continue;
}
// load filter
wxTextFile filtfile (dirname
+ wxFileName::GetPathSeparator()
+ wxString::Format (wxT("%d_"), (int) chan_pos)
+ wxString::Format (wxT("%d_"), (int) ppos)
+ wxString::FromAscii (specmod->getConfigName().c_str())
+ wxT(".filter"));
if (filtfile.Open()) {
loadFilter (specmod, filtfile);
filtfile.Close();
}
// set bypassed
if ((prop = filtNode->property ("bypassed"))) {
wxString value (wxString::FromAscii (prop->value().c_str()));
if (value.ToULong(&uval)) {
specmod->setBypassed (uval==1 ? true: false);
}
}
// actual linkage must wait for later
long linked = -1;
if ((prop = filtNode->property ("linked"))) {
wxString value (wxString::FromAscii (prop->value().c_str()));
if (value.ToLong(&linked) && linked >= 0) {
_linkCache.push_back (LinkCache(chan_pos, linked, ppos, fpos));
}
else {
specmod->unlink(false);
}
}
// extra node
XMLNode * extraNode = find_named_node (filtNode, "Extra");
if (extraNode) {
specmod->setExtraNode (extraNode);
}
}
// insert procmod
if (!ignore_iosup)
{
engine->insertProcessorModule (procmod, ppos);
}
else {
// add to vector in the right spot
vector<FTprocI*>::iterator iter = procvec[chan_pos].begin();
for (unsigned int n=0; n < ppos && iter!=procvec[chan_pos].end(); ++n) {
++iter;
}
procvec[chan_pos].insert (iter, procmod);
}
}
if (ignore_iosup) {
// can skip to the next one
continue;
}
// apply global settings
engine->setFFTsize ((FTspectralEngine::FFT_Size) fft_size);
engine->setWindowing ((FTspectralEngine::Windowing) windowing);
engine->setUpdateSpeed ((FTspectralEngine::UpdateSpeed)(int) update_speed);
// input ports
if (restore_ports)
{
XMLNode * inputsNode = find_named_node (chanNode, "Inputs");
if (inputsNode )
{
XMLNodeList portlist = inputsNode->children();
XMLNodeConstIterator portiter;
iosup->disconnectPathInput(chan_pos, NULL); // disconnect all
for (portiter = portlist.begin(); portiter != portlist.end(); ++portiter)
{
XMLNode * port = *portiter;
if (port->name() == "Port") {
XMLProperty * prop = port->property("name");
if (prop) {
iosup->connectPathInput(chan_pos, prop->value().c_str());
}
}
}
}
else {
fprintf (stderr, "channel inputs node not found in %s!\n", configfname.c_str());
}
// output ports
XMLNode * outputsNode = find_named_node (chanNode, "Outputs");
if (inputsNode )
{
XMLNodeList portlist = outputsNode->children();
XMLNodeConstIterator portiter;
iosup->disconnectPathOutput(chan_pos, NULL); // disconnect all
for (portiter = portlist.begin(); portiter != portlist.end(); ++portiter)
{
XMLNode * port = *portiter;
if (port->name() == "Port") {
XMLProperty * prop = port->property("name");
if (prop) {
iosup->connectPathOutput(chan_pos, prop->value().c_str());
}
}
}
}
else {
fprintf (stderr, "channel outputs node not found in %s!\n", configfname.c_str());
}
}
// // TEMPORARY
// FTprocI * firstproc = engine->getProcessorModule(0);
// if (firstproc) {
// FTmodulatorI * modul = FTmodulatorManager::instance()->getModuleByConfigName("Shift")->clone();
// modul->initialize();
// modul->addSpecMod (firstproc->getFilter(0));
// engine->appendModulator(modul);
// }
}
// Modulations
// clear all modulators from all engines
for (int i=0; i < FTioSupport::instance()->getActivePathCount(); i++) {
FTprocessPath * procpath = FTioSupport::instance()->getProcessPath(i);
if (procpath) {
FTspectralEngine *engine = procpath->getSpectralEngine();
engine->clearModulators ();
}
}
XMLNode * modulatorsNode = find_named_node (rootNode, "Modulators");
if ( modulatorsNode )
{
loadModulators (modulatorsNode);
}
if (!ignore_iosup)
{
// now we can apply linkages
list<LinkCache>::iterator liter;
for (liter = _linkCache.begin(); liter != _linkCache.end(); ++liter)
{
LinkCache & lc = *liter;
FTspectrumModifier *source = iosup->getProcessPath(lc.source_chan)->getSpectralEngine()
->getProcessorModule(lc.mod_n)->getFilter(lc.filt_n);
FTspectrumModifier *dest = iosup->getProcessPath(lc.dest_chan)->getSpectralEngine()
->getProcessorModule(lc.mod_n)->getFilter(lc.filt_n);
if (dest && source) {
source->link (dest);
}
else {
fprintf(stderr, "could not link! source or dest does not exist!\n");
}
}
}
else
{
// just use the stored ones
list<LinkCache>::iterator liter;
for (liter = _linkCache.begin(); liter != _linkCache.end(); ++liter)
{
LinkCache & lc = *liter;
FTspectrumModifier *source = procvec[lc.source_chan][lc.mod_n]->getFilter(lc.filt_n);
FTspectrumModifier *dest = procvec[lc.dest_chan][lc.mod_n]->getFilter(lc.filt_n);
source->link (dest);
}
}
return true;
}
void FTconfigManager::loadModulators (const XMLNode * modulatorsNode)
{
XMLNodeList modlist = modulatorsNode->children();
XMLNodeConstIterator moditer;
XMLNode * modNode;
XMLProperty * prop;
wxString tmpstr;
for (moditer=modlist.begin(); moditer != modlist.end(); ++moditer)
{
modNode = *moditer;
if (modNode->name() != "Modulator") continue;
if (!(prop = modNode->property ("name"))) {
fprintf (stderr, "name missing in modulator!\n");
continue;
}
string modname = prop->value();
string usermodname;
if (!(prop = modNode->property ("user_name"))) {
fprintf (stderr, "user_name missing in modulator!\n");
} else {
usermodname = prop->value();
}
bool bypass = false;
if (!(prop = modNode->property ("bypassed"))) {
fprintf (stderr, "bypassed missing in modulator!\n");
}
else {
unsigned long bypassi = 0;
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToULong (&bypassi)) {
fprintf (stderr, "invalid bypass flag in modulator!\n");
}
bypass = (bypassi==0 ? false: true);
}
long channel = -1;
if (!(prop = modNode->property ("channel"))) {
fprintf (stderr, "channel missing in modulator!\n");
} else
{
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToLong (&channel)) {
fprintf (stderr, "invalid channel in modulator!\n");
}
}
// create the modulator
FTmodulatorI * protomod = FTmodulatorManager::instance()->getModuleByConfigName (modname);
if (!protomod) {
fprintf (stderr, "module %s could not be found\n", modname.c_str());
continue;
}
FTmodulatorI * mod = protomod->clone();
mod->initialize();
mod->setUserName (usermodname);
mod->setBypassed (bypass);
// get all controls from real one
FTmodulatorI::ControlList ctrllist;
mod->getControls (ctrllist);
// now do controls
XMLNode * modControlsNode = find_named_node (modNode, "Controls");
if (modControlsNode) {
XMLNodeList modctrllist = modControlsNode->children();
XMLNodeConstIterator modctrliter;
XMLNode * ctrlNode;
for (modctrliter=modctrllist.begin(); modctrliter != modctrllist.end(); ++modctrliter)
{
ctrlNode = *modctrliter;
if (ctrlNode->name() != "Control") continue;
if (!(prop = ctrlNode->property ("name"))) {
fprintf (stderr, "name missing in modulator control!\n");
continue;
}
string ctrlname = prop->value();
// lookup control by name
for (FTmodulatorI::ControlList::iterator citer = ctrllist.begin(); citer != ctrllist.end(); ++citer) {
FTmodulatorI::Control * ctrl = (*citer);
if (ctrl->getConfName() == ctrlname)
{
if (ctrl->getType() == FTmodulatorI::Control::IntegerType) {
long intval = 0;
if (!(prop = ctrlNode->property ("value"))) {
fprintf (stderr, "int value missing in modulator control!\n");
} else
{
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToLong (&intval)) {
fprintf (stderr, "invalid value in modulator control!\n");
}
else {
ctrl->setValue ((int)intval);
}
}
}
else if (ctrl->getType() == FTmodulatorI::Control::FloatType) {
double fval = 0;
if (!(prop = ctrlNode->property ("value"))) {
fprintf (stderr, "float value missing in modulator control!\n");
} else
{
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToDouble (&fval)) {
fprintf (stderr, "invalid value in modulator control!\n");
}
else {
ctrl->setValue ((float)fval);
}
}
}
else if (ctrl->getType() == FTmodulatorI::Control::StringType ||
ctrl->getType() == FTmodulatorI::Control::EnumType)
{
if (!(prop = ctrlNode->property ("value"))) {
fprintf (stderr, "string enum value missing in modulator control!\n");
} else {
string valstr = prop->value();
ctrl->setValue(valstr);
}
}
else if (ctrl->getType() == FTmodulatorI::Control::BooleanType) {
long intval = 0;
if (!(prop = ctrlNode->property ("value"))) {
fprintf (stderr, "bool value missing in modulator control!\n");
} else
{
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToLong (&intval)) {
fprintf (stderr, "invalid value in modulator control!\n");
}
else {
ctrl->setValue ((intval == 0 ? false : true));
}
}
}
break;
}
}
}
} else {
fprintf (stderr, "module controls node could not be found\n");
}
// link to filters
XMLNode * modFiltersNode = find_named_node (modNode, "Filters");
if (modFiltersNode) {
XMLNodeList filtlist = modFiltersNode->children();
XMLNodeConstIterator filtiter;
XMLNode * filtNode;
for (filtiter=filtlist.begin(); filtiter != filtlist.end(); ++filtiter)
{
filtNode = *filtiter;
if (filtNode->name() != "Filter") continue;
unsigned long filtchan = 0;
if (!(prop = filtNode->property ("channel"))) {
fprintf (stderr, "int value missing in modulator filter channel!\n");
continue;
}
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToULong (&filtchan)) {
fprintf (stderr, "invalid channel value in modulator filter control!\n");
continue;
}
unsigned long modpos = 0;
if (!(prop = filtNode->property ("modpos"))) {
fprintf (stderr, "int value missing in modulator filter pos!\n");
continue;
}
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToULong (&modpos)) {
fprintf (stderr, "invalid modpos value in modulator filter pos control!\n");
continue;
}
unsigned long filtpos = 0;
if (!(prop = filtNode->property ("filtpos"))) {
fprintf (stderr, "int value missing in modulator filter pos!\n");
continue;
}
tmpstr = wxString::FromAscii (prop->value().c_str());
if (!tmpstr.ToULong (&filtpos)) {
fprintf (stderr, "invalid channel value in modulator filter pos control!\n");
continue;
}
// finally look it up
FTspectrumModifier * specmod = lookupFilter (filtchan, modpos, filtpos);
if (specmod) {
mod->addSpecMod (specmod);
}
}
}
// add it to proper spectral engine
if (channel > -1) {
FTprocessPath * procpath = FTioSupport::instance()->getProcessPath(channel);
if (procpath) {
FTspectralEngine *engine = procpath->getSpectralEngine();
engine->appendModulator (mod);
}
else {
delete mod;
}
}
else {
// for NOW, just delete it
delete mod;
}
}
}
void FTconfigManager::loadFilter (FTspectrumModifier *specmod, wxTextFile & tf)
{
// FORMAT FOR FILTER FILES
// -----------------------
//
// One line per bin description, a bin description is:
// [start_bin:stop_bin] value
//
// If the optional bin range is missing (one token in line) then
// the value is assigned to the bin following the most recently filled bin.
// The bin indexes start from 0 and the ranges are inclusive
float *values = specmod->getValues();
// parse lines from it
wxString line;
line = tf.GetFirstLine();
int lastbin = -1;
double val;
unsigned long sbin, ebin;
for ( unsigned int i =0; i < tf.GetLineCount(); i++ )
{
line = tf[i];
line.Trim(true);
line.Trim(false);
if (line.IsEmpty() || line.GetChar(0) == '#')
{
continue; // ignore
}
// look for whitespace separating two possible tokens
wxString rangestr;
wxString value;
int pos = line.find_first_of (wxT(" \t"));
if (pos >= 0) {
rangestr = line.substr(0, pos);
value = line.Mid(pos).Strip(wxString::both);
// printf ("rangestr is %s, value is %s\n", rangestr.c_str(), value.c_str());
if (rangestr.BeforeFirst(':').ToULong(&sbin)
&& rangestr.AfterFirst(':').ToULong(&ebin))
{
for (unsigned int j=sbin; j <=ebin; j++) {
if (value.ToDouble(&val)) {
values[j] = (float) val;
}
}
lastbin = ebin;
}
}
else {
// just value
value = line;
lastbin += 1;
// printf ("bin=%d value is %s\n", lastbin, value.c_str());
if (value.ToDouble(&val)) {
values[lastbin] = (float) val;
}
}
}
}
void FTconfigManager::writeFilter (FTspectrumModifier *specmod, wxTextFile & tf)
{
// FORMAT FOR FILTER FILES
// -----------------------
//
// One line per bin description, a bin description is:
// [start_bin:stop_bin] value
//
// If the optional bin range is missing (one token in line) then
// the value is assigned to the bin following the most recently filled bin.
// The bin indexes start from 0 and the ranges are inclusive
float * values = specmod->getValues();
int totbins = specmod->getLength();
int pos = 0;
int i;
float lastval = values[0];
for (i = 1; i < totbins; i++)
{
// if (wxString::Format("%.10g", values[i]) == wxString::Format("%.20g", lastval)) {
if (values[i] == lastval) {
continue;
}
else if (i == pos + 1 ) {
// just write last number
tf.AddLine ( wxString::Format (wxT("%.20g"), lastval));
pos = i;
lastval = values[i];
}
else {
// write range
tf.AddLine ( wxString::Format (wxT("%d:%d %.20g"), pos, i-1, values[pos]));
pos = i;
lastval = values[i];
}
}
// write last
if (pos < totbins) {
tf.AddLine ( wxString::Format (wxT("%d:%d %.20g"), pos, totbins-1, values[pos]));
}
}
list<string> FTconfigManager::getSettingsNames()
{
wxString dirname (wxString::FromAscii(_basedir.c_str()) + wxFileName::GetPathSeparator() + wxT("presets"));
list<string> flist;
wxDir dir(dirname);
if ( !dir.IsOpened() ) {
return flist;
}
wxString filename;
bool cont = dir.GetFirst(&filename, wxT(""), wxDIR_DIRS);
while ( cont )
{
//printf ("%s\n", filename.c_str());
flist.push_back (static_cast<const char *> (filename.fn_str()));
cont = dir.GetNext(&filename);
}
return flist;
}
XMLNode *
FTconfigManager::find_named_node (const XMLNode * node, string name)
{
XMLNodeList nlist;
XMLNodeConstIterator niter;
XMLNode* child;
nlist = node->children();
for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
child = *niter;
if (child->name() == name) {
return child;
}
}
return 0;
}
bool FTconfigManager::lookupFilterLocation (FTspectrumModifier * specmod, int & chan, int & modpos, int & filtpos)
{
// brute force
FTioSupport * iosup = FTioSupport::instance();
bool done = false;
for (int i=0; i < iosup->getActivePathCount(); i++)
{
FTprocessPath * procpath = iosup->getProcessPath(i);
if (!procpath) continue; // shouldnt happen
FTspectralEngine *engine = procpath->getSpectralEngine();
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
for (unsigned int n=0; n < procmods.size(); ++n)
{
FTprocI *pm = procmods[n];
vector<FTspectrumModifier *> filts;
pm->getFilters (filts);
for (unsigned int m=0; m < filts.size(); ++m)
{
if (specmod == filts[m]) {
chan = i;
modpos = n;
filtpos = m;
done = true;
goto done;
}
}
}
}
done:
return done;
}
FTspectrumModifier * FTconfigManager::lookupFilter (int chan, int modpos, int filtpos)
{
FTioSupport * iosup = FTioSupport::instance();
FTprocessPath * procpath = iosup->getProcessPath(chan);
if (procpath) {
FTspectralEngine *engine = procpath->getSpectralEngine();
FTprocI * procmod = engine->getProcessorModule (modpos);
if (procmod) {
FTspectrumModifier * specmod = procmod->getFilter (filtpos);
return specmod;
}
}
return 0;
}
| 38,714
|
C++
|
.cpp
| 1,101
| 30.046322
| 152
| 0.642181
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,925
|
FTactiveBarGraph.cpp
|
essej_freqtweak/src/FTactiveBarGraph.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <stdio.h>
#include <math.h>
#include "FTactiveBarGraph.hpp"
#include "FTspectrumModifier.hpp"
#include "FTutils.hpp"
#include "FTmainwin.hpp"
#include "FTjackSupport.hpp"
enum
{
FT_1Xscale=1000,
FT_2Xscale,
FT_LogaXscale,
FT_LogbXscale,
};
// the event tables connect the wxWindows events with the functions (event
// handlers) which process them. It can be also done at run-time, but for the
// simple menu events like this the static method is much simpler.
BEGIN_EVENT_TABLE(FTactiveBarGraph, wxPanel)
EVT_PAINT(FTactiveBarGraph::OnPaint)
EVT_SIZE(FTactiveBarGraph::OnSize)
EVT_LEFT_DOWN(FTactiveBarGraph::OnMouseActivity)
EVT_LEFT_UP(FTactiveBarGraph::OnMouseActivity)
EVT_RIGHT_DOWN(FTactiveBarGraph::OnMouseActivity)
EVT_RIGHT_UP(FTactiveBarGraph::OnMouseActivity)
EVT_MIDDLE_DOWN(FTactiveBarGraph::OnMouseActivity)
EVT_MIDDLE_UP(FTactiveBarGraph::OnMouseActivity)
EVT_MOTION(FTactiveBarGraph::OnMouseActivity)
EVT_ENTER_WINDOW(FTactiveBarGraph::OnMouseActivity)
EVT_LEAVE_WINDOW(FTactiveBarGraph::OnMouseActivity)
EVT_MOTION(FTactiveBarGraph::OnMouseActivity)
EVT_MENU (FT_1Xscale,FTactiveBarGraph::OnXscaleMenu)
EVT_MENU (FT_2Xscale,FTactiveBarGraph::OnXscaleMenu)
EVT_MENU (FT_LogaXscale,FTactiveBarGraph::OnXscaleMenu)
EVT_MENU (FT_LogbXscale,FTactiveBarGraph::OnXscaleMenu)
END_EVENT_TABLE()
FTactiveBarGraph::FTactiveBarGraph(FTmainwin *win, wxWindow *parent, wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style ,
const wxString& name)
: wxPanel(parent, id, pos, size, style, name)
//, _topHeight(4), _bottomHeight(4), _leftWidth(4, _rightWidth(4)
, _width(1), _height(1)
, _specMod(0), _topSpecMod(0), _min(0.0), _max(1.0), _absmin(0.0), _absmax(1.0)
,_mindb(-50.0), _maxdb(0.0), _absmindb(-60), _absmaxdb(0.0), _absposmindb(0.0f), _absposmaxdb(24.0)
,_minsemi(-12.0), _maxsemi(12), _absminsemi(-12), _absmaxsemi(12)
, _tmpfilt(0), _toptmpfilt(0)
, _barColor0(135, 207, 235), _barColor1(69, 130, 181)
, _barColor2(46, 140, 87), _barColor3(143, 189, 143)
,_barColorDead(77,77,77)
,_tipColor(200,200,0)
, _penColor(0,0,255), _gridColor(64,64,64)
,_backingMap(0)
, _xScaleType(XSCALE_1X), _lastX(0)
, _dragging(false), _zooming(false)
, _mainwin(win)
, _gridFlag(false), _gridSnapFlag(false)
, _mouseCaptured(false), _bypassed(false)
//, _boundsFont(8, wxDEFAULT, wxNORMAL, wxNORMAL, false, "Helvetica")
, _boundsFont(8, wxDEFAULT, wxNORMAL, wxNORMAL)
, _textColor(255,255,255)
, _tempo(120)
{
SetBackgroundColour(*wxBLACK);
_mainwin->normalizeFontSize(_boundsFont, 11, wxT("999"));
_barBrush0.SetColour(_barColor0);
_barBrush0.SetStyle(wxSOLID);
_barBrush1.SetColour(_barColor1);
_barBrush1.SetStyle(wxSOLID);
_barBrush2.SetColour(_barColor2);
_barBrush2.SetStyle(wxSOLID);
_barBrush3.SetColour(_barColor3);
_barBrush3.SetStyle(wxSOLID);
_barBrushDead.SetColour(_barColorDead);
_barBrushDead.SetStyle(wxSOLID);
_bypassBrush.SetColour(wxColour(77,77,77));
_bypassBrush.SetStyle(wxSOLID);
_tipBrush.SetColour(_tipColor);
_tipBrush.SetStyle(wxSOLID);
_bgBrush.SetColour(wxColour(30,50,30));
//_bgBrush.SetStyle(wxCROSS_HATCH);
_barPen.SetColour(_penColor);
_barPen.SetStyle(wxTRANSPARENT);
_gridPen.SetColour(_gridColor);
_gridPen.SetStyle(wxSOLID);
_xscaleMenu = new wxMenu(wxT(""));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_1Xscale, wxT("1x Scale")));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_2Xscale, wxT("2x Scale")));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_LogaXscale, wxT("logA Scale")));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_LogbXscale, wxT("logB Scale")));
// grid choices can't be determined until we get a specmod
updateSize();
}
FTactiveBarGraph::~FTactiveBarGraph()
{
if (_tmpfilt) delete [] _tmpfilt;
if (_toptmpfilt) delete [] _toptmpfilt;
if (_backingMap) delete _backingMap;
delete _xscaleMenu;
if (_specMod) _specMod->unregisterListener(this);
if (_topSpecMod) _topSpecMod->unregisterListener(this);
}
void FTactiveBarGraph::refreshBounds()
{
// mainly to handle when certain units change
if (!_specMod) return;
_xscale = _width/(float)_specMod->getLength();
_min = _absmin = _specMod->getMin();
_max = _absmax = _specMod->getMax();
if (_specMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER)
{
_mindb = _absmindb;
_maxdb = _absmaxdb;
_absmin = valToDb(_absmin); // special case
_absmax = valToDb(_absmax); // special case
_min = dbToVal(_mindb);
_max = dbToVal(_maxdb);
}
else if (_specMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
_mindb = _absposmindb;
_maxdb = _absposmaxdb;
_absmin = valToDb(_absmin); // special case
_absmax = valToDb(_absmax); // special case
_min = dbToVal(_mindb);
_max = dbToVal(_maxdb);
}
else if (_specMod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER)
{
_minsemi = valToSemi(_min);
_maxsemi = valToSemi(_max);
}
_mtype = _specMod->getModifierType();
makeGridChoices(true);
recalculate();
}
void FTactiveBarGraph::setSpectrumModifier (FTspectrumModifier *sm)
{
int origlength=-1;
if (_specMod) {
origlength = _specMod->getLength();
// unregister from previous
_specMod->unregisterListener (this);
}
_specMod = sm;
if (sm == 0) {
return;
}
_specMod->registerListener (this);
if (_specMod->getLength() != origlength) {
if (_tmpfilt) delete [] _tmpfilt;
_tmpfilt = new float[_specMod->getLength()];
}
refreshBounds();
}
void FTactiveBarGraph::goingAway (FTspectrumModifier * sm)
{
if (sm == _specMod) {
// clean it up
_specMod = 0;
}
else if (sm == _topSpecMod) {
// clean it up
_topSpecMod = 0;
}
}
void FTactiveBarGraph::setTopSpectrumModifier (FTspectrumModifier *sm)
{
if (_topSpecMod) {
// unregister from previous
_topSpecMod->unregisterListener (this);
}
_topSpecMod = sm;
if (sm == 0) {
return;
}
_topSpecMod->registerListener (this);
// should be same as other one
_xscale = _width/(float)_topSpecMod->getLength();
_min = _absmin = _topSpecMod->getMin();
_max = _absmax = _topSpecMod->getMax();
if (_topSpecMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER)
{
_mindb = _absmindb;
_maxdb = _absmaxdb;
_absmin = valToDb(_absmin); // special case
_absmax = valToDb(_absmax); // special case
_min = dbToVal(_mindb);
_max = dbToVal(_maxdb);
}
else if (_topSpecMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
_mindb = _absposmindb;
_maxdb = _absposmaxdb;
_absmin = valToDb(_absmin); // special case
_absmax = valToDb(_absmax); // special case
_min = dbToVal(_mindb);
_max = dbToVal(_maxdb);
}
else if (_topSpecMod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER)
{
_minsemi = valToSemi(_min);
_maxsemi = valToSemi(_max);
}
if (_toptmpfilt) delete [] _toptmpfilt;
_toptmpfilt = new float[_topSpecMod->getLength()];
_mtype = _specMod->getModifierType();
makeGridChoices(true);
recalculate();
}
void FTactiveBarGraph::makeGridChoices (bool setdefault)
{
_gridChoices.clear();
_gridValues.clear();
float tscale;
switch(_mtype)
{
case FTspectrumModifier::GAIN_MODIFIER:
case FTspectrumModifier::POS_GAIN_MODIFIER:
_gridChoices.push_back (wxT("1 dB"));
_gridValues.push_back (1.0);
_gridChoices.push_back (wxT("3 dB"));
_gridValues.push_back (3.0);
_gridChoices.push_back (wxT("6 dB"));
_gridValues.push_back (6.0);
_gridChoices.push_back (wxT("12 dB"));
_gridValues.push_back (12.0);
_gridChoices.push_back (wxT("18 dB"));
_gridValues.push_back (18.0);
_gridChoices.push_back (wxT("24 dB"));
_gridValues.push_back (24.0);
if (setdefault) {
// default
_gridFactor = 6.0;
_gridChoiceIndex = 2;
}
break;
case FTspectrumModifier::SEMITONE_MODIFIER:
_gridChoices.push_back (wxT("1/2 semi"));
_gridValues.push_back (0.5);
_gridChoices.push_back (wxT("1 semi"));
_gridValues.push_back (1.0);
_gridChoices.push_back (wxT("2 semi"));
_gridValues.push_back (2.0);
_gridChoices.push_back (wxT("3 semi"));
_gridValues.push_back (3.0);
_gridChoices.push_back (wxT("4 semi"));
_gridValues.push_back (4.0);
_gridChoices.push_back (wxT("6 semi"));
_gridValues.push_back (6.0);
if (setdefault) {
// default
_gridFactor = 1.0;
_gridChoiceIndex = 1;
}
break;
case FTspectrumModifier::TIME_MODIFIER:
_gridChoices.push_back (wxT("1000 msec"));
_gridValues.push_back (1.0);
_gridChoices.push_back (wxT("500 msec"));
_gridValues.push_back (2.0);
_gridChoices.push_back (wxT("250 msec"));
_gridValues.push_back (4.0);
_gridChoices.push_back (wxT("200 msec"));
_gridValues.push_back (5.0);
_gridChoices.push_back (wxT("100 msec"));
_gridValues.push_back (10.0);
_gridChoices.push_back (wxT("50 msec"));
_gridValues.push_back (20.0);
_gridChoices.push_back (wxT("25 msec"));
_gridValues.push_back (40.0);
_gridChoices.push_back (wxT("10 msec"));
_gridValues.push_back (100.0);
_gridChoices.push_back (wxT("5 msec"));
_gridValues.push_back (200.0);
_beatscutoff = _gridValues.size();
_gridChoices.push_back (wxT(""));
_gridValues.push_back (0.0);
// meter time
tscale = 60.0 / _tempo;
_gridChoices.push_back (wxT("1/16 beat"));
_gridValues.push_back (tscale * 64.0);
_gridChoices.push_back (wxT("1/8 beat"));
_gridValues.push_back (tscale * 32.0);
_gridChoices.push_back (wxT("1/4 beat"));
_gridValues.push_back (tscale * 16.0);
_gridChoices.push_back (wxT("1/3 beat"));
_gridValues.push_back (tscale * 12.0);
_gridChoices.push_back (wxT("1/2 beat"));
_gridValues.push_back (tscale * 8.0);
_gridChoices.push_back (wxT("1 beat"));
_gridValues.push_back (tscale * 4.0);
_gridChoices.push_back (wxT("2 beats"));
_gridValues.push_back (tscale * 2.0);
_gridChoices.push_back (wxT("4 beats"));
_gridValues.push_back (tscale * 1.0);
if (setdefault) {
// default
_gridFactor = 4.0;
_gridChoiceIndex = 2;
}
break;
case FTspectrumModifier::UNIFORM_MODIFIER:
case FTspectrumModifier::RATIO_MODIFIER:
_gridChoices.push_back (wxT("50 %"));
_gridValues.push_back (2.0);
_gridChoices.push_back (wxT("25 %"));
_gridValues.push_back (4.0);
_gridChoices.push_back (wxT("20 %"));
_gridValues.push_back (5.0);
_gridChoices.push_back (wxT("10 %"));
_gridValues.push_back (10.0);
_gridChoices.push_back (wxT("5 %"));
_gridValues.push_back (20.0);
if (setdefault) {
// default
_gridFactor = 10.0;
_gridChoiceIndex = 3;
}
break;
case FTspectrumModifier::FREQ_MODIFIER:
break;
case FTspectrumModifier::DB_MODIFIER:
_gridChoices.push_back (wxT("1 dB"));
_gridValues.push_back (1.0);
_gridChoices.push_back (wxT("3 dB"));
_gridValues.push_back (3.0);
_gridChoices.push_back (wxT("6 dB"));
_gridValues.push_back (6.0);
_gridChoices.push_back (wxT("12 dB"));
_gridValues.push_back (12.0);
_gridChoices.push_back (wxT("18 dB"));
_gridValues.push_back (18.0);
_gridChoices.push_back (wxT("24 dB"));
_gridValues.push_back (24.0);
if (setdefault) {
// default
_gridFactor = 6.0;
_gridChoiceIndex = 2;
}
break;
default:
break;
}
}
void FTactiveBarGraph::setGridChoice (unsigned int index, bool writeextra)
{
if ( index < _gridValues.size()) {
_gridFactor = _gridValues[index];
_gridChoiceIndex = index;
if (writeextra) {
writeExtra (_specMod != 0 ? _specMod : _topSpecMod);
}
recalculate();
}
}
void FTactiveBarGraph::setGridLines (bool flag, bool writeextra)
{
_gridFlag = flag;
if (writeextra) {
writeExtra (_specMod != 0 ? _specMod : _topSpecMod);
}
recalculate();
}
void FTactiveBarGraph::setXscale(XScaleType sc, bool writeextra)
{
_xScaleType = sc;
if (writeextra) {
writeExtra (_specMod != 0 ? _specMod : _topSpecMod);
}
Refresh(FALSE);
}
void FTactiveBarGraph::setTempo(int bpm)
{
if (_tempo <= 0) return; // this is important!!
_tempo = bpm;
if (_mtype == FTspectrumModifier::TIME_MODIFIER) {
makeGridChoices();
_gridFactor = _gridValues[_gridChoiceIndex];
recalculate();
}
}
bool FTactiveBarGraph::setMinMax(float min, float max)
{
FTspectrumModifier *specmod;
if (_specMod) specmod = _specMod;
else if (_topSpecMod) specmod = _topSpecMod;
else return false;
if (min >= specmod->getMin() && max <= specmod->getMax()) {
_min = min;
_max = max;
recalculate();
return true;
}
else {
Refresh(FALSE);
}
return false;
}
void FTactiveBarGraph::setGridSnap (bool flag, bool writeextra)
{
_gridSnapFlag = flag;
if (writeextra) {
writeExtra (_specMod != 0 ? _specMod : _topSpecMod);
}
}
void FTactiveBarGraph::xToFreqRange(int x, float &fromfreq, float &tofreq, int &frombin, int &tobin)
{
float freqPerBin = FTjackSupport::instance()->getSampleRate()/(2.0 * (double)_specMod->getLength());
//printf ("specmod length = %d freqperbin=%g\n", _specMod->getLength(), freqPerBin);
xToBinRange(x, frombin, tobin);
fromfreq = freqPerBin * frombin;
tofreq = freqPerBin * tobin + freqPerBin;
}
void FTactiveBarGraph::xToBinRange(int x, int &frombin, int &tobin)
{
if (!_specMod) {
frombin = tobin = 0;
return;
}
// converts x coord into filter bin
// according to scaling
int lbin, rbin;
int totbins = _specMod->getLength();
//float xscale = _width / (float)totbins;
if (x < 0) x = 0;
else if (x >= _width) x = _width-1;
if (_xScaleType == XSCALE_1X) {
rbin = lbin = (int)(x / _xscale);
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest with same x
while ( ((int)((lbin-1)*_xscale) == x) && (lbin > 0)) {
lbin--;
}
// find highest with same x
while ( ((int)((rbin+1)*_xscale) == x) && (rbin < totbins-1)) {
rbin++;
}
frombin = lbin;
tobin = rbin;
}
else if (_xScaleType == XSCALE_2X) {
float hxscale = _xscale * 2;
if (x >= _width-2) {
lbin = totbins/2;
rbin = totbins-1;
}
else {
rbin = lbin = (int)(x / hxscale);
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest with same x
while ( ((int)((lbin-1)*hxscale) == x) && (lbin > 0)) {
lbin--;
}
// find highest with same x
while ( ((int)((rbin+1)*hxscale) == x) && (rbin < totbins>>1)) {
rbin++;
}
}
frombin = lbin;
tobin = rbin;
}
else if (_xScaleType == XSCALE_LOGA)
{
if (x >= _width-1) {
lbin = totbins/2;
rbin = totbins-1;
}
else {
float xscale = x / (float)_width;
// use log scale for freq
lbin = rbin = (int) ::pow ( (double) (totbins>>1), (double) xscale) - 1;
// find lowest with same x
while ( (lbin > 0) && ((int)(((FTutils::fast_log10(lbin) / FTutils::fast_log10(totbins/2)) * _width)) == x)) {
lbin--;
}
// find highest with same x
while ( (rbin < totbins>>1) && ((int)(((FTutils::fast_log10(rbin) / FTutils::fast_log10(totbins/2)) )) == x)) {
rbin++;
}
}
frombin = lbin;
tobin = rbin;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else if (_xScaleType == XSCALE_LOGB)
{
if (x >= _width-1) {
lbin = (int) (totbins/3.0);
rbin = totbins-1;
}
else {
float xscale = x / (float)_width;
// use log scale for freq
lbin = rbin = (int) ::pow ( (double)(totbins/3.0), xscale) - 1;
// find lowest with same x
while ( (lbin > 0) && ((int)(((FTutils::fast_log10(lbin) / FTutils::fast_log10(totbins/3.0)) * _width)) == x)) {
lbin--;
}
// find highest with same x
while ( (rbin < (int)(totbins/3.0)) && ((int)(((FTutils::fast_log10(rbin) / FTutils::fast_log10(totbins/3.0)) )) == x)) {
rbin++;
}
}
frombin = lbin;
tobin = rbin;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else {
frombin = 0;
tobin = 0;
}
//printf ("x=%d frombin=%d tobin=%d\n", x, frombin, tobin);
}
int FTactiveBarGraph::xDeltaToBinDelta(int xdelt)
{
return (int) (xdelt / _xscale);
}
float FTactiveBarGraph::valDiffY(float val, int lasty, int newy)
{
float retval;
if (_specMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER
|| _specMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
// db scaled
float vdb = valToDb (val);
float ddb = ((lasty-newy)/(float)_height) * (_maxdb - _mindb) ;
retval = dbToVal (vdb + ddb);
}
else if (_specMod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER) {
// semitone scaled
float vsemi = valToSemi (val);
float dsemi = ((lasty-newy)/(float)_height) * (_maxsemi - _minsemi) ;
retval = semiToVal (vsemi + dsemi);
}
else {
float shiftval = yToVal(newy) - yToVal(lasty);
retval = ( val + shiftval);
}
if (_gridSnapFlag) {
retval = snapValue(retval);
}
return retval;
}
void FTactiveBarGraph::binToXRange(int bin, int &fromx, int &tox)
{
if (!_specMod) {
fromx = tox = 0;
return;
}
// converts bin into x coord range
// according to scaling
int lx, rx;
int totbins = _specMod->getLength();
//float xscale = _width / (float)totbins;
if (bin < 0) bin = 0;
else if (bin >= totbins) bin = totbins-1;
if (_xScaleType == XSCALE_1X) {
//bin = rbin = lbin = (int)(x / xscale);
lx = rx = (int) (bin * _xscale);
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest x with same bin
while ( ((int)((lx-1)/_xscale) == bin) && (lx > 0)) {
lx--;
}
// find highest with same x
while ( ((int)((rx+1)/_xscale) == bin) && (rx < _width-1)) {
rx++;
}
fromx = lx;
tox = rx;
}
else if (_xScaleType == XSCALE_2X) {
float hxscale = _xscale * 2;
if (bin >= totbins>>1) {
rx = (int) (totbins * _xscale);
lx = rx - 2;
}
else {
//bin = rbin = lbin = (int)(x / xscale);
lx = rx = (int) (bin * hxscale );
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest x with same bin
while ( ((int)((lx-1)/(hxscale)) == bin) && (lx > 0)) {
lx--;
}
// find highest with same x
while ( ((int)((rx+1)/hxscale) == bin) && (rx < _width-1)) {
rx++;
}
}
fromx = lx;
tox = rx;
}
else if (_xScaleType == XSCALE_LOGA)
{
// use log scale for freq
if (bin > totbins/2) {
lx = rx = (int) (totbins * _xscale);
} else if (bin == 0) {
lx = 0;
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.5)) * _width);
} else {
lx = (int) ((FTutils::fast_log10(bin+1) / FTutils::fast_log10(totbins*0.5)) * _width);
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.5)) * _width);
}
fromx = lx;
tox = rx;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else if (_xScaleType == XSCALE_LOGB)
{
// use log scale for freq
if (bin > (int)(totbins*0.3333)) {
lx = rx = (int) (totbins * _xscale);
} else if (bin == 0) {
lx = 0;
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.3333)) * _width);
} else {
lx = (int) ((FTutils::fast_log10(bin+1) / FTutils::fast_log10(totbins*0.3333)) * _width);
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.3333)) * _width);
}
fromx = lx;
tox = rx;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else {
fromx = 0;
tox = 0;
}
//printf ("bin=%d fromx=%d tox=%d\n", bin, fromx, tox);
}
int FTactiveBarGraph::valToY(float val)
{
int y = 0;
if (_specMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER
||_specMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
// db scale it
float db = valToDb(val);
y = (int) (( (db - _mindb) / (_maxdb - _mindb)) * _height);
//printf ("val=%g db=%g y=%d\n", val, db, y);
}
else if (_specMod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER) {
// go from octave to semitone
float semi = valToSemi (val);
y = (int) (( (semi - _minsemi) / (_maxsemi - _minsemi)) * _height);
}
else if (_specMod->getModifierType() == FTspectrumModifier::FREQ_MODIFIER) {
if (_xScaleType == XSCALE_1X || _xScaleType == XSCALE_2X)
{
y = (int) ( (val - _min)/(_max-_min) * _height);
}
else if (_xScaleType == XSCALE_LOGA)
{
// use log scale for freq
y = (int) ((FTutils::fast_log10(val+1) / FTutils::fast_log10(_absmax*0.5)) * _height);
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else if (_xScaleType == XSCALE_LOGB)
{
y = (int) ((FTutils::fast_log10(val+1) / FTutils::fast_log10(_absmax*0.3333)) * _height);
}
// scale it however the X scale is
}
else {
y = (int) ( (val - _min)/(_max-_min) * _height);
}
//printf ("val to y: %g to %d\n", val, y);
return y;
}
float FTactiveBarGraph::yToDb(int y)
{
return (((_height - y)/(float)_height) * (_maxdb-_mindb)) + _mindb ;
}
float FTactiveBarGraph::yToSemi(int y)
{
return (((_height - y)/(float)_height) * (_maxsemi-_minsemi)) + _minsemi ;
}
float FTactiveBarGraph::yToVal(int y)
{
float val = 0.0;
if (_specMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER
||_specMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
// go from db to linear
float db = yToDb (y);
val = dbToVal(db);
//printf ("y=%d val=%g db=%g\n", y, val, db);
}
else if (_specMod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER) {
// go from semitone to octave
float semi = (((_height - y)/(float)_height) * (_maxsemi-_minsemi)) + _minsemi ;
// Up a semitone is * 1.0593 or 12 2 (12th root of 2)
val = semiToVal(semi);
//printf ("y=%d val=%g db=%g\n", y, val, db);
}
else if (_specMod->getModifierType() == FTspectrumModifier::FREQ_MODIFIER) {
if (_xScaleType == XSCALE_1X || _xScaleType == XSCALE_2X)
{
val = (((_height - y) / (float)_height)) * (_max-_min) + _min;
//y = (int) ( (val - _min)/(_max-_min) * _height);
}
else if (_xScaleType == XSCALE_LOGA)
{
// use log scale for freq
//y = (int) ((FTutils::fast_log10(val) / FTutils::fast_log10(_absmax*0.5)) * _height);
val = (int) ::pow ( (double) (_absmax*0.5), (double) (_height-y)/_height ) - 1;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else if (_xScaleType == XSCALE_LOGB)
{
//y = (int) ((FTutils::fast_log10(val) / FTutils::fast_log10(_absmax*0.3333)) * _height);
val = (int) ::pow ( (double) (_absmax*0.3333), (double) (_height-y)/_height ) - 1;
}
}
else {
val = (((_height - y) / (float)_height)) * (_max-_min) + _min;
}
return val;
}
float FTactiveBarGraph::snapValue(float val)
{
// takes a given value (as passed to the specmanip)
// and snaps it to the nearest gridline
float snapval = val;
if (_specMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER)
{
// every 6 db
float dbval = valToDb(val) / _gridFactor;
float numDivs = ((_absmaxdb - _absmindb) / _gridFactor);
float divdb = (_absmaxdb - _absmindb) / numDivs;
snapval = divdb * rint(dbval);
//printf ("gain snap: %g \n", snapval);
snapval = dbToVal (snapval);
}
else if (_specMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
// every 6 db
float dbval = valToDb(val) / _gridFactor;
float numDivs = ((_absposmaxdb - _absposmindb) / _gridFactor);
float divdb = (_absposmaxdb - _absposmindb) / numDivs;
snapval = divdb * rint(dbval);
//printf ("gain snap: %g \n", snapval);
snapval = dbToVal (snapval);
}
else if (_specMod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER)
{
float semival = valToSemi(val) / _gridFactor;
snapval = rint(semival) * _gridFactor;
//printf ("semi snap: %g \n", snapval);
snapval = semiToVal (snapval);
}
else if (_specMod->getModifierType() == FTspectrumModifier::TIME_MODIFIER) {
// every 500 msec
float updiv = val * _gridFactor;
snapval = rint(updiv) / _gridFactor;
}
else if (_specMod->getModifierType() == FTspectrumModifier::UNIFORM_MODIFIER) {
// every 0.2
float updiv = val * _gridFactor;
snapval = rint(updiv) / _gridFactor;
}
else if (_specMod->getModifierType() == FTspectrumModifier::DB_MODIFIER) {
// every 12 db
float dbval = val / _gridFactor;
float numDivs = ((_absmax - _absmin) / _gridFactor);
float divdb = (_absmax - _absmin) / numDivs;
snapval = divdb * rint(dbval);
//printf ("gain snap: %g \n", snapval);
}
return snapval;
}
void FTactiveBarGraph::OnPaint(wxPaintEvent & event)
{
if (!_backingMap || !_specMod) {
event.Skip();
return;
}
//printf ("ActiveBarGraph::OnPaint xscale=%g\n", _xscale);
//Clear();
wxPaintDC dc(this);
wxMemoryDC backdc;
backdc.SelectObject(*_backingMap);
int bincnt = _specMod->getLength();
//float barwidthF = _width / (float) barcnt;
//int currx = 0;
float *bvalues = 0, *tvalues=0;
FTspectrumModifier * specmod = 0;
if (_specMod) {
bvalues = _specMod->getValues();
specmod = _specMod;
}
if (_topSpecMod) {
tvalues = _topSpecMod->getValues();
specmod = _topSpecMod;
}
bool both = false;
if (bvalues && tvalues) {
both = true;
}
else if (!specmod) {
return;
}
backdc.SetBackground(_bgBrush);
backdc.Clear();
// draw bars
//backdc.SetBrush(_barBrush);
backdc.SetPen(_barPen);
/*
if (_width == barcnt)
{
for (int i=0; i < barcnt; i++ )
{
int val = (int) ( (values[i] - _min)/(_max-_min) * _height);
backdc.DrawRectangle( i, _height - val, 1, val);
}
}
*/
for (int i=0; i < bincnt; i++ )
{
int yu=0 , yl = _height;
if (bvalues) {
yu = _height - valToY (bvalues[i]);
}
if (tvalues) {
yl = _height - valToY (tvalues[i]);
}
int leftx, rightx;
binToXRange(i, leftx, rightx);
//printf ("%08x: %d %d\n", (unsigned) this, leftx, rightx);
// main bar
if (_bypassed) {
backdc.SetBrush(_bypassBrush);
backdc.DrawRectangle( leftx, yu , rightx - leftx + 1, yl - yu);
}
else if (yu < yl) {
if (both) {
if (i%2==0) {
backdc.SetBrush(_barBrush2);
}
else {
backdc.SetBrush(_barBrush3);
}
}
else {
if (i%2==0) {
backdc.SetBrush(_barBrush1);
}
else {
backdc.SetBrush(_barBrush0);
}
}
backdc.DrawRectangle( leftx, yu , rightx - leftx + 1, yl - yu);
// top line
backdc.SetBrush(_tipBrush);
backdc.DrawRectangle( leftx, yu, rightx - leftx + 1, 2);
backdc.DrawRectangle( leftx, yl, rightx - leftx + 1, 2);
}
else {
backdc.SetBrush(_barBrushDead);
backdc.DrawRectangle( leftx, yu , rightx - leftx + 1, yl - yu);
}
}
// draw gridlines
if (_gridFlag) {
paintGridlines (backdc);
}
// draw min and max text
backdc.SetFont(_boundsFont);
wxCoord mtw, mth, xtw, xth;
backdc.GetTextExtent(_maxstr, &xtw, &xth);
backdc.GetTextExtent(_minstr, &mtw, &mth);
backdc.SetTextForeground(*wxBLACK);
backdc.DrawText(_maxstr, (_width - xtw) - 1, 1);
backdc.DrawText(_minstr, (_width - mtw) - 1, (_height - mth) + 1);
backdc.SetTextForeground(_textColor);
backdc.DrawText(_maxstr, (_width - xtw) - 2, 0);
backdc.DrawText(_minstr, (_width - mtw) - 2, (_height - mth));
if (_zooming) {
// draw xor'd box
backdc.SetLogicalFunction (wxINVERT);
backdc.DrawRectangle ( 0, _topzoomY, _width, _bottomzoomY - _topzoomY);
}
// blit to screen
dc.Blit(0,0, _width, _height, &backdc, 0,0);
// event.Skip();
}
void FTactiveBarGraph::paintGridlines(wxDC & dc)
{
wxRasterOperationMode origfunc = dc.GetLogicalFunction();
wxPen origPen = dc.GetPen();
dc.SetPen(_gridPen);
dc.SetLogicalFunction(wxOR);
// draw grid lines
list<int>::iterator yend = _gridPoints.end();
for (list<int>::iterator y = _gridPoints.begin() ; y != yend; ++y)
{
dc.DrawLine (0, *y, _width, *y);
}
dc.SetPen(origPen);
dc.SetLogicalFunction(origfunc);
}
void FTactiveBarGraph::recalculate()
{
if (!_specMod) return;
int totbins = _specMod->getLength();
_xscale = _width / (float)totbins;
_gridPoints.clear();
wxString maxstr, minstr;
if (_mtype == FTspectrumModifier::GAIN_MODIFIER
|| _mtype == FTspectrumModifier::POS_GAIN_MODIFIER) {
}
else if (_mtype == FTspectrumModifier::SEMITONE_MODIFIER) {
maxstr = wxString::Format(wxT("%.3g"), _maxsemi);
minstr = wxString::Format(wxT("%.3g"), _minsemi);
}
else {
maxstr = wxString::Format(wxT("%.3g"), _max);
minstr = wxString::Format(wxT("%.3g"), _min);
}
if (_specMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER
|| _specMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
// every _gridFactor db
_mindb = valToDb(_min);
_maxdb = valToDb(_max);
float numDivs = ((_absmax - _absmin) / _gridFactor);
float divdb = _gridFactor;
int y;
float cdb;
for (int i=1; i < (int)numDivs; ++i) {
cdb = _absmax - (divdb * i);
if (cdb <= _maxdb && cdb >= _mindb) {
// add line
y = (int) (( (cdb - _mindb) / (_maxdb - _mindb)) * _height);
_gridPoints.push_back (_height - y);
//printf ("gain grid %d: %g y=%d\n", i, cdb, y);
}
}
_maxstr = wxString::Format(wxT("%.1f"), _maxdb);
_minstr = wxString::Format(wxT("%.1f"), _mindb);
}
else if (_specMod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER)
{
// every semitone
_minsemi = valToSemi(_min);
_maxsemi = valToSemi(_max);
float numDivs = (_absmaxsemi - _absminsemi) / _gridFactor;
float updiv = _gridFactor;
int y;
float cunit;
for (int i=1; i < (int)numDivs; ++i) {
cunit = _absmaxsemi - (updiv * i);
if (cunit <= _maxsemi && cunit >= _minsemi) {
// add line
y = valToY(semiToVal(cunit));
_gridPoints.push_back (_height - y);
//printf ("pitch grid %d: %g y=%d\n", i, cunit, y);
}
}
_maxstr = wxString::Format(wxT("%+.1f"), _maxsemi);
_minstr = wxString::Format(wxT("%+.1f"), _minsemi);
}
else if (_specMod->getModifierType() == FTspectrumModifier::TIME_MODIFIER) {
// every 500 msec
float updiv = 1 / _gridFactor;
int y;
for (float i=updiv; i < _absmax; i+=updiv) {
if (i <= _max && i >= _min) {
// add line
y = valToY(i);
_gridPoints.push_back (_height - y);
//printf ("time grid: %g y=%d\n", i, y);
}
}
if (_gridChoiceIndex >= _beatscutoff) {
_maxstr = wxString::Format(wxT("%.2f"), _max * _tempo/60.0);
_minstr = wxString::Format(wxT("%.2f"), _min * _tempo/60.0);
} else {
_maxstr = wxString::Format(wxT("%.0f"), _max * 1000);
_minstr = wxString::Format(wxT("%.0f"), _min * 1000);
}
}
else if (_specMod->getModifierType() == FTspectrumModifier::UNIFORM_MODIFIER) {
// every 0.2
float updiv = 1 / _gridFactor;
int y;
for (float i=updiv; i < _absmax; i+=updiv) {
if (i <= _max && i >= _min) {
// add line
y = valToY(i);
_gridPoints.push_back (_height - y);
//printf ("uniform grid: %g y=%d\n", i, y);
}
}
_maxstr = wxString::Format(wxT("%.1f"), _max * 100);
_minstr = wxString::Format(wxT("%.1f"), _min * 100);
}
else if (_specMod->getModifierType() == FTspectrumModifier::DB_MODIFIER) {
// every 12 db
float numDivs = ((_absmax - _absmin) / _gridFactor);
float divdb = _gridFactor;
int y;
float cdb;
for (int i=1; i < (int)numDivs; ++i) {
cdb = _absmax - (divdb * i);
if (cdb <= _max && cdb >= _min) {
// add line
y = (int) (( (cdb - _min) / (_max - _min)) * _height);
_gridPoints.push_back (_height - y);
//printf ("gain grid %d: %g y=%d\n", i, cdb, y);
}
}
_maxstr = wxString::Format(wxT("%.1f"), _max);
_minstr = wxString::Format(wxT("%.1f"), _min);
}
else if (_specMod->getModifierType() == FTspectrumModifier::RATIO_MODIFIER) {
_maxstr = wxString::Format(wxT("%.0f"), _max);
_minstr = wxString::Format(wxT("%.0f"), _min);
}
Refresh(FALSE);
}
void FTactiveBarGraph::updateSize()
{
GetClientSize(&_width, &_height);
//printf ("ActiveBarGraph::OnSize: width=%d\n", _width);
if (_width > 0 && _height > 0 )
{
if (_backingMap) delete _backingMap;
_backingMap = new wxBitmap(_width, _height);
SetBackgroundColour(*wxBLACK);
//Clear();
recalculate();
}
}
void FTactiveBarGraph::OnSize(wxSizeEvent & event)
{
updateSize();
event.Skip();
}
void FTactiveBarGraph::writeExtra (FTspectrumModifier * specmod)
{
XMLNode * extra = specmod->getExtraNode();
extra->add_property ("xscale", static_cast<const char *> (wxString::Format(wxT("%d"), _xScaleType).mb_str()));
extra->add_property ("gridsnap", static_cast<const char *> (wxString::Format(wxT("%d"), (int) _gridSnapFlag).mb_str()));
extra->add_property ("grid", static_cast<const char *> (wxString::Format(wxT("%d"), (int) _gridChoiceIndex).mb_str()));
extra->add_property ("gridlines", static_cast<const char *> (wxString::Format(wxT("%d"), (int) _gridFlag).mb_str()));
}
void FTactiveBarGraph::readExtra (FTspectrumModifier * specmod)
{
XMLNode * extra = specmod->getExtraNode();
XMLProperty * prop;
long val;
wxString strval;
if ((prop = extra->property ("xscale"))) {
strval = wxString::FromAscii (prop->value().c_str());
if (strval.ToLong (&val)) {
setXscale ((XScaleType) val, false);
}
}
if ((prop = extra->property ("grid"))) {
strval = wxString::FromAscii (prop->value().c_str());
if (strval.ToLong (&val)) {
setGridChoice ((unsigned int) val, false);
}
}
if ((prop = extra->property ("gridsnap"))) {
strval = wxString::FromAscii (prop->value().c_str());
if (strval.ToLong (&val)) {
setGridSnap ( val != 0 ? true : false, false);
}
}
if ((prop = extra->property ("gridlines"))) {
strval = wxString::FromAscii (prop->value().c_str());
if (strval.ToLong (&val)) {
setGridLines ( val != 0 ? true : false, false);
}
}
}
void FTactiveBarGraph::OnMouseActivity( wxMouseEvent &event)
{
if (!_specMod) {
event.Skip();
return;
}
int pX = event.GetX();
int pY = event.GetY();
int i,j;
//int length = _specMod->getLength();
//float xscale = (float) _width / (float)length;
FTspectrumModifier *specm;
if (_specMod) {
specm = _specMod;
}
else if (_topSpecMod) {
specm = _topSpecMod;
}
else {
// nothing to do
return;
}
if (event.LeftDown()) {
if (event.RightIsDown()) {
SetCursor(wxCURSOR_HAND);
}
else if (event.ControlDown() && event.ShiftDown() && event.AltDown() && !_dragging)
{
// ZOOMING
SetCursor(wxCURSOR_MAGNIFIER);
}
if (!_mouseCaptured) {
CaptureMouse();
_mouseCaptured = true;
}
}
else if (event.RightDown()) {
SetCursor(wxCURSOR_HAND);
if (!_mouseCaptured) {
CaptureMouse();
_mouseCaptured = true;
}
}
if (event.Entering()) {
SetCursor(wxCURSOR_PENCIL);
updatePositionLabels(pX, pY, true);
}
else if (event.Leaving()) {
SetCursor(*wxSTANDARD_CURSOR);
_mainwin->updatePosition(wxT(""), wxT(""));
}
else if (event.MiddleUp()) {
// popup scale menu
this->PopupMenu ( _xscaleMenu, pX, pY);
}
else if (!_dragging && event.LeftIsDown() && (_zooming || (event.ControlDown() && event.ShiftDown() && event.AltDown())))
{
// zooming related
if (event.LeftDown()) {
_zooming = true;
if (_gridSnapFlag) {
_firstY = _topzoomY = _bottomzoomY = valToY(snapValue(yToVal(_height - pY))) + 1;
} else {
_firstY = _topzoomY = _bottomzoomY = pY;
}
Refresh(FALSE);
}
else if (event.LeftIsDown()) {
if (_gridSnapFlag) {
if (pY < _firstY) {
_bottomzoomY = _firstY;
_topzoomY = valToY(snapValue(yToVal(_height - pY))) + 1;
pY = _topzoomY + 1;
}
else {
pY = valToY(snapValue(yToVal(_height - pY)));
_bottomzoomY = valToY(snapValue(yToVal(_height - pY))) + 1;
_topzoomY = _firstY;
pY = _bottomzoomY;
}
}
else {
if (pY < _firstY) {
_bottomzoomY = _firstY;
_topzoomY = pY;
}
else {
_bottomzoomY = pY;
_topzoomY = _firstY;
}
}
if (_topzoomY < 0) _topzoomY = 0;
if (_bottomzoomY > _height) _bottomzoomY = _height;
Refresh(FALSE);
updatePositionLabels(pX, pY, true);
}
}
else if ((event.LeftDown() || (_dragging && event.Dragging() && event.LeftIsDown())) && !event.RightIsDown() && !_zooming)
{
// Pencil drawing
if (event.LeftDown()) {
_firstX = _lastX = pX;
_firstY = _lastY = pY;
_dragging = true;
}
// modify spectrumModifier for bins
float *values ;
FTspectrumModifier *specmod=0;
if (_topSpecMod) {
if (event.ShiftDown() && _specMod) {
// shift does regular specmod if there is a topspecmod
values = _specMod->getValues();
specmod =_specMod;
}
else {
values = _topSpecMod->getValues();
specmod = _topSpecMod;
}
}
else if (_specMod) {
values = _specMod->getValues();
specmod = _specMod;
}
else {
event.Skip();
return;
}
int leftx, rightx;
int sign, linesign = 0;
if (_lastX <= pX) {
leftx = _lastX;
rightx = pX;
sign = 1;
}
else {
leftx = pX;
rightx = _lastX;
sign = -1;
}
// compute values to modify
int frombin, tobin, fromi, toi;
xToBinRange(leftx, fromi, toi);
frombin = fromi;
xToBinRange(rightx, fromi, toi);
tobin = toi;
//int fromi = (int) (_lastX / xscale);
//int toi = (int) (pX / xscale);
int useY = pY;
if (event.ControlDown() && !event.AltDown()) {
if (_firstCtrl) {
_firstY = pY;
_firstX = pX;
_firstCtrl = false;
}
useY = _firstY;
if (useY < 0) useY = 0;
else if (useY > _height) useY = _height;
float val = yToVal (useY);
if (_gridSnapFlag) {
val = snapValue(val);
}
for ( i=frombin; i<=tobin; i++)
{
values[i] = val;
//values[i] = (((_height - useY) / (float)_height)) * (_max-_min) + _min;
//printf ("i=%d values %g\n", i, values[i]);
}
}
else {
_firstCtrl = true;
if (useY < 0) useY = 0;
else if (useY > _height) useY = _height;
if (event.ControlDown() && event.AltDown())
{
if (_firstX <= pX) {
leftx = _firstX;
rightx = pX;
linesign = 1;
}
else {
leftx = pX;
rightx = _firstX;
linesign = -1;
}
}
int leftY, rightY;
if (sign != linesign)
{
if (sign > 0) {
leftY = _lastY;
rightY = useY;
}
else {
leftY = useY;
rightY = _lastY;
}
// if (specmod->getModifierType() != FTspectrumModifier::GAIN_MODIFIER)
{
float rightval = yToVal(rightY);
float leftval = yToVal(leftY);
if (_gridSnapFlag) {
leftval = snapValue(leftval);
rightval = snapValue(rightval);
}
float slope = (rightval - leftval) / (float)(1+tobin-frombin);
int n = 0;
if (_gridSnapFlag) {
for ( i=frombin; i<=tobin; i++, n++)
{
values[i] = snapValue(leftval + slope * n);
}
}
else {
for ( i=frombin; i<=tobin; i++, n++)
{
values[i] = leftval + slope * n;
}
}
}
// else {
// // do linear interpolation between firsty and usey
// float slope = (rightY - leftY) / (float)(1+tobin-frombin);
// //printf ("adjust is %g useY=%d lasty=%d\n", adj, useY, _lastY);
// int n=0;
// for ( i=frombin; i<=tobin; i++, n++)
// {
// values[i] = yToVal((int) (leftY + slope*n));
// }
// }
}
if (event.ControlDown() && event.AltDown())
{
xToBinRange(leftx, fromi, toi);
frombin = fromi;
xToBinRange(rightx, fromi, toi);
tobin = toi;
if (linesign > 0) {
leftY = _firstY;
rightY = useY;
}
else {
leftY = useY;
rightY = _firstY;
}
//if (specmod->getModifierType() != FTspectrumModifier::GAIN_MODIFIER)
{
float rightval = yToVal(rightY);
float leftval = yToVal(leftY);
if (_gridSnapFlag) {
leftval = snapValue(leftval);
rightval = snapValue(rightval);
}
float slope = (rightval - leftval) / (float)(1+tobin-frombin);
int n = 0;
if (_gridSnapFlag) {
for ( i=frombin; i<=tobin; i++, n++)
{
values[i] = snapValue(leftval + slope * n);
}
}
else {
for ( i=frombin; i<=tobin; i++, n++)
{
values[i] = leftval + slope * n;
}
}
}
// else {
// // do linear interpolation between firsty and usey
// float slope = (rightY - leftY) / (float)(1+tobin-frombin);
// //printf ("adjust is %g useY=%d lasty=%d\n", adj, useY, _lastY);
// int n=0;
// for ( i=frombin; i<=tobin; i++, n++)
// {
// values[i] = yToVal((int) (leftY + slope*n));
// }
// }
}
}
Refresh(FALSE);
_mainwin->updateGraphs(this, specm->getSpecModifierType());
_lastX = pX;
_lastY = useY;
updatePositionLabels(pX, useY, true, specmod);
}
else if ((event.RightDown() || (_dragging && event.Dragging() && event.RightIsDown())) && !_zooming)
{
// shift entire contour around
if (event.RightDown()) {
_firstX = _lastX = pX;
_firstY = _lastY = pY;
SetCursor(wxCURSOR_HAND);
_dragging = true;
_firstMove = true;
}
float * valueslist[2];
FTspectrumModifier *specmod = _specMod;
bool edgehold = event.ControlDown();
float *values;
int totbins;
if (_topSpecMod) {
if (event.ShiftDown() && _specMod) {
valueslist[0] = _specMod->getValues();
specmod = _specMod;
totbins = _specMod->getLength();
valueslist[1] = 0;
// do both
if (event.LeftIsDown()) {
valueslist[1] = _topSpecMod->getValues();
}
}
else {
valueslist[0] = _topSpecMod->getValues();
specmod = _topSpecMod;
totbins = _topSpecMod->getLength();
valueslist[1] = 0;
// do both
if (event.LeftIsDown()) {
valueslist[1] = _specMod->getValues();
}
}
}
else if (_specMod) {
valueslist[0] = _specMod->getValues();
specmod = _specMod;
totbins = _specMod->getLength();
valueslist[1] = 0;
if (event.LeftIsDown() && _topSpecMod) {
valueslist[1] = _topSpecMod->getValues();
}
}
else {
event.Skip();
return;
}
if (_gridSnapFlag)
{
int fromi, toi;
xToBinRange(_firstX, fromi, toi);
if (_firstMove) {
_lastVal = snapValue(valueslist[0][fromi]);
_firstMove = false;
}
else {
if (_lastY != pY) {
float tval = valDiffY (_lastVal, _lastY, pY);
if (tval == _lastVal) {
//
//printf ("not good enough returning: %g\n", tval);
pY = _lastY;
}
else {
_lastVal = tval;
//printf ("good enough: new lastval=%g\n", _lastVal);
}
}
}
}
// compute difference in x and y from last
int diffX;
diffX = pX - _lastX;
int shiftbins = xDeltaToBinDelta (diffX);
//float shiftval = yToVal(pY) - yToVal(_lastY);
//printf ("shiftbins %d diffx %d diffy %d\n", shiftbins, diffX, diffY);
for (int n = 0; n < 2 && valueslist[n]; n++)
{
values = valueslist[n];
if (shiftbins < 0) {
// shiftbins is NEGATIVE shift left
// store first shiftbins
for (i=0; i < -shiftbins; i++) {
_tmpfilt[i] = valDiffY (values[i], _lastY, pY);
}
for (i=0; i < totbins + shiftbins; i++) {
values[i] = valDiffY (values[i-shiftbins], _lastY, pY);
}
// finish off with end
if (edgehold) {
for (i=totbins+shiftbins; i < totbins; i++) {
values[i] = values[i-1];
}
}
else {
for (j=0, i=totbins+shiftbins; i < totbins; i++, j++) {
values[i] = _tmpfilt[j];
}
}
}
else if (shiftbins > 0) {
// shiftbins is POSITIVE, shift right
// store last shiftbins
for (i=totbins-shiftbins; i < totbins; i++) {
_tmpfilt[i] = valDiffY (values[i], _lastY, pY);
}
for ( i=totbins-1; i >= shiftbins; i--) {
values[i] = valDiffY (values[i-shiftbins], _lastY, pY);
}
// start off with first values (either wrapped or edge held)
if (edgehold) {
for ( i=shiftbins-1; i >= 0; i--) {
values[i] = values[i+1];
}
}
else {
for (j=totbins-shiftbins, i=0; i < shiftbins; i++, j++) {
values[i] = _tmpfilt[j];
}
}
}
else {
// no bin shift just values
for ( i=0; i < totbins; i++) {
values[i] = valDiffY (values[i], _lastY, pY);
}
}
}
Refresh(FALSE);
_mainwin->updateGraphs(this, specm->getSpecModifierType());
if (shiftbins != 0) {
_lastX = pX;
}
_lastY = pY;
updatePositionLabels(pX, pY, true, specmod);
}
else if (event.ButtonUp() && !event.LeftIsDown() && !event.RightIsDown()) {
if (_mouseCaptured) {
ReleaseMouse();
_mouseCaptured = false;
}
SetCursor(wxCURSOR_PENCIL);
_dragging = false;
if (event.RightUp() && event.ControlDown() && event.AltDown())
{
if (event.ShiftDown())
{
// reset zoom
_zooming = false;
if (_specMod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER)
{
_mindb = _absmindb;
_maxdb = _absmaxdb;
_min = dbToVal(_mindb);
_max = dbToVal(_maxdb);
recalculate();
}
else if (_specMod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
_mindb = _absposmindb;
_maxdb = _absposmaxdb;
_min = dbToVal(_mindb);
_max = dbToVal(_maxdb);
recalculate();
}
else {
setMinMax (_absmin, _absmax);
}
}
else {
// reset filter
if (_specMod) {
_specMod->reset();
}
if (_topSpecMod) {
_topSpecMod->reset();
}
Refresh(FALSE);
_mainwin->updateGraphs(this, specm->getSpecModifierType());
updatePositionLabels(pX, pY, true);
}
}
else if (_zooming)
{
// commit zoom
_zooming = false;
if (_gridSnapFlag) {
setMinMax ( snapValue(yToVal (_bottomzoomY)), snapValue(yToVal (_topzoomY)) );
} else {
setMinMax ( yToVal (_bottomzoomY), yToVal (_topzoomY) );
}
}
event.Skip();
}
else if (event.Moving())
{
if (_topSpecMod && !event.ShiftDown()) {
updatePositionLabels(pX, pY, true, _topSpecMod);
}
else if (_specMod) {
updatePositionLabels(pX, pY, true, _specMod);
}
}
else {
event.Skip();
}
}
void FTactiveBarGraph::updatePositionLabels(int pX, int pY, bool showreal, FTspectrumModifier *specmod)
{
// calculate freq range and val for status bar
float sfreq, efreq;
int frombin, tobin;
xToFreqRange(pX, sfreq, efreq, frombin, tobin);
_freqstr.Printf (wxT("%5d - %5d Hz"), (int) sfreq, (int) efreq);
float val, realval;
if (!specmod) {
if (_specMod) specmod = _specMod;
else if (_topSpecMod) specmod = _topSpecMod;
else return;
}
float *data = specmod->getValues();
if (specmod->getModifierType() == FTspectrumModifier::GAIN_MODIFIER
||specmod->getModifierType() == FTspectrumModifier::POS_GAIN_MODIFIER)
{
val = yToDb (pY);
if (showreal) {
realval = valToDb (data[frombin]);
_valstr.Printf (wxT("C: %7.1f dB @: %7.1f dB"), val, realval);
}
else {
_valstr.Printf (wxT("C: %7.1f dB"), val);
}
}
else if (specmod->getModifierType() == FTspectrumModifier::SEMITONE_MODIFIER) {
val = yToSemi (pY);
if (showreal) {
realval = valToSemi (data[frombin]);
_valstr.Printf (wxT("C: %7.1f semi @: %7.1f semi"), val, realval);
}
else {
_valstr.Printf (wxT("C: %7.1f dB"), val);
}
}
else if (specmod->getModifierType() == FTspectrumModifier::TIME_MODIFIER) {
val = yToVal (pY);
if (showreal) {
realval = data[frombin];
if (_gridChoiceIndex >= _beatscutoff) {
_valstr.Printf (wxT("C: %7.3f beats @: %7.3f beats"), val * _tempo/60.0, realval * _tempo/60.0);
} else {
_valstr.Printf (wxT("C: %7.0f ms @: %7.0f ms"), val * 1000.0, realval * 1000.0);
}
}
else {
if (_gridChoiceIndex >= _beatscutoff) {
_valstr.Printf (wxT("C: %7.3f beats"), val * _tempo/60.0);
} else {
_valstr.Printf (wxT("C: %7.0f ms"), val * 1000.0);
}
}
}
else if (specmod->getModifierType() == FTspectrumModifier::UNIFORM_MODIFIER) {
val = yToVal (pY);
if (showreal) {
realval = data[frombin];
_valstr.Printf (wxT("C: %7.1f %% @: %7.1f %%"), val * 100.0, realval * 100.0);
}
else {
_valstr.Printf (wxT("C: %7.1f %%"), val * 100.0);
}
}
else if (specmod->getModifierType() == FTspectrumModifier::DB_MODIFIER) {
val = yToVal (pY);
if (showreal) {
realval = data[frombin];
_valstr.Printf (wxT("C: %7.2f dB @: %7.2f dB"), val, realval);
}
else {
_valstr.Printf (wxT("C: %8.2f dB"), val);
}
}
else if (specmod->getModifierType() == FTspectrumModifier::FREQ_MODIFIER) {
FTioSupport *iosup = FTioSupport::instance();
float samprate = (float) iosup->getSampleRate();
val = yToVal (pY);
val = ((val - _absmin) / (_absmax-_absmin)) * samprate * 0.5;
if (showreal) {
realval = data[frombin];
realval = ((realval - _absmin) / (_absmax-_absmin)) * samprate * 0.5;
_valstr.Printf (wxT("C: %5d Hz @: %5d Hz"), (int) val, (int) realval);
}
else {
_valstr.Printf (wxT("C: %5d Hz"), (int)val);
}
}
else {
val = yToVal (pY);
if (showreal) {
realval = data[frombin];
_valstr.Printf (wxT("C: %7.3f @: %7.3f "), val, realval);
}
else {
_valstr.Printf (wxT("C: %8.3f"), val);
}
}
_mainwin->updatePosition ( _freqstr, _valstr );
}
void FTactiveBarGraph::OnXscaleMenu (wxCommandEvent &event)
{
//wxMenuItem *item = (wxMenuItem *) event.GetEventObject();
if (event.GetId() == FT_1Xscale) {
_xScaleType = XSCALE_1X;
}
else if (event.GetId() == FT_2Xscale) {
_xScaleType = XSCALE_2X;
}
else if (event.GetId() == FT_LogaXscale) {
_xScaleType = XSCALE_LOGA;
}
else if (event.GetId() == FT_LogbXscale) {
_xScaleType = XSCALE_LOGB;
}
else {
event.Skip();
}
Refresh(FALSE);
}
| 50,403
|
C++
|
.cpp
| 1,721
| 25.754213
| 124
| 0.632338
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,926
|
FTmodRandomize.cpp
|
essej_freqtweak/src/FTmodRandomize.cpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTmodRandomize.hpp"
#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
using namespace PBD;
FTmodRandomize::FTmodRandomize (nframes_t samplerate, unsigned int fftn)
: FTmodulatorI ("Randomize","Randomize", samplerate, fftn)
{
}
FTmodRandomize::FTmodRandomize (const FTmodRandomize & other)
: FTmodulatorI ("Randomize", "Randomize", other._sampleRate, other._fftN)
{
}
void FTmodRandomize::initialize()
{
_lastframe = 0;
_rate = new Control (Control::FloatType, "rate", "Rate", "Hz");
_rate->_floatLB = 0.0;
_rate->_floatUB = 20.0;
_rate->setValue (0.0f);
_controls.push_back (_rate);
_minval = new Control (Control::FloatType, "min_val", "Min Val", "%");
_minval->_floatLB = 0.0;
_minval->_floatUB = 100.0;
_minval->setValue (_minval->_floatLB);
_controls.push_back (_minval);
_maxval = new Control (Control::FloatType, "max_val", "Max Val", "%");
_maxval->_floatLB = 0.0;
_maxval->_floatUB = 100.0;
_maxval->setValue (_maxval->_floatUB);
_controls.push_back (_maxval);
_minfreq = new Control (Control::FloatType, "min_freq", "Min Freq", "Hz");
_minfreq->_floatLB = 0.0;
_minfreq->_floatUB = _sampleRate / 2;
_minfreq->setValue (_minfreq->_floatLB);
_controls.push_back (_minfreq);
_maxfreq = new Control (Control::FloatType, "max_freq", "Max Freq", "Hz");
_maxfreq->_floatLB = 0.0;
_maxfreq->_floatUB = _sampleRate / 2;
_maxfreq->setValue (_maxfreq->_floatUB);
_controls.push_back (_maxfreq);
srand(0);
_inited = true;
}
FTmodRandomize::~FTmodRandomize()
{
if (!_inited) return;
_controls.clear();
delete _rate;
delete _minfreq;
delete _maxfreq;
delete _minval;
delete _maxval;
}
void FTmodRandomize::modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes)
{
TentativeLockMonitor lm (_specmodLock, __LINE__, __FILE__);
if (!lm.locked() || !_inited || _bypassed) return;
float rate = 1.0;
float ub,lb, tmplb, tmpub;
float * filter;
unsigned int len;
_rate->getValue (rate);
if (rate == 0.0)
return;
unsigned int minbin, maxbin;
float minval = 0.0, maxval = 0.0;
float minfreq = 0.0, maxfreq = 0.0;
double samps = _sampleRate / rate;
_minval->getValue (minval);
_maxval->getValue (maxval);
if (minval > maxval) {
minval = maxval;
}
_minfreq->getValue (minfreq);
_maxfreq->getValue (maxfreq);
if (minfreq >= maxfreq) {
return;
}
double delta = current_frame - _lastframe;
if (delta >= samps)
{
// fprintf (stderr, "randomize at %lu : samps=%g s*c=%g s*e=%g \n", (unsigned long) current_frame, samps, (current_frame/samps), ((current_frame + nframes)/samps) );
for (SpecModList::iterator iter = _specMods.begin(); iter != _specMods.end(); ++iter)
{
FTspectrumModifier * sm = (*iter);
if (sm->getBypassed()) continue;
filter = sm->getValues();
sm->getRange(tmplb, tmpub);
len = sm->getLength();
lb = tmplb + (tmpub-tmplb) * minval * 0.01;
ub = tmplb + (tmpub-tmplb) * maxval * 0.01;
// cerr << " lb: " << lb << " ub: " << ub
// << " minval: " << minval << " maxval: " << maxval
// << " tmlb: " << tmplb << " tmpub: " << tmpub
// << endl;
minbin = (int) ((minfreq*2/ _sampleRate) * len);
maxbin = (int) ((maxfreq*2/ _sampleRate) * len);
// crap random
for (unsigned int i=minbin; i < maxbin; ++i) {
filter[i] = lb + (float) ((ub-lb) * rand() / (RAND_MAX+1.0));
}
sm->setDirty(true);
}
_lastframe = current_frame;
}
}
| 4,311
|
C++
|
.cpp
| 126
| 31.738095
| 170
| 0.670785
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,927
|
FTapp.cpp
|
essej_freqtweak/src/FTapp.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <signal.h>
#include <stdio.h>
#include <pthread.h>
#include <iostream>
//#include <wx/wx.h>
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWindows headers
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/cmdline.h>
#include "version.h"
#include "FTapp.hpp"
#include "FTtypes.hpp"
#include "FTmainwin.hpp"
#include "FTioSupport.hpp"
#include "FTprocessPath.hpp"
// Create a new application object: this macro will allow wxWindows to create
// the application object during program execution (it's better than using a
// static object for many reasons) and also declares the accessor function
// wxGetApp() which will return the reference of the right type (i.e. MyApp and
// not wxApp)
IMPLEMENT_APP(FTapp)
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// the application class
// ----------------------------------------------------------------------------
static const wxCmdLineEntryDesc cmdLineDesc[] =
{
{ wxCMD_LINE_SWITCH, wxT_2("h"), wxT_2("help"), wxT_2("show this help"), wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
{ wxCMD_LINE_OPTION, wxT_2("c"), wxT_2("channels"), wxT_2("# processing channels (1-4) default is 2"), wxCMD_LINE_VAL_NUMBER },
{ wxCMD_LINE_OPTION, wxT_2("i"), wxT_2("inputs"), wxT_2("connect inputs from these jack ports (separate each channel with commas).\n\t\t\tDefaults to 'alsa_pcm:capture_1,...") },
{ wxCMD_LINE_OPTION, wxT_2("o"), wxT_2("outputs"), wxT_2("connect outputs to these jack ports (separate each channel with commas).\n\t\t\tDefaults to 'alsa_pcm:playback_1,...'") },
{ wxCMD_LINE_OPTION, wxT_2("n"), wxT_2("jack-name"), wxT_2("jack name. default is freqtweak_1")},
{ wxCMD_LINE_OPTION, wxT_2("S"), wxT_2("jack-server"), wxT_2("jack server name")},
{ wxCMD_LINE_OPTION, wxT_2("p"), wxT_2("preset"), wxT_2("load given preset initially")},
{ wxCMD_LINE_OPTION, wxT_2("r"), wxT_2("rc-dir"), wxT_2("what directory to use for run-control state. default is ~/.freqtweak")},
{ wxCMD_LINE_NONE }
};
FTapp::FTapp()
: _mainwin(0)
{
}
static void* watchdog_thread(void* arg)
{
sigset_t signalset;
//struct ecasound_state* state = reinterpret_cast<struct ecasound_state*>(arg);
int signalno;
bool exiting = false;
/* register cleanup routine */
//atexit(&ecasound_atexit_cleanup);
// cerr << "Watchdog-thread created, pid=" << getpid() << "." << endl;
while (!exiting)
{
sigemptyset(&signalset);
/* handle the following signals explicitly */
sigaddset(&signalset, SIGTERM);
sigaddset(&signalset, SIGINT);
sigaddset(&signalset, SIGHUP);
sigaddset(&signalset, SIGPIPE);
/* block until a signal received */
sigwait(&signalset, &signalno);
//cerr << endl << "freqtweak: watchdog-thread received signal " << signalno << ". Cleaning up..." << endl;
if (signalno == SIGHUP) {
// reinit iosupport
// cerr << "freqtweak got SIGHUP... reiniting" << endl;
// wxThread::Sleep(200);
// FTioSupport * iosup = FTioSupport::instance();
// if (!iosup->isInited()) {
// iosup->init();
// if (iosup->startProcessing()) {
// iosup->reinit();
// }
// }
// if (::wxGetApp().getMainwin()) {
// ::wxGetApp().getMainwin()->updateDisplay();
// }
exiting = true;
}
else {
exiting = true;
}
}
::wxGetApp().getMainwin()->Close(TRUE);
::wxGetApp().ExitMainLoop();
printf ("bye bye, hope you had fun...\n");
/* to keep the compilers happy; never actually executed */
return(0);
}
/**
* Sets up a signal mask with sigaction() that blocks
* all common signals, and then launces an watchdog
* thread that waits on the blocked signals using
* sigwait().
*/
void FTapp::setupSignals()
{
pthread_t watchdog;
/* man pthread_sigmask:
* "...signal actions and signal handlers, as set with
* sigaction(2), are shared between all threads"
*/
struct sigaction blockaction;
blockaction.sa_handler = SIG_IGN;
sigemptyset(&blockaction.sa_mask);
blockaction.sa_flags = 0;
/* ignore the following signals */
sigaction(SIGTERM, &blockaction, 0);
sigaction(SIGINT, &blockaction, 0);
sigaction(SIGHUP, &blockaction, 0);
sigaction(SIGPIPE, &blockaction, 0);
int res = pthread_create(&watchdog,
NULL,
watchdog_thread,
NULL);
if (res != 0) {
cerr << "freqtweak: Warning! Unable to create watchdog thread." << endl;
}
}
// `Main program' equivalent: the program execution "starts" here
bool FTapp::OnInit()
{
// signal (SIGTERM, onTerminate);
// signal (SIGINT, onTerminate);
// signal (SIGHUP, onHangup);
wxString inputports[FT_MAXPATHS];
wxString outputports[FT_MAXPATHS];
wxString jackname;
wxString preset;
wxString rcdir;
wxString jackdir;
int pcnt = 2;
int icnt = 0;
int ocnt = 0;
bool connected = true;
SetExitOnFrameDelete(TRUE);
setupSignals();
if (sizeof(sample_t) != sizeof(float)) {
fprintf(stderr, "FFTW Mismatch! You need to build FreqTweak against a single-precision\n");
fprintf(stderr, " FFTW library. See the INSTALL file for instructions.\n");
return FALSE;
}
// use stderr as log
wxLog *logger=new wxLogStderr();
logger->SetTimestamp(wxEmptyString);
wxLog::SetActiveTarget(logger);
wxCmdLineParser parser(argc, argv);
parser.SetDesc(cmdLineDesc);
parser.SetLogo(wxT("FreqTweak ") +
wxString::FromAscii (freqtweak_version) +
wxT("\nCopyright 2002-2004 Jesse Chappell\n")
wxT("FreqTweak comes with ABSOLUTELY NO WARRANTY\n")
wxT("This is free software, and you are welcome to redistribute it\n")
wxT("under certain conditions; see the file COPYING for details\n"));
int ret = parser.Parse();
if (ret != 0) {
// help or error
return FALSE;
}
wxString strval;
long longval;
if (parser.Found (wxT("c"), &longval)) {
if (longval < 1 || longval > FT_MAXPATHS) {
fprintf(stderr, "Error: channel count must be in range [1-%d]\n", FT_MAXPATHS);
parser.Usage();
return FALSE;
}
pcnt = (int) longval;
}
if (parser.Found (wxT("S"), &jackdir)) {
FTioSupport::setDefaultServer ((const char *) jackdir.ToAscii());
}
if (parser.Found (wxT("n"), &jackname)) {
// FIXME: needs wchar_t->char conversion
FTioSupport::setDefaultName ((const char *)jackname.ToAscii());
}
parser.Found (wxT("r"), &rcdir);
parser.Found (wxT("p"), &preset);
// initialize jack support
FTioSupport * iosup = FTioSupport::instance();
if (!iosup->init()) {
fprintf(stderr, "Error connecting to jack!\n");
return FALSE;
}
if (parser.Found (wxT("i"), &strval))
{
// parse comma separated values
wxString port = strval.BeforeFirst(',');
wxString remain = strval.AfterFirst(',');
int id=0;
while (!port.IsEmpty() && id < pcnt) {
inputports[id++] = port;
port = remain.BeforeFirst(',');
remain = remain.AfterFirst(',');
++icnt;
}
}
else {
// Do not use default input ports anymore
icnt = 0;
// const char ** ports = iosup->getPhysicalInputPorts();
// if (ports) {
// // default input ports
// for (int id=0; id < pcnt && ports[id]; ++id, ++icnt) {
// inputports[id] = ports[id];
// }
// free (ports);
// }
}
// OUTPUT PORTS
if (parser.Found (wxT("o"), &strval))
{
// parse comma separated values
wxString port = strval.BeforeFirst(',');
wxString remain = strval.AfterFirst(',');
int id=0;
while (!port.IsEmpty() && id < pcnt) {
outputports[id++] = port;
port = remain.BeforeFirst(',');
remain = remain.AfterFirst(',');
++ocnt;
}
}
else {
const char ** ports = iosup->getPhysicalOutputPorts();
if (ports) {
// default output ports
for (int id=0; id < pcnt && ports[id]; ++id, ++ocnt) {
// FIXME: needs wchar_t->char conversion
outputports[id] = wxString::FromAscii (ports[id]);
}
free (ports);
}
}
// Create the main application window
_mainwin = new FTmainwin(pcnt, wxT("FreqTweak"), rcdir,
wxPoint(100, 100), wxDefaultSize);
// Show it and tell the application that it's our main window
_mainwin->SetSize(669,770);
_mainwin->Show(TRUE);
SetTopWindow(_mainwin);
if (connected)
{
// only start processing after building mainwin and connected
// to JACK
iosup->startProcessing();
if ( preset.IsEmpty()) {
// connect initial I/O
for (int id=0; id < icnt; ++id)
{
iosup->connectPathInput(id, (const char *) inputports[id].ToAscii());
}
for (int id=0; id < ocnt; ++id)
{
iosup->connectPathOutput(id, (const char *) outputports[id].ToAscii());
}
// load last settings
_mainwin->loadPreset(wxT(""), true);
}
else {
_mainwin->loadPreset(preset);
}
}
_mainwin->updateDisplay();
// success: wxApp::OnRun() will be called which will enter the main message
// loop and the application will run. If we returned FALSE here, the
// application would exit immediately.
return TRUE;
}
| 10,155
|
C++
|
.cpp
| 294
| 31.503401
| 182
| 0.656914
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,928
|
FTprocPitch.cpp
|
essej_freqtweak/src/FTprocPitch.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include <math.h>
#include "FTprocPitch.hpp"
#include "FTutils.hpp"
FTprocPitch::FTprocPitch (nframes_t samprate, unsigned int fftn)
: FTprocI("Pitch", samprate, fftn)
{
_confname = "Pitch";
}
FTprocPitch::FTprocPitch (const FTprocPitch & other)
: FTprocI (other._name, other._sampleRate, other._fftN)
{
_confname = "Pitch";
}
void FTprocPitch::initialize()
{
// create filter
_filter = new FTspectrumModifier("Pitch", "scale", 0, FTspectrumModifier::SEMITONE_MODIFIER, SCALE_SPECMOD, _fftN/2, 1.0);
_filter->setRange(0.5, 2.0);
_filter->setBypassed(true); // by default
_filterlist.push_back (_filter);
gLastPhase = new float [FT_MAX_FFT_SIZE];
gSumPhase = new float [FT_MAX_FFT_SIZE];
gAnaFreq = new float [FT_MAX_FFT_SIZE];
gSynFreq = new float [FT_MAX_FFT_SIZE];
gAnaMagn = new float [FT_MAX_FFT_SIZE];
gSynMagn = new float [FT_MAX_FFT_SIZE];
memset(gLastPhase, 0, FT_MAX_FFT_SIZE*sizeof(float));
memset(gSumPhase, 0, FT_MAX_FFT_SIZE*sizeof(float));
memset(gAnaFreq, 0, FT_MAX_FFT_SIZE*sizeof(float));
memset(gSynFreq, 0, FT_MAX_FFT_SIZE*sizeof(float));
memset(gAnaMagn, 0, FT_MAX_FFT_SIZE*sizeof(float));
memset(gSynMagn, 0, FT_MAX_FFT_SIZE*sizeof(float));
_inited = true;
}
FTprocPitch::~FTprocPitch()
{
if (!_inited) return;
delete [] gLastPhase;
delete [] gSumPhase;
delete [] gAnaFreq;
delete [] gSynFreq;
delete [] gAnaMagn;
delete [] gSynMagn;
_filterlist.clear();
delete _filter;
}
void FTprocPitch::process (fft_data *data, unsigned int fftn)
{
if (!_inited || _filter->getBypassed()) {
return;
}
float *filter = _filter->getValues();
double magn, phase, tmp, real, imag;
double freqPerBin, expct;
long k, qpd, index, stepSize;
int fftFrameSize2 = fftn / 2;
int fftFrameLength = fftn;
float min = _filter->getMin();
float max = _filter->getMax();
float filt;
int osamp = _oversamp;
stepSize = fftFrameLength/osamp;
freqPerBin = _sampleRate*2.0/(double)fftFrameLength;
expct = 2.0*M_PI*(double)stepSize/(double)fftFrameLength;
/* this is the analysis step */
for (k = 1; k < fftFrameSize2-1; k++) {
real = data[k];
imag = data[fftFrameLength - k];
/* compute magnitude and phase */
magn = sqrt(real*real + imag*imag);
phase = atan2(imag,real);
/* compute phase difference */
tmp = phase - gLastPhase[k];
gLastPhase[k] = phase;
/* subtract expected phase difference */
tmp -= (double)k*expct;
/* map delta phase into +/- Pi interval */
qpd = (long) (tmp/M_PI);
if (qpd >= 0) qpd += qpd&1;
else qpd -= qpd&1;
tmp -= M_PI*(double)qpd;
/* get deviation from bin frequency from the +/- Pi interval */
tmp = osamp*tmp/(2.0f*M_PI);
/* compute the k-th partials' true frequency */
tmp = (double)k*freqPerBin + tmp*freqPerBin;
/* store magnitude and true frequency in analysis arrays */
gAnaMagn[k] = magn;
gAnaFreq[k] = tmp;
}
/* ***************** PROCESSING ******************* */
/* this does the actual pitch scaling */
memset(gSynMagn, 0, fftFrameLength*sizeof(float));
memset(gSynFreq, 0, fftFrameLength*sizeof(float));
for (k = 0; k <= fftFrameSize2; k++)
{
filt = FTutils::f_clamp (filter[k], min, max);
index = (long) (k/filt);
if (index <= fftFrameSize2) {
/* new bin overrides existing if magnitude is higher */
if (gAnaMagn[index] > gSynMagn[k]) {
gSynMagn[k] = gAnaMagn[index];
gSynFreq[k] = gAnaFreq[index] * filt;
}
/* fill empty bins with nearest neighbour */
if ((gSynFreq[k] == 0.) && (k > 0)) {
gSynFreq[k] = gSynFreq[k-1];
gSynMagn[k] = gSynMagn[k-1];
}
}
}
/* ***************** SYNTHESIS ******************* */
/* this is the synthesis step */
for (k = 1; k < fftFrameSize2-1; k++) {
/* get magnitude and true frequency from synthesis arrays */
magn = gSynMagn[k];
tmp = gSynFreq[k];
/* subtract bin mid frequency */
tmp -= (double)k*freqPerBin;
/* get bin deviation from freq deviation */
tmp /= freqPerBin;
/* take osamp into account */
tmp = 2.*M_PI*tmp/osamp;
/* add the overlap phase advance back in */
tmp += (double)k*expct;
/* accumulate delta phase to get bin phase */
gSumPhase[k] += tmp;
phase = gSumPhase[k];
data[k] = magn*cos(phase);
data[fftFrameLength - k] = magn*sin(phase);
}
}
| 5,091
|
C++
|
.cpp
| 149
| 31.241611
| 123
| 0.679572
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,929
|
FTutils.cpp
|
essej_freqtweak/src/FTutils.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
** and Jay Gibble
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "FTutils.hpp"
#include <stdint.h>
#include <locale.h>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
/*
* Please excuse all the macros.
* They are used for explicit inlining of
* the "vector" versions of these functions.
*/
/* Logarithm base-10. */
/* absolute error < 6.4e-4 */
/* input must be > 0 */
float FTutils::fast_log10 (float x)
{
/******************************************************************/
/* strategy: factor x into */
/* 2^k * xprime */
/* (where xprime is in the interval [1, 2)) */
/* and compute log2 of both parts. */
/* */
/* (Then convert to log10.) */
/* */
/* a) log2 of 2^k is k (exact) */
/* b) log2 of xprime is approximated with */
/* a minimax polynomial. */
/* */
/* The answer is the sum of the answers (a) and (b). */
/* */
/* The approximation used for (b) yields max error of */
/* 6.4e-4 over the interval [1, 2) */
/******************************************************************/
/* minimax approximation courtesy of MAPLE */
/* invocation: */
/* > with('numapprox'); */
/* > y := minimax(log(x)/log(2), 1..2, [3,0], 1, 'maxerror'); */
/* > maxerror; */
#define FAST_LOG10_PREFACE \
\
/* coefficient to convert from log2 to log10 */ \
static const float log10_2 = 0.3010299957; \
\
/* coefficients for polynomial approximation */ \
static const float c0 = -2.153620718; \
static const float c1 = 3.047884161; \
static const float c2 = -1.051875031; \
static const float c3 = 0.1582487046; \
\
float ans = 0; \
\
\
/* "bits" representation of the argument "x" */ \
uint32_t* xbits = (uint32_t*)&x; \
\
/* exponent of IEEE float */ \
int expo; \
FAST_LOG10_PREFACE
#define FAST_LOG10_BODY \
/* get the IEEE float exponent and debias */ \
expo = (int) (*xbits >> 23) - 127; \
\
/* force the exponent of x to zero */ \
/* (range reduction to [1, 2)): */ \
*xbits &= 0x007fffff; \
*xbits += 0x3f800000; \
\
/* do the polynomial approximation */ \
ans = c0 + (c1 + (c2 + c3 * x) * x) * x; \
\
/* add the log2(2^k) term */ \
ans += expo; \
\
/******************************************/ \
/* convert to log10 */ \
/******************************************/ \
ans *= log10_2; \
FAST_LOG10_BODY
return ans;
}
/* Logarithm base-10. */
/* absolute error < 6.4e-4 */
/* input must be > 0 */
float FTutils::fast_log2 (float x)
{
/******************************************************************/
/* strategy: factor x into */
/* 2^k * xprime */
/* (where xprime is in the interval [1, 2)) */
/* and compute log2 of both parts. */
/* */
/* a) log2 of 2^k is k (exact) */
/* b) log2 of xprime is approximated with */
/* a minimax polynomial. */
/* */
/* The answer is the sum of the answers (a) and (b). */
/* */
/* The approximation used for (b) yields max error of */
/* 6.4e-4 over the interval [1, 2) */
/******************************************************************/
/* minimax approximation courtesy of MAPLE */
/* invocation: */
/* > with('numapprox'); */
/* > y := minimax(log(x)/log(2), 1..2, [3,0], 1, 'maxerror'); */
/* > maxerror; */
#define FAST_LOG2_PREFACE \
\
/* coefficients for polynomial approximation */ \
static const float c0 = -2.153620718; \
static const float c1 = 3.047884161; \
static const float c2 = -1.051875031; \
static const float c3 = 0.1582487046; \
\
float ans = 0; \
\
\
/* "bits" representation of the argument "x" */ \
uint32_t* xbits = (uint32_t*)&x; \
\
/* exponent of IEEE float */ \
int expo; \
FAST_LOG2_PREFACE
#define FAST_LOG2_BODY \
/* get the IEEE float exponent and debias */ \
expo = (int) (*xbits >> 23) - 127; \
\
/* force the exponent of x to zero */ \
/* (range reduction to [1, 2)): */ \
*xbits &= 0x007fffff; \
*xbits += 0x3f800000; \
\
/* do the polynomial approximation */ \
ans = c0 + (c1 + (c2 + c3 * x) * x) * x; \
\
/* add the log2(2^k) term */ \
ans += expo; \
FAST_LOG2_BODY
return ans;
}
/* Fourth root. */
/* relative error < 0.06% */
/* input must be >= 0 */
float FTutils::fast_fourth_root (float x)
{
/******************************************************************/
/* strategy: factor x into */
/* 2^(4k) * 2^({0,1,2,3}) * xprime */
/* (where xprime is in the interval [1/2, 1)) */
/* and compute the fourth root */
/* on each of the three parts. */
/* */
/* a) The fourth root of 2^(4k) is 2^k */
/* b) The fourth root of 2^({0,1,2,3}) is saved in a lookup table */
/* c) The fourth root of xprime is approximated with */
/* a minimax polynomial. */
/* */
/* The answer is the product of the answers from (a),(b) and (c) */
/* */
/* The approximation used for (c) yields max error of */
/* 5.2e-4 over the interval [1/2, 1) */
/* */
/* Relative error is always < 0.06% */
/******************************************************************/
/* minimax approximations courtesy of MAPLE */
/* invocation: */
/* > with('numapprox'); */
/* > y := minimax(x->(x^0.25), 0.5..1, [2,0], 1, 'maxerror'); */
/* > maxerror; */
#define FAST_FOURTH_ROOT_PREFACE \
\
/* table of fourth roots of small powers of 2 */ \
static const float fourth_root_pow_2[] = \
{ \
1.0, /* 1^(1/4) */ \
1.189207115, /* 2^(1/4) */ \
1.414213562, /* 4^(1/4) */ \
1.681792831 /* 8^(1/4) */ \
}; \
\
/* 2nd degree poly: */ \
/* max error = 5.2e-4 */ \
/* y := x -> 0.6011250669 + */ \
/* (0.5627811782 - 0.1644203886 x) x */ \
static const float c0 = 0.6011250669; \
static const float c1 = 0.5627811782; \
static const float c2 = -0.1644203886; \
\
/* 3rd degree poly: */ \
/* max error = 6.1e-5 */ \
/* y := x -> 0.5511182600 + (0.7764109321 + */ \
/* (-0.4594631650 + 0.1319948485 x) x) x */ \
\
/* 4th degree poly: */ \
/* max error = 7.8e-6 */ \
/* y := x -> 0.5167374448 + */ \
/* (0.9719985167 + (-0.8683104381 + */ \
/* (0.5043560567 - 0.1247894259 x) x) x) x */ \
\
\
/* "bits" representation of argument x */ \
uint32_t* xbits = (uint32_t*) &x; \
\
/* factor of 2^(4k) */ \
float two_to_4k = 1.0; \
/* bits representation */ \
int* two_to_4k_bits = (int *) &two_to_4k; \
\
/* exponent of IEEE float */ \
int expo; \
/* remainder of "expo" after dividing out factor of 2^(4k) */ \
int expo_rem; \
\
/* result */ \
float ans; \
FAST_FOURTH_ROOT_PREFACE
#define FAST_FOURTH_ROOT_BODY \
/* get the IEEE float exponent and debias */ \
/* (assuming non-negative sign bit) */ \
/* NOTE: we are debiasing to a reference point of 2^(-1) */ \
expo = (int) (*xbits >> 23) - 126; \
/* get the remainder after division of exponent by 4 */ \
expo_rem = expo & 0x03; \
/* do the division by 4 */ \
expo >>= 2; \
/* rebias and shift back up to make an IEEE float */ \
*two_to_4k_bits = (expo + 127) << 23; \
\
/* force the exponent of x to -1 */ \
/* (range reduction to [1/2, 1): */ \
\
/* mask out any exponent bits */ \
*xbits &= 0x007FFFFF; \
/* "0x3F000000" is the exponent for 2^(-1) (=126) shifted left by 23 */ \
*xbits += 0x3F000000; \
\
/* do the polynomial approximation */ \
ans = c0 + (c1 + c2 * x) * x; \
\
/* include the other factors */ \
ans *= fourth_root_pow_2 [expo_rem]; \
ans *= two_to_4k; \
FAST_FOURTH_ROOT_BODY
return ans;
}
/* Square root. */
/* relative error < 0.08% */
/* input must be >= 0 */
float FTutils::fast_square_root (float x)
{
/******************************************************************/
/* strategy: factor x into */
/* 2^(2k) * 2^({0,1}) * xprime */
/* (where xprime is in the interval [1/2, 1)) */
/* and compute the square root */
/* on each of the three parts. */
/* */
/* a) The square root of 2^(2k) is 2^k */
/* b) The square root of 2^({0,1}) is saved in a lookup table */
/* c) The square root of xprime is approximated with */
/* a minimax polynomial. */
/* */
/* The answer is the product of the answers from (a),(b) and (c) */
/* */
/* The approximation used for (c) yields max error of */
/* 5.4e-4 over the interval [1/2, 1) */
/* */
/* Relative error is always < 0.08% */
/******************************************************************/
/* minimax approximations courtesy of MAPLE */
/* invocation: */
/* > with('numapprox'); */
/* > y := minimax(x->(x^0.5), 0.5..1, [2,0], 1, 'maxerror'); */
/* > maxerror; */
#define FAST_SQUARE_ROOT_PREFACE \
\
/* table of square roots of small powers of 2 */ \
static const float square_root_pow_2[] = \
{ \
1.0, /* 1^(1/2) */ \
1.414213562 /* 2^(1/2) */ \
}; \
\
/* 2nd degree poly: */ \
/* max error = 5.4e-4 */ \
/* y := x -> 0.3151417738 + */ \
/* (0.8856989002 - 0.2013800934 x) x */ \
static const float c0 = 0.3151417738; \
static const float c1 = 0.8856989002; \
static const float c2 = -0.2013800934; \
\
\
/* "bits" representation of argument x */ \
uint32_t* xbits = (uint32_t*) &x; \
\
/* factor of 2^(2k) */ \
float two_to_2k = 1.0; \
/* bits representation */ \
int* two_to_2k_bits = (int *) &two_to_2k; \
\
/* exponent of IEEE float */ \
int expo; \
/* remainder of "expo" after dividing out factor of 2^(4k) */ \
int expo_rem; \
\
/* result */ \
float ans; \
FAST_SQUARE_ROOT_PREFACE
#define FAST_SQUARE_ROOT_BODY \
\
/* get the IEEE float exponent and debias */ \
/* (assuming non-negative sign bit) */ \
/* NOTE: we are debiasing to a reference point of 2^(-1) */ \
expo = (int) (*xbits >> 23) - 126; \
/* get the remainder after division of exponent by 2 */ \
expo_rem = expo & 0x01; \
/* do the division by 2 */ \
expo >>= 1; \
/* rebias and shift back up to make an IEEE float */ \
*two_to_2k_bits = (expo + 127) << 23; \
\
/* force the exponent of x to -1 */ \
/* (range reduction to [1/2, 1): */ \
\
/* mask out any exponent bits */ \
*xbits &= 0x007FFFFF; \
/* "0x3F000000" is the exponent for 2^(-1) (=126) shifted left by 23 */ \
*xbits += 0x3F000000; \
\
/* do the polynomial approximation */ \
ans = c0 + (c1 + c2 * x) * x; \
\
/* include the other factors */ \
ans *= square_root_pow_2 [expo_rem]; \
ans *= two_to_2k; \
FAST_SQUARE_ROOT_BODY
return ans;
}
/******************************************************************************/
/* here are some explicitly inlined vector versions */
/******************************************************************************/
void FTutils::vector_fast_log10 (const float* x_input, float* y_output, int N)
{
int i;
float x;
FAST_LOG10_PREFACE;
for (i=0; i<N; ++i)
{
x = x_input[i];
FAST_LOG10_BODY
y_output[i] = ans;
}
}
void FTutils::vector_fast_log2 (const float* x_input, float* y_output, int N)
{
int i;
float x;
FAST_LOG2_PREFACE;
for (i=0; i<N; ++i)
{
x = x_input[i];
FAST_LOG2_BODY
y_output[i] = ans;
}
}
void FTutils::vector_fast_square_root (const float* x_input, float* y_output, int N)
{
int i;
float x;
FAST_SQUARE_ROOT_PREFACE;
for (i=0; i<N; ++i)
{
x = x_input[i];
FAST_SQUARE_ROOT_BODY
y_output[i] = ans;
}
}
void FTutils::vector_fast_fourth_root (const float* x_input, float* y_output, int N)
{
int i;
float x;
FAST_FOURTH_ROOT_PREFACE;
for (i=0; i<N; ++i)
{
x = x_input[i];
FAST_FOURTH_ROOT_BODY
y_output[i] = ans;
}
}
double FTutils::sine_wave (double time, double freq_Hz)
{
return sin (2.0 * M_PI * freq_Hz * time);
}
double FTutils::square_wave (double time, double freq_Hz)
{
double sq = 1.0;
/* get fractional time in the current period */
/* of the waveform */
double norm_time = time * freq_Hz;
double frac = norm_time - floor(norm_time);
/* check which half of period we're in */
if (frac < 0.5)
{
sq = -1.0;
}
return sq;
}
double FTutils::triangle_wave (double time, double freq_Hz)
{
double tr;
/* get fractional time in the current period */
/* of the waveform */
double norm_time = time * freq_Hz;
double frac = norm_time - floor(norm_time);
/* check which half of period we're in */
if (frac < 0.5)
{
/* ascending slope */
/* frac in range [0, 1/2) */
tr = -1.0 + 4.0*frac;
}
else
{
/* descending slope */
/* frac in range [1/2, 1) */
tr = 3.0 - 4.0*frac;
}
return tr;
}
LocaleGuard::LocaleGuard (const char* str)
{
old = strdup (setlocale (LC_NUMERIC, NULL));
if (strcmp (old, str)) {
setlocale (LC_NUMERIC, str);
}
}
LocaleGuard::~LocaleGuard ()
{
setlocale (LC_NUMERIC, old);
free ((char*)old);
}
| 27,146
|
C++
|
.cpp
| 463
| 47.326134
| 84
| 0.274092
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,930
|
FTpresetBlendDialog.cpp
|
essej_freqtweak/src/FTpresetBlendDialog.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <string>
using namespace std;
#include <wx/wx.h>
#include <wx/listctrl.h>
#include "FTpresetBlendDialog.hpp"
#include "FTioSupport.hpp"
#include "FTmainwin.hpp"
#include "FTdspManager.hpp"
#include "FTprocI.hpp"
#include "FTprocessPath.hpp"
#include "FTspectralEngine.hpp"
#include "FTpresetBlender.hpp"
enum {
ID_PriPresetCombo=2000,
ID_SecPresetCombo,
ID_MasterSlider,
ID_FilterBlendSlider
};
BEGIN_EVENT_TABLE(FTpresetBlendDialog, wxFrame)
EVT_CLOSE(FTpresetBlendDialog::onClose)
EVT_SIZE (FTpresetBlendDialog::onSize)
EVT_PAINT (FTpresetBlendDialog::onPaint)
EVT_COMMAND_SCROLL (ID_MasterSlider, FTpresetBlendDialog::onSliders)
EVT_COMMAND_SCROLL (ID_FilterBlendSlider, FTpresetBlendDialog::onSliders)
EVT_COMBOBOX (ID_PriPresetCombo, FTpresetBlendDialog::onCombo)
EVT_COMBOBOX (ID_SecPresetCombo, FTpresetBlendDialog::onCombo)
END_EVENT_TABLE()
FTpresetBlendDialog::FTpresetBlendDialog(FTmainwin * parent, FTconfigManager *confman,
wxWindowID id,
const wxString & title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name )
: wxFrame(parent, id, title, pos, size, style, name),
_mainwin(parent), _justResized(false), _namewidth(85),
_configMan(confman)
{
_presetBlender = new FTpresetBlender(_configMan);
init();
}
FTpresetBlendDialog::~FTpresetBlendDialog()
{
delete _presetBlender;
}
void FTpresetBlendDialog::onSize(wxSizeEvent &ev)
{
_justResized = true;
ev.Skip();
}
void FTpresetBlendDialog::onPaint(wxPaintEvent &ev)
{
if (_justResized) {
_justResized = false;
}
ev.Skip();
}
void FTpresetBlendDialog::init()
{
wxBoxSizer * mainsizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *tmpsizer, *tmpsizer2;
wxStaticText * stattext;
wxBoxSizer * comboSizer = new wxBoxSizer(wxHORIZONTAL);
tmpsizer = new wxBoxSizer(wxVERTICAL);
tmpsizer2 = new wxBoxSizer(wxHORIZONTAL);
stattext = new wxStaticText(this, -1, wxT("Preset 1: "), wxDefaultPosition, wxSize(-1, -1));
//stattext->SetFont(titleFont);
tmpsizer2->Add(stattext, 0, wxALL|wxEXPAND, 1);
_priStatus = new wxStaticText(this, -1, wxT("not set"), wxDefaultPosition, wxSize(-1, -1));
tmpsizer2->Add(_priStatus, 0, wxALL, 1);
tmpsizer->Add (tmpsizer2, 0, wxALL|wxEXPAND, 1);
_priPresetBox = new wxComboBox (this, ID_PriPresetCombo, wxT(""), wxDefaultPosition, wxSize(175,-1), 0, 0, wxCB_READONLY|wxCB_SORT);
tmpsizer->Add( _priPresetBox, 0, wxALL|wxEXPAND|wxALIGN_LEFT, 1);
comboSizer->Add( tmpsizer, 0, wxALL|wxALIGN_LEFT, 1);
comboSizer->Add(1,-1,1);
tmpsizer = new wxBoxSizer(wxVERTICAL);
tmpsizer2 = new wxBoxSizer(wxHORIZONTAL);
stattext = new wxStaticText(this, -1, wxT("Preset 2: "), wxDefaultPosition, wxSize(-1, -1));
//stattext->SetFont(titleFont);
tmpsizer2->Add(stattext, 0, wxALL|wxEXPAND, 1);
_secStatus = new wxStaticText(this, -1, wxT("not set"), wxDefaultPosition, wxSize(-1, -1));
tmpsizer2->Add(_secStatus, 0, wxALL|wxEXPAND, 1);
tmpsizer->Add (tmpsizer2, 0, wxALL|wxEXPAND, 1);
_secPresetBox = new wxComboBox (this, ID_SecPresetCombo, wxT(""), wxDefaultPosition, wxSize(175,-1), 0, 0, wxCB_READONLY|wxCB_SORT);
tmpsizer->Add( _secPresetBox, 0, wxALL|wxEXPAND|wxALIGN_LEFT, 1);
comboSizer->Add( tmpsizer, 0, wxALL|wxALIGN_LEFT, 1);
mainsizer->Add (comboSizer, 0, wxEXPAND|wxALL, 2);
tmpsizer = new wxBoxSizer(wxHORIZONTAL);
stattext = new wxStaticText(this, -1, wxT("Master"), wxDefaultPosition, wxSize(_namewidth, -1));
//stattext->SetFont(titleFont);
stattext->SetSize(_namewidth, -1);
tmpsizer->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 1);
_masterBlend = new wxSlider(this, ID_MasterSlider, 0, 0, 1000);
tmpsizer->Add (_masterBlend, 1, wxALL|wxALIGN_CENTRE_VERTICAL, 3);
mainsizer->Add (tmpsizer, 0, wxEXPAND|wxALL, 5);
mainsizer->Add (2,5);
//wxScrolledWindow * scrolled = new wxScrolledWindow(this, -1);
_procSizer = new wxBoxSizer(wxVERTICAL);
wxScrolledWindow *scrolled = new wxScrolledWindow(this, -1, wxDefaultPosition, wxDefaultSize, wxVSCROLL|wxSUNKEN_BORDER);
scrolled->SetScrollRate (0,20);
_procPanel = scrolled;
refreshState();
_procPanel->SetAutoLayout( TRUE );
_procSizer->Fit( _procPanel );
_procSizer->SetSizeHints( this );
_procPanel->SetSizer( _procSizer );
mainsizer->Add (_procPanel, 1, wxEXPAND|wxALL, 2);
SetAutoLayout( TRUE );
mainsizer->Fit( this );
mainsizer->SetSizeHints( this );
SetSizer( mainsizer );
this->SetSizeHints(400,100);
}
void FTpresetBlendDialog::refreshState(const wxString & defname, bool usefirst, const wxString & defsec, bool usesec)
{
//wxFont titleFont(12, wxDEFAULT, wxNORMAL, wxBOLD);
// not compatible with old wx
_procSizer->Clear (true);
_procSizer->Layout();
_blendSliders.clear();
_blendPairs.clear();
_filtRefs.clear();
// reload presets
list<string> presetlist = _mainwin->getConfigManager().getSettingsNames();
wxString origfirst = _priPresetBox->GetValue();
wxString origsec = _secPresetBox->GetValue();
_priPresetBox->Clear();
_secPresetBox->Clear();
for (list<string>::iterator name=presetlist.begin(); name != presetlist.end(); ++name)
{
_priPresetBox->Append(wxString::FromAscii ((*name).c_str()));
_secPresetBox->Append(wxString::FromAscii ((*name).c_str()));
}
_priPresetBox->SetValue(defname.c_str());
_secPresetBox->SetValue(defsec.c_str());
// get configured modules from the first procpath
FTprocessPath * procpath = FTioSupport::instance()->getProcessPath(0);
if (procpath) {
FTspectralEngine *engine = procpath->getSpectralEngine();
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
for (unsigned int n=0; n < procmods.size(); ++n)
{
// item.SetText (procmods[n]->getName().c_str());
// item.SetData ((unsigned) procmods[n]);
// item.SetId (n);
// _targetList->InsertItem(item);
FTprocI *pm = procmods[n];
vector<FTspectrumModifier *> filts;
pm->getFilters (filts);
for (unsigned int m=0; m < filts.size(); ++m)
{
wxBoxSizer * tmpsizer = new wxBoxSizer(wxHORIZONTAL);
wxStaticText * stattext = new wxStaticText(_procPanel,
-1,
wxString::FromAscii (filts[m]->getName().c_str()),
wxDefaultPosition,
wxSize(_namewidth, -1));
//stattext->SetFont(titleFont);
stattext->SetSize(_namewidth, -1);
tmpsizer->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 1);
wxSlider * slid = new wxSlider(_procPanel, ID_FilterBlendSlider, 0, 0, 1000);
tmpsizer->Add (slid, 1, wxALL|wxALIGN_CENTRE_VERTICAL, 1);
_blendSliders.push_back (slid);
_blendPairs.push_back (ProcPair(n, m));
_filtRefs.push_back (filts[m]);
_procSizer->Add (tmpsizer, 0, wxEXPAND|wxALL, 4);
}
}
}
_procSizer->Layout();
// try to load them up
if (usefirst) {
if (_presetBlender->setPreset (static_cast<const char *> (defname.mb_str()), 0)) {
_priPresetBox->SetValue (wxString(defname.c_str()));
_priStatus->SetLabel (wxT("ready"));
}
else {
_priStatus->SetLabel (wxT("not set or invalid"));
}
}
else {
if (_presetBlender->setPreset (static_cast<const char *> (origfirst.mb_str()), 0)) {
_priPresetBox->SetValue (origfirst);
_priStatus->SetLabel (wxT("ready"));
}
else {
_priStatus->SetLabel (wxT("not set or invalid"));
}
}
if (usesec) {
if (_presetBlender->setPreset (static_cast<const char *> (defsec.mb_str()), 1)) {
_secPresetBox->SetValue (wxString(defsec.c_str()));
_secStatus->SetLabel (wxT("ready"));
}
else {
_secStatus->SetLabel (wxT("not set or invalid"));
}
}
else {
if (_presetBlender->setPreset (static_cast<const char *> (origsec.mb_str()), 1)) {
_secPresetBox->SetValue (origsec);
_secStatus->SetLabel (wxT("ready"));
}
else {
_secStatus->SetLabel (wxT("not set or invalid"));
}
}
}
void FTpresetBlendDialog::onClose(wxCloseEvent & ev)
{
if (!ev.CanVeto()) {
Destroy();
}
else {
ev.Veto();
Show(false);
}
}
void FTpresetBlendDialog::onCombo(wxCommandEvent &ev)
{
if (ev.GetId() == ID_PriPresetCombo) {
wxString name = _priPresetBox->GetStringSelection();
if (!name.empty()) {
if (!_presetBlender->setPreset(static_cast<const char *> (name.mb_str()), 0)) {
// display error message
printf ("error could not load preset %s\n", static_cast<const char *> (name.mb_str()));
_priPresetBox->SetSelection(-1);
_priPresetBox->SetValue(wxT(""));
_priStatus->SetLabel (wxT("not set or invalid"));
}
else {
_priStatus->SetLabel (wxT("ready"));
}
}
}
else if (ev.GetId() == ID_SecPresetCombo) {
wxString name = _secPresetBox->GetStringSelection();
if (!name.empty()) {
if (!_presetBlender->setPreset(static_cast<const char *> (name.mb_str()), 1)) {
// display error message
printf ("error could not load preset %s\n", static_cast<const char *> (name.mb_str()));
_secPresetBox->SetSelection(-1);
_secPresetBox->SetValue(wxT(""));
_secStatus->SetLabel (wxT("not set or invalid"));
}
else {
_secStatus->SetLabel (wxT("ready"));
}
}
}
}
void FTpresetBlendDialog::onSliders(wxScrollEvent &ev)
{
wxSlider * source = (wxSlider *) ev.GetEventObject();
bool updateall = false;
static bool ignoreevent = false;
if (ignoreevent) return;
for (unsigned int i=0; i < _blendSliders.size(); ++i)
{
if (_masterBlend == source) {
ProcPair & ppair = _blendPairs[i];
float max = (float) _masterBlend->GetMax();
float min = (float) _masterBlend->GetMin();
float newval = (((float)_masterBlend->GetValue() - min) / (max-min));
_presetBlender->setBlend (ppair.first, ppair.second, 1.0 - newval);
ignoreevent = true;
_blendSliders[i]->SetValue(_masterBlend->GetValue());
updateall = true;
}
else if (_blendSliders[i] == source) {
ProcPair & ppair = _blendPairs[i];
float max = (float) _blendSliders[i]->GetMax();
float min = (float) _blendSliders[i]->GetMin();
float newval = ((_blendSliders[i]->GetValue() - min) / (max-min));
_presetBlender->setBlend (ppair.first, ppair.second, 1.0 - newval);
_mainwin->updateGraphs(0, _filtRefs[i]->getSpecModifierType());
break;
}
}
if (updateall)
{
_mainwin->updateGraphs(0, ALL_SPECMOD);
if (ignoreevent) {
ignoreevent = false;
}
}
}
| 11,171
|
C++
|
.cpp
| 309
| 32.815534
| 135
| 0.707806
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,931
|
FTprocBoost.cpp
|
essej_freqtweak/src/FTprocBoost.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTprocBoost.hpp"
#include "FTutils.hpp"
FTprocBoost::FTprocBoost (nframes_t samprate, unsigned int fftn)
: FTprocI("EQ Boost", samprate, fftn)
{
_confname = "Boost";
}
FTprocBoost::FTprocBoost (const FTprocBoost & other)
: FTprocI (other._name, other._sampleRate, other._fftN)
{
_confname = "Boost";
}
void FTprocBoost::initialize()
{
// create filter
_eqfilter = new FTspectrumModifier("EQ Boost", "freq_boost", 0, FTspectrumModifier::POS_GAIN_MODIFIER, BOOST_SPECMOD, _fftN/2, 1.0);
_eqfilter->setRange(1.0, 16.0);
_filterlist.push_back (_eqfilter);
_inited = true;
}
FTprocBoost::~FTprocBoost()
{
if (!_inited) return;
_filterlist.clear();
delete _eqfilter;
}
void FTprocBoost::process (fft_data *data, unsigned int fftn)
{
if (!_inited || _eqfilter->getBypassed()) {
return;
}
float *filter = _eqfilter->getValues();
float min = _eqfilter->getMin();
float max = _eqfilter->getMax();
float filt;
int fftN2 = (fftn+1) >> 1;
filt = FTutils::f_clamp(filter[0], min, max);
data[0] *= filt;
for (int i = 1; i < fftN2-1; i++)
{
filt = FTutils::f_clamp(filter[i], min, max);
data[i] *= filt;
data[fftn-i] *= filt;
}
}
| 1,980
|
C++
|
.cpp
| 63
| 29.333333
| 133
| 0.711498
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,932
|
FThelpWindow.cpp
|
essej_freqtweak/src/FThelpWindow.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "FThelpWindow.hpp"
FThelpWindow::FThelpWindow(wxWindow * parent, wxWindowID id, const wxString & title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
: wxFrame(parent, id, title, pos, size, style, name)
{
init();
}
FThelpWindow::~FThelpWindow()
{
}
void FThelpWindow::init()
{
wxBoxSizer * mainsizer = new wxBoxSizer(wxVERTICAL);
_htmlWin = new wxHtmlWindow(this, -1, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxHW_SCROLLBAR_AUTO);
mainsizer->Add (_htmlWin, 1, wxALL|wxEXPAND, 4);
SetAutoLayout( TRUE );
mainsizer->Fit( this );
mainsizer->SetSizeHints( this );
SetSizer( mainsizer );
const int sizes[] = {7, 8, 10, 12, 16, 22, 30};
_htmlWin->SetFonts(wxT(""), wxT(""), sizes);
#ifndef __WXMAC__
wxString helppath = wxString(wxT(HELP_HTML_PATH)) + wxFileName::GetPathSeparator() + wxString(wxT("usagehelp.html"));
#else
wxString helppath(wxT(""));
#endif
if (wxFile::Access(helppath, wxFile::read))
{
_htmlWin->LoadPage(helppath);
}
else {
_htmlWin->SetPage(wxString(wxT("Help information could not be found at ")) + helppath +
wxString(wxT(" . If you can't get it, please see http://freqtweak.sf.net")));
}
this->SetSizeHints(200,100);
this->SetSize(600,400);
}
| 2,132
|
C++
|
.cpp
| 61
| 32.377049
| 119
| 0.723446
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,933
|
FTmodulatorManager.cpp
|
essej_freqtweak/src/FTmodulatorManager.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTmodulatorManager.hpp"
#include "FTioSupport.hpp"
#include "FTmodulatorI.hpp"
#include "FTmodRandomize.hpp"
#include "FTmodRotate.hpp"
#include "FTmodRotateLFO.hpp"
#include "FTmodValueLFO.hpp"
FTmodulatorManager * FTmodulatorManager::_instance = 0;
FTmodulatorManager::FTmodulatorManager()
{
unsigned int fftn = 512;
nframes_t samprate = FTioSupport::instance()->getSampleRate();
// TODO: load initial dynamically
FTmodulatorI * procmod = new FTmodRotate (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTmodRotateLFO (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTmodValueLFO (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTmodRandomize (samprate, fftn);
_prototypes.push_back (procmod);
}
FTmodulatorManager::~FTmodulatorManager()
{
// cleanup prototypes
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
delete (*iter);
}
_prototypes.clear();
}
void FTmodulatorManager::getAvailableModules (ModuleList & outlist)
{
outlist.clear();
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
outlist.push_back(*iter);
}
}
FTmodulatorI * FTmodulatorManager::getModuleByName (const string & name)
{
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
if ((*iter)->getName() == name) {
return (*iter);
}
}
return 0;
}
FTmodulatorI * FTmodulatorManager::getModuleByConfigName (const string & name)
{
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
if ((*iter)->getConfName() == name) {
return (*iter);
}
}
return 0;
}
FTmodulatorI * FTmodulatorManager::getModuleByIndex (unsigned int index)
{
if (index < _prototypes.size()) {
unsigned int n=0;
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
if (n == index) {
return (*iter);
}
n++;
}
}
return 0;
}
| 2,804
|
C++
|
.cpp
| 86
| 30.372093
| 92
| 0.731099
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,934
|
FTioSupport.cpp
|
essej_freqtweak/src/FTioSupport.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <string>
using namespace std;
#include "FTioSupport.hpp"
#include "FTjackSupport.hpp"
FTioSupport * FTioSupport::_instance = 0;
FTioSupport::IOtype FTioSupport::_iotype = FTioSupport::IO_JACK;
string FTioSupport::_defaultName;
string FTioSupport::_defaultServ;
FTioSupport * FTioSupport::createInstance()
{
// static method
if (_iotype == IO_JACK) {
return new FTjackSupport(_defaultName.c_str(), _defaultServ.c_str());
}
else {
return 0;
}
}
void FTioSupport::setName (const string & name)
{
_name = name;
}
| 1,393
|
C++
|
.cpp
| 44
| 30.045455
| 80
| 0.753731
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,935
|
FTprocessPath.cpp
|
essej_freqtweak/src/FTprocessPath.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <string.h>
#include "FTprocessPath.hpp"
#include "FTdspManager.hpp"
#include "FTspectralEngine.hpp"
#include "FTprocI.hpp"
#include "RingBuffer.hpp"
FTprocessPath::FTprocessPath()
: _maxBufsize(16384), _sampleRate(44100), _specEngine(0), _readyToDie(false), _id(0)
{
// construct lockfree ringbufer
_inputFifo = new RingBuffer(sizeof(sample_t) * FT_FIFOLENGTH);
_outputFifo = new RingBuffer(sizeof(sample_t) * FT_FIFOLENGTH);
initSpectralEngine();
}
FTprocessPath::~FTprocessPath()
{
printf ("$#$#$#$#$ processpath \n");
delete _inputFifo;
delete _outputFifo;
if (_specEngine) delete _specEngine;
}
void FTprocessPath::initSpectralEngine()
{
_specEngine = new FTspectralEngine();
// load all dsp modules from dsp manager and put them in
FTdspManager::ModuleList mlist;
FTdspManager::instance()->getAvailableModules (mlist);
FTdspManager::ModuleList::iterator mod = mlist.begin();
for (; mod != mlist.end(); ++mod)
{
if (!(*mod)->useAsDefault())
continue;
FTprocI * newmod = (*mod)->clone();
newmod->initialize();
_specEngine->appendProcessorModule (newmod);
}
}
void FTprocessPath::setId (int id)
{
_id = id;
if (_specEngine) _specEngine->setId (id);
}
/**
* This will get called from the jack thread
*/
void FTprocessPath::processData (sample_t * inbuf, sample_t *outbuf, nframes_t nframes)
{
bool good;
if (_specEngine->getBypassed())
{
if (_specEngine->getMuted()) {
memset (outbuf, 0, sizeof(sample_t) * nframes);
}
else if (inbuf != outbuf) {
memcpy (outbuf, inbuf, sizeof(sample_t) * nframes);
}
}
else
{
// copy data from inbuf to the lock free fifo at write pointer
if (_inputFifo->write_space() >= (nframes * sizeof(sample_t)))
{
_inputFifo->write ((char *) inbuf, sizeof(sample_t) * nframes);
}
else {
//fprintf(stderr, "BLAH! Can't write into input fifo!\n");
}
// DO SPECTRAL PROCESSING
good = _specEngine->processNow (this);
// copy data from fifo at read pointer into outbuf
if (good && _outputFifo->read_space() >= (nframes * sizeof(sample_t)))
{
_outputFifo->read ((char *) outbuf, sizeof(sample_t) * nframes);
if (_specEngine->getMuted()) {
memset (outbuf, 0, sizeof(sample_t) * nframes);
}
}
else {
//fprintf(stderr, "BLAH! Can't read enough data from output fifo!\n");
if (_specEngine->getMuted()) {
memset (outbuf, 0, sizeof(sample_t) * nframes);
}
else {
memcpy (outbuf, inbuf, sizeof(sample_t) * nframes);
}
}
}
}
| 3,367
|
C++
|
.cpp
| 110
| 28.036364
| 87
| 0.70375
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,936
|
FTprocOrderDialog.cpp
|
essej_freqtweak/src/FTprocOrderDialog.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <wx/wx.h>
#include <wx/listctrl.h>
#include "FTprocOrderDialog.hpp"
#include "FTioSupport.hpp"
#include "FTmainwin.hpp"
#include "FTdspManager.hpp"
#include "FTprocI.hpp"
#include "FTprocessPath.hpp"
#include "FTspectralEngine.hpp"
enum {
ID_AddButton=8000,
ID_UpButton,
ID_DownButton,
ID_RemoveButton,
ID_CommitButton,
ID_CloseButton,
ID_SourceList,
ID_TargetList,
ID_AutoCheck
};
BEGIN_EVENT_TABLE(FTprocOrderDialog, wxFrame)
EVT_CLOSE(FTprocOrderDialog::onClose)
EVT_BUTTON(ID_UpButton, FTprocOrderDialog::onTargetButtons)
EVT_BUTTON(ID_DownButton, FTprocOrderDialog::onTargetButtons)
EVT_BUTTON(ID_RemoveButton, FTprocOrderDialog::onTargetButtons)
EVT_BUTTON(ID_CommitButton, FTprocOrderDialog::onCommit)
EVT_BUTTON(ID_AddButton, FTprocOrderDialog::onAddButton)
EVT_CHECKBOX(ID_AutoCheck, FTprocOrderDialog::onAutoCheck)
EVT_SIZE (FTprocOrderDialog::onSize)
EVT_PAINT (FTprocOrderDialog::onPaint)
END_EVENT_TABLE()
FTprocOrderDialog::FTprocOrderDialog(FTmainwin * parent, wxWindowID id,
const wxString & title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name )
: wxFrame(parent, id, title, pos, size, style, name),
_mainwin(parent)
{
init();
}
FTprocOrderDialog::~FTprocOrderDialog()
{
}
void FTprocOrderDialog::onSize(wxSizeEvent &ev)
{
_justResized = true;
ev.Skip();
}
void FTprocOrderDialog::onPaint(wxPaintEvent &ev)
{
if (_justResized) {
int width,height;
_justResized = false;
_sourceList->GetClientSize(&width, &height);
_sourceList->SetColumnWidth(0, width);
_targetList->GetClientSize(&width, &height);
_targetList->SetColumnWidth(0, width);
}
ev.Skip();
}
void FTprocOrderDialog::init()
{
wxBoxSizer * mainsizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer * sourceSizer = new wxBoxSizer(wxVERTICAL);
_sourceList = new wxListCtrl (this, ID_SourceList, wxDefaultPosition, wxDefaultSize, wxLC_REPORT|wxSUNKEN_BORDER);
_sourceList->InsertColumn(0, wxT("Available Modules"));
sourceSizer->Add (_sourceList, 1, wxEXPAND|wxALL, 2);
mainsizer->Add (sourceSizer, 1, wxEXPAND|wxALL, 6);
wxBoxSizer *midbuttSizer = new wxBoxSizer(wxVERTICAL);
wxButton * butt;
midbuttSizer->Add (-1, 20);
butt = new wxButton(this, ID_AddButton, wxT("Add ->"), wxDefaultPosition, wxSize(-1,-1));
midbuttSizer->Add(butt, 0, wxEXPAND|wxALL, 2);
butt = new wxButton(this, ID_RemoveButton, wxT("Remove"), wxDefaultPosition, wxSize(-1,-1));
midbuttSizer->Add(butt, 0, wxEXPAND|wxALL, 2);
midbuttSizer->Add (-1, 15);
butt = new wxButton(this, ID_UpButton, wxT("Up"), wxDefaultPosition, wxSize(-1,-1));
midbuttSizer->Add(butt, 0, wxEXPAND|wxALL, 2);
butt = new wxButton(this, ID_DownButton, wxT("Down"), wxDefaultPosition, wxSize(-1, -1));
midbuttSizer->Add(butt, 0, wxEXPAND|wxALL, 2);
midbuttSizer->Add (-1, 5, 1);
_modifiedText = new wxStaticText (this, -1, wxT(""), wxDefaultPosition, wxDefaultSize, wxALIGN_CENTRE);
midbuttSizer->Add(_modifiedText, 0, wxALL|wxEXPAND|wxALIGN_CENTRE_VERTICAL|wxALIGN_CENTRE, 3);
//butt = new wxButton(this, ID_CloseButton, "Close");
//midbuttSizer->Add(butt, 1, wxALL, 2);
mainsizer->Add (midbuttSizer, 0, wxEXPAND|wxALL, 4);
wxBoxSizer * targSizer = new wxBoxSizer(wxVERTICAL);
_targetList = new wxListCtrl (this, ID_TargetList, wxDefaultPosition, wxDefaultSize, wxLC_REPORT|wxSUNKEN_BORDER|wxLC_SINGLE_SEL);
_targetList->InsertColumn(0, wxT("Configured Modules"));
targSizer->Add (_targetList, 1, wxEXPAND|wxALL, 2);
// button bar
wxBoxSizer * buttSizer = new wxBoxSizer(wxHORIZONTAL);
_autoCheck = new wxCheckBox(this, ID_AutoCheck, wxT("Auto"));
buttSizer->Add( _autoCheck, 0, wxALL, 2);
butt = new wxButton(this, ID_CommitButton, wxT("Commit"));
buttSizer->Add(butt, 1, wxALL, 2);
targSizer->Add(buttSizer, 0, wxALL|wxEXPAND, 0);
mainsizer->Add(targSizer, 1, wxALL|wxEXPAND, 6);
refreshState();
SetAutoLayout( TRUE );
mainsizer->Fit( this );
mainsizer->SetSizeHints( this );
SetSizer( mainsizer );
this->SetSizeHints(200,100);
}
void FTprocOrderDialog::refreshState()
{
_sourceList->DeleteAllItems();
wxListItem item;
item.SetColumn(0);
item.SetMask (wxLIST_MASK_TEXT|wxLIST_MASK_DATA);
// get available modules
FTdspManager::ModuleList mlist;
FTdspManager::instance()->getAvailableModules (mlist);
FTdspManager::ModuleList::iterator mod = mlist.begin();
unsigned int pos = 0;
for (; mod != mlist.end(); ++mod)
{
item.SetText (wxString::FromAscii ((*mod)->getName().c_str()));
item.SetData (*mod);
item.SetId(pos++);
_sourceList->InsertItem(item);
}
// get configured modules from the first procpath
_targetList->DeleteAllItems();
FTprocessPath * procpath = FTioSupport::instance()->getProcessPath(0);
if (procpath) {
FTspectralEngine *engine = procpath->getSpectralEngine();
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
for (unsigned int n=0; n < procmods.size(); ++n)
{
item.SetText (wxString::FromAscii (procmods[n]->getName().c_str()));
item.SetData (procmods[n]);
item.SetId (n);
_targetList->InsertItem(item);
}
}
if (_lastSelected >= 0 && _lastSelected < _targetList->GetItemCount()) {
_targetList->SetItemState (_lastSelected, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
}
_actions.clear();
_modifiedText->SetLabel (wxT(""));
}
void FTprocOrderDialog::onClose(wxCloseEvent & ev)
{
if (!ev.CanVeto()) {
Destroy();
}
else {
ev.Veto();
Show(false);
}
}
void FTprocOrderDialog::onAutoCheck (wxCommandEvent &ev)
{
if (_autoCheck->GetValue() == true) {
// commit immediately
onCommit(ev);
}
}
void FTprocOrderDialog::onCommit(wxCommandEvent & ev)
{
//_mainwin->suspendProcessing();
FTioSupport * iosup = FTioSupport::instance();
// do this for every active process path
FTprocessPath * procpath;
for (int i=0; i < iosup->getActivePathCount(); ++i)
{
procpath = iosup->getProcessPath(i);
if (!procpath) break;
FTspectralEngine *engine = procpath->getSpectralEngine();
// go through the actions
for (list<ModAction>::iterator action = _actions.begin(); action != _actions.end(); ++action)
{
ModAction & act = *action;
if (act.remove) {
engine->removeProcessorModule ((unsigned int) act.from);
}
else if (act.from < 0) {
// no from, this is an addition
FTprocI * newproc = act.procmod->clone();
newproc->initialize();
engine->appendProcessorModule (newproc);
}
else {
// this is a move
engine->moveProcessorModule ((unsigned int) act.from, (unsigned int) act.to);
}
}
}
_actions.clear();
// rebuild UI parts
_mainwin->rebuildDisplay(false);
// _mainwin->restoreProcessing();
refreshState();
}
void FTprocOrderDialog::onTargetButtons(wxCommandEvent & ev)
{
int id = ev.GetId();
int itemi;
if (id == ID_RemoveButton)
{
itemi = _targetList->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (itemi != -1) {
_targetList->DeleteItem(itemi);
_actions.push_back (ModAction ((FTprocI*) _targetList->GetItemData(itemi),
itemi , -1, true));
if (itemi >= _targetList->GetItemCount()) itemi -= 1;
_targetList->SetItemState (itemi, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
_lastSelected = itemi;
if (_autoCheck->GetValue()) {
// commit immediately
onCommit(ev);
}
else {
_modifiedText->SetLabel (wxT("* modified *"));
}
}
}
else if (id == ID_UpButton)
{
itemi = _targetList->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (itemi > 0) {
// swap with item above
wxListItem item;
item.SetId(itemi);
item.SetMask(wxLIST_MASK_STATE|wxLIST_MASK_TEXT|wxLIST_MASK_DATA);
_targetList->GetItem (item);
_targetList->DeleteItem(itemi);
item.SetId(itemi-1);
_targetList->InsertItem(item);
_targetList->SetItemState (itemi-1, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
_actions.push_back (ModAction ((FTprocI*) item.GetData(),
itemi , itemi-1, false));
_lastSelected = itemi-1;
if (_autoCheck->GetValue()) {
// commit immediately
onCommit(ev);
}
else {
_modifiedText->SetLabel (wxT("* modified *"));
}
}
}
else if (id == ID_DownButton)
{
itemi = _targetList->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (itemi != -1 && itemi < _targetList->GetItemCount()-1) {
// swap with item below
wxListItem item;
item.SetId(itemi);
item.SetMask(wxLIST_MASK_STATE|wxLIST_MASK_TEXT|wxLIST_MASK_DATA);
_targetList->GetItem (item);
_targetList->DeleteItem(itemi);
item.SetId(itemi+1);
_targetList->InsertItem(item);
_targetList->SetItemState (itemi+1, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
_actions.push_back (ModAction ((FTprocI*) item.GetData(),
itemi , itemi+1, false));
_lastSelected = itemi+1;
if (_autoCheck->GetValue()) {
// commit immediately
onCommit(ev);
}
else {
_modifiedText->SetLabel (wxT("* modified *"));
}
}
}
else {
ev.Skip();
}
}
void FTprocOrderDialog::onAddButton(wxCommandEvent & ev)
{
// append selected procmods from source
wxListItem item;
item.SetColumn(0);
item.SetMask (wxLIST_MASK_TEXT|wxLIST_MASK_DATA);
long itemi = -1;
bool didsomething = false;
for ( ;; )
{
itemi = _sourceList->GetNextItem(itemi,
wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
if ( itemi == -1 )
break;
FTprocI * proc = (FTprocI *) _sourceList->GetItemData(itemi);
if (proc) {
item.SetText (wxString::FromAscii (proc->getName().c_str()));
item.SetData (proc);
item.SetId (_targetList->GetItemCount());
_targetList->InsertItem(item);
_actions.push_back (ModAction (proc, -1 , _targetList->GetItemCount(), false));
didsomething = true;
}
}
if (didsomething) {
if (_autoCheck->GetValue()) {
onCommit(ev);
}
else {
_modifiedText->SetLabel (wxT("* modified *"));
}
}
}
| 10,868
|
C++
|
.cpp
| 331
| 29.465257
| 131
| 0.713333
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,937
|
FTprocEQ.cpp
|
essej_freqtweak/src/FTprocEQ.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTprocEQ.hpp"
#include "FTutils.hpp"
FTprocEQ::FTprocEQ (nframes_t samprate, unsigned int fftn)
: FTprocI("EQ Cut", samprate, fftn)
{
_confname = "EQ";
}
FTprocEQ::FTprocEQ (const FTprocEQ & other)
: FTprocI (other._name, other._sampleRate, other._fftN)
{
_confname = "EQ";
}
void FTprocEQ::initialize()
{
// create filter
_eqfilter = new FTspectrumModifier("EQ Cut", "freq", 0, FTspectrumModifier::GAIN_MODIFIER, FREQ_SPECMOD, _fftN/2, 1.0);
_eqfilter->setRange(0.0, 1.0);
_filterlist.push_back (_eqfilter);
_inited = true;
}
FTprocEQ::~FTprocEQ()
{
if (!_inited) return;
_filterlist.clear();
delete _eqfilter;
}
void FTprocEQ::process (fft_data *data, unsigned int fftn)
{
if (!_inited || _eqfilter->getBypassed()) {
return;
}
float *filter = _eqfilter->getValues();
float min = _eqfilter->getMin();
float max = _eqfilter->getMax();
float filt;
int fftN2 = fftn/2;
filt = FTutils::f_clamp (filter[0], min, max);
data[0] *= filt;
for (int i = 1; i < fftN2-1; i++)
{
filt = FTutils::f_clamp (filter[i], min, max);
data[i] *= filt;
data[fftn-i] *= filt;
}
}
| 1,922
|
C++
|
.cpp
| 63
| 28.412698
| 120
| 0.706202
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,938
|
FTdspManager.cpp
|
essej_freqtweak/src/FTdspManager.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTdspManager.hpp"
#include "FTioSupport.hpp"
#include "FTprocI.hpp"
#include "FTprocEQ.hpp"
#include "FTprocGate.hpp"
#include "FTprocDelay.hpp"
#include "FTprocPitch.hpp"
#include "FTprocLimit.hpp"
#include "FTprocWarp.hpp"
#include "FTprocCompressor.hpp"
#include "FTprocBoost.hpp"
FTdspManager * FTdspManager::_instance = 0;
FTdspManager::FTdspManager()
{
unsigned int fftn = 512;
nframes_t samprate = FTioSupport::instance()->getSampleRate();
// TODO: load initial dynamically
FTprocI * procmod = new FTprocEQ (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTprocBoost (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTprocPitch (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTprocGate (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTprocDelay (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTprocLimit (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTprocWarp (samprate, fftn);
_prototypes.push_back (procmod);
procmod = new FTprocCompressor (samprate, fftn);
_prototypes.push_back (procmod);
}
FTdspManager::~FTdspManager()
{
// cleanup prototypes
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
delete (*iter);
}
_prototypes.clear();
}
void FTdspManager::getAvailableModules (ModuleList & outlist)
{
outlist.clear();
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
outlist.push_back(*iter);
}
}
FTprocI * FTdspManager::getModuleByName (const string & name)
{
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
if ((*iter)->getName() == name) {
return (*iter);
}
}
return 0;
}
FTprocI * FTdspManager::getModuleByConfigName (const string & name)
{
for (ModuleList::iterator iter = _prototypes.begin(); iter != _prototypes.end(); ++iter) {
if ((*iter)->getConfName() == name) {
return (*iter);
}
}
return 0;
}
| 2,836
|
C++
|
.cpp
| 85
| 31.270588
| 91
| 0.734484
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,939
|
FTprocI.cpp
|
essej_freqtweak/src/FTprocI.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "FTprocI.hpp"
FTprocI::FTprocI (const string & name, nframes_t samprate, unsigned int fftn)
: _sampleRate(samprate), _fftN(fftn), _oversamp(4), _inited(false), _name(name), _confname(name)
{
}
FTprocI::~FTprocI()
{
}
void FTprocI::setBypassed (bool flag)
{
_bypassed = flag;
for (FilterList::iterator filt = _filterlist.begin();
filt != _filterlist.end(); ++filt)
{
(*filt)->setBypassed (flag);
}
}
void FTprocI::setId (int id)
{
_id = id;
for (FilterList::iterator filt = _filterlist.begin();
filt != _filterlist.end(); ++filt)
{
(*filt)->setId(id);
}
}
| 1,440
|
C++
|
.cpp
| 47
| 28.638298
| 97
| 0.718116
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,940
|
RingBuffer.cpp
|
essej_freqtweak/src/RingBuffer.cpp
|
/*
Copyright (C) 2000 Paul Barton-Davis
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 2 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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301 USA.
$Id: RingBuffer.cpp,v 1.2 2004/11/10 17:16:08 trutkin Exp $
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <sys/types.h>
#include <sys/mman.h>
#include <cstring>
#include "RingBuffer.hpp"
RingBuffer::~RingBuffer ()
{
if (mlocked) {
munlock (buf, size);
}
delete [] buf;
}
size_t
RingBuffer::read (char *dest, size_t cnt)
{
size_t free_cnt;
size_t cnt2;
size_t to_read;
size_t n1, n2;
if ((free_cnt = read_space ()) == 0) {
return 0;
}
to_read = cnt > free_cnt ? free_cnt : cnt;
cnt2 = read_ptr + to_read;
if (cnt2 > size) {
n1 = size - read_ptr;
n2 = cnt2 & size_mask;
} else {
n1 = to_read;
n2 = 0;
}
memcpy (dest, &buf[read_ptr], n1);
read_ptr += n1;
read_ptr &= size_mask;
if (n2) {
memcpy (dest+n1, &buf[read_ptr], n2);
read_ptr += n2;
read_ptr &= size_mask;
}
return to_read;
}
size_t
RingBuffer::write (char *src, size_t cnt)
{
size_t free_cnt;
size_t cnt2;
size_t to_write;
size_t n1, n2;
if ((free_cnt = write_space ()) == 0) {
return 0;
}
to_write = cnt > free_cnt ? free_cnt : cnt;
cnt2 = write_ptr + to_write;
if (cnt2 > size) {
n1 = size - write_ptr;
n2 = cnt2 & size_mask;
} else {
n1 = to_write;
n2 = 0;
}
memcpy (&buf[write_ptr], src, n1);
write_ptr += n1;
write_ptr &= size_mask;
if (n2) {
memcpy (&buf[write_ptr], src+n1, n2);
write_ptr += n2;
write_ptr &= size_mask;
}
return to_write;
}
int
RingBuffer::mlock ()
{
if (::mlock (buf, size)) {
return -1;
}
mlocked = true;
return 0;
}
void RingBuffer::mem_set ( char val)
{
::memset ( buf, val, size );
}
void
RingBuffer::get_read_vector (rw_vector *vec)
{
size_t free_cnt;
size_t cnt2;
size_t w, r;
w = write_ptr;
r = read_ptr;
if (w > r) {
free_cnt = w - r;
} else {
free_cnt = (w - r + size) & size_mask;
}
cnt2 = r + free_cnt;
if (cnt2 > size) {
/* Two part vector: the rest of the buffer after the
current write ptr, plus some from the start of
the buffer.
*/
vec[0].buf = &buf[r];
vec[0].len = size - r;
vec[1].buf = buf;
vec[1].len = cnt2 & size_mask;
} else {
/* Single part vector: just the rest of the buffer */
vec[0].buf = &buf[r];
vec[0].len = free_cnt;
vec[1].len = 0;
}
}
void
RingBuffer::get_write_vector (rw_vector *vec)
{
size_t free_cnt;
size_t cnt2;
size_t w, r;
w = write_ptr;
r = read_ptr;
if (w > r) {
free_cnt = ((r - w + size) & size_mask) - 1;
} else if (w < r) {
free_cnt = (r - w) - 1;
} else {
free_cnt = size - 1;
}
cnt2 = w + free_cnt;
if (cnt2 > size) {
/* Two part vector: the rest of the buffer after the
current write ptr, plus some from the start of
the buffer.
*/
vec[0].buf = &buf[w];
vec[0].len = size - w;
vec[1].buf = buf;
vec[1].len = cnt2 & size_mask;
} else {
vec[0].buf = &buf[w];
vec[0].len = free_cnt;
vec[1].len = 0;
}
}
| 3,661
|
C++
|
.cpp
| 162
| 19.759259
| 72
| 0.635993
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,941
|
xml++.cpp
|
essej_freqtweak/src/xml++.cpp
|
/* xml++.cc
* libxml++ and this file are copyright (C) 2000 by Ari Johnson, and
* are covered by the GNU Lesser General Public License, which should be
* included with libxml++ as the file COPYING.
*/
#include "xml++.hpp"
static XMLNode *readnode(xmlNodePtr);
static void writenode(xmlDocPtr, XMLNode *, xmlNodePtr, int);
XMLTree::XMLTree(const XMLTree * from)
{
_filename = from->filename();
_root = new XMLNode(*from->root());
_compression = from->compression();
_initialized = true;
}
XMLTree::~XMLTree()
{
if (_initialized && _root)
delete _root;
}
int XMLTree::set_compression(int c)
{
if (c > 9)
c = 9;
if (c < 0)
c = 0;
_compression = c;
return _compression;
}
bool XMLTree::read(void)
{
xmlDocPtr doc;
if (_root) {
delete _root;
_root = NULL;
}
xmlKeepBlanksDefault(0);
doc = xmlParseFile(_filename.c_str());
if (!doc) {
_initialized = false;
return false;
}
_root = readnode(xmlDocGetRootElement(doc));
xmlFreeDoc(doc);
_initialized = true;
return true;
}
bool XMLTree::read_buffer(const string & buffer)
{
xmlDocPtr doc;
_filename = "";
if (_root) {
delete _root;
_root = NULL;
}
doc = xmlParseMemory((char *) buffer.c_str(), buffer.length());
if (!doc) {
_initialized = false;
return false;
}
_root = readnode(xmlDocGetRootElement(doc));
xmlFreeDoc(doc);
_initialized = true;
return true;
}
bool XMLTree::write(void) const
{
xmlDocPtr doc;
XMLNodeList children;
int result;
xmlKeepBlanksDefault(0);
doc = xmlNewDoc((xmlChar *) "1.0");
xmlSetDocCompressMode(doc, _compression);
writenode(doc, _root, doc->children, 1);
result = xmlSaveFormatFile(_filename.c_str(), doc, 1);
xmlFreeDoc(doc);
if (result == -1)
return false;
return true;
}
const string & XMLTree::write_buffer(void) const
{
static string retval;
char *ptr;
int len;
xmlDocPtr doc;
XMLNodeList children;
xmlKeepBlanksDefault(0);
doc = xmlNewDoc((xmlChar *) "1.0");
xmlSetDocCompressMode(doc, _compression);
writenode(doc, _root, doc->children, 1);
xmlDocDumpMemory(doc, (xmlChar **) & ptr, &len);
xmlFreeDoc(doc);
retval = ptr;
free(ptr);
return retval;
}
XMLNode::XMLNode(const string & n)
: _name(n), _is_content(false), _content(string())
{
if (_name.empty())
_initialized = false;
else
_initialized = true;
}
XMLNode::XMLNode(const string & n, const string & c)
:_name(string()), _is_content(true), _content(c)
{
_initialized = true;
}
XMLNode::XMLNode(const XMLNode& from)
: _initialized(false)
{
XMLPropertyList props;
XMLPropertyIterator curprop;
XMLNodeList nodes;
XMLNodeIterator curnode;
_name = from.name();
set_content(from.content());
props = from.properties();
for (curprop = props.begin(); curprop != props.end(); curprop++)
add_property((*curprop)->name(), (*curprop)->value());
nodes = from.children();
for (curnode = nodes.begin(); curnode != nodes.end(); curnode++)
add_child_copy(**curnode);
}
XMLNode::~XMLNode()
{
XMLNodeIterator curchild;
XMLPropertyIterator curprop;
for (curchild = _children.begin(); curchild != _children.end();
curchild++)
delete *curchild;
for (curprop = _proplist.begin(); curprop != _proplist.end();
curprop++)
delete *curprop;
}
const string & XMLNode::set_content(const string & c)
{
if (c.empty())
_is_content = false;
else
_is_content = true;
_content = c;
return _content;
}
const XMLNodeList & XMLNode::children(const string & n) const
{
static XMLNodeList retval;
XMLNodeConstIterator cur;
if (n.length() == 0)
return _children;
retval.erase(retval.begin(), retval.end());
for (cur = _children.begin(); cur != _children.end(); cur++)
if ((*cur)->name() == n)
retval.insert(retval.end(), *cur);
return retval;
}
XMLNode *XMLNode::add_child(const string & n)
{
return add_child_copy(XMLNode (n));
}
void
XMLNode::add_child_nocopy (XMLNode& n)
{
_children.insert(_children.end(), &n);
}
XMLNode *
XMLNode::add_child_copy(const XMLNode& n)
{
XMLNode *copy = new XMLNode (n);
_children.insert(_children.end(), copy);
return copy;
}
XMLNode *XMLNode::add_content(const string & c)
{
return add_child_copy(XMLNode (string(), c));
}
XMLProperty *XMLNode::property(const string & n)
{
if (_propmap.find(n) == _propmap.end())
return NULL;
return _propmap[n];
}
XMLProperty *XMLNode::add_property(const string & n, const string & v)
{
if(_propmap.find(n) != _propmap.end()){
remove_property(n);
}
XMLProperty *tmp = new XMLProperty(n, v);
if (!tmp)
return NULL;
_propmap[tmp->name()] = tmp;
_proplist.insert(_proplist.end(), tmp);
return tmp;
}
void XMLNode::remove_property(const string & n)
{
if (_propmap.find(n) != _propmap.end()) {
_proplist.remove(_propmap[n]);
_propmap.erase(n);
}
}
void XMLNode::remove_nodes(const string & n)
{
XMLNodeIterator i = _children.begin();
XMLNodeIterator tmp;
while (i != _children.end()) {
tmp = i;
++tmp;
if ((*i)->name() == n) {
_children.remove(*i);
}
i = tmp;
}
}
static XMLNode *readnode(xmlNodePtr node)
{
string name, content;
xmlNodePtr child;
XMLNode *tmp;
xmlAttrPtr attr;
if (node->name)
name = (char *) node->name;
else
name = string();
tmp = new XMLNode(name);
for (attr = node->properties; attr; attr = attr->next) {
name = (char *) attr->name;
content = "";
if (attr->children)
content = (char *) attr->children->content;
tmp->add_property(name, content);
}
if (node->content)
tmp->set_content((char *) node->content);
else
tmp->set_content(string());
for (child = node->children; child; child = child->next)
tmp->add_child_nocopy (*readnode(child));
return tmp;
}
static void writenode(xmlDocPtr doc, XMLNode * n, xmlNodePtr p, int root =
0)
{
XMLPropertyList props;
XMLPropertyIterator curprop;
XMLNodeList children;
XMLNodeIterator curchild;
xmlNodePtr node;
if (root)
node = doc->children =
xmlNewDocNode(doc, NULL, (xmlChar *) n->name().c_str(), NULL);
else
node = xmlNewChild(p, NULL, (xmlChar *) n->name().c_str(), NULL);
if (n->is_content()) {
node->type = XML_TEXT_NODE;
xmlNodeSetContentLen(node, (const xmlChar *) n->content().c_str(),
n->content().length());
}
props = n->properties();
for (curprop = props.begin(); curprop != props.end(); curprop++)
xmlSetProp(node, (xmlChar *) (*curprop)->name().c_str(),
(xmlChar *) (*curprop)->value().c_str());
children = n->children();
for (curchild = children.begin(); curchild != children.end();
curchild++)
writenode(doc, *curchild, node);
}
| 6,917
|
C++
|
.cpp
| 269
| 21.933086
| 74
| 0.646388
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,942
|
FTmodRotateLFO.cpp
|
essej_freqtweak/src/FTmodRotateLFO.cpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTmodRotateLFO.hpp"
#include "FTutils.hpp"
#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
using namespace PBD;
FTmodRotateLFO::FTmodRotateLFO (nframes_t samplerate, unsigned int fftn)
: FTmodulatorI ("RotateLFO", "Rotate LFO", samplerate, fftn)
{
}
FTmodRotateLFO::FTmodRotateLFO (const FTmodRotateLFO & other)
: FTmodulatorI ("RotateLFO", "Rotate LFO", other._sampleRate, other._fftN)
{
}
void FTmodRotateLFO::initialize()
{
_lastframe = 0;
_lastshift = 0;
_rate = new Control (Control::FloatType, "rate", "Rate", "Hz");
_rate->_floatLB = 0.0;
_rate->_floatUB = 20.0;
_rate->setValue (0.0f);
_controls.push_back (_rate);
_depth = new Control (Control::FloatType, "depth", "Depth", "Hz");
_depth->_floatLB = 0;
_depth->_floatUB = (float) _sampleRate/2;
_depth->setValue (_depth->_floatUB);
_controls.push_back (_depth);
_lfotype = new Control (Control::EnumType, "lfo_type", "LFO Type", "");
_lfotype->_enumList.push_back("Sine");
_lfotype->_enumList.push_back("Triangle");
_lfotype->_enumList.push_back("Square");
_lfotype->setValue (string("Sine"));
_controls.push_back (_lfotype);
_minfreq = new Control (Control::FloatType, "min_freq", "Min Freq", "Hz");
_minfreq->_floatLB = 0.0;
_minfreq->_floatUB = _sampleRate / 2;
_minfreq->setValue (_minfreq->_floatLB);
_controls.push_back (_minfreq);
_maxfreq = new Control (Control::FloatType, "max_freq", "Max Freq", "Hz");
_maxfreq->_floatLB = 0.0;
_maxfreq->_floatUB = _sampleRate / 2;
_maxfreq->setValue (_maxfreq->_floatUB);
_controls.push_back (_maxfreq);
_tmpfilt = new float[_fftN];
_inited = true;
}
FTmodRotateLFO::~FTmodRotateLFO()
{
if (!_inited) return;
_controls.clear();
delete _rate;
delete _depth;
delete _lfotype;
delete _minfreq;
delete _maxfreq;
}
void FTmodRotateLFO::setFFTsize (unsigned int fftn)
{
_fftN = fftn;
if (_inited) {
delete _tmpfilt;
_tmpfilt = new float[_fftN];
}
}
void FTmodRotateLFO::modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes)
{
TentativeLockMonitor lm (_specmodLock, __LINE__, __FILE__);
if (!lm.locked() || !_inited || _bypassed) return;
float rate = 1.0;
double currdev = 0.0;
float ub,lb;
float * filter;
int len;
int i,j;
float minfreq = 0.0, maxfreq = 0.0;
float depth = 1.0;
int minbin, maxbin;
double hzperbin;
double current_secs;
string shape;
// in hz
_rate->getValue (rate);
_lfotype->getValue (shape);
// in hz
_depth->getValue (depth);
_minfreq->getValue (minfreq);
_maxfreq->getValue (maxfreq);
if (minfreq >= maxfreq) {
return;
}
hzperbin = _sampleRate / (double) fftn;
// last_secs = _lastframe / (double) _sampleRate;
current_secs = current_frame / (double) _sampleRate;
int shiftval = 0;
if (shape == "Sine")
{
currdev = (double) (FTutils::sine_wave (current_secs, (double) rate) * (depth * 0.5 / hzperbin));
} else if (shape == "Square")
{
currdev = (double) (FTutils::square_wave (current_secs, (double) rate) * (depth * 0.5 / hzperbin));
}
else if (shape == "Triangle")
{
currdev = (double) (FTutils::triangle_wave (current_secs, (double) rate) * (depth * 0.5 / hzperbin));
}
else {
return;
}
shiftval = (int) (currdev - _lastshift);
//cerr << "currdev: " << currdev << " depth: " << depth << " hzper: " << hzperbin << " shift: " << shiftval << endl;
if (current_frame != _lastframe && shiftval != 0)
{
// fprintf (stderr, "shift at %lu : samps=%g s*c=%g s*e=%g \n", (unsigned long) current_frame, samps, (current_frame/samps), ((current_frame + nframes)/samps) );
for (SpecModList::iterator iter = _specMods.begin(); iter != _specMods.end(); ++iter)
{
FTspectrumModifier * sm = (*iter);
if (sm->getBypassed()) continue;
// cerr << "shiftval is: " << shiftval
// << " hz/bin: " << hzperbin
// << " rate: " << rate << endl;
filter = sm->getValues();
sm->getRange(lb, ub);
len = (int) sm->getLength();
minbin = (int) ((minfreq*2/ _sampleRate) * len);
maxbin = (int) ((maxfreq*2/ _sampleRate) * len);
len = maxbin - minbin;
if (len <= 0) {
continue;
}
int shiftbins = (abs(shiftval) % len) * (shiftval > 0 ? 1 : -1);
// fprintf(stderr, "shifting %d %d:%d at %lu\n", shiftbins, minbin, maxbin, (unsigned long) current_frame);
if (shiftbins > 0) {
// shiftbins is POSITIVE, shift right
// store last shiftbins
for (i=maxbin-shiftbins; i < maxbin; i++) {
_tmpfilt[i] = filter[i];
}
for ( i=maxbin-1; i >= minbin + shiftbins; i--) {
filter[i] = filter[i-shiftbins];
}
for (j=maxbin-shiftbins, i=minbin; i < minbin + shiftbins; i++, j++) {
filter[i] = _tmpfilt[j];
}
}
else if (shiftbins < 0) {
// shiftbins is NEGATIVE, shift left
// store last shiftbins
// store first shiftbins
for (i=minbin; i < minbin-shiftbins; i++) {
_tmpfilt[i] = filter[i];
}
for (i=minbin; i < maxbin + shiftbins; i++) {
filter[i] = filter[i-shiftbins];
}
for (j=minbin, i=maxbin+shiftbins; i < maxbin; i++, j++) {
filter[i] = _tmpfilt[j];
}
}
sm->setDirty(true);
}
_lastframe = current_frame;
_lastshift = (int) currdev;
}
}
| 6,113
|
C++
|
.cpp
| 184
| 30.119565
| 166
| 0.657094
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,943
|
FTprocDelay.cpp
|
essej_freqtweak/src/FTprocDelay.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTprocDelay.hpp"
#include "RingBuffer.hpp"
FTprocDelay::FTprocDelay (nframes_t samprate, unsigned int fftn)
: FTprocI("Delay", samprate, fftn),
_delayFilter(0), _feedbackFilter(0), _frameFifo(0), _maxDelay(2.5)
{
_confname = "Delay";
}
FTprocDelay::FTprocDelay (const FTprocDelay & other)
: FTprocI (other._name, other._sampleRate, other._fftN),
_delayFilter(0), _feedbackFilter(0), _frameFifo(0), _maxDelay(2.5)
{
_confname = "Delay";
}
void FTprocDelay::initialize()
{
// create filters
_delayFilter = new FTspectrumModifier("Delay", "delay", 0, FTspectrumModifier::TIME_MODIFIER, DELAY_SPECMOD, _fftN/2, 0.0);
_delayFilter->setRange(0.0, _maxDelay);
_feedbackFilter = new FTspectrumModifier("D Feedback", "feedback", 1, FTspectrumModifier::UNIFORM_MODIFIER, FEEDB_SPECMOD, _fftN/2, 0.0);
_feedbackFilter->setRange(0.0, 1.0);
setMaxDelay(_maxDelay);
_filterlist.push_back(_delayFilter);
_filterlist.push_back(_feedbackFilter);
_inited = true;
}
FTprocDelay::~FTprocDelay()
{
if (!_inited) return;
delete _frameFifo;
_filterlist.clear();
delete _delayFilter;
delete _feedbackFilter;
}
void FTprocDelay::reset()
{
// flush FIFOs
_frameFifo->reset();
_frameFifo->mem_set(0);
}
void FTprocDelay::setMaxDelay(float secs)
{
// THIS MUST NOT BE CALLED WHILE WE ARE ACTIVATED!
if (secs <= 0.0) return;
unsigned long maxsamples = 1;
_maxDelay = secs;
_maxDelaySamples = (unsigned long) (_maxDelay * _sampleRate) * sizeof(sample_t);
// we need to force this to the next bigger power of 2 for the memory allocation
while (maxsamples < _maxDelaySamples) {
maxsamples <<= 1;
}
if (_frameFifo)
delete _frameFifo;
//printf ("using %lu for maxsamples\n", maxsamples);
// this is a big boy containing the frequency data frames over time
_frameFifo = new RingBuffer( maxsamples * sizeof(fft_data) );
// adjust time filter
if (_delayFilter) {
_delayFilter->setRange (0.0, _maxDelay);
_delayFilter->reset();
}
}
void FTprocDelay::process (fft_data *data, unsigned int fftn)
{
if (!_inited) return;
if (_delayFilter->getBypassed())
{
_frameFifo->write ( (char *) data, sizeof(fft_data) * fftn);
_frameFifo->read( (char *) data, sizeof(fft_data) * fftn);
// RETURNS HERE
return;
}
float *delay = _delayFilter->getValues();
float *feedb = _feedbackFilter->getValues();
float feedback = 0.0;
bool bypassfeed = _feedbackFilter->getBypassed();
float mindelay = _delayFilter->getMin();
float maxdelay = _delayFilter->getMax();
float thisdelay;
float *rdest = 0, *idest = 0;
float *rcurr = 0, *icurr = 0;
nframes_t bshift, fshift;
int fftn2 = (fftn+1) >> 1;
//RingBuffer::rw_vector readvec[2];
RingBuffer::rw_vector wrvec[2];
_frameFifo->get_write_vector(wrvec);
for (int i = 0; i < fftn2-1; i++)
{
if (bypassfeed) {
feedback = 0.0;
}
else {
feedback = feedb[i] < 0.0 ? 0.0 : feedb[i];
}
if (delay[i] > maxdelay) {
thisdelay = maxdelay;
}
else if (delay[i] <= mindelay) {
// force feedback to 0 if no delay
feedback = 0.0;
thisdelay = mindelay;
}
else {
thisdelay = delay[i];
}
// frames to shift
fshift = ((nframes_t)(_sampleRate * thisdelay * sizeof(sample_t))) / fftn;
//nframes_t bshift = fshift * fftn * sizeof(sample_t);
//printf ("bshift %Zd wrvec[0]=%d\n", bshift, wrvec[0].len);
// byte offset to start of frame
//bshift = fshift * fftn * sizeof(sample_t);
bshift = fshift * fftn * sizeof(sample_t);
// we know the next frame is in the first segment of the FIFO
// because our FIFO size is always shifted one frame at a time
rcurr = (float * ) (wrvec[0].buf + i*sizeof(sample_t));
icurr = (float * ) (wrvec[0].buf + (fftn-i)*sizeof(sample_t));
if (wrvec[0].len > bshift) {
rdest = (float *) (wrvec[0].buf + bshift + i*sizeof(sample_t));
idest = (float *) (wrvec[0].buf + bshift + (fftn-i)*sizeof(sample_t));
}
else if (wrvec[1].len) {
bshift -= wrvec[0].len;
rdest = (float *) (wrvec[1].buf + bshift + i*sizeof(sample_t));
idest = (float *) (wrvec[1].buf + bshift + (fftn-i)*sizeof(sample_t));
}
else {
printf ("BLAHHALALAHLA\n");
continue;
}
*rdest = data[i] + (*rcurr)*feedback;
if (i > 0) {
*idest = data[fftn-i] + (*icurr)*feedback;
}
}
// advance it
_frameFifo->write_advance(fftn * sizeof(fft_data));
//_frameFifo->write ( (char *) data, sizeof(fft_data) * fftn);
// read data into output
_frameFifo->read( (char *) data, sizeof(fft_data) * fftn);
}
| 5,315
|
C++
|
.cpp
| 158
| 30.860759
| 138
| 0.687931
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,944
|
FTspectralEngine.cpp
|
essej_freqtweak/src/FTspectralEngine.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#if USING_FFTW3
#include <fftw3.h>
#else
#ifdef HAVE_SFFTW_H
#include <sfftw.h>
#else
#include <fftw.h>
#endif
#ifdef HAVE_SRFFTW_H
#include <srfftw.h>
#else
#include <rfftw.h>
#endif
#endif
#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <cmath>
#include <algorithm>
#include "FTtypes.hpp"
#include "FTspectralEngine.hpp"
#include "FTprocessPath.hpp"
#include "RingBuffer.hpp"
#include "FTspectrumModifier.hpp"
#include "FTioSupport.hpp"
#include "FTupdateToken.hpp"
#include "FTprocI.hpp"
#include "FTmodulatorI.hpp"
using namespace PBD;
using namespace std;
const int FTspectralEngine::_windowStringCount = 4;
const char * FTspectralEngine::_windowStrings[] = {
"Hanning", "Hamming", "Blackman", "Rectangle"
};
const int FTspectralEngine::_fftSizeCount = 9;
const int FTspectralEngine::_fftSizes[] = {
32, 64, 128, 256, 512, 1024, 2048, 4096, 8192
};
// in samples (about 3 seconds at 44100)
#define FT_MAX_DELAYSAMPLES (1 << 19)
FTspectralEngine::FTspectralEngine()
: _fftN (512), _windowing(FTspectralEngine::WINDOW_HANNING)
, _oversamp(4), _averages(8), _fftnChanged(false)
, _inputGain(1.0), _mixRatio(1.0), _bypassFlag(false), _mutedFlag(false), _updateSpeed(SPEED_MED)
, _id(0), _updateToken(0), _maxDelay(2.5)
, _currInAvgIndex(0), _currOutAvgIndex(0), _avgReady(false)
{
// one time allocations, why? because mysterious crash occurs when
// when reallocating them
_inputPowerSpectra = new fft_data [FT_MAX_FFT_SIZE_HALF];
_outputPowerSpectra = new fft_data [FT_MAX_FFT_SIZE_HALF];
memset((char *) _inputPowerSpectra, 0, FT_MAX_FFT_SIZE_HALF*sizeof(fft_data));
memset((char *) _outputPowerSpectra, 0, FT_MAX_FFT_SIZE_HALF*sizeof(fft_data));
_runningInputPower = new fft_data [FT_MAX_FFT_SIZE_HALF];
_runningOutputPower = new fft_data [FT_MAX_FFT_SIZE_HALF];
memset((char *) _runningOutputPower, 0, FT_MAX_FFT_SIZE_HALF*sizeof(fft_data));
memset((char *) _runningInputPower, 0, FT_MAX_FFT_SIZE_HALF*sizeof(fft_data));
initState();
}
void FTspectralEngine::initState()
{
_inwork = new fft_data [_fftN];
_accum = new fft_data [2 * _fftN];
memset((char *) _accum, 0, 2*_fftN*sizeof(fft_data));
memset((char *) _inwork, 0, _fftN*sizeof(fft_data));
#if USING_FFTW3
_outwork = (fft_data *) fftwf_malloc(sizeof(fft_data) * _fftN);
_winwork = (fft_data *) fftwf_malloc(sizeof(fft_data) * _fftN);
_fftPlan = fftwf_plan_r2r_1d(_fftN, _winwork, _outwork, FFTW_R2HC, FFTW_ESTIMATE);
_ifftPlan = fftwf_plan_r2r_1d(_fftN, _outwork, _winwork, FFTW_HC2R, FFTW_ESTIMATE);
#else
_outwork = new fft_data [_fftN];
_winwork = new fft_data [_fftN];
_fftPlan = rfftw_create_plan(_fftN, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE);
_ifftPlan = rfftw_create_plan(_fftN, FFTW_COMPLEX_TO_REAL, FFTW_ESTIMATE);
#endif
_sampleRate = FTioSupport::instance()->getSampleRate();
// window init
createWindowVectors();
_averages = (int) (_oversamp * _updateSpeed * 512/(float)_fftN); // magic?
if (_averages == 0) _averages = 1;
// reset averages
_currInAvgIndex = 0;
_currOutAvgIndex = 0;
_avgReady = false;
for (vector<FTprocI*>::iterator iter = _procModules.begin();
iter != _procModules.end(); ++iter)
{
(*iter)->reset();
}
}
void FTspectralEngine::destroyState()
{
delete [] _inwork;
delete [] _accum;
// destroy window vectors
for(int i = 0; i < NUM_WINDOWS; i++)
{
delete [] _mWindows[i];
}
#if USING_FFTW3
fftwf_destroy_plan (_fftPlan);
fftwf_destroy_plan (_ifftPlan);
fftwf_free (_winwork);
fftwf_free (_outwork);
#else
rfftw_destroy_plan (_fftPlan);
rfftw_destroy_plan (_ifftPlan);
delete [] _outwork;
delete [] _winwork;
#endif
}
FTspectralEngine::~FTspectralEngine()
{
destroyState();
delete [] _inputPowerSpectra;
delete [] _outputPowerSpectra;
delete [] _runningInputPower;
delete [] _runningOutputPower;
for (vector<FTprocI*>::iterator iter = _procModules.begin();
iter != _procModules.end(); ++iter)
{
delete (*iter);
}
}
void FTspectralEngine::getProcessorModules (vector<FTprocI *> & modules)
{
modules.clear();
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
modules.insert (modules.begin(), _procModules.begin(), _procModules.end());
}
FTprocI * FTspectralEngine::getProcessorModule ( unsigned int num)
{
LockMonitor (_procmodLock, __LINE__, __FILE__);
if (num < _procModules.size()) {
return _procModules[num];
}
return 0;
}
void FTspectralEngine::insertProcessorModule (FTprocI * procmod, unsigned int index)
{
if (!procmod) return;
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
vector<FTprocI*>::iterator iter = _procModules.begin();
for (unsigned int n=0; n < index && iter!=_procModules.end(); ++n) {
++iter;
}
procmod->setOversamp (_oversamp);
procmod->setFFTsize (_fftN);
procmod->setSampleRate (_sampleRate);
_procModules.insert (iter, procmod);
}
void FTspectralEngine::appendProcessorModule (FTprocI * procmod)
{
if (!procmod) return;
LockMonitor (_procmodLock, __LINE__, __FILE__);
procmod->setOversamp (_oversamp);
procmod->setFFTsize (_fftN);
procmod->setSampleRate (_sampleRate);
_procModules.push_back (procmod);
}
void FTspectralEngine::moveProcessorModule (unsigned int from, unsigned int to)
{
// both indexes refer to current positions within the list
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
vector<FTprocI*>::iterator iter = _procModules.begin();
for (unsigned int n=0; n < from && iter!=_procModules.end(); ++n) {
++iter;
}
if (iter == _procModules.end())
return;
// remove from
FTprocI * fproc = (*iter);
_procModules.erase (iter);
iter = _procModules.begin();
if (to >= from) {
// need to go one less
for (unsigned int n=0; n < to && iter!=_procModules.end(); ++n) {
++iter;
}
}
else {
for (unsigned int n=0; n < to && iter!=_procModules.end(); ++n) {
++iter;
}
}
_procModules.insert (iter, fproc);
}
void FTspectralEngine::removeProcessorModule (unsigned int index, bool destroy)
{
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
if (index >= _procModules.size()) return;
vector<FTprocI*>::iterator iter = _procModules.begin();
for (unsigned int n=0; n < index && iter!=_procModules.end(); ++n) {
++iter;
}
if (iter == _procModules.end())
return;
if (destroy) {
FTprocI * proc = (*iter);
delete proc;
}
_procModules.erase(iter);
}
void FTspectralEngine::clearProcessorModules (bool destroy)
{
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
vector<FTprocI*>::iterator iter = _procModules.begin();
if (destroy) {
for (; iter != _procModules.end(); ++iter) {
delete (*iter);
}
}
_procModules.clear();
}
void FTspectralEngine::getModulators (vector<FTmodulatorI *> & modules)
{
modules.clear();
LockMonitor pmlock(_modulatorLock, __LINE__, __FILE__);
modules.insert (modules.begin(), _modulators.begin(), _modulators.end());
}
FTmodulatorI * FTspectralEngine::getModulator ( unsigned int num)
{
LockMonitor (_modulatorLock, __LINE__, __FILE__);
if (num < _modulators.size()) {
return _modulators[num];
}
return 0;
}
void FTspectralEngine::insertModulator (FTmodulatorI * procmod, unsigned int index)
{
if (!procmod) return;
{
LockMonitor pmlock(_modulatorLock, __LINE__, __FILE__);
vector<FTmodulatorI*>::iterator iter = _modulators.begin();
for (unsigned int n=0; n < index && iter!=_modulators.end(); ++n) {
++iter;
}
procmod->setFFTsize (_fftN);
procmod->setSampleRate (_sampleRate);
_modulators.insert (iter, procmod);
}
ModulatorAdded (procmod); // emit
}
void FTspectralEngine::appendModulator (FTmodulatorI * procmod)
{
if (!procmod) return;
{
LockMonitor (_modulatorLock, __LINE__, __FILE__);
procmod->setFFTsize (_fftN);
procmod->setSampleRate (_sampleRate);
_modulators.push_back (procmod);
}
ModulatorAdded (procmod); // emit
}
void FTspectralEngine::moveModulator (unsigned int from, unsigned int to)
{
// both indexes refer to current positions within the list
LockMonitor pmlock(_modulatorLock, __LINE__, __FILE__);
vector<FTmodulatorI*>::iterator iter = _modulators.begin();
for (unsigned int n=0; n < from && iter!=_modulators.end(); ++n) {
++iter;
}
if (iter == _modulators.end())
return;
// remove from
FTmodulatorI * fproc = (*iter);
_modulators.erase (iter);
iter = _modulators.begin();
if (to >= from) {
// need to go one less
for (unsigned int n=0; n < to && iter!=_modulators.end(); ++n) {
++iter;
}
}
else {
for (unsigned int n=0; n < to && iter!=_modulators.end(); ++n) {
++iter;
}
}
_modulators.insert (iter, fproc);
}
void FTspectralEngine::removeModulator (unsigned int index, bool destroy)
{
LockMonitor pmlock(_modulatorLock, __LINE__, __FILE__);
if (index >= _modulators.size()) return;
vector<FTmodulatorI*>::iterator iter = _modulators.begin();
for (unsigned int n=0; n < index && iter!=_modulators.end(); ++n) {
++iter;
}
if (iter == _modulators.end())
return;
if (destroy) {
FTmodulatorI * proc = (*iter);
delete proc;
}
_modulators.erase(iter);
}
void FTspectralEngine::removeModulator (FTmodulatorI * procmod, bool destroy)
{
bool candel = false;
{
LockMonitor pmlock(_modulatorLock, __LINE__, __FILE__);
for (vector<FTmodulatorI*>::iterator iter = _modulators.begin();
iter != _modulators.end(); ++iter)
{
if (procmod == *iter) {
_modulators.erase(iter);
candel = true;
break;
}
}
}
if (destroy && candel) {
delete procmod;
}
}
bool FTspectralEngine::hasModulator (FTmodulatorI * procmod)
{
LockMonitor pmlock(_modulatorLock, __LINE__, __FILE__);
return (find(_modulators.begin(), _modulators.end(), procmod) != _modulators.end());
}
void FTspectralEngine::clearModulators (bool destroy)
{
LockMonitor pmlock(_modulatorLock, __LINE__, __FILE__);
vector<FTmodulatorI*>::iterator iter = _modulators.begin();
if (destroy) {
for (; iter != _modulators.end(); ++iter) {
delete (*iter);
}
}
_modulators.clear();
}
void FTspectralEngine::setId (int id)
{
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
_id = id;
// set the id of all our filters
for (vector<FTprocI*>::iterator iter = _procModules.begin();
iter != _procModules.end(); ++iter)
{
(*iter)->setId (id);
}
}
void FTspectralEngine::setFFTsize (FTspectralEngine::FFT_Size sz)
{
// THIS MUST NOT BE CALLED WHILE WE ARE ACTIVATED!
//LockMonitor pmlock(_fftLock, __LINE__, __FILE__);
if ((int) sz != _fftN)
{
_fftN = sz;
// change these first
for (vector<FTprocI*>::iterator iter = _procModules.begin();
iter != _procModules.end(); ++iter)
{
(*iter)->setFFTsize (_fftN);
}
destroyState();
initState();
}
}
void FTspectralEngine::setOversamp (int osamp)
{
_oversamp = osamp;
_averages = (int) (_oversamp * (float) _updateSpeed * 512/(float)_fftN); // magic?
if (_averages == 0) _averages = 1;
// reset averages
memset(_runningOutputPower, 0, _fftN * sizeof(float));
memset(_runningInputPower, 0, _fftN * sizeof(float));
_currInAvgIndex = 0;
_currOutAvgIndex = 0;
_avgReady = false;
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
// set it in all the modules
for (vector<FTprocI*>::iterator iter = _procModules.begin();
iter != _procModules.end(); ++iter)
{
(*iter)->setOversamp (_oversamp);
}
}
void FTspectralEngine::setUpdateSpeed (UpdateSpeed speed)
{
_updateSpeed = speed;
_averages = (int) (_oversamp * (float) _updateSpeed * 512/(float)_fftN); // magic?
if (_averages == 0) _averages = 1;
// reset averages
memset(_runningOutputPower, 0, _fftN * sizeof(float));
memset(_runningInputPower, 0, _fftN * sizeof(float));
_currInAvgIndex = 0;
_currOutAvgIndex = 0;
_avgReady = false;
}
void FTspectralEngine::setMaxDelay(float secs)
{
// THIS MUST NOT BE CALLED WHILE WE ARE ACTIVATED!
if (secs <= 0.0) return;
LockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
_maxDelay = secs;
for (vector<FTprocI*>::iterator iter = _procModules.begin();
iter != _procModules.end(); ++iter)
{
(*iter)->setMaxDelay (secs);
}
}
nframes_t FTspectralEngine::getLatency()
{
int step_size = _fftN / _oversamp;
int latency = _fftN - step_size;
return latency;
}
/**
* Main FFT processing done here
* this is called from the i/o thread
*/
bool FTspectralEngine::processNow (FTprocessPath *procpath)
{
int i;
int osamp = _oversamp;
int step_size = _fftN / osamp;
int latency = _fftN - step_size;
float * win = _mWindows[_windowing];
nframes_t current_frame = FTioSupport::instance()->getTransportFrame();
// do we have enough data for next frame (oversampled)?
while (procpath->getInputFifo()->read_space() >= (step_size * sizeof(sample_t)))
{
//printf ("processing spectral sizeof sample = %d fft_data = %d\n", sizeof(sample_t), sizeof(fftw_real));
// copy data into fft work buf
procpath->getInputFifo()->read ( (char *) (&_inwork[latency]), step_size * sizeof(sample_t) );
//printf ("real data 1 = %g\n", _inwork[1]);
// window data into winwork
for(i = 0; i < _fftN; i++)
{
_winwork[i] = _inwork[i] * win[i] * _inputGain;
}
#if USING_FFTW3
// do forward real FFT
fftwf_execute(_fftPlan);
#else
// do forward real FFT
rfftw_one(_fftPlan, _winwork, _outwork);
#endif
// compute running mag^2 buffer for input
computeAverageInputPower (_outwork);
// do modulation in order with each modulator
{
TentativeLockMonitor modlock(_modulatorLock, __LINE__, __FILE__);
if (modlock.locked()) {
for (vector<FTmodulatorI*>::iterator iter = _modulators.begin();
iter != _modulators.end(); ++iter)
{
(*iter)->modulate (current_frame, _outwork, _fftN, _inwork, _fftN);
}
}
}
// do processing in order with each processing module
{
TentativeLockMonitor pmlock(_procmodLock, __LINE__, __FILE__);
if (pmlock.locked()) {
for (vector<FTprocI*>::iterator iter = _procModules.begin();
iter != _procModules.end(); ++iter)
{
// do it in place
(*iter)->process (_outwork, _fftN);
}
}
}
// compute running mag^2 buffer for output
computeAverageOutputPower (_outwork);
#if USING_FFTW3
// do reverse FFT
fftwf_execute(_ifftPlan);
#else
// do reverse FFT
rfftw_one(_ifftPlan, _outwork, _winwork);
#endif
// the output is scaled by fftN, we need to normalize it and window it
for ( i=0; i < _fftN; i++)
{
_accum[i] += _mixRatio * 4.0f * win[i] * _winwork[i] / ((float)_fftN * osamp);
}
// mix in dry only if necessary
if (_mixRatio < 1.0) {
float dry = 1.0 - _mixRatio;
for (i=0; i < step_size; i++) {
_accum[i] += dry * _inwork[i] ;
}
}
// put step_size worth of the real data into the processPath out buffer
procpath->getOutputFifo()->write( (char *)_accum, sizeof(sample_t) * step_size);
// shift output accumulator data
memmove(_accum, _accum + step_size, _fftN*sizeof(sample_t));
// shift input fifo (inwork)
memmove(_inwork, _inwork + step_size, latency*sizeof(sample_t));
// update events for those who listen
if (_avgReady && _updateToken) {
_updateToken->setUpdated(true);
_avgReady = false;
}
current_frame += step_size;
}
return true;
}
void FTspectralEngine::computeAverageInputPower (fft_data *fftbuf)
{
int fftn2 = _fftN / 2;
if (_averages > 1) {
if (_currInAvgIndex > 0) {
_inputPowerSpectra[0] += fftbuf[0] * fftbuf[0];
for (int i=1; i < fftn2-1; i++)
{
_inputPowerSpectra[i] += (fftbuf[i] * fftbuf[i]) + (fftbuf[_fftN-i] * fftbuf[_fftN-i]);
}
}
else {
_inputPowerSpectra[0] = fftbuf[0] * fftbuf[0];
for (int i=1; i < fftn2-1 ; i++)
{
_inputPowerSpectra[i] = (fftbuf[i] * fftbuf[i]) + (fftbuf[_fftN-i] * fftbuf[_fftN-i]);
}
}
_currInAvgIndex = (_currInAvgIndex+1) % _averages;
if (_currInAvgIndex == 0) {
_runningInputPower[0] = _inputPowerSpectra[0] / _averages;
for (int i=1; i < fftn2-1 ; i++)
{
_runningInputPower[i] = _inputPowerSpectra[i] / _averages;
}
_avgReady = true;
}
}
else {
// 1 average, minimize looping
_runningInputPower[0] = (fftbuf[0] * fftbuf[0]);
for (int i=1; i < fftn2-1 ; i++)
{
_runningInputPower[i] = (fftbuf[i] * fftbuf[i]) + (fftbuf[_fftN-i] * fftbuf[_fftN-i]);
}
_avgReady = true;
}
}
void FTspectralEngine::computeAverageOutputPower (fft_data *fftbuf)
{
int fftn2 = (_fftN+1) / 2;
if (_averages > 1) {
if (_currOutAvgIndex > 0) {
_outputPowerSpectra[0] += (fftbuf[0] * fftbuf[0]);
for (int i=1; i < fftn2-1; i++)
{
_outputPowerSpectra[i] += (fftbuf[i] * fftbuf[i]) + (fftbuf[_fftN-i] * fftbuf[_fftN-i]);
}
}
else {
_outputPowerSpectra[0] = (fftbuf[0] * fftbuf[0]);
for (int i=1; i < fftn2-1 ; i++)
{
_outputPowerSpectra[i] = (fftbuf[i] * fftbuf[i]) + (fftbuf[_fftN-i] * fftbuf[_fftN-i]);
}
}
_currOutAvgIndex = (_currOutAvgIndex+1) % _averages;
if (_currOutAvgIndex == 0) {
_runningOutputPower[0] = _outputPowerSpectra[0] / _averages;
for (int i=1; i < fftn2-1 ; i++)
{
_runningOutputPower[i] = _outputPowerSpectra[i] / _averages;
}
_avgReady = true;
}
}
else {
// 1 average, minimize looping
_runningOutputPower[0] = (fftbuf[0] * fftbuf[0]);
for (int i=1; i < fftn2-1 ; i++)
{
_runningOutputPower[i] = (fftbuf[i] * fftbuf[i]) + (fftbuf[_fftN-i] * fftbuf[_fftN-i]);
}
_avgReady = true;
}
}
void FTspectralEngine::createWindowVectors (bool noalloc)
{
///////////////////////////////////////////////////////////////////////////
int i;
///////////////////////////////////////////////////////////////////////////
if (!noalloc)
{
///////////////////////////////////////////////////////////////////////////
// create window array
_mWindows = new float*[NUM_WINDOWS];
///////////////////////////////////////////////////////////////////////////
// allocate vectors
for(i = 0; i < NUM_WINDOWS; i++)
{
_mWindows[i] = new float[_fftN];
}
}
///////////////////////////////////////////////////////////////////////////
// create windows
createRectangleWindow ();
createHanningWindow ();
createHammingWindow ();
createBlackmanWindow ();
}
void FTspectralEngine::createRectangleWindow ()
{
///////////////////////////////////////////////////////////////////////////
int i;
///////////////////////////////////////////////////////////////////////////
for(i = 0; i < _fftN; i++)
{
_mWindows[WINDOW_RECTANGLE][i] = 0.5;
}
}
void FTspectralEngine::createHanningWindow ()
{
///////////////////////////////////////////////////////////////////////////
int i;
///////////////////////////////////////////////////////////////////////////
for(i = 0; i < _fftN; i++)
{
_mWindows[WINDOW_HANNING][i] = 0.81 * ( // fudge factor
0.5 -
(0.5 *
//(float) cos(2.0 * M_PI * i / (_fftN - 1.0)));
(float) cos(2.0 * M_PI * i / (_fftN))));
}
}
void FTspectralEngine::createHammingWindow ()
{
///////////////////////////////////////////////////////////////////////////
int i;
///////////////////////////////////////////////////////////////////////////
for(i = 0; i < _fftN; i++)
{
_mWindows[WINDOW_HAMMING][i] = 0.82 * ( // fudge factor
0.54 -
(0.46 *
(float) cos(2.0 * M_PI * i / (_fftN - 1.0))));
}
}
void FTspectralEngine::createBlackmanWindow ()
{
///////////////////////////////////////////////////////////////////////////
int i;
///////////////////////////////////////////////////////////////////////////
for(i = 0; i < _fftN; i++)
{
_mWindows[WINDOW_BLACKMAN][i] = 0.9 * ( // fudge factor
0.42 -
(0.50 * (float) cos(
2.0 * M_PI * i /(_fftN - 1.0))) +
(0.08 * (float) cos(
4.0 * M_PI * i /(_fftN - 1.0))));
}
}
| 20,843
|
C++
|
.cpp
| 675
| 27.703704
| 108
| 0.6322
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,945
|
slider_bar.cpp
|
essej_freqtweak/src/slider_bar.cpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include <wx/wx.h>
#include <iostream>
#include <cmath>
#include "FTutils.hpp"
#include "slider_bar.hpp"
using namespace JLCui;
using namespace std;
// Convert a value in dB's to a coefficent
#undef DB_CO
#define DB_CO(g) ((g) > -144.0 ? pow(10.0, (g) * 0.05) : 0.0)
#undef CO_DB
#define CO_DB(v) (20.0 * log10(v))
static inline double
gain_to_slider_position (double g)
{
if (g == 0) return 0;
//return pow((6.0*log(g)/log(2.0)+192.0)/198.0, 8.0);
return pow((6.0*log(g)/log(2.0)+198.0)/198.0, 8.0);
}
static inline double
slider_position_to_gain (double pos)
{
if (pos == 0) {
return 0.0;
}
/* XXX Marcus writes: this doesn't seem right to me. but i don't have a better answer ... */
//return pow (2.0,(sqrt(sqrt(sqrt(pos)))*198.0-192.0)/6.0);
return pow (2.0,(sqrt(sqrt(sqrt(pos)))*198.0-198.0)/6.0);
}
enum {
ID_TextCtrl = 8000,
ID_EditMenuOp,
ID_DefaultMenuOp,
ID_BindMenuOp
};
BEGIN_EVENT_TABLE(SliderBar, wxWindow)
EVT_SIZE(SliderBar::OnSize)
EVT_PAINT(SliderBar::OnPaint)
EVT_MOUSE_EVENTS(SliderBar::OnMouseEvents)
EVT_MOUSEWHEEL (SliderBar::OnMouseEvents)
//EVT_TEXT (ID_TextCtrl, SliderBar::on_text_event)
EVT_TEXT_ENTER (ID_TextCtrl, SliderBar::on_text_event)
EVT_MENU (ID_EditMenuOp , SliderBar::on_menu_events)
EVT_MENU (ID_DefaultMenuOp , SliderBar::on_menu_events)
EVT_MENU (ID_BindMenuOp , SliderBar::on_menu_events)
END_EVENT_TABLE()
SliderBar::SliderBar(wxWindow * parent, wxWindowID id, float lb, float ub, float val, bool midibindable, const wxPoint& pos, const wxSize& size)
: wxWindow(parent, id, pos, size)
{
_lower_bound = lb;
_upper_bound = ub;
_default_val = _value = val;
_backing_store = 0;
_indbm = 0;
_dragging = false;
_decimal_digits = 1;
_text_ctrl = 0;
_ignoretext = false;
_oob_flag = false;
_showval_flag = true;
_show_ind_bar = false;
_ind_value = 0.0f;
_use_pending = false;
_pending_val = 0.0f;
_bgcolor.Set(30,30,30);
_bgbrush.SetColour (_bgcolor);
SetBackgroundColour (_bgcolor);
SetThemeEnabled(false);
_valuecolor.Set(244, 255, 178);
_textcolor = *wxWHITE;
_barcolor.Set(14, 50, 89);
_overbarcolor.Set(20, 65, 104);
_barbrush.SetColour(_barcolor);
_bordercolor.Set(67, 83, 103);
_borderpen.SetColour(_bordercolor);
_borderpen.SetWidth(1);
_borderbrush.SetColour(_bgcolor);
_linebrush.SetColour(wxColour(154, 245, 168));
_bar_style = FromLeftStyle;
_scale_mode = LinearMode;
_snap_mode = NoSnap;
_popup_menu = new wxMenu(wxT(""));
_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_EditMenuOp, wxT("Edit")));
_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_DefaultMenuOp, wxT("Set to default")));
if (midibindable) {
_popup_menu->AppendSeparator();
_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_BindMenuOp, wxT("Learn MIDI Binding")));
}
_indcolor.Set(47, 149, 133);
_indbrush.SetColour(_indcolor);
_indmaxcolor.Set(200, 20, 20);
_indmaxbrush.SetColour(_indmaxcolor);
update_size();
}
SliderBar::~SliderBar()
{
_memdc.SelectObject(wxNullBitmap);
if (_backing_store) {
delete _backing_store;
}
_inddc.SelectObject(wxNullBitmap);
if (_indbm) {
delete _indbm;
}
}
bool
SliderBar::SetFont(const wxFont & fnt)
{
bool ret = wxWindow::SetFont(fnt);
_memdc.SetFont(fnt);
do_redraw();
return ret;
}
void
SliderBar::set_style (BarStyle md)
{
if (md != _bar_style) {
_bar_style = md;
do_redraw();
}
}
void
SliderBar::set_snap_mode (SnapMode md)
{
if (md != _snap_mode) {
_snap_mode = md;
}
}
void
SliderBar::set_scale_mode (ScaleMode mode)
{
if (mode != _scale_mode) {
_scale_mode = mode;
update_value_str();
do_redraw();
}
}
void
SliderBar::set_bounds (float lb, float ub)
{
if (_lower_bound != lb || _upper_bound != ub) {
_lower_bound = lb;
_upper_bound = ub;
// force value to within
if (_value < _lower_bound) {
_value = _lower_bound;
update_value_str();
do_redraw();
}
else if (_value > _upper_bound) {
_value = _upper_bound;
update_value_str();
do_redraw();
}
}
}
void
SliderBar::set_label (const wxString & label)
{
_label_str = label;
do_redraw();
}
void
SliderBar::set_units (const wxString & units)
{
_units_str = units.Strip(wxString::both);
if (!_units_str.empty()) {
_units_str = wxT(" ") + _units_str;
}
update_value_str();
do_redraw();
}
void
SliderBar::set_decimal_digits (int val)
{
_decimal_digits = val;
update_value_str();
do_redraw();
}
void
SliderBar::set_value (float val, bool refresh)
{
float newval = val;
if (_scale_mode == ZeroGainMode) {
newval = gain_to_slider_position (val);
}
// if (_snap_mode == IntegerSnap) {
// newval = nearbyintf (newval);
// }
if (!_oob_flag) {
newval = min (newval, _upper_bound);
newval = max (newval, _lower_bound);
}
if (_dragging) {
// don't update current value if mid drag
_use_pending = true;
_pending_val = newval;
return;
}
if (newval != _value) {
_value = newval;
update_value_str();
if (refresh) {
do_redraw();
}
}
}
void
SliderBar::set_indicator_value (float val)
{
float newval = val;
if (_scale_mode == ZeroGainMode) {
newval = gain_to_slider_position (val);
}
if (!_oob_flag) {
newval = f_min (newval, _upper_bound);
newval = f_max (newval, _lower_bound);
}
if (newval != _ind_value) {
_ind_value = newval;
Refresh(false);
}
}
float
SliderBar::get_value ()
{
if (_scale_mode == ZeroGainMode) {
return slider_position_to_gain(_value);
}
else {
return _value;
}
}
float
SliderBar::get_indicator_value ()
{
if (_scale_mode == ZeroGainMode) {
return slider_position_to_gain(_ind_value);
}
else {
return _ind_value;
}
}
void
SliderBar::update_value_str()
{
if (_scale_mode == ZeroGainMode) {
float gain = slider_position_to_gain(_value);
if (gain == 0) {
_value_str.Printf(wxT("-inf%s"), _units_str.c_str());
}
else {
_value_str.Printf(wxT("%.*f%s"), _decimal_digits, CO_DB(gain), _units_str.c_str());
}
}
else {
_value_str.Printf(wxT("%.*f%s"), _decimal_digits, _value, _units_str.c_str());
}
}
wxString SliderBar::get_precise_value_str()
{
wxString valstr;
if (_scale_mode == ZeroGainMode) {
float gain = slider_position_to_gain(_value);
if (gain == 0) {
valstr.Printf(wxT("-inf"));
}
else if (_snap_mode == IntegerSnap) {
valstr.Printf(wxT("%g"), CO_DB(gain));
}
else {
valstr.Printf(wxT("%.8f"), CO_DB(gain));
}
}
else {
if (_snap_mode == IntegerSnap) {
valstr.Printf(wxT("%g"), _value);
}
else {
valstr.Printf(wxT("%.8f"), _value);
}
}
return valstr;
}
void SliderBar::set_bg_color (const wxColour & col)
{
_bgcolor = col;
_bgbrush.SetColour (col);
SetBackgroundColour (col);
do_redraw();
}
void SliderBar::set_text_color (const wxColour & col)
{
_textcolor = col;
do_redraw();
}
void SliderBar::set_border_color (const wxColour & col)
{
_bordercolor = col;
_borderbrush.SetColour (col);
do_redraw();
}
void SliderBar::set_indicator_bar_color (const wxColour & col)
{
_indcolor = col;
_indbrush.SetColour (col);
do_redraw();
}
void SliderBar::set_indicator_max_bar_color (const wxColour & col)
{
_indmaxcolor = col;
_indmaxbrush.SetColour (col);
do_redraw();
}
void SliderBar::set_bar_color (const wxColour & col)
{
_barcolor = col;
_barbrush.SetColour (col);
do_redraw();
}
void
SliderBar::update_size()
{
GetClientSize(&_width, &_height);
if (_width > 0 && _height > 0) {
_val_scale = (_upper_bound - _lower_bound) / (_width);
_memdc.SelectObject (wxNullBitmap);
if (_backing_store) {
delete _backing_store;
}
_backing_store = new wxBitmap(_width, _height);
_memdc.SelectObject(*_backing_store);
_memdc.SetFont(GetFont());
_inddc.SelectObject (wxNullBitmap);
if (_indbm) {
delete _indbm;
}
_indbm = new wxBitmap(_width, _height);
_inddc.SelectObject(*_indbm);
}
}
void
SliderBar::OnSize(wxSizeEvent & event)
{
update_size();
do_redraw();
event.Skip();
}
void SliderBar::do_redraw ()
{
if (!_backing_store) {
return;
}
draw_area(_memdc);
Refresh(false);
}
void SliderBar::OnPaint(wxPaintEvent & event)
{
wxPaintDC pdc(this);
//draw_area(_memdc);
if (_show_ind_bar) {
// first blit memdc into the inddc
_inddc.Blit(0, 0, _width, _height, &_memdc, 0, 0);
// draw the indicator
draw_ind (_inddc);
// final blit
pdc.Blit(0, 0, _width, _height, &_inddc, 0, 0);
}
else {
pdc.Blit(0, 0, _width, _height, &_memdc, 0, 0);
}
}
void
SliderBar::OnMouseEvents (wxMouseEvent &ev)
{
if (!IsEnabled()) {
ev.Skip();
return;
}
if (ev.Entering() && !_dragging) {
_barbrush.SetColour(_overbarcolor);
do_redraw();
}
else if (ev.Leaving() && !_dragging) {
_barbrush.SetColour(_barcolor);
do_redraw();
}
if (ev.Dragging() && _dragging)
{
int delta = ev.GetX() - _last_x;
float fdelta = delta * _val_scale;
if (ev.ControlDown()) {
fdelta *= 0.5f;
if (ev.ShiftDown()) {
fdelta *= 0.5f;
}
}
float newval = _value + fdelta;
//cerr << "dragging: " << ev.GetX() << " " << delta << " " << fdelta << " " << newval << endl;
if (_snap_mode == IntegerSnap) {
newval = nearbyintf (newval);
}
newval = max (min (newval, _upper_bound), _lower_bound);
if (newval != _value) {
_value = newval;
value_changed (get_value()); // emit
update_value_str();
do_redraw();
//cerr << "new val is: " << _value << endl;
}
_last_x = ev.GetX();
}
else if (ev.Moving()) {
// do nothing
}
else if (ev.GetEventType() == wxEVT_MOUSEWHEEL)
{
// don't get the events right now
float fscale = 0.02f * (ev.ControlDown() ? 0.5f: 1.0f);
float newval;
if (ev.GetWheelRotation() > 0) {
newval = _value + (_upper_bound - _lower_bound) * fscale;
}
else {
newval = _value - (_upper_bound - _lower_bound) * fscale;
}
if (_snap_mode == IntegerSnap) {
newval = nearbyintf (newval);
}
newval = max (min (newval, _upper_bound), _lower_bound);
_value = newval;
value_changed (get_value()); // emit
update_value_str();
do_redraw();
}
else if (ev.RightDown()) {
this->PopupMenu ( _popup_menu, ev.GetX(), ev.GetY());
}
else if (ev.RightUp()) {
//this->PopupMenu ( _popup_menu, ev.GetX(), ev.GetY());
}
else if (ev.ButtonDown())
{
CaptureMouse();
_dragging = true;
_last_x = ev.GetX();
pressed(); // emit
if (ev.MiddleDown() && !ev.ControlDown()) {
// set immediately
float newval = (ev.GetX() * _val_scale) + _lower_bound;
if (_snap_mode == IntegerSnap) {
newval = nearbyintf (newval);
}
_value = newval;
value_changed (get_value()); // emit
update_value_str();
do_redraw();
}
else if (ev.LeftDown() && ev.ShiftDown()) {
// set to default
_value = max (min (_default_val, _upper_bound), _lower_bound);
value_changed(get_value());
update_value_str();
do_redraw();
}
}
else if (ev.ButtonUp())
{
_dragging = false;
ReleaseMouse();
if (_use_pending) {
// This didn't really work
//if (_pending_val != _value) {
// _value = _pending_val;
// update_value_str();
//}
_use_pending = false;
}
if (ev.GetX() >= _width || ev.GetX() < 0
|| ev.GetY() < 0 || ev.GetY() > _height) {
_barbrush.SetColour(_barcolor);
do_redraw();
}
else {
_barbrush.SetColour(_overbarcolor);
do_redraw();
}
if (ev.MiddleUp() && ev.ControlDown())
{
// binding click
bind_request(); // emit
}
released(); // emit
}
else if (ev.ButtonDClick()) {
// this got annoying
//show_text_ctrl ();
}
else {
ev.Skip();
}
}
void SliderBar::on_menu_events (wxCommandEvent &ev)
{
if (ev.GetId() == ID_BindMenuOp) {
bind_request(); // emit
}
else if (ev.GetId() == ID_EditMenuOp) {
show_text_ctrl ();
}
else if (ev.GetId() == ID_DefaultMenuOp) {
_value = max (min (_default_val, _upper_bound), _lower_bound);
value_changed(get_value());
update_value_str();
do_redraw();
}
}
void SliderBar::draw_area(wxDC & dc)
{
wxCoord w,h;
int pixw;
dc.SetBackground(_bgbrush);
dc.Clear();
dc.SetBrush(_borderbrush);
dc.SetPen(_borderpen);
dc.DrawRectangle (0, 0, _width, _height);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(_barbrush);
if (_bar_style == FromLeftStyle)
{
pixw = (int) ((_value - _lower_bound) / _val_scale);
dc.DrawRectangle (1, 1, pixw-1, _height-2);
}
else if (_bar_style == FromRightStyle)
{
pixw = (int) ((_upper_bound - _value) / _val_scale);
dc.DrawRectangle (pixw, 1, _width - pixw - 1, _height-2);
}
if (_bar_style != HiddenStyle)
{
dc.SetBrush(_linebrush);
pixw = (int) ((_value - _lower_bound) / _val_scale);
dc.DrawRectangle (pixw - 1, 1, 2, _height-2);
}
dc.SetTextForeground(_textcolor);
dc.GetTextExtent(_label_str, &w, &h);
dc.DrawText (_label_str, 3, _height - h - 3);
if (_showval_flag) {
dc.SetTextForeground(_valuecolor);
dc.GetTextExtent(_value_str, &w, &h);
dc.DrawText (_value_str, _width - w - 3, _height - h - 3);
}
}
void SliderBar::draw_ind(wxDC & dc)
{
int pixw;
dc.SetPen(*wxTRANSPARENT_PEN);
if (_bar_style == FromLeftStyle)
{
pixw = (int) ((_ind_value - _lower_bound) / _val_scale);
if (pixw > 0) {
if (_ind_value >= _upper_bound) {
dc.SetBrush(_indmaxbrush);
}
else {
dc.SetBrush(_indbrush);
}
dc.DrawRectangle (1, 1, pixw-1, 1);
dc.DrawRectangle (1, _height - 2, pixw-1, 1);
}
}
else if (_bar_style == FromRightStyle)
{
pixw = (int) ((_upper_bound - _ind_value) / _val_scale);
if (pixw < _width) {
if (_ind_value >= _upper_bound) {
dc.SetBrush(_indmaxbrush);
}
else {
dc.SetBrush(_indbrush);
}
dc.DrawRectangle (pixw, 1, _width - pixw -1, 2);
dc.DrawRectangle (pixw, _height - 2, _width - pixw - 1, 1);
}
}
pixw = (int) ((_ind_value - _lower_bound) / _val_scale);
if (pixw > 0) {
if (_ind_value >= _upper_bound) {
dc.SetBrush(_indmaxbrush);
}
else {
dc.SetBrush(_indbrush);
}
dc.DrawRectangle (pixw - 2, 1, 2, _height-2);
}
}
void SliderBar::show_text_ctrl ()
{
wxString valstr = get_precise_value_str();
if (!_text_ctrl) {
_text_ctrl = new HidingTextCtrl(this, ID_TextCtrl, valstr, wxPoint(1,1), wxSize(_width - 2, _height - 2),
wxTE_PROCESS_ENTER|wxTE_RIGHT);
_text_ctrl->SetName (wxT("KeyAware"));
_text_ctrl->SetFont(GetFont());
}
_text_ctrl->SetValue (valstr);
_text_ctrl->SetSelection (-1, -1);
_text_ctrl->SetSize (_width - 2, _height - 2);
_text_ctrl->Show(true);
_text_ctrl->SetFocus();
}
void SliderBar::hide_text_ctrl ()
{
if (_text_ctrl && _text_ctrl->IsShown()) {
_text_ctrl->Show(false);
SetFocus();
}
}
void SliderBar::on_text_event (wxCommandEvent &ev)
{
if (ev.GetEventType() == wxEVT_COMMAND_TEXT_ENTER) {
// commit change
bool good = false;
bool neginf = false;
double newval = 0.0;
if (_scale_mode == ZeroGainMode && _text_ctrl->GetValue().Strip(wxString::both) == wxT("-inf")) {
newval = 0.0;
good = neginf = true;
}
else if (_text_ctrl->GetValue().ToDouble(&newval)) {
good = true;
}
if (good) {
if (_scale_mode == ZeroGainMode && !neginf) {
newval = DB_CO(newval);
}
set_value ((float) newval);
value_changed (get_value()); // emit
}
hide_text_ctrl();
}
}
BEGIN_EVENT_TABLE(SliderBar::HidingTextCtrl, wxTextCtrl)
EVT_KILL_FOCUS (SliderBar::HidingTextCtrl::on_focus_event)
END_EVENT_TABLE()
void SliderBar::HidingTextCtrl::on_focus_event (wxFocusEvent & ev)
{
if (ev.GetEventType() == wxEVT_KILL_FOCUS) {
Show(false);
}
}
| 16,267
|
C++
|
.cpp
| 669
| 21.663677
| 145
| 0.653921
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,946
|
FTspectragram.cpp
|
essej_freqtweak/src/FTspectragram.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <math.h>
#include "FTspectragram.hpp"
#include "FTmainwin.hpp"
#include "FTioSupport.hpp"
#include "FTtypes.hpp"
int FTspectragram::_colorCount = 128;
int FTspectragram::_maxColorCount = 256;
int FTspectragram::_maxDiscreteColorCount = 16;
int FTspectragram::_discreteColorCount = 10;
unsigned char ** FTspectragram::_colorMap = 0;
unsigned char ** FTspectragram::_discreteColors = 0;
enum
{
FT_1Xscale=1000,
FT_2Xscale,
FT_LogaXscale,
FT_LogbXscale,
};
// the event tables connect the wxWindows events with the functions (event
// handlers) which process them. It can be also done at run-time, but for the
// simple menu events like this the static method is much simpler.
BEGIN_EVENT_TABLE(FTspectragram, wxPanel)
EVT_PAINT(FTspectragram::OnPaint)
EVT_SIZE(FTspectragram::OnSize)
EVT_MOTION(FTspectragram::OnMouseActivity)
EVT_ENTER_WINDOW(FTspectragram::OnMouseActivity)
EVT_LEAVE_WINDOW(FTspectragram::OnMouseActivity)
EVT_MIDDLE_DOWN(FTspectragram::OnMouseActivity)
EVT_MIDDLE_UP(FTspectragram::OnMouseActivity)
EVT_RIGHT_DOWN(FTspectragram::OnMouseActivity)
EVT_RIGHT_UP(FTspectragram::OnMouseActivity)
EVT_MENU (FT_1Xscale,FTspectragram::OnXscaleMenu)
EVT_MENU (FT_2Xscale,FTspectragram::OnXscaleMenu)
EVT_MENU (FT_LogaXscale,FTspectragram::OnXscaleMenu)
EVT_MENU (FT_LogbXscale,FTspectragram::OnXscaleMenu)
END_EVENT_TABLE()
FTspectragram::FTspectragram(FTmainwin * mwin, wxWindow *parent, wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style ,
const wxString& name,
PlotType pt)
: wxPanel(parent, id, pos, size, style, name)
, _mwin(mwin), _ptype(pt)
, _width(0), _height(0)
, _minCutoff(0.0), _dbAbsMin(-200.0), _dbAdjust(-38.0)
, _yMin(-90.0), _yMax(0.0), _imageBuf(0)
, _rasterImage(0), _rasterData(0)
, _colorTableType(COLOR_BVRYW), _justresized(false)
, _fillColor(20,120,120), _maxval(0.0), _xScaleType(XSCALE_1X)
, _dataLength(1024)
{
initColorTable();
// max size
_rasterData = new unsigned char[1600 * 3];
_rasterImage = new wxImage(1600, 1 , _rasterData, true);
_points = new wxPoint[FT_MAX_FFT_SIZE/2 + 3];
_fillBrush.SetColour(_fillColor);
_fillBrush.SetStyle(wxSOLID);
_xscaleMenu = new wxMenu(wxT(""));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_1Xscale, wxT("1x Scale")));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_2Xscale, wxT("2x Scale")));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_LogaXscale, wxT("logA Scale")));
_xscaleMenu->Append ( new wxMenuItem(_xscaleMenu, FT_LogbXscale, wxT("logB Scale")));
_linePen.SetColour(255,255,255);
updateSize();
}
FTspectragram::~FTspectragram()
{
delete [] _rasterData;
if (_imageBuf) delete _imageBuf;
if (_rasterImage) delete _rasterImage;
delete _xscaleMenu;
delete [] _points;
}
void FTspectragram::setDataLength(unsigned int len)
{
// this is the new max length our raster
// data needs to handle
if (_rasterData)
delete [] _rasterData;
if ((int) len < _width) {
_rasterData = new unsigned char[_width * 3];
_dataLength = _width;
}
else {
_rasterData = new unsigned char[len * 3];
_dataLength = len;
}
if (_rasterImage)
delete _rasterImage;
//_rasterImage = new wxImage(_width, 1 , _rasterData, true);
_rasterImage = new wxImage(_dataLength, 1 , _rasterData, true);
}
void FTspectragram::setPlotType (PlotType pt)
{
if (_ptype != pt) {
_ptype = pt;
_justresized = true;
Refresh(TRUE);
}
}
void FTspectragram::OnPaint(wxPaintEvent & event)
{
//printf ("Spectragram::OnPaint\n");
wxPaintDC dc(this);
wxMemoryDC sdc;
if (_justresized)
{
if (_imageBuf) delete _imageBuf;
_imageBuf = new wxBitmap(_width, _height);
sdc.SelectObject(*_imageBuf);
sdc.SetBackground(*wxBLACK_BRUSH);
sdc.Clear();
_justresized = false;
}
if (_imageBuf) {
sdc.SelectObject(*_imageBuf);
dc.Blit(0,0, _width, _height, &sdc, 0,0);
}
//event.Skip();
}
void FTspectragram::updateSize()
{
int w,h;
GetClientSize(&w, &h);
//printf ("Spectragram::OnSize w=%d h=%d\n", _width, _height);
if (w != _width || h != _height) {
_justresized = true;
}
_width = w;
_height = h;
if (_width > (int) _dataLength) {
setDataLength(_width);
}
else {
if (_rasterImage)
delete _rasterImage;
//_rasterImage = new wxImage(_width, 1 , _rasterData, true);
_rasterImage = new wxImage(_dataLength, 1 , _rasterData, true);
}
}
void FTspectragram::OnSize(wxSizeEvent & event)
{
updateSize();
event.Skip();
}
void FTspectragram::plotNextData (const float *data, int length)
{
if (_ptype == SPECTRAGRAM) {
plotNextDataSpectragram (data, length);
}
else if (_ptype == AMPFREQ_LINES || _ptype == AMPFREQ_SOLID) {
plotNextDataAmpFreq (data, length);
}
//printf ("maxval is %g\n", _maxval);
}
void FTspectragram::plotNextDataSpectragram (const float *data, int length)
{
wxClientDC dc(this);
//wxMemoryDC rdc;
//rdc.SelectObject(*_raster);
wxMemoryDC sdc;
if (_imageBuf)
sdc.SelectObject(*_imageBuf);
else return;
//sdc.SetOptimization(true);
//dc.SetOptimization(true);
//rdc.SetOptimization(true);
float dbval, sum;
int coli, i, j;
double xSkipD = (double)length / (double)_width;
int xSkipI = (int)(xSkipD + 0.5);
if (xSkipI < 1) xSkipI = 1;
//wxPen pen = rdc.GetPen();
_xscale = (double)_width/(double)length;
_length = length;
int x1,x2;
// if (_width >= length)
if (_width == length)
{
/*
if (_width > length) {
//printf ("undersampled: w=%d l=%d sxale=%g\n", _width, length, xscale);
rdc.SetUserScale(_xscale, 1.0);
}
*/
// draw new raster
for (int i=0; i < length; i++)
{
dbval = powerLogScale(data[i]);
coli = (int) (((dbval - _yMin) / ( _yMax - _yMin)) * _colorCount);
if (coli >= _colorCount) {
coli = _colorCount-1;
}
else if (coli < 0) {
coli = 0;
}
//pen.SetColour((int)_colorMap[coli][0], (int)_colorMap[coli][1], (int)_colorMap[coli][2] );
//rdc.SetPen(pen);
//rdc.DrawLine(i,0,i+1,0);
binToXRange(i, x1, x2, _length, _length);
for (int n=x1; n <= x2; n++) {
_rasterData[3*n] = _colorMap[coli][0];
_rasterData[3*n + 1] = _colorMap[coli][1];
_rasterData[3*n + 2] = _colorMap[coli][2];
}
}
}
else if (_width > length)
{
double xscale = (double)_width / ((double)length-1);
int xadj = (int) (xscale * 0.5);
double xposf = -xadj;
int lasti = 0;
coli = 0;
for(j = 0; j < length; j++, xposf+=xscale)
{
i = (int) lrint(xposf);
while (lasti < i) {
// fill blanks with last
binToXRange(lasti, x1, x2, _length, _length);
for (int n=x1; n <= x2; ++n) {
_rasterData[3*n] = _colorMap[coli][0];
_rasterData[3*n+1] = _colorMap[coli][1];
_rasterData[3*n+2] = _colorMap[coli][2];
}
++lasti;
}
dbval = powerLogScale(data[j]);
// normalize it from _dataRefMin/Max to 0-numcolors
coli = (int) (((dbval - _yMin) / ( _yMax - _yMin)) * _colorCount);
if (coli >= (int)_colorCount) {
coli = (int) (_colorCount-1);
}
else if (coli < 0) {
coli = 0;
}
}
while (lasti < _width) {
// fill blanks with last
binToXRange(lasti, x1, x2, _length, _length);
for (int n=x1; n <= x2; ++n) {
_rasterData[3*n] = _colorMap[coli][0];
_rasterData[3*n+1] = _colorMap[coli][1];
_rasterData[3*n+2] = _colorMap[coli][2];
}
++lasti;
}
}
else {
j = 0;
int nextj;
for(i = 0; i < _width; i++)
{
nextj = (int)((i+1)*xSkipD + 0.5);
sum = -100000;
for (; j < nextj; ++j)
{
if ((data[j] ) > sum)
{
sum = (data[j] );
}
}
dbval = powerLogScale(sum);
// normalize it from _dataRefMin/Max to 0-numcolors
//coli = (int) (((sum - _dataRefMin) / refDiff) * _colorCount);
coli = (int) (((dbval - _yMin) / ( _yMax - _yMin)) * _colorCount);
if (coli >= (int) _colorCount) {
coli = (int)_colorCount-1;
}
else if (coli < 0) {
coli = 0;
}
binToXRange(i, x1, x2, _length, _length);
for (int n=x1; n <= x2; ++n) {
_rasterData[3*n] = _colorMap[coli][0];
_rasterData[3*n+1] = _colorMap[coli][1];
_rasterData[3*n+2] = _colorMap[coli][2];
}
}
}
/*
else {
// Assume they want average
// (_scaleType == DATA_MAX)
//_dataElements = _plotWidth;
for(i = 0; i < _width; i++)
{
sum = 0;
for (k = 0, j = (int)(i*xSkipD); k < xSkipI; j++, k++)
{
sum += (data[j]);
//if (sum < data[j]) {
// sum = data[j];
//}
}
sum /= xSkipI;
dbval = powerLogScale(sum);
coli = (int) (((dbval - _yMin) / ( _yMax - _yMin)) * _colorCount);
if (coli >= _colorCount) {
coli = _colorCount-1;
}
else if (coli < 0) {
coli = 0;
}
//printf ("dbval= %g coli=%d\n", dbval, coli);
//pen.SetColour((int)_colorMap[coli][0], (int)_colorMap[coli][1], (int)_colorMap[coli][2] );
//rdc.SetPen(pen);
//rdc.DrawLine(i,0, i+1, 0);
binToXRange(i, x1, x2, _length, _length);
for (int n=x1; n <= x2; n++) {
_rasterData[3*n] = _colorMap[coli][0];
_rasterData[3*n + 1] = _colorMap[coli][1];
_rasterData[3*n + 2] = _colorMap[coli][2];
}
}
}
*/
// this is double buffered
// move the specbuf down
sdc.Blit(0,1,_width,_height-1, &sdc, 0, 0);
// blit the new raster
//sdc.Blit(0,0,_width, 1, &rdc, 0,0);
//if (_width > length) {
//printf ("undersampled: w=%d l=%d sxale=%g\n", _width, length, _xscale);
// sdc.SetUserScale(_xscale, 1.0);
//}
sdc.DrawBitmap (wxBitmap (*_rasterImage), 0, 0, false);
// blit to screen
dc.Blit(0,0, _width, _height, &sdc, 0,0);
}
void FTspectragram::plotNextDataAmpFreq (const float *data, int length)
{
// printf ("Plot new data\n");
wxClientDC dc(this);
wxMemoryDC sdc;
if (_imageBuf)
sdc.SelectObject(*_imageBuf);
else
return;
//sdc.SetOptimization(true);
//dc.SetOptimization(true);
float dbval, sum;
int yval, i, k, j;
double xSkipD = (double)length / (double)_width;
int xSkipI = (int)(xSkipD + 0.5);
if (xSkipI < 1) xSkipI = 1;
_xscale = (double)_width/(double)length;
_length = length;
sdc.SetBackground(*wxBLACK_BRUSH);
sdc.Clear();
sdc.SetPen(_linePen);
sdc.SetBrush(_fillBrush);
_points[0].x = 0;
_points[0].y = _height + 2;
int x1,x2, lastx=0;
if (_width >= length)
{
for (int i=0; i < length; i++)
{
dbval = powerLogScale(data[i]);
yval = _height - (int) (((dbval - _yMin) / ( _yMax - _yMin)) * _height);
if (yval >= _height) {
yval = _height;
}
else if (yval < 0) {
yval = 0;
}
switch (_ptype)
{
case AMPFREQ_LINES:
if (_xScaleType != XSCALE_1X) {
binToXRange(i, x1, x2, _length, _length);
_points[i+2].x = (int) ( (x1+ ((x2-x1)>>1)) * _xscale);
}
else {
_points[i+2].x = (int) (i * _xscale);
}
_points[i+2].y = yval;
//printf ("avg dbval=%g yval=%d data=%g\n", dbval, yval, sum);
break;
case AMPFREQ_SOLID:
binToXRange(i, x1, x2, _width, _length);
sdc.DrawRectangle ( (int)(lastx), yval,
(int) (x2-lastx) , _height-yval);
lastx = x2;
break;
default: break;
}
//printf ("dbval=%g yval=%d data=%g\n", dbval, yval, data[i]);
}
if (_ptype == AMPFREQ_LINES) {
_points[1].x = 0;
_points[1].y = _points[2].y;
_points[length].x = _width + 1;
_points[length].y = _height + 2;
_points[length+1].x = _points[0].x;
_points[length+1].y = _points[0].y;
// sdc.DrawLines(length+2, _points);
sdc.DrawPolygon(length+2, _points);
}
}
else {
// Assume they want average
// (_scaleType == DATA_MAX)
//_dataElements = _plotWidth;
for(i = 0; i < _width; i++)
{
sum = 0;
for (k = 0, j = (int)(i*xSkipD); k < xSkipI; j++, k++)
{
sum += (data[j]);
}
sum /= xSkipI;
dbval = powerLogScale(sum);
yval = _height - (int) (((dbval - _yMin) / ( _yMax - _yMin)) * _height);
if (yval >= _height) {
yval = _height;
}
else if (yval < 0) {
yval = 0;
}
switch (_ptype)
{
case AMPFREQ_LINES:
if (_xScaleType != XSCALE_1X) {
binToXRange(i, x1, x2, _width, _width);
_points[i+1].x = (int) ( x1+ ((x2-x1)>>1));
}
else {
_points[i+1].x = (int) (i);
}
_points[i+2].y = yval;
//printf ("avg dbval=%g yval=%d data=%g\n", dbval, yval, sum);
break;
case AMPFREQ_SOLID:
// treat even points as x,y odd as width,height
binToXRange(i, x1, x2, _width, _width);
sdc.DrawRectangle ( lastx, yval, (x2-lastx), _height-yval);
lastx = x2;
break;
default: break;
}
}
//printf ("undersampled: w=%d l=%d sxale=%g\n", _width, length, xscale);
//sdc.SetUserScale(_xscale, 1.0);
if (_ptype == AMPFREQ_LINES) {
_points[1].x = 0;
_points[1].y = _points[2].y;
_points[_width].x = _width+1;
_points[_width].y = _height + 2;
_points[_width+1].x = _points[0].x;
_points[_width+1].y = _points[0].y;
// sdc.DrawLines(_width+2, _points);
sdc.DrawPolygon(_width+2, _points);
}
}
// this is double buffered
//sdc.SetTextForeground(*wxWHITE);
//sdc.DrawText(wxString::Format("%g", _maxval), 0, 0);
// blit to screen
dc.Blit(0,0, _width, _height, &sdc, 0,0);
}
void FTspectragram::setXscale(XScaleType sc)
{
_xScaleType = sc;
Refresh(FALSE);
}
void FTspectragram::initColorTable()
{
if (!_colorMap) {
// this is only allocated once (and it is static)
_colorMap = new unsigned char * [_maxColorCount];
for (int i=0; i < _maxColorCount; i++) {
_colorMap[i] = new unsigned char[3];
}
}
if (!_discreteColors) {
_discreteColors = new unsigned char * [_maxDiscreteColorCount];
for (int i=0; i < _maxDiscreteColorCount; i++) {
_discreteColors[i] = new unsigned char[3];
}
// for now we are just using
if (_colorTableType == COLOR_GRAYSCALE) {
_discreteColorCount = 2;
// black
_discreteColors[0][0] = 0;
_discreteColors[0][1] = 0;
_discreteColors[0][2] = 0;
// white
_discreteColors[1][0] = 0xff;
_discreteColors[1][1] = 0xff;
_discreteColors[1][2] = 0xff;
}
if (_colorTableType == COLOR_GREENSCALE) {
_discreteColorCount = 2;
// black
_discreteColors[0][0] = 0;
_discreteColors[0][1] = 0;
_discreteColors[0][2] = 0;
// green
_discreteColors[1][0] = 0;
_discreteColors[1][1] = 200;
_discreteColors[1][2] = 0;
}
else if (_colorTableType == COLOR_BVRYW)
{
_discreteColorCount = 6;
setDiscreteColor(0, 0, 0, 0); // black
setDiscreteColor(1, 0, 0, 149); // blue
setDiscreteColor(2, 57, 122, 138); // blue-green
setDiscreteColor(3, 92, 165, 79); // green
setDiscreteColor(4, 229, 171, 0); // orange
setDiscreteColor(5, 255, 0, 18); // red
/*
_discreteColorCount = 7;
// black
_discreteColors[0][0] = 0;
_discreteColors[0][1] = 0;
_discreteColors[0][2] = 0;
// blue
_discreteColors[1][0] = 0;
_discreteColors[1][1] = 0;
_discreteColors[1][2] = 200;
// violet
_discreteColors[2][0] = 200;
_discreteColors[2][1] = 0;
_discreteColors[2][2] = 200;
// red
_discreteColors[3][0] = 200;
_discreteColors[3][1] = 0;
_discreteColors[3][2] = 0;
// orangish
_discreteColors[4][0] = 238;
_discreteColors[4][1] = 118;
_discreteColors[4][2] = 33;
// yellow
_discreteColors[5][0] = 200;
_discreteColors[5][1] = 200;
_discreteColors[5][2] = 0;
// pale green
_discreteColors[6][0] = 100;
_discreteColors[6][1] = 160;
_discreteColors[6][2] = 100;
*/
}
}
float seglen = _colorCount * 1.0/(_discreteColorCount-1);
float ratio;
int pos = 0;
// printf ("seglen is %f\n", seglen);
for (int dcol=0; dcol < _discreteColorCount-1; dcol++)
{
// fade this color into the next one
for (int i=0; i < (int)seglen; i++)
{
ratio = i / seglen;
_colorMap[i + pos][0] = (unsigned char) (_discreteColors[dcol][0]*(1-ratio) + _discreteColors[dcol+1][0]*ratio) & 0xff ;
_colorMap[i + pos][1] = (unsigned char) (_discreteColors[dcol][1]*(1-ratio) + _discreteColors[dcol+1][1]*ratio) & 0xff ;
_colorMap[i + pos][2] = (unsigned char) (_discreteColors[dcol][2]*(1-ratio) + _discreteColors[dcol+1][2]*ratio) & 0xff ;
}
pos += (int) seglen;
}
// finish off
for (; pos < _colorCount; pos++) {
_colorMap[pos][0] = (unsigned char) (_discreteColors[_discreteColorCount-1][0]);
_colorMap[pos][1] = (unsigned char) (_discreteColors[_discreteColorCount-1][1]);
_colorMap[pos][2] = (unsigned char) (_discreteColors[_discreteColorCount-1][2]);
}
}
float FTspectragram::powerLogScale(float yval)
{
if (yval <= _minCutoff) {
return _dbAbsMin;
}
// if (yval > _maxval) {
// _maxval = yval;
// }
//float nval = (10.0 * FTutils::fast_log10(yval / _dataRefMax));
float nval = (10.0 * FTutils::fast_log10(yval)) + _dbAdjust;
// printf ("scaled value is %g mincut=%g\n", nval, _minCutoff);
return nval;
}
void FTspectragram::updatePositionLabels(int pX, int pY, bool showreal)
{
// calculate freq range and val for status bar
float sfreq, efreq;
int frombin, tobin;
xToFreqRange(pX, sfreq, efreq, frombin, tobin);
_freqstr.Printf (wxT("%5d - %5d Hz"), (int) sfreq, (int) efreq);
_mwin->updatePosition ( _freqstr, wxT("") );
}
void FTspectragram::xToFreqRange(int x, float &fromfreq, float &tofreq, int &frombin, int &tobin)
{
float freqPerBin = FTioSupport::instance()->getSampleRate()/(2.0 * (double)_length);
//printf ("specmod length = %d freqperbin=%g\n", _specMod->getLength(), freqPerBin);
xToBinRange(x, frombin, tobin);
fromfreq = freqPerBin * frombin;
tofreq = freqPerBin * tobin + freqPerBin;
}
/*
void FTspectragram::xToBinRange(int x, int &frombin, int &tobin)
{
// converts x coord into filter bin
// according to scaling
int bin, lbin, rbin;
int totbins = _length;
//float xscale = _width / (float)totbins;
if (x < 0) x = 0;
else if (x >= _width) x = _width-1;
if (_xScaleType == XSCALE_1X) {
bin = rbin = lbin = (int)(x / _xscale);
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest with same x
while ( ((int)((lbin-1)*_xscale) == x) && (lbin > 0)) {
lbin--;
}
// find highest with same x
while ( ((int)((rbin+1)*_xscale) == x) && (rbin < totbins-1)) {
rbin++;
}
frombin = lbin;
tobin = rbin;
}
else {
frombin = 0;
tobin = 0;
}
//printf ("x=%d frombin=%d tobin=%d\n", x, frombin, tobin);
}
*/
void FTspectragram::xToBinRange(int x, int &frombin, int &tobin)
{
// converts x coord into filter bin
// according to scaling
int lbin, rbin;
int totbins = _length;
//int totbins = _specMod->getLength();
//float xscale = _width / (float)totbins;
//if (x < 0) x = 0;
//else if (x >= _width) x = _width-1;
if (_xScaleType == XSCALE_1X) {
rbin = lbin = (int)(x / _xscale);
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest with same x
while ( ((int)((lbin-1)*_xscale) == x) && (lbin > 0)) {
lbin--;
}
// find highest with same x
while ( ((int)((rbin+1)*_xscale) == x) && (rbin < totbins-1)) {
rbin++;
}
frombin = lbin;
tobin = rbin;
}
else if (_xScaleType == XSCALE_2X) {
float hxscale = _xscale * 2;
if (x >= _width-2) {
lbin = totbins/2;
rbin = totbins-1;
}
else {
rbin = lbin = (int)(x / hxscale);
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest with same x
while ( ((int)((lbin-1)*hxscale) == x) && (lbin > 0)) {
lbin--;
}
// find highest with same x
while ( ((int)((rbin+1)*hxscale) == x) && (rbin < totbins>>1)) {
rbin++;
}
}
frombin = lbin;
tobin = rbin;
}
else if (_xScaleType == XSCALE_LOGA)
{
if (x >= _width-1) {
lbin = totbins/2;
rbin = totbins-1;
}
else {
float xscale = x / (float)_width;
// use log scale for freq
lbin = rbin = (int) pow ( totbins>>1, xscale) - 1;
// find lowest with same x
while ( (lbin > 0) && ((int)(((FTutils::fast_log10(lbin) / FTutils::fast_log10(totbins/2)) * _width)) == x)) {
lbin--;
}
// find highest with same x
while ( (rbin < totbins>>1) && ((int)(((FTutils::fast_log10(rbin) / FTutils::fast_log10(totbins/2)) )) == x)) {
rbin++;
}
}
frombin = lbin;
tobin = rbin;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else if (_xScaleType == XSCALE_LOGB)
{
if (x >= _width-1) {
lbin = (int) (totbins/3.0);
rbin = totbins-1;
}
else {
float xscale = x / (float)_width;
// use log scale for freq
lbin = rbin = (int) pow ( (float)(totbins/3.0), xscale) - 1;
// find lowest with same x
while ( (lbin > 0) && ((int)(((FTutils::fast_log10(lbin) / FTutils::fast_log10(totbins/3.0)) * _width)) == x)) {
lbin--;
}
// find highest with same x
while ( (rbin < (int)(totbins/3.0)) && ((int)(((FTutils::fast_log10(rbin) / FTutils::fast_log10(totbins/3.0)) )) == x)) {
rbin++;
}
}
frombin = lbin;
tobin = rbin;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else {
frombin = 0;
tobin = 0;
}
//printf ("x=%d frombin=%d tobin=%d\n", x, frombin, tobin);
}
void FTspectragram::binToXRange(int bin, int &fromx, int &tox, int length, int bins)
{
// converts bin into x coord range
// according to scaling
int lx, rx;
int totbins = bins;
float xscale = length / (float)totbins;
// assume width whatever passed in
int width = length;
//if (bin < 0) bin = 0;
//else if (bin >= totbins) bin = totbins-1;
if (_xScaleType == XSCALE_1X) {
//bin = rbin = lbin = (int)(x / xscale);
lx = rx = (int) (bin * xscale);
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest x with same bin
while ( ((int)((lx-1)/xscale) == bin) && (lx > 0)) {
lx--;
}
// find highest with same x
while ( ((int)((rx+1)/xscale) == bin) && (rx < width-1)) {
rx++;
}
fromx = lx;
tox = rx;
}
else if (_xScaleType == XSCALE_2X) {
float hxscale = xscale * 2;
if (bin >= totbins>>1) {
rx = (int) (totbins * xscale);
lx = rx - 2;
}
else {
//bin = rbin = lbin = (int)(x / xscale);
lx = rx = (int) (bin * hxscale );
//printf (" %d %g %d\n", x, bin*xscale, (int)(bin * xscale));
// find lowest x with same bin
while ( ((int)((lx-1)/(hxscale)) == bin) && (lx > 0)) {
lx--;
}
// find highest with same x
while ( ((int)((rx+1)/hxscale) == bin) && (rx < width-1)) {
rx++;
}
}
fromx = lx;
tox = rx;
}
else if (_xScaleType == XSCALE_LOGA)
{
// use log scale for freq
if (bin > totbins/2) {
lx = rx = (int) (totbins * xscale);
} else if (bin == 0) {
lx = 0;
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.5)) * width);
} else {
lx = (int) ((FTutils::fast_log10(bin+1) / FTutils::fast_log10(totbins*0.5)) * width);
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.5)) * width);
}
fromx = lx;
tox = rx;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else if (_xScaleType == XSCALE_LOGB)
{
// use log scale for freq
if (bin > (int)(totbins*0.3333)) {
lx = rx = (int) (totbins * xscale);
} else if (bin == 0) {
lx = 0;
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.3333)) * width);
} else {
lx = (int) ((FTutils::fast_log10(bin+1) / FTutils::fast_log10(totbins*0.3333)) * width);
rx = (int) ((FTutils::fast_log10(bin+2) / FTutils::fast_log10(totbins*0.3333)) * width);
}
fromx = lx;
tox = rx;
// printf ("bin %d fromx=%d tox=%d\n", bin, fromx, tox);
}
else {
fromx = 0;
tox = 0;
}
//printf ("bin=%d fromx=%d tox=%d\n", bin, fromx, tox);
}
void FTspectragram::OnMouseActivity( wxMouseEvent &event)
{
int pX = event.GetX();
int pY = event.GetY();
if (event.Moving() || event.Entering())
{
updatePositionLabels(pX, pY, true);
}
else if (event.Leaving()) {
_mwin->updatePosition(wxT(""), wxT(""));
}
else if (event.MiddleUp() || event.RightUp()) {
// popup scale menu
this->PopupMenu ( _xscaleMenu, pX, pY);
}
else {
event.Skip();
}
}
void FTspectragram::OnXscaleMenu (wxCommandEvent &event)
{
//wxMenuItem *item = (wxMenuItem *) event.GetEventObject();
if (event.GetId() == FT_1Xscale) {
_xScaleType = XSCALE_1X;
}
else if (event.GetId() == FT_2Xscale) {
_xScaleType = XSCALE_2X;
}
else if (event.GetId() == FT_LogaXscale) {
_xScaleType = XSCALE_LOGA;
}
else if (event.GetId() == FT_LogbXscale) {
_xScaleType = XSCALE_LOGB;
}
else {
event.Skip();
}
Refresh(FALSE);
}
| 25,790
|
C++
|
.cpp
| 880
| 25.610227
| 124
| 0.616218
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,947
|
FTpresetBlender.cpp
|
essej_freqtweak/src/FTpresetBlender.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTpresetBlender.hpp"
#include "FTioSupport.hpp"
#include "FTprocI.hpp"
#include "FTprocessPath.hpp"
#include "FTconfigManager.hpp"
#include "FTspectralEngine.hpp"
#include "FTspectrumModifier.hpp"
FTpresetBlender::FTpresetBlender(FTconfigManager * confman)
: _configMan(confman)
{
// add two elements both intially null
_presetList.push_back(0);
_presetList.push_back(0);
_presetNames.push_back("");
_presetNames.push_back("");
}
FTpresetBlender::~FTpresetBlender()
{
for (unsigned int n=0; n < _presetList.size(); ++n) {
if (_presetList[n]) {
delete _presetList[n];
}
}
_presetList.clear();
}
bool FTpresetBlender::setPreset(const string & name, int index)
{
// try to load it up and compare the resulting FTprocs to the
// currently active ones
if (index >= (int) _presetList.size()) {
return false;
}
// delete old one no matter what
if (_presetList[index]) {
delete _presetList[index];
_presetList[index] = 0;
}
vector<vector <FTprocI *> > * procvec = new vector<vector<FTprocI*> > ();
bool succ = _configMan->loadSettings (name.c_str(), false, true, *procvec, false);
if (!succ) {
delete procvec;
return false;
}
FTioSupport * iosup = FTioSupport::instance();
if ((int)procvec->size() != iosup->getActivePathCount()) {
delete procvec;
return false;
}
for ( unsigned int i=0; i < procvec->size(); i++)
{
FTprocessPath * procpath = iosup->getProcessPath(i);
if (!procpath) {
delete procvec;
return false; // shouldnt happen
}
vector<FTprocI*> & pvec = (*procvec)[i];
FTspectralEngine * engine = procpath->getSpectralEngine();
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
for (unsigned int n=0; n < procmods.size(); ++n)
{
FTprocI *pm = procmods[n];
// compare the proctype
if (pvec.size() <= n || pm->getName() != pvec[n]->getName()) {
fprintf (stderr, "mismatch at %d %d: %s %lu\n", i, n, pm->getName().c_str(), pvec.size());
delete procvec;
return false;
}
}
}
// if we got here we are a match
_presetList[index] = procvec;
_presetNames[index] = name;
return true;
}
string FTpresetBlender::getPreset(int index)
{
if (index < (int) _presetNames.size()) {
return _presetNames[index];
}
return "";
}
bool FTpresetBlender::setBlend (unsigned int specmod_n, unsigned int filt_n, float val)
{
// for the given filter given by specmod_n, filt_n, set the ratio to use
// and adjust the active filters accordingly
// TODO: support more than 2 presets
// Assume that both proc lists have the same structure
if (!_presetList[0] || !_presetList[1]) {
return false;
}
FTioSupport * iosup = FTioSupport::instance();
vector<vector <FTprocI *> > * procvec0 = _presetList[0];
vector<vector <FTprocI *> > * procvec1 = _presetList[1];
for (unsigned int chan=0; chan < procvec0->size(); ++chan)
{
vector<FTprocI*> & procvec0_p = (*procvec0)[chan];
vector<FTprocI*> & procvec1_p = (*procvec1)[chan];
FTprocessPath * procpath = iosup->getProcessPath((int) chan);
if (!procpath) continue; // shouldnt happen
FTspectralEngine *engine = procpath->getSpectralEngine();
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
if (specmod_n < procvec0_p.size() && specmod_n < procvec1_p.size()
&& specmod_n < procmods.size())
{
FTspectrumModifier * targFilt = procmods[specmod_n]->getFilter(filt_n);
FTspectrumModifier * filt0 = procvec0_p[specmod_n]->getFilter(filt_n);
FTspectrumModifier * filt1 = procvec1_p[specmod_n]->getFilter(filt_n);
if (targFilt && filt0 && filt1)
{
// do the blend
blendFilters (targFilt, filt0, filt1, val);
}
}
}
return true;
}
float FTpresetBlender::getBlend (unsigned int specmod_n, unsigned int filt_n)
{
return 0.0;
}
void FTpresetBlender::blendFilters (FTspectrumModifier * targFilt, FTspectrumModifier *filt0, FTspectrumModifier *filt1, float val)
{
float * targvals = targFilt->getValues();
float * filt0vals = filt0->getValues();
float * filt1vals = filt1->getValues();
for (int i=0; i < targFilt->getLength(); ++i)
{
targvals[i] = val*filt0vals[i] + (1.0-val)*filt1vals[i];
}
}
| 4,980
|
C++
|
.cpp
| 150
| 30.52
| 131
| 0.70745
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,948
|
FTmodValueLFO.cpp
|
essej_freqtweak/src/FTmodValueLFO.cpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTmodValueLFO.hpp"
#include "FTutils.hpp"
#include <cstdlib>
#include <cstdio>
#include <iostream>
using namespace std;
using namespace PBD;
FTmodValueLFO::FTmodValueLFO (nframes_t samplerate, unsigned int fftn)
: FTmodulatorI ("ValueLFO", "Value LFO", samplerate, fftn)
{
}
FTmodValueLFO::FTmodValueLFO (const FTmodValueLFO & other)
: FTmodulatorI ("ValueLFO", "Value LFO", other._sampleRate, other._fftN)
{
}
void FTmodValueLFO::initialize()
{
_lastframe = 0;
_rate = new Control (Control::FloatType, "rate", "Rate", "Hz");
_rate->_floatLB = 0.0;
_rate->_floatUB = 20.0;
_rate->setValue (0.0f);
_controls.push_back (_rate);
_depth = new Control (Control::FloatType, "depth", "Depth", "%");
_depth->_floatLB = 0.0;
_depth->_floatUB = 100.0;
_depth->setValue (0.0f);
_controls.push_back (_depth);
_lfotype = new Control (Control::EnumType, "lfo_type", "LFO Type", "");
_lfotype->_enumList.push_back("Sine");
_lfotype->_enumList.push_back("Triangle");
_lfotype->_enumList.push_back("Square");
_lfotype->setValue (string("Sine"));
_controls.push_back (_lfotype);
_minfreq = new Control (Control::FloatType, "min_freq", "Min Freq", "Hz");
_minfreq->_floatLB = 0.0;
_minfreq->_floatUB = _sampleRate / 2;
_minfreq->setValue (_minfreq->_floatLB);
_controls.push_back (_minfreq);
_maxfreq = new Control (Control::FloatType, "max_freq", "Max Freq", "Hz");
_maxfreq->_floatLB = 0.0;
_maxfreq->_floatUB = _sampleRate / 2;
_maxfreq->setValue (_maxfreq->_floatUB);
_controls.push_back (_maxfreq);
_tmpfilt = new float[_fftN];
_inited = true;
}
FTmodValueLFO::~FTmodValueLFO()
{
if (!_inited) return;
_controls.clear();
delete _rate;
delete _depth;
delete _lfotype;
delete _minfreq;
delete _maxfreq;
}
void FTmodValueLFO::addSpecMod (FTspectrumModifier * specmod)
{
{
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
_lastshifts[specmod] = 0.0;
}
FTmodulatorI::addSpecMod (specmod);
}
void FTmodValueLFO::removeSpecMod (FTspectrumModifier * specmod)
{
FTmodulatorI::removeSpecMod (specmod);
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
_lastshifts.erase(specmod);
}
void FTmodValueLFO::clearSpecMods ()
{
FTmodulatorI::clearSpecMods();
LockMonitor pmlock(_specmodLock, __LINE__, __FILE__);
_lastshifts.clear();
}
void FTmodValueLFO::setFFTsize (unsigned int fftn)
{
_fftN = fftn;
if (_inited) {
delete _tmpfilt;
_tmpfilt = new float[_fftN];
}
}
void FTmodValueLFO::modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes)
{
TentativeLockMonitor lm (_specmodLock, __LINE__, __FILE__);
if (!lm.locked() || !_inited || _bypassed) return;
float rate = 1.0;
double currdev = 0.0;
float ub,lb, tmplb, tmpub;
float * filter;
int len;
float minfreq = 0.0, maxfreq = 0.0;
float depth = 1.0;
unsigned int minbin, maxbin;
float shiftval = 0;
double current_secs;
double lastshift;
string shape;
// in hz
_rate->getValue (rate);
_lfotype->getValue (shape);
// in %
_depth->getValue (depth);
_minfreq->getValue (minfreq);
_maxfreq->getValue (maxfreq);
if (minfreq >= maxfreq) {
return;
}
current_secs = current_frame / (double) _sampleRate;
if (current_frame != _lastframe)
{
// fprintf (stderr, "shift at %lu : samps=%g s*c=%g s*e=%g \n", (unsigned long) current_frame, samps, (current_frame/samps), ((current_frame + nframes)/samps) );
for (SpecModList::iterator iter = _specMods.begin(); iter != _specMods.end(); ++iter)
{
FTspectrumModifier * sm = (*iter);
if (sm->getBypassed()) continue;
// cerr << "shiftval is: " << shiftval
// << " hz/bin: " << hzperbin
// << " rate: " << rate << endl;
filter = sm->getValues();
sm->getRange(tmplb, tmpub);
len = (int) sm->getLength();
minbin = (int) ((minfreq*2/ _sampleRate) * len);
maxbin = (int) ((maxfreq*2/ _sampleRate) * len);
// lb = tmplb + (tmpub-tmplb) * minval*0.01;
// ub = tmplb + (tmpub-tmplb) * maxval*0.01;
lb = tmplb;
ub = tmpub;
len = maxbin - minbin;
if (len <= 0) {
continue;
}
if (shape == "Sine")
{
currdev = (double) (FTutils::sine_wave (current_secs, (double) rate) * ( (ub-lb)* (depth * 0.01) * 0.5 ));
} else if (shape == "Square")
{
currdev = (double) (FTutils::square_wave (current_secs, (double) rate) * ( (ub-lb)* (depth * 0.01) * 0.5 ));
}
else if (shape == "Triangle")
{
currdev = (double) (FTutils::triangle_wave (current_secs, (double) rate) * ( (ub-lb)* (depth * 0.01) * 0.5 ));
}
else {
continue;
}
lastshift = _lastshifts[sm];
shiftval = (float) (currdev - lastshift);
// fprintf(stderr, "shifting %d %d:%d at %lu\n", shiftbins, minbin, maxbin, (unsigned long) current_frame);
for (unsigned int i=minbin; i < maxbin; ++i) {
filter[i] += shiftval;
}
sm->setDirty(true);
_lastshifts[sm] = currdev;
}
_lastframe = current_frame;
}
}
| 5,797
|
C++
|
.cpp
| 179
| 29.636872
| 166
| 0.672217
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,949
|
FTprocLimit.cpp
|
essej_freqtweak/src/FTprocLimit.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTprocLimit.hpp"
#include "FTutils.hpp"
#include <cmath>
using namespace std;
FTprocLimit::FTprocLimit (nframes_t samprate, unsigned int fftn)
: FTprocI("Limit", samprate, fftn)
, _dbAdjust(-48.0)
{
_confname = "Limit";
}
FTprocLimit::FTprocLimit (const FTprocLimit & other)
: FTprocI (other._name, other._sampleRate, other._fftN)
, _dbAdjust(-48.0)
{
_confname = "Limit";
}
void FTprocLimit::initialize()
{
// create filter
_threshfilter = new FTspectrumModifier("Limit", "limit_thresh", 0, FTspectrumModifier::DB_MODIFIER, MASH_SPECMOD, _fftN/2, 0.0);
_threshfilter->setRange(-90.0, 0.0);
_filterlist.push_back (_threshfilter);
_inited = true;
}
FTprocLimit::~FTprocLimit()
{
if (!_inited) return;
_filterlist.clear();
delete _threshfilter;
}
void FTprocLimit::process (fft_data *data, unsigned int fftn)
{
if (!_inited || _threshfilter->getBypassed()) {
return;
}
float *filter = _threshfilter->getValues();
float min = _threshfilter->getMin();
float max = _threshfilter->getMax();
float filt;
float power;
float db;
float scale;
int fftN2 = (fftn+1) >> 1;
// do for first element
filt = FTutils::f_clamp (filter[0], min, max);
power = (data[0] * data[0]);
db = FTutils::powerLogScale (power, 0.0000000) + _dbAdjust; // total fudge factors
if (filt < db) {
// apply limiting
scale = 1 / (pow (2, (db-filt) / 6.0));
data[0] *= scale;
}
// do for the rest
for (int i = 1; i < fftN2-1; i++)
{
filt = FTutils::f_clamp (filter[i], min, max);
power = (data[i] * data[i]) + (data[fftn-i] * data[fftn-i]);
db = FTutils::powerLogScale (power, 0.0000000) + _dbAdjust; // total fudge factors
if (filt < db) {
// apply limiting
scale = 1 / (pow (2, (db-filt) / 6.0));
data[i] *= scale;
data[fftn-i] *= scale;
}
}
}
| 2,618
|
C++
|
.cpp
| 84
| 28.797619
| 129
| 0.690771
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,950
|
FTmodulatorGui.cpp
|
essej_freqtweak/src/FTmodulatorGui.cpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include <wx/wx.h>
#include "FTmodulatorGui.hpp"
#include "FTmodulatorI.hpp"
#include "FTspectralEngine.hpp"
#include "FTioSupport.hpp"
#include "FTprocessPath.hpp"
#include "FTprocI.hpp"
using namespace sigc;
enum
{
ID_RemoveButton = 8000,
ID_AttachButton,
ID_ChannelButton,
ID_DetachAll,
ID_AttachAll,
ID_ModUserName,
ID_BypassCheck
};
enum {
ID_ControlBase = 10000,
ID_SpecModBase = 11000,
ID_ChannelBase = 12000
};
class FTmodControlObject : public wxObject
{
public:
FTmodControlObject(FTmodulatorI::Control *ctrl)
: control(ctrl)
, slider(0), textctrl(0), choice(0), checkbox(0)
{}
FTmodulatorI::Control * control;
wxSlider * slider;
wxTextCtrl * textctrl;
wxChoice * choice;
wxCheckBox * checkbox;
};
class FTspecmodObject : public wxObject
{
public:
FTspecmodObject(int chan, int mi, int fi) : channel(chan), modIndex(mi), filtIndex(fi) {}
int channel;
int modIndex;
int filtIndex;
};
class FTchannelObject : public wxObject
{
public:
FTchannelObject(int chan) : channel(chan) {}
int channel;
};
BEGIN_EVENT_TABLE(FTmodulatorGui, wxPanel)
EVT_BUTTON(ID_RemoveButton, FTmodulatorGui::onRemoveButton)
EVT_BUTTON(ID_AttachButton, FTmodulatorGui::onAttachButton)
EVT_BUTTON(ID_ChannelButton, FTmodulatorGui::onChannelButton)
EVT_CHECKBOX(ID_BypassCheck, FTmodulatorGui::onBypassButton)
EVT_TEXT_ENTER (ID_ModUserName, FTmodulatorGui::onTextEnter)
EVT_MENU (ID_AttachAll, FTmodulatorGui::onAttachMenu)
EVT_MENU (ID_DetachAll, FTmodulatorGui::onAttachMenu)
END_EVENT_TABLE()
FTmodulatorGui::FTmodulatorGui (FTioSupport * iosup, FTmodulatorI *mod, wxWindow *parent, wxWindowID id,
const wxPoint& pos,
const wxSize& size,
long style ,
const wxString& name)
: wxPanel(parent, id, pos, size, style, name),
_modulator (mod), _iosup(iosup), _popupMenu(0), _channelPopupMenu(0)
{
init();
}
FTmodulatorGui::~FTmodulatorGui()
{
// cerr << "MODGUI destructor" << endl;
}
void FTmodulatorGui::init()
{
wxBoxSizer * mainSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer * topSizer = new wxBoxSizer(wxHORIZONTAL);
// wxBoxSizer *tmpsizer, *tmpsizer2;
wxStaticText * stattext;
stattext = new wxStaticText(this, -1, wxString::FromAscii(_modulator->getName().c_str()),
wxDefaultPosition, wxSize(-1, -1));
stattext->SetFont(wxFont(stattext->GetFont().GetPointSize(), wxDEFAULT, wxNORMAL, wxBOLD));
topSizer->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
_nameText = new wxTextCtrl (this, ID_ModUserName, wxString::FromAscii(_modulator->getUserName().c_str()), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER);
topSizer->Add (_nameText, 1, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
wxCheckBox * bypassCheck = new wxCheckBox(this, ID_BypassCheck, wxT("Bypass"));
bypassCheck->SetValue(_modulator->getBypassed());
topSizer->Add (bypassCheck, 0, wxTOP|wxBOTTOM|wxALIGN_CENTRE_VERTICAL, 2);
// wxButton * chanButton = new wxButton(this, ID_ChannelButton, wxT("Source..."), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
// topSizer->Add (chanButton, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
wxButton * attachButton = new wxButton(this, ID_AttachButton, wxT("Attach..."), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
topSizer->Add (attachButton, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
wxButton * removeButton = new wxButton(this, ID_RemoveButton, wxT("X"), wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
topSizer->Add (removeButton, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
mainSizer->Add (topSizer, 0, wxEXPAND|wxALL, 2);
wxBoxSizer * controlSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer * rowsizer;
int ctrlid = ID_ControlBase;
int textwidth = 70;
// get controls
FTmodulatorI::ControlList controls;
_modulator->getControls (controls);
for (FTmodulatorI::ControlList::iterator ctrliter = controls.begin(); ctrliter != controls.end(); ++ctrliter)
{
FTmodulatorI::Control * ctrl = (FTmodulatorI::Control *) *ctrliter;
wxString unitstr = wxString::Format(wxT("%s"), ctrl->getName().c_str());
if (!ctrl->getUnits().empty()) {
unitstr += wxString::Format(wxT(" [%s]"), ctrl->getUnits().c_str());
}
if (ctrl->getType() == FTmodulatorI::Control::BooleanType) {
// make a checkbox
wxCheckBox * checkb = new wxCheckBox(this, ctrlid, unitstr);
FTmodControlObject * ctrlobj = new FTmodControlObject(ctrl);
ctrlobj->checkbox = checkb;
Connect( ctrlid, wxEVT_COMMAND_CHECKBOX_CLICKED,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction)
&FTmodulatorGui::onCheckboxChanged,
ctrlobj);
controlSizer->Add (checkb, 0, wxEXPAND|wxALL, 2);
}
else if (ctrl->getType() == FTmodulatorI::Control::IntegerType) {
// make a slider and spinbox for now
rowsizer = new wxBoxSizer(wxHORIZONTAL);
stattext = new wxStaticText(this, -1, unitstr);
rowsizer->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
int currval = 0;
int minval=0,maxval=1;
ctrl->getValue(currval);
ctrl->getBounds(minval, maxval);
wxSlider * slider = new wxSlider(this, ctrlid, currval, minval, maxval);
rowsizer->Add (slider, 1, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
ctrlid++;
wxTextCtrl * textctrl = new wxTextCtrl(this, ctrlid, wxString::Format(wxT("%d"), currval), wxDefaultPosition, wxSize(textwidth, -1),
wxTE_PROCESS_ENTER|wxTE_RIGHT);
rowsizer->Add (textctrl, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
FTmodControlObject * ctrlobj = new FTmodControlObject(ctrl);
ctrlobj->slider = slider;
ctrlobj->textctrl = textctrl;
Connect( slider->GetId(), wxEVT_SCROLL_THUMBTRACK,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxScrollEventFunction)
&FTmodulatorGui::onSliderChanged,
ctrlobj);
ctrlobj= new FTmodControlObject(ctrl);
ctrlobj->slider = slider;
ctrlobj->textctrl = textctrl;
Connect( textctrl->GetId(), wxEVT_COMMAND_TEXT_ENTER,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction)
&FTmodulatorGui::onTextEnter,
ctrlobj);
controlSizer->Add (rowsizer, 0, wxEXPAND|wxALL, 2);
}
else if (ctrl->getType() == FTmodulatorI::Control::FloatType) {
// make a slider and spinbox for now
rowsizer = new wxBoxSizer(wxHORIZONTAL);
stattext = new wxStaticText(this, -1, unitstr);
rowsizer->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
float currval = 0;
float minval=0,maxval=1;
int calcval = 0;
ctrl->getValue(currval);
ctrl->getBounds(minval, maxval);
// we'll always have slider values between 0 and 1000 for now
calcval = (int) (((currval-minval) / (maxval - minval)) * 1000);
wxSlider * slider = new wxSlider(this, ctrlid, (int) calcval, 0, 1000);
rowsizer->Add (slider, 1, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
ctrlid++;
wxTextCtrl * textctrl = new wxTextCtrl(this, ctrlid, wxString::Format(wxT("%.6g"), currval), wxDefaultPosition, wxSize(textwidth, -1),
wxTE_PROCESS_ENTER|wxTE_RIGHT);
rowsizer->Add (textctrl, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
FTmodControlObject * ctrlobj = new FTmodControlObject(ctrl);
ctrlobj->slider = slider;
ctrlobj->textctrl = textctrl;
Connect( slider->GetId(), wxEVT_SCROLL_THUMBTRACK,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) (wxScrollEventFunction)
&FTmodulatorGui::onSliderChanged,
ctrlobj);
ctrlobj= new FTmodControlObject(ctrl);
ctrlobj->slider = slider;
ctrlobj->textctrl = textctrl;
Connect( textctrl->GetId(), wxEVT_COMMAND_TEXT_ENTER,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction)
&FTmodulatorGui::onTextEnter,
ctrlobj);
controlSizer->Add (rowsizer, 0, wxEXPAND|wxALL, 2);
}
else if (ctrl->getType() == FTmodulatorI::Control::EnumType) {
// use a wxChoice
rowsizer = new wxBoxSizer(wxHORIZONTAL);
stattext = new wxStaticText(this, -1, unitstr);
rowsizer->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
string currval;
list<string> vallist;
ctrl->getValue(currval);
ctrl->getEnumStrings (vallist);
wxChoice * choice = new wxChoice(this, ctrlid, wxDefaultPosition, wxDefaultSize, 0, 0);
for (list<string>::iterator citer = vallist.begin(); citer != vallist.end(); ++citer) {
choice->Append (wxString::FromAscii((*citer).c_str()));
}
choice->SetStringSelection (wxString::FromAscii(currval.c_str()));
rowsizer->Add (choice, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 2);
FTmodControlObject * ctrlobj = new FTmodControlObject(ctrl);
ctrlobj->choice = choice;
Connect( ctrlid, wxEVT_COMMAND_CHOICE_SELECTED,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction)
&FTmodulatorGui::onChoiceChanged,
ctrlobj);
controlSizer->Add (rowsizer, 0, wxEXPAND|wxALL, 2);
}
ctrlid++;
}
//controlSizer->Add(new wxButton(this, -1, wxT("BIG TEST"), wxDefaultPosition, wxSize(120, 90)),
// 1, wxEXPAND|wxALL, 2);
_modulator->GoingAway.connect ( sigc::mem_fun(*this, &FTmodulatorGui::onModulatorDeath));
mainSizer->Add (controlSizer, 1, wxEXPAND|wxALL, 2);
SetAutoLayout( TRUE );
mainSizer->Fit( this );
mainSizer->SetSizeHints( this );
SetSizer( mainSizer );
}
void FTmodulatorGui::refreshMenu()
{
if (_popupMenu) {
delete _popupMenu;
}
_popupMenu = new wxMenu();
int itemid = ID_SpecModBase;
_popupMenu->Append (ID_DetachAll, wxT("Detach All"));
_popupMenu->Append (ID_AttachAll, wxT("Attach All"));
FTprocessPath * procpath;
for (int i=0; i < _iosup->getActivePathCount(); ++i)
{
procpath = _iosup->getProcessPath(i);
if (procpath) {
FTspectralEngine *engine = procpath->getSpectralEngine();
_popupMenu->AppendSeparator();
_popupMenu->Append (itemid, wxString::Format(wxT("Channel %d"), i+1));
_popupMenu->Enable (itemid, false);
itemid++;
// go through all the spectrum modifiers in the engine
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
for (unsigned int n=0; n < procmods.size(); ++n)
{
FTprocI *pm = procmods[n];
vector<FTspectrumModifier *> filts;
pm->getFilters (filts);
for (unsigned int m=0; m < filts.size(); ++m)
{
_popupMenu->AppendCheckItem (itemid, wxString::FromAscii (filts[m]->getName().c_str()));
if (_modulator->hasSpecMod (filts[m])) {
_popupMenu->Check (itemid, true);
}
Connect( itemid, wxEVT_COMMAND_MENU_SELECTED,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction)
&FTmodulatorGui::onAttachMenu,
(wxObject *) new FTspecmodObject(i, n, m));
itemid++;
}
}
}
}
}
void FTmodulatorGui::onAttachMenu (wxCommandEvent & ev)
{
int id = ev.GetId();
if (id == ID_AttachAll) {
// go through every one and add it
FTprocessPath * procpath;
for (int i=0; i < _iosup->getActivePathCount(); ++i)
{
procpath = _iosup->getProcessPath(i);
if (procpath) {
FTspectralEngine *engine = procpath->getSpectralEngine();
vector<FTprocI *> procmods;
engine->getProcessorModules (procmods);
for (unsigned int n=0; n < procmods.size(); ++n)
{
FTprocI *pm = procmods[n];
vector<FTspectrumModifier *> filts;
pm->getFilters (filts);
for (unsigned int m=0; m < filts.size(); ++m)
{
_modulator->addSpecMod (filts[m]);
}
}
}
}
}
else if (id == ID_DetachAll)
{
_modulator->clearSpecMods();
}
else {
// a filter menu item
FTspecmodObject * smo = (FTspecmodObject *) ev.m_callbackUserData;
FTprocI * procmod;
FTspectrumModifier * specmod;
FTprocessPath * procpath;
FTspectralEngine * engine;
if (smo
&& (procpath = _iosup->getProcessPath(smo->channel))
&& (engine = procpath->getSpectralEngine())
&& (procmod = engine->getProcessorModule(smo->modIndex))
&& (specmod = procmod->getFilter(smo->filtIndex)))
{
if (ev.IsChecked()) {
_modulator->addSpecMod (specmod);
}
else {
_modulator->removeSpecMod (specmod);
}
}
}
}
void FTmodulatorGui::onRemoveButton (wxCommandEvent & ev)
{
// remove our own dear mod
//cerr << "on remove" << endl;
RemovalRequest (); // emit signal
// remove from old engine
for (int i=0; i < _iosup->getActivePathCount(); ++i)
{
FTprocessPath * ppath = _iosup->getProcessPath(i);
if (ppath) {
ppath->getSpectralEngine()->removeModulator (_modulator);
}
}
//cerr << "post remove" << endl;
_modulator = 0;
}
void FTmodulatorGui::onModulatorDeath (FTmodulatorI * mod)
{
// cerr << "modguiuui: mod death" << endl;
_modulator = 0;
}
void FTmodulatorGui::onAttachButton (wxCommandEvent & ev)
{
wxWindow * source = (wxWindow *) ev.GetEventObject();
wxRect pos = source->GetRect();
refreshMenu();
PopupMenu(_popupMenu, pos.x, pos.y + pos.height);
}
void FTmodulatorGui::onSliderChanged(wxScrollEvent &ev)
{
wxSlider * slider = (wxSlider *) ev.GetEventObject();
FTmodControlObject * obj = (FTmodControlObject *) ev.m_callbackUserData;
FTmodulatorI::Control * ctrl;
if (obj && (ctrl = obj->control)) {
if (ctrl->getType() == FTmodulatorI::Control::IntegerType) {
int currval = slider->GetValue();
ctrl->setValue(currval);
//cerr << "slider int changed for " << ctrl->getName() << ": new val = " << currval << endl;
if (obj->textctrl) {
obj->textctrl->SetValue(wxString::Format(wxT("%d"), currval));
}
}
else if (ctrl->getType() == FTmodulatorI::Control::FloatType) {
float minval,maxval;
ctrl->getBounds(minval, maxval);
float currval = (slider->GetValue() / 1000.0) * (maxval - minval) + minval;
ctrl->setValue (currval);
//cerr << "slider float changed for " << ctrl->getName() << ": new val = " << currval << endl;
if (obj->textctrl) {
obj->textctrl->SetValue(wxString::Format(wxT("%.6g"), currval));
}
}
}
}
void FTmodulatorGui::onChoiceChanged(wxCommandEvent &ev)
{
wxChoice * choice = (wxChoice *) ev.GetEventObject();
FTmodControlObject * obj = (FTmodControlObject *) ev.m_callbackUserData;
FTmodulatorI::Control * ctrl;
if (obj && (ctrl = obj->control)) {
ctrl->setValue (string(static_cast<const char *> (choice->GetStringSelection().mb_str())));
//cerr << " choice changed for " << ctrl->getName() << ": new val = " << choice->GetStringSelection().c_str() << endl;
}
}
void FTmodulatorGui::onCheckboxChanged(wxCommandEvent &ev)
{
FTmodControlObject * obj = (FTmodControlObject *) ev.m_callbackUserData;
FTmodulatorI::Control * ctrl;
if (obj && (ctrl = obj->control) && obj->checkbox) {
ctrl->setValue ((bool) obj->checkbox->GetValue());
// cerr << " checkbox changed for " << ctrl->getName() << ": new val = " << obj->checkbox->GetValue() << endl;
}
}
void FTmodulatorGui::refreshChannelMenu ()
{
if (_channelPopupMenu) {
delete _channelPopupMenu;
}
_channelPopupMenu = new wxMenu();
int itemid = ID_ChannelBase;
FTprocessPath * procpath;
for (int i=0; i < _iosup->getActivePathCount(); ++i)
{
procpath = _iosup->getProcessPath(i);
if (procpath) {
_channelPopupMenu->AppendCheckItem (itemid, wxString::Format(wxT("Channel %d"), i+1));
if (procpath->getSpectralEngine()->hasModulator(_modulator)) {
_channelPopupMenu->Check (itemid, true);
}
Connect( itemid, wxEVT_COMMAND_MENU_SELECTED,
(wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction)
&FTmodulatorGui::onChannelMenu,
(wxObject *) new FTchannelObject(i));
itemid++;
}
}
}
void FTmodulatorGui::onChannelMenu (wxCommandEvent &ev)
{
FTchannelObject * smo = (FTchannelObject *) ev.m_callbackUserData;
FTprocessPath * procpath;
if (smo
&& (procpath = _iosup->getProcessPath(smo->channel))
&& (!procpath->getSpectralEngine()->hasModulator(_modulator)))
{
// only if engine doesn't already contain it
// cerr << "on channel menu" << endl;
// remove from old engine without destroying
for (int i=0; i < _iosup->getActivePathCount(); ++i)
{
FTprocessPath * ppath = _iosup->getProcessPath(i);
if (ppath) {
ppath->getSpectralEngine()->removeModulator (_modulator, false);
}
}
// add to new one
procpath->getSpectralEngine()->appendModulator(_modulator);
}
}
void FTmodulatorGui::onChannelButton (wxCommandEvent &ev)
{
wxWindow * source = (wxWindow *) ev.GetEventObject();
wxRect pos = source->GetRect();
refreshChannelMenu();
PopupMenu(_channelPopupMenu, pos.x, pos.y + pos.height);
}
void FTmodulatorGui::onTextEnter (wxCommandEvent &ev)
{
if (ev.GetId() == ID_ModUserName)
{
string name = static_cast<const char *> (_nameText->GetValue().fn_str());
_modulator->setUserName (name);
// cerr << "name changed to :" << name << endl;
}
else {
FTmodControlObject * cobj = (FTmodControlObject *) ev.m_callbackUserData;
wxString tmpstr;
long tmplong;
double tmpfloat;
if (cobj && cobj->textctrl) {
tmpstr = cobj->textctrl->GetValue();
if (cobj->control->getType() == FTmodulatorI::Control::IntegerType) {
int lb,ub,currval;
cobj->control->getBounds(lb, ub);
cobj->control->getValue(currval);
if (tmpstr.ToLong (&tmplong)
&& cobj->control->setValue ((int) tmplong)
&& (float)tmpfloat >= lb && (float)tmpfloat <= ub)
{
// change slider too
cobj->slider->SetValue (tmplong);
}
else {
cobj->textctrl->SetValue(wxString::Format(wxT("%d"), currval));
}
}
else if (cobj->control->getType() == FTmodulatorI::Control::FloatType) {
float lb,ub,currval;
cobj->control->getBounds(lb, ub);
cobj->control->getValue(currval);
if (tmpstr.ToDouble (&tmpfloat)
&& cobj->control->setValue ((float) tmpfloat)
&& (float)tmpfloat >= lb && (float)tmpfloat <= ub)
{
// change slider too
int slidval = (int) ((tmpfloat - lb) / (ub-lb) * 1000.0);
cobj->slider->SetValue (slidval);
}
else {
cobj->textctrl->SetValue(wxString::Format(wxT("%.6g"), currval));
}
}
}
}
}
void FTmodulatorGui::onBypassButton (wxCommandEvent &ev)
{
if (_modulator->getBypassed() != ev.IsChecked()) {
_modulator->setBypassed (ev.IsChecked());
}
}
| 19,133
|
C++
|
.cpp
| 513
| 33.230019
| 161
| 0.704213
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,951
|
FTspectrumModifier.cpp
|
essej_freqtweak/src/FTspectrumModifier.cpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <algorithm>
using namespace std;
#include "FTspectrumModifier.hpp"
#include "FTtypes.hpp"
FTspectrumModifier::FTspectrumModifier(const string &name, const string &configName, int group,
FTspectrumModifier::ModifierType mtype, SpecModType smtype, int length, float initval)
: _modType(mtype), _specmodType(smtype), _name(name), _configName(configName), _group(group),
_values(0), _length(length), _linkedTo(0), _initval(initval),
_id(0), _bypassed(false), _dirty(false), _extra_node(0)
{
_values = new float[FT_MAX_FFT_SIZE/2];
_tmpvalues = new float[FT_MAX_FFT_SIZE/2];
for (int i=0; i < FT_MAX_FFT_SIZE/2; i++)
{
_values[i] = initval;
}
}
FTspectrumModifier::~FTspectrumModifier()
{
for (list<Listener*>::iterator iter = _listenerList.begin(); iter != _listenerList.end(); ++iter)
{
(*iter)->goingAway(this);
}
unlink(true);
//printf ("delete specmod\n");
delete [] _values;
delete [] _tmpvalues;
}
void FTspectrumModifier::registerListener (Listener * listener)
{
if ( find(_listenerList.begin(), _listenerList.end(), listener) == _listenerList.end())
{
_listenerList.push_back (listener);
}
}
void FTspectrumModifier::unregisterListener (Listener *listener)
{
_listenerList.remove (listener);
}
void FTspectrumModifier::setLength(int length)
{
int origlen = _length;
if (length < FT_MAX_FFT_SIZE/2) {
_length = length;
// now resample existing values into new length
if (! _linkedTo)
{
float scale = origlen / (float) length;
for (int i=0; i < length; i++) {
_tmpvalues[i] = _values[(int)(i*scale)];
}
memcpy(_values, _tmpvalues, length * sizeof(float));
}
}
}
bool FTspectrumModifier::link (FTspectrumModifier *specmod)
{
unlink(false);
// do a cycle check
FTspectrumModifier * spec = specmod;
while (spec)
{
if (spec == this) {
// cycle!!! bad!!
return false;
}
spec = spec->getLink();
}
_linkedTo = specmod;
specmod->addedLinkFrom(this);
return true;
}
void FTspectrumModifier::unlink (bool unlinksources)
{
if (_linkedTo) {
_linkedTo->removedLinkFrom ( this );
// copy their values into our internal
copy (_linkedTo);
}
_linkedTo = 0;
if (unlinksources) {
// now unlink all who are linked to me
for (list<FTspectrumModifier*>::iterator node = _linkedFrom.begin();
node != _linkedFrom.end(); )
{
FTspectrumModifier *specmod = (*node);
specmod->unlink(false);
node = _linkedFrom.begin();
}
_linkedFrom.clear();
}
}
void FTspectrumModifier::addedLinkFrom (FTspectrumModifier * specmod)
{
// called from link()
if ( find(_linkedFrom.begin(), _linkedFrom.end(), specmod) == _linkedFrom.end())
{
_linkedFrom.push_back (specmod);
}
}
void FTspectrumModifier::removedLinkFrom (FTspectrumModifier * specmod)
{
// called from unlink()
_linkedFrom.remove (specmod);
}
bool FTspectrumModifier::isLinkedFrom (FTspectrumModifier *specmod)
{
list<FTspectrumModifier*>::iterator node = find (_linkedFrom.begin(),
_linkedFrom.end(),
specmod);
return ( node != _linkedFrom.end());
}
float * FTspectrumModifier::getValues()
{
if (_linkedTo) {
return _linkedTo->getValues();
}
return _values;
}
void FTspectrumModifier::reset()
{
float *data;
if (getModifierType() == FREQ_MODIFIER)
{
float incr = (_max - _min) / _length;
float val = _min;
if (_linkedTo) {
data = _linkedTo->getValues();
for (int i=0; i < _length; i++) {
_values[i] = data[i] = val;
val += incr;
}
}
else {
for (int i=0; i < _length; i++) {
_values[i] = val;
val += incr;
}
}
}
else {
if (_linkedTo) {
data = _linkedTo->getValues();
for (int i=0; i < _length; i++) {
_values[i] = data[i] = _initval;
}
}
else {
for (int i=0; i < _length; i++) {
_values[i] = _initval;
}
}
}
}
void FTspectrumModifier::copy (FTspectrumModifier *specmod)
{
// this always copies into our internal values
if (!specmod) return;
float * othervals = specmod->getValues();
memcpy (_values, othervals, _length * sizeof(float));
}
XMLNode * FTspectrumModifier::getExtraNode()
{
if (!_extra_node) {
// create one
_extra_node = new XMLNode("Extra");
}
return _extra_node;
}
void FTspectrumModifier::setExtraNode (XMLNode * node)
{
if (!node) return;
if (_extra_node) delete _extra_node;
_extra_node = new XMLNode(*node);
}
| 5,281
|
C++
|
.cpp
| 199
| 23.864322
| 98
| 0.692477
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,952
|
FTprocWarp.cpp
|
essej_freqtweak/src/FTprocWarp.cpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include "FTprocWarp.hpp"
#include "FTutils.hpp"
FTprocWarp::FTprocWarp (nframes_t samprate, unsigned int fftn)
: FTprocI("Warp", samprate, fftn)
{
_confname = "Warp";
}
FTprocWarp::FTprocWarp (const FTprocWarp & other)
: FTprocI (other._name, other._sampleRate, other._fftN)
{
_confname = "Warp";
}
void FTprocWarp::initialize()
{
// create filter
_filter = new FTspectrumModifier("Warp", "warp", 0, FTspectrumModifier::FREQ_MODIFIER, WARP_SPECMOD, _fftN/2, 0.0);
_filter->setRange(0.0, _fftN/2.0);
_filter->reset();
_filterlist.push_back (_filter);
_tmpdata = new fft_data[FT_MAX_FFT_SIZE];
_inited = true;
}
FTprocWarp::~FTprocWarp()
{
if (!_inited) return;
_filterlist.clear();
delete _filter;
delete [] _tmpdata;
}
void FTprocWarp::process (fft_data *data, unsigned int fftn)
{
if (!_inited || _filter->getBypassed()) {
return;
}
float *filter = _filter->getValues();
float min = _filter->getMin();
float max = _filter->getMax();
float filt;
int fftN2 = (fftn+1) >> 1;
memset(_tmpdata, 0, fftn * sizeof(fft_data));
for (int i = 1; i < fftN2-1; i++)
{
filt = FTutils::f_clamp(filter[i], min, max);
// _tmpdata[i] += data[(int)filt];
// _tmpdata[fftn-i] += data[fftn - ((int)filt)];
_tmpdata[(int)filt] += data[i];
if (i > 0 && filt > 0) {
_tmpdata[fftn-((int)filt)] += data[fftn - i];
}
}
memcpy (data, _tmpdata, fftn * sizeof(fft_data));
}
void FTprocWarp::setFFTsize (unsigned int fftn)
{
FTprocI::setFFTsize (fftn);
// reset our filters max
_filter->setRange (0.0, (float) (fftn >> 1));
_filter->reset();
}
| 2,396
|
C++
|
.cpp
| 77
| 28.948052
| 116
| 0.69083
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,953
|
spin_box.cpp
|
essej_freqtweak/src/spin_box.cpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#include <wx/wx.h>
#include <iostream>
#include <cmath>
#include "spin_box.hpp"
using namespace JLCui;
using namespace std;
// Convert a value in dB's to a coefficent
#define DB_CO(g) ((g) > -144.0 ? pow(10.0, (g) * 0.05) : 0.0)
#define CO_DB(v) (20.0 * log10(v))
static inline double
gain_to_slider_position (double g)
{
if (g == 0) return 0;
//return pow((6.0*log(g)/log(2.0)+192.0)/198.0, 8.0);
return pow((6.0*log(g)/log(2.0)+198.0)/198.0, 8.0);
}
static inline double
slider_position_to_gain (double pos)
{
if (pos == 0) {
return 0.0;
}
/* XXX Marcus writes: this doesn't seem right to me. but i don't have a better answer ... */
//return pow (2.0,(sqrt(sqrt(sqrt(pos)))*198.0-192.0)/6.0);
return pow (2.0,(sqrt(sqrt(sqrt(pos)))*198.0-198.0)/6.0);
}
enum {
ID_TextCtrl = 8000,
ID_EditMenuOp,
ID_DefaultMenuOp,
ID_BindMenuOp,
ID_UpdateTimer
};
BEGIN_EVENT_TABLE(SpinBox, wxWindow)
EVT_SIZE(SpinBox::OnSize)
EVT_PAINT(SpinBox::OnPaint)
EVT_MOUSE_EVENTS(SpinBox::OnMouseEvents)
EVT_MOUSEWHEEL (SpinBox::OnMouseEvents)
//EVT_TEXT (ID_TextCtrl, SpinBox::on_text_event)
EVT_TEXT_ENTER (ID_TextCtrl, SpinBox::on_text_event)
EVT_MENU (ID_EditMenuOp , SpinBox::on_menu_events)
EVT_MENU (ID_DefaultMenuOp , SpinBox::on_menu_events)
EVT_MENU (ID_BindMenuOp , SpinBox::on_menu_events)
EVT_TIMER (ID_UpdateTimer, SpinBox::on_update_timer)
EVT_KILL_FOCUS (SpinBox::OnFocusEvent)
END_EVENT_TABLE()
SpinBox::SpinBox(wxWindow * parent, wxWindowID id, float lb, float ub, float val, bool midibindable, const wxPoint& pos, const wxSize& size)
: wxWindow(parent, id, pos, size)
{
_lower_bound = lb;
_upper_bound = ub;
_default_val = _value = val;
_backing_store = 0;
_dragging = false;
_decimal_digits = 1;
_text_ctrl = 0;
_ignoretext = false;
_oob_flag = false;
_showval_flag = true;
_increment = 1.0f;
_direction = 0.0f;
_bgcolor.Set(30,30,30);
_bgbrush.SetColour (_bgcolor);
SetBackgroundColour (_bgcolor);
SetThemeEnabled(false);
_valuecolor.Set(244, 255, 178);
_textcolor = *wxWHITE;
_barcolor.Set(14, 50, 100);
_overbarcolor.Set(20, 50, 80);
_barbrush.SetColour(_bgcolor);
//_bgbordercolor.Set(30,30,30);
_bordercolor.Set(67, 83, 103);
_borderpen.SetColour(_bordercolor);
_borderpen.SetWidth(1);
_borderbrush.SetColour(_bgcolor);
_linebrush.SetColour(wxColour(154, 245, 168));
_scale_mode = LinearMode;
_snap_mode = NoSnap;
_popup_menu = new wxMenu(wxT(""));
_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_EditMenuOp, wxT("Edit")));
_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_DefaultMenuOp, wxT("Set to default")));
if (midibindable) {
_popup_menu->AppendSeparator();
_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_BindMenuOp, wxT("Learn MIDI Binding")));
}
_update_timer = new wxTimer(this, ID_UpdateTimer);
update_size();
}
SpinBox::~SpinBox()
{
_memdc.SelectObject(wxNullBitmap);
if (_backing_store) {
delete _backing_store;
}
}
bool
SpinBox::SetFont(const wxFont & fnt)
{
bool ret = wxWindow::SetFont(fnt);
_memdc.SetFont(fnt);
return ret;
}
void
SpinBox::set_snap_mode (SnapMode md)
{
if (md != _snap_mode) {
_snap_mode = md;
}
}
void
SpinBox::set_scale_mode (ScaleMode mode)
{
if (mode != _scale_mode) {
_scale_mode = mode;
update_value_str();
Refresh(false);
}
}
void
SpinBox::set_bounds (float lb, float ub)
{
if (_lower_bound != lb || _upper_bound != ub) {
_lower_bound = lb;
_upper_bound = ub;
// force value to within
if (_value < _lower_bound) {
_value = _lower_bound;
update_value_str();
Refresh(false);
}
else if (_value > _upper_bound) {
_value = _upper_bound;
update_value_str();
Refresh(false);
}
}
}
void
SpinBox::set_label (const wxString & label)
{
_label_str = label;
Refresh(false);
}
void
SpinBox::set_units (const wxString & units)
{
_units_str = units;
update_value_str();
Refresh(false);
}
void
SpinBox::set_decimal_digits (int val)
{
_decimal_digits = val;
update_value_str();
Refresh(false);
}
void
SpinBox::set_value (float val)
{
float newval = val;
if (_scale_mode == ZeroGainMode) {
newval = gain_to_slider_position (val);
}
// if (_snap_mode == IntegerSnap) {
// newval = nearbyintf (newval);
// }
if (!_oob_flag) {
newval = min (newval, _upper_bound);
newval = max (newval, _lower_bound);
}
if (newval != _value) {
_value = newval;
update_value_str();
Refresh(false);
}
}
float
SpinBox::get_value ()
{
if (_scale_mode == ZeroGainMode) {
return slider_position_to_gain(_value);
}
else {
return _value;
}
}
void
SpinBox::update_value_str()
{
if (_scale_mode == ZeroGainMode) {
float gain = slider_position_to_gain(_value);
if (gain == 0) {
_value_str.Printf(wxT("-inf %s"), _units_str.c_str());
}
else {
_value_str.Printf(wxT("%.*f %s"), _decimal_digits, CO_DB(gain), _units_str.c_str());
}
}
else {
_value_str.Printf(wxT("%.*f %s"), _decimal_digits, _value, _units_str.c_str());
}
}
wxString SpinBox::get_precise_value_str()
{
wxString valstr;
if (_scale_mode == ZeroGainMode) {
float gain = slider_position_to_gain(_value);
if (gain == 0) {
valstr.Printf(wxT("-inf"));
}
else if (_snap_mode == IntegerSnap) {
valstr.Printf(wxT("%g"), CO_DB(gain));
}
else {
valstr.Printf(wxT("%.8f"), CO_DB(gain));
}
}
else {
if (_snap_mode == IntegerSnap) {
valstr.Printf(wxT("%g"), _value);
}
else {
valstr.Printf(wxT("%.8f"), _value);
}
}
return valstr;
}
void SpinBox::set_bg_color (const wxColour & col)
{
_bgcolor = col;
_bgbrush.SetColour (col);
SetBackgroundColour (col);
Refresh(false);
}
void SpinBox::set_text_color (const wxColour & col)
{
_textcolor = col;
Refresh(false);
}
void SpinBox::set_border_color (const wxColour & col)
{
_bordercolor = col;
_borderbrush.SetColour (col);
Refresh(false);
}
void SpinBox::set_bar_color (const wxColour & col)
{
_barcolor = col;
_barbrush.SetColour (col);
Refresh(false);
}
void
SpinBox::update_size()
{
GetClientSize(&_width, &_height);
if (_width > 0 && _height > 0) {
_val_scale = (_upper_bound - _lower_bound) / (_width);
_memdc.SelectObject (wxNullBitmap);
if (_backing_store) {
delete _backing_store;
}
_backing_store = new wxBitmap(_width, _height);
_memdc.SelectObject(*_backing_store);
_memdc.SetFont(GetFont());
_border_shape[0].x = 0; _border_shape[0].y = _height-3;
_border_shape[1].x = 0; _border_shape[1].y = 2;
_border_shape[2].x = 2; _border_shape[2].y = 0;
_border_shape[3].x = _width - 3; _border_shape[3].y = 0;
_border_shape[4].x = _width -1; _border_shape[4].y = 2;
_border_shape[5].x = _width -1; _border_shape[5].y = _height - 3;
_border_shape[6].x = _width -3; _border_shape[6].y = _height - 1;
_border_shape[7].x = 2; _border_shape[7].y = _height - 1;
update_bar_shape();
}
}
void
SpinBox::update_bar_shape()
{
if (_direction < 0) {
_bar_shape[0].x = 1; _bar_shape[0].y = 1;
_bar_shape[1].x = _width/2 - 1; _bar_shape[1].y = 1;
_bar_shape[2].x = _width/2 - _height/2; _bar_shape[2].y = _height/2;
_bar_shape[3].x = _width/2 - 1; _bar_shape[3].y = _height - 1;
_bar_shape[4].x = 1; _bar_shape[4].y = _height - 1;
}
else {
_bar_shape[0].x = _width - 1; _bar_shape[0].y = 1;
_bar_shape[1].x = _width/2 ; _bar_shape[1].y = 1;
_bar_shape[2].x = _width/2 + _height/2 - 1; _bar_shape[2].y = _height/2;
_bar_shape[3].x = _width/2; _bar_shape[3].y = _height - 1;
_bar_shape[4].x = _width - 1; _bar_shape[4].y = _height - 1;
}
}
void
SpinBox::OnSize(wxSizeEvent & event)
{
update_size();
event.Skip();
}
void SpinBox::OnPaint(wxPaintEvent & event)
{
wxPaintDC pdc(this);
if (!_backing_store) {
return;
}
draw_area(_memdc);
pdc.Blit(0, 0, _width, _height, &_memdc, 0, 0);
}
void
SpinBox::on_update_timer (wxTimerEvent &ev)
{
// update value with current adjust
float newval = _value;
long deltatime = ::wxGetLocalTime() - _press_time;
if (deltatime > 2) {
newval += _curr_adjust * deltatime * deltatime * deltatime;
}
else {
newval += _curr_adjust;
}
if (_snap_mode == IntegerSnap) {
newval = nearbyintf (newval);
}
newval = max (min (newval, _upper_bound), _lower_bound);
_value = newval;
value_changed (get_value()); // emit
update_value_str();
Refresh(false);
_update_timer->Start (_curr_timeout, true);
}
void
SpinBox::OnMouseEvents (wxMouseEvent &ev)
{
if (!IsEnabled()) {
ev.Skip();
return;
}
if (ev.Entering() && !_dragging) {
//_borderbrush.SetColour(_overbarcolor);
_direction = ev.GetX() < _width/2 ? -1.0f : 1.0f;
update_bar_shape();
_barbrush.SetColour(_overbarcolor);
Refresh(false);
}
else if (ev.Leaving() && !_dragging) {
_barbrush.SetColour(_bgcolor);
//_borderbrush.SetColour(_bgcolor);
_direction = 0;
Refresh(false);
}
if (ev.Dragging() && _dragging)
{
ev.Skip();
}
else if (ev.Moving()) {
// do nothing
float dirct = ev.GetX() < _width/2 ? -1.0f : 1.0f;
if (dirct != _direction) {
_direction = dirct;
update_bar_shape();
Refresh(false);
}
}
else if (ev.GetEventType() == wxEVT_MOUSEWHEEL)
{
float fscale = (ev.ShiftDown() ? 10.0f : 1.0f) * (ev.ControlDown() ? 2.0f: 1.0f);
float newval;
if (ev.GetWheelRotation() > 0) {
//newval = _value + (_upper_bound - _lower_bound) * fscale;
newval = _value + _increment * fscale;
}
else {
newval = _value - _increment * fscale;
}
if (_snap_mode == IntegerSnap) {
newval = nearbyintf (newval);
}
newval = max (min (newval, _upper_bound), _lower_bound);
_value = newval;
value_changed (get_value()); // emit
update_value_str();
Refresh(false);
}
else if (ev.RightDown()) {
this->PopupMenu ( _popup_menu, ev.GetX(), ev.GetY());
}
else if (ev.RightUp()) {
//this->PopupMenu ( _popup_menu, ev.GetX(), ev.GetY());
}
else if (ev.ButtonDown() || ev.LeftDClick())
{
CaptureMouse();
_dragging = true;
_curr_timeout = -1;
_barbrush.SetColour(_barcolor);
pressed(); // emit
if (ev.MiddleDown() && !ev.ControlDown()) {
// start editing
show_text_ctrl ();
}
else if (ev.LeftDown() && ev.ShiftDown()) {
// set to default
_value = max (min (_default_val, _upper_bound), _lower_bound);
value_changed(get_value());
update_value_str();
}
else {
float newval = _value;
_direction = ev.GetX() < _width/2 ? -1.0f : 1.0f;
_curr_adjust = _increment * _direction;
newval += _curr_adjust;
if (_snap_mode == IntegerSnap) {
newval = nearbyintf (newval);
}
newval = max (min (newval, _upper_bound), _lower_bound);
_value = newval;
value_changed (get_value()); // emit
update_value_str();
_press_time = ::wxGetLocalTime(); // seconds
_curr_timeout = 20; // for now
_update_timer->Start(400, true); // oneshot
update_bar_shape();
}
Refresh(false);
}
else if (ev.ButtonUp())
{
_dragging = false;
_update_timer->Stop();
_curr_timeout = -1;
ReleaseMouse();
if (ev.GetX() >= _width || ev.GetX() < 0
|| ev.GetY() < 0 || ev.GetY() > _height) {
//_borderbrush.SetColour(_bgcolor);
_barbrush.SetColour(_bgcolor);
Refresh(false);
}
else {
//_borderbrush.SetColour(_overbarcolor);
_barbrush.SetColour(_overbarcolor);
Refresh(false);
}
if (ev.MiddleUp() && ev.ControlDown())
{
// binding click
bind_request(); // emit
}
released(); // emit
}
else {
ev.Skip();
}
}
void SpinBox::OnFocusEvent (wxFocusEvent &ev)
{
if (ev.GetEventType() == wxEVT_KILL_FOCUS) {
// focus kill
_borderbrush.SetColour(_bgcolor);
_barbrush.SetColour(_bgcolor);
Refresh(false);
}
ev.Skip();
}
void SpinBox::on_menu_events (wxCommandEvent &ev)
{
if (ev.GetId() == ID_BindMenuOp) {
bind_request(); // emit
}
else if (ev.GetId() == ID_EditMenuOp) {
show_text_ctrl ();
}
else if (ev.GetId() == ID_DefaultMenuOp) {
_value = max (min (_default_val, _upper_bound), _lower_bound);
value_changed(get_value());
update_value_str();
Refresh(false);
}
}
void SpinBox::draw_area(wxDC & dc)
{
wxCoord w,h;
dc.SetBackground(_bgbrush);
dc.Clear();
dc.SetBrush(_borderbrush);
dc.SetPen(_borderpen);
//dc.DrawRectangle (0, 0, _width, _height);
dc.DrawPolygon (8, _border_shape);
dc.SetPen(*wxTRANSPARENT_PEN);
dc.SetBrush(_barbrush);
if (_direction != 0.0f) {
dc.DrawPolygon (5, _bar_shape);
}
dc.SetTextForeground(_textcolor);
dc.GetTextExtent(_label_str, &w, &h);
dc.DrawText (_label_str, 3, _height - h - 3);
if (_showval_flag) {
dc.SetTextForeground(_valuecolor);
dc.GetTextExtent(_value_str, &w, &h);
dc.DrawText (_value_str, _width - w - 3, _height - h - 3);
}
}
void SpinBox::show_text_ctrl ()
{
wxString valstr = get_precise_value_str();
if (!_text_ctrl) {
_text_ctrl = new HidingTextCtrl(this, ID_TextCtrl, valstr, wxPoint(1,1), wxSize(_width - 2, _height - 2),
wxTE_PROCESS_ENTER|wxTE_RIGHT);
_text_ctrl->SetName (wxT("KeyAware"));
_text_ctrl->SetFont(GetFont());
}
_text_ctrl->SetValue (valstr);
_text_ctrl->SetSelection (-1, -1);
_text_ctrl->SetSize (_width - 2, _height - 2);
_text_ctrl->Show(true);
_text_ctrl->SetFocus();
}
void SpinBox::hide_text_ctrl ()
{
if (_text_ctrl && _text_ctrl->IsShown()) {
_text_ctrl->Show(false);
SetFocus();
}
}
void SpinBox::on_text_event (wxCommandEvent &ev)
{
if (ev.GetEventType() == wxEVT_COMMAND_TEXT_ENTER) {
// commit change
bool good = false;
bool neginf = false;
double newval = 0.0;
if (_scale_mode == ZeroGainMode && _text_ctrl->GetValue().Strip(wxString::both) == wxT("-inf")) {
newval = 0.0;
good = neginf = true;
}
else if (_text_ctrl->GetValue().ToDouble(&newval)) {
good = true;
}
if (good) {
if (_scale_mode == ZeroGainMode && !neginf) {
newval = DB_CO(newval);
}
set_value ((float) newval);
value_changed (get_value()); // emit
}
hide_text_ctrl();
}
}
BEGIN_EVENT_TABLE(SpinBox::HidingTextCtrl, wxTextCtrl)
EVT_KILL_FOCUS (SpinBox::HidingTextCtrl::on_focus_event)
END_EVENT_TABLE()
void SpinBox::HidingTextCtrl::on_focus_event (wxFocusEvent & ev)
{
if (ev.GetEventType() == wxEVT_KILL_FOCUS) {
Show(false);
}
}
| 14,995
|
C++
|
.cpp
| 575
| 23.457391
| 141
| 0.657573
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,954
|
FTprocCompressor.hpp
|
essej_freqtweak/src/FTprocCompressor.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCCOMPRESSOR_HPP__
#define __FTPROCCOMPRESSOR_HPP__
#include "FTprocI.hpp"
#include "FTutils.hpp"
#include <cmath>
#define RMS_BUF_SIZE 64
typedef struct {
float buffer[RMS_BUF_SIZE];
unsigned int pos;
float sum;
} rms_env;
class FTprocCompressor
: public FTprocI
{
public:
FTprocCompressor(nframes_t samprate, unsigned int fftn);
FTprocCompressor (const FTprocCompressor & other);
virtual ~FTprocCompressor();
FTprocI * clone() { return new FTprocCompressor(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
virtual void setFFTsize (unsigned int fftn);
virtual void setOversamp (int osamp);
virtual bool useAsDefault() { return false; }
inline float db2lin(float db);
inline float lin2db(float pow);
protected:
FTspectrumModifier * _thresh_filter;
FTspectrumModifier * _ratio_filter;
FTspectrumModifier * _attack_filter;
FTspectrumModifier * _release_filter;
FTspectrumModifier * _makeup_filter;
// state
float * _sum;
float * _amp;
float * _gain;
float * _gain_t;
float * _env;
unsigned int * _count;
float * _as;
rms_env ** _rms;
float _dbAdjust;
};
inline float FTprocCompressor::db2lin(float db)
{
//float nval = (20.0 * FTutils::fast_log10(yval / refmax));
float nval = ::pow ( (float)10.0, db/20);
// printf ("scaled value is %g mincut=%g\n", nval, _minCutoff);
return nval;
}
inline float FTprocCompressor::lin2db(float power)
{
//float db = FTutils::powerLogScale (power, 0.0000000) + _dbAdjust; // total fudge factors
float db = FTutils::powerLogScale (power, 0.0000000);
return db;
}
#endif
| 2,428
|
C++
|
.h
| 75
| 30.28
| 91
| 0.740517
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,955
|
FTutils.hpp
|
essej_freqtweak/src/FTutils.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTUTILS_HPP__
#define __FTUTILS_HPP__
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <cmath>
#include <wx/string.h>
#if 0
# define DEBUGOUT(x) (std::cout << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": " << x)
#else
# define DEBUGOUT(x) ;
#endif
class FTutils
{
public:
/* Rough but quick versions of some basic math functions */
/* There is no input error checking. */
/* Logarithm base-10. */
/* absolute error < 6.4e-4 */
/* input must be > 0 */
static float fast_log10 (float x);
/* Logarithm base-2. */
/* absolute error < 6.4e-4 */
/* input must be > 0 */
static float fast_log2 (float x);
/* Square root. */
/* relative error < 0.08% */
/* input must be >= 0 */
static float fast_square_root (float x);
/* Fourth root. */
/* relative error < 0.06% */
/* input must be >= 0 */
static float fast_fourth_root (float x);
/* vector versions of the above. */
/* "in" and "out" pointer can refer */
/* to the same array for in-place */
/* computation */
static void vector_fast_log2 (const float* x_input, float* y_output, int N);
static void vector_fast_log10 (const float* x_input, float* y_output, int N);
static void vector_fast_square_root (const float* x_input, float* y_output, int N);
static void vector_fast_fourth_root (const float* x_input, float* y_output, int N);
static inline float powerLogScale(float yval, float min);
static inline float f_clamp(float x, float a, float b)
{
const float x1 = std::fabs(x - a);
const float x2 = std::fabs(x - b);
x = x1 + a + b;
x -= x2;
x *= 0.5;
return x;
}
/* these are not too cheap */
static double sine_wave (double time, double freq_Hz);
static double square_wave (double time, double freq_Hz);
static double triangle_wave (double time, double freq_Hz);
};
inline float FTutils::powerLogScale(float yval, float min)
{
if (yval <= min) {
return -200.0;
}
// if (yval > _maxval) {
// _maxval = yval;
// }
//float nval = (10.0 * FTutils::fast_log10(yval / max));
float nval = (10.0 * FTutils::fast_log10 (yval));
// printf ("scaled value is %g mincut=%g\n", nval, _minCutoff);
return nval;
}
/* 32 bit "pointer cast" union */
typedef union {
float f;
int32_t i;
} ls_pcast32;
static inline float flush_to_zero(float f)
{
ls_pcast32 v;
v.f = f;
// original: return (v.i & 0x7f800000) == 0 ? 0.0f : f;
// version from Tim Blechmann
return (v.i & 0x7f800000) < 0x08000000 ? 0.0f : f;
}
/* A set of branchless clipping operations from Laurent de Soras */
static inline float f_max(float x, float a)
{
x -= a;
x += fabsf(x);
x *= 0.5;
x += a;
return x;
}
static inline float f_min(float x, float b)
{
x = b - x;
x += fabsf(x);
x *= 0.5;
x = b - x;
return x;
}
static inline float f_clamp(float x, float a, float b)
{
const float x1 = fabsf(x - a);
const float x2 = fabsf(x - b);
x = x1 + a + b;
x -= x2;
x *= 0.5;
return x;
}
struct LocaleGuard {
LocaleGuard (const char*);
~LocaleGuard ();
const char* old;
};
#define DB_CO(g) ((g) > -90.0f ? pow(10.0, (g) * 0.05) : 0.0)
#define CO_DB(v) (20.0 * log10(v))
#endif
| 4,069
|
C++
|
.h
| 134
| 28.149254
| 100
| 0.647774
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,956
|
FTmodRotateLFO.hpp
|
essej_freqtweak/src/FTmodRotateLFO.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODROTATELFO_HPP__
#define __FTMODROTATELFO_HPP__
#include "FTmodulatorI.hpp"
class FTmodRotateLFO
: public FTmodulatorI
{
public:
FTmodRotateLFO(nframes_t samplerate, unsigned int fftn);
FTmodRotateLFO (const FTmodRotateLFO & other);
virtual ~FTmodRotateLFO();
FTmodulatorI * clone() { return new FTmodRotateLFO(*this); }
void initialize();
void modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes);
void setFFTsize (unsigned int fftn);
protected:
Control * _rate;
Control * _depth;
Control * _lfotype;
Control * _minfreq;
Control * _maxfreq;
nframes_t _lastframe;
int _lastshift;
float * _tmpfilt;
};
#endif
| 1,515
|
C++
|
.h
| 43
| 33.116279
| 120
| 0.756198
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,957
|
FTprocessPath.hpp
|
essej_freqtweak/src/FTprocessPath.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCESSPATH_HPP__
#define __FTPROCESSPATH_HPP__
#include "FTtypes.hpp"
class RingBuffer;
class FTspectralEngine;
class FTprocessPath
{
public:
FTprocessPath();
virtual ~FTprocessPath();
void setId (int id);
int getId () { return _id; }
void setMaxBufsize (nframes_t bsize) { _maxBufsize = bsize; }
void setSampleRate (nframes_t srate) { _sampleRate = srate; }
//void setSpectralEngine (FTspectralEngine * sengine) { _specEngine = sengine; }
FTspectralEngine * getSpectralEngine () { return _specEngine; }
void processData (sample_t *inbuf, sample_t *outbuf, nframes_t nframes);
RingBuffer * getInputFifo() { return _inputFifo; }
RingBuffer * getOutputFifo() { return _outputFifo; }
bool getReadyToDie() { return _readyToDie; }
void setReadyToDie(bool flag) { _readyToDie = flag; }
protected:
void initSpectralEngine();
nframes_t _maxBufsize;
nframes_t _sampleRate;
RingBuffer * _inputFifo;
RingBuffer * _outputFifo;
FTspectralEngine * _specEngine;
bool _readyToDie;
int _id;
};
#endif
| 1,839
|
C++
|
.h
| 50
| 34.62
| 81
| 0.751701
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,958
|
FTspectralEngine.hpp
|
essej_freqtweak/src/FTspectralEngine.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTSPECTRALENGINE_HPP__
#define __FTSPECTRALENGINE_HPP__
#if HAVE_CONFIG_H
#include <config.h>
#endif
#if USING_FFTW3
#include <fftw3.h>
#else
#ifdef HAVE_SRFFTW_H
#include <srfftw.h>
#else
#include <rfftw.h>
#endif
#endif
#include "FTutils.hpp"
#include "FTtypes.hpp"
#include "LockMonitor.hpp"
#include <sigc++/sigc++.h>
#include <vector>
using namespace std;
class FTprocessPath;
class RingBuffer;
class FTspectrumModifier;
class FTupdateToken;
class FTmodulatorI;
class FTprocI;
class FTspectralEngine
{
public:
FTspectralEngine();
virtual ~FTspectralEngine();
bool processNow (FTprocessPath *procpath);
enum FFT_Size
{
FFT_32 = 32,
FFT_64 = 64,
FFT_128 = 128,
FFT_256 = 256,
FFT_512 = 512,
FFT_1024 = 1024,
FFT_2048 = 2048,
FFT_4096 = 4096,
FFT_8192 = 8192
};
enum Windowing
{
WINDOW_HANNING = 0,
WINDOW_HAMMING,
WINDOW_BLACKMAN,
WINDOW_RECTANGLE
};
enum UpdateSpeed
{
SPEED_FAST = 1,
SPEED_MED = 2,
SPEED_SLOW = 4,
SPEED_TURTLE = 8,
};
static const int NUM_WINDOWS = 5;
void setId (int id);
int getId () { return _id; }
void setUpdateToken (FTupdateToken *tok) { _updateToken = tok; }
FTupdateToken * getUpdateToken() { return _updateToken; }
void setFFTsize (FFT_Size sz); // ONLY call when not processing
FFT_Size getFFTsize() { return (FFT_Size) _fftN; }
void setSampleRate (nframes_t rate) { _sampleRate = rate; }
nframes_t getSampleRate() { return _sampleRate; }
void setWindowing (Windowing w) { _windowing = w; }
Windowing getWindowing() { return _windowing; }
void setAverages (int avg) { if (avg > _maxAverages) _averages = _maxAverages; _averages = avg; }
int getAverages () { return _averages; }
void setOversamp (int osamp);
int getOversamp () { return _oversamp; }
void setUpdateSpeed (UpdateSpeed speed);
UpdateSpeed getUpdateSpeed () { return _updateSpeed; }
void setInputGain (float gain) { _inputGain = gain; }
float getInputGain () { return _inputGain; }
// 1.0 is fully wet
void setMixRatio (float ratio) { _mixRatio = ratio; }
float getMixRatio () { return _mixRatio;}
void setBypassed (bool flag) { _bypassFlag = flag; }
bool getBypassed () { return _bypassFlag; }
void setMuted (bool flag) { _mutedFlag = flag; }
bool getMuted () { return _mutedFlag; }
float getMaxDelay () { return _maxDelay; }
void setMaxDelay (float secs); // ONLY call when not processing
void setTempo (int tempo) { _tempo = tempo; }
int getTempo() { return _tempo; }
const float * getRunningInputPower() { return _runningInputPower; }
const float * getRunningOutputPower() { return _runningOutputPower; }
nframes_t getLatency();
// processor module handling
void insertProcessorModule (FTprocI * procmod, unsigned int index);
void appendProcessorModule (FTprocI * procmod);
void moveProcessorModule (unsigned int from, unsigned int to);
void removeProcessorModule (unsigned int index, bool destroy=true);
void clearProcessorModules (bool destroy=true);
void getProcessorModules (vector<FTprocI *> & modules);
FTprocI * getProcessorModule ( unsigned int num);
// modulator handling
void insertModulator (FTmodulatorI * procmod, unsigned int index);
void appendModulator (FTmodulatorI * procmod);
void moveModulator (unsigned int from, unsigned int to);
void removeModulator (unsigned int index, bool destroy=true);
void removeModulator (FTmodulatorI * procmod, bool destroy=true);
void clearModulators (bool destroy=true);
void getModulators (vector<FTmodulatorI *> & modules);
FTmodulatorI * getModulator ( unsigned int num);
bool hasModulator (FTmodulatorI * procmod);
sigc::signal1<void, FTmodulatorI *> ModulatorAdded;
static const char ** getWindowStrings() { return (const char **) _windowStrings; }
static const int getWindowStringsCount() { return _windowStringCount; }
static const int * getFFTSizes() { return (const int *) _fftSizes; }
static const int getFFTSizeCount() { return _fftSizeCount; }
protected:
void computeAverageInputPower (fft_data *fftbuf);
void computeAverageOutputPower (fft_data *fftbuf);
void createWindowVectors(bool noalloc=false);
void createRaisedCosineWindow();
void createRectangleWindow();
void createHanningWindow();
void createHammingWindow();
void createBlackmanWindow();
void initState();
void destroyState();
static const int _windowStringCount;
static const char * _windowStrings[];
static const int _fftSizeCount;
static const int _fftSizes[];
// the processing modules
vector<FTprocI *> _procModules;
PBD::NonBlockingLock _procmodLock;
// the modulators
vector<FTmodulatorI *> _modulators;
PBD::NonBlockingLock _modulatorLock;
// fft size (thus frame length)
int _fftN;
Windowing _windowing;
int _oversamp;
int _maxAverages;
int _averages;
#ifdef USING_FFTW3
fftwf_plan _fftPlan;
fftwf_plan _ifftPlan;
#else
rfftw_plan _fftPlan; // forward fft
rfftw_plan _ifftPlan; // inverse fft
#endif
int _newfftN;
bool _fftnChanged;
PBD::NonBlockingLock _fftLock;
// space for average input power buffer
// elements = _fftN/2 * MAX_AVERAGES * MAX_OVERSAMP
fft_data * _inputPowerSpectra;
fft_data * _outputPowerSpectra;
// the current running avg power
// elements = _fftN/2
fft_data * _runningInputPower;
fft_data * _runningOutputPower;
nframes_t _sampleRate;
float _inputGain;
float _mixRatio;
bool _bypassFlag;
bool _mutedFlag;
UpdateSpeed _updateSpeed;
int _id;
FTupdateToken * _updateToken;
int _tempo;
float _maxDelay;
private:
fft_data *_inwork, *_outwork;
fft_data *_winwork;
fft_data *_accum;
fft_data *_scaletemp;
// for windowing
float ** _mWindows;
// for averaging
int _currInAvgIndex;
int _currOutAvgIndex;
bool _avgReady;
};
#endif
| 6,577
|
C++
|
.h
| 200
| 30.385
| 98
| 0.749402
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,959
|
FTportSelectionDialog.hpp
|
essej_freqtweak/src/FTportSelectionDialog.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPOERTSELECTIONDIALOG_HPP__
#define __FTPOERTSELECTIONDIALOG_HPP__
#include <wx/wx.h>
#include <vector>
class FTportSelectionDialog
: public wxDialog
{
public:
enum PortType
{
OUTPUT = 0,
INPUT
};
FTportSelectionDialog(wxWindow * parent, wxWindowID id, int pathIndex, PortType ptype, const wxString & title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400,600),
long style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER,
const wxString& name = wxT("PortSelectionDialog"));
std::vector<wxString> getSelectedPorts();
void update();
protected:
void init();
void OnOK(wxCommandEvent &event);
void OnDeselectAll(wxCommandEvent &event);
int _pathIndex;
PortType _portType;
wxListBox * _listBox;
wxArrayString _selectedPorts;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
#endif
| 1,786
|
C++
|
.h
| 51
| 31.235294
| 114
| 0.734982
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,960
|
FTmainwin.hpp
|
essej_freqtweak/src/FTmainwin.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMAINWIN_HPP__
#define __FTMAINWIN_HPP__
#include <vector>
using namespace std;
#include <sigc++/sigc++.h>
#include <wx/wx.h>
//#include <wx/sashwin.h>
#include <wx/laywin.h>
#include <wx/spinctrl.h>
#include "FTtypes.hpp"
#include "FTspectragram.hpp"
#include "FTconfigManager.hpp"
#include "FTspectrumModifier.hpp"
class FTprocessPath;
class FTactiveBarGraph;
class FTspectralEngine;
class FTspectrumModifier;
class FTupdateToken;
class FTupdateTimer;
class FTrefreshTimer;
class FTlinkMenu;
class FTprocOrderDialog;
class FTpresetBlendDialog;
class FTmodulatorDialog;
namespace JLCui {
class PixButton;
}
BEGIN_DECLARE_EVENT_TYPES()
DECLARE_EVENT_TYPE( FT_EVT_TITLEMENU_COMMAND, 9000)
END_DECLARE_EVENT_TYPES()
#define EVT_TITLEMENU_COMMAND(id, fn) \
DECLARE_EVENT_TABLE_ENTRY( \
FT_EVT_TITLEMENU_COMMAND, id, -1, \
(wxObjectEventFunction)(wxEventFunction)(wxCommandEventFunction)&fn, \
(wxObject *) NULL \
),
class FTtitleMenuEvent
: public wxCommandEvent
{
public:
enum CmdType
{
ExpandEvt = 1,
MinimizeEvt,
RemoveEvt
};
FTtitleMenuEvent(int id=0, CmdType ctype=ExpandEvt, wxWindow * targ=0)
: wxCommandEvent(FT_EVT_TITLEMENU_COMMAND, id),
cmdType(ctype), target(targ), ready(false)
{
}
FTtitleMenuEvent(const FTtitleMenuEvent & ev)
: wxCommandEvent(ev),
cmdType (ev.cmdType),
target (ev.target), ready(ev.ready)
{
}
virtual ~FTtitleMenuEvent() {}
wxEvent *Clone(void) const { return new FTtitleMenuEvent(*this); }
CmdType cmdType;
wxWindow * target;
bool ready;
private:
DECLARE_DYNAMIC_CLASS(FTtitleMenuEvent)
};
/**
* FTmainWin
*
*/
class FTmainwin : public wxFrame
{
public:
// ctor(s)
FTmainwin(int startpaths, const wxString& title, const wxString &rcdir , const wxPoint& pos, const wxSize& size);
// event handlers (these functions should _not_ be virtual)
void OnQuit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnIdle(wxIdleEvent & event);
void OnClose(wxCloseEvent &event);
//void OnSize(wxSizeEvent &event);
void updateDisplay();
void updateGraphs(FTactiveBarGraph *exclude, SpecModType smtype, bool refreshonly=false);
void updatePosition(const wxString &freqstr, const wxString &valstr);
void loadPreset (const wxString & name, bool uselast=false);
void cleanup ();
void handleGridButtonMouse (wxMouseEvent &event);
void handleTitleButtonMouse (wxMouseEvent &event, bool minimized);
void doMinimizeExpand (wxWindow * source);
void doRemoveRow (wxWindow * source);
void suspendProcessing();
void restoreProcessing();
void rebuildDisplay(bool dolink=true);
FTconfigManager & getConfigManager() { return _configManager; }
void normalizeFontSize(wxFont & fnt, int height, wxString fitstr);
protected:
void buildGui();
void updatePlot(int plotnum);
void checkEvents();
void checkRefreshes();
// per path handlers
void handleInputButton (wxCommandEvent &event);
void handleOutputButton (wxCommandEvent &event);
void handleBypassButtons (wxCommandEvent &event);
void handleLinkButtons (wxCommandEvent &event);
void handleLabelButtons (wxCommandEvent &event);
void bypass_clicked_events (int button, JLCui::PixButton *);
void link_clicked_events (int button, JLCui::PixButton *);
void plot_clicked_events (int button, JLCui::PixButton *);
void grid_clicked_events (int button, JLCui::PixButton *);
void grid_pressed_events (int button, JLCui::PixButton *);
void handlePlotTypeButtons (wxCommandEvent &event);
void handleGridButtons (wxCommandEvent &event);
void handleChoices (wxCommandEvent &event);
void handleSashDragged (wxSashEvent &event);
void handleSpins (wxSpinEvent &event);
void handleMixSlider (wxScrollEvent &event);
void handleGain (wxSpinEvent &event);
void handlePathCount (wxCommandEvent &event);
void changePathCount (int newcnt, bool rebuild=false, bool ignorelink=false);
void handleStoreButton (wxCommandEvent &event);
void handleLoadButton (wxCommandEvent &event);
void handleIOButtons (wxCommandEvent &event);
void OnProcMod (wxCommandEvent &event);
void OnPresetBlend (wxCommandEvent &event);
void OnModulatorDialog (wxCommandEvent &event);
void handleTitleMenuCmd (FTtitleMenuEvent & ev);
void rowpanelScrollSize();
void removePathStuff(int i, bool deactivate=true);
void createPathStuff(int i);
void rebuildPresetCombo();
void pushProcRow(FTspectrumModifier *specmod);
void popProcRow();
void updateAllExtra();
void minimizeRow (wxWindow * shown, wxWindow * hidden, int rownum, bool layout=true);
FTprocessPath * _processPath[FT_MAXPATHS];
int _startpaths;
// overall controls
wxChoice * _freqBinsChoice;
wxChoice * _overlapChoice;
wxChoice * _windowingChoice;
wxChoice * _freqScaleChoice;
wxSlider * _timescaleSlider;
wxChoice * _pathCountChoice;
wxTextCtrl * _ioNameText;
// array of spectragrams
FTspectragram * _inputSpectragram[FT_MAXPATHS];
FTspectragram * _outputSpectragram[FT_MAXPATHS];
vector<FTactiveBarGraph **> _barGraphs;
// FTactiveBarGraph * _scaleGraph[FT_MAXPATHS];
// FTactiveBarGraph * _freqGraph[FT_MAXPATHS];
// FTactiveBarGraph * _delayGraph[FT_MAXPATHS];
// FTactiveBarGraph * _feedbackGraph[FT_MAXPATHS];
// FTactiveBarGraph * _mashGraph[FT_MAXPATHS];
// FTactiveBarGraph * _gateGraph[FT_MAXPATHS];
//wxButton * _bypassAllButton;
//wxButton * _muteAllButton;
wxCheckBox * _bypassAllCheck;
wxCheckBox * _muteAllCheck;
vector<JLCui::PixButton *> _bypassAllButtons;
// wxButton * _scaleBypassAllButton;
// wxButton * _mashBypassAllButton;
// wxButton * _gateBypassAllButton;
// wxButton * _freqBypassAllButton;
// wxButton * _delayBypassAllButton;
// wxButton * _feedbBypassAllButton;
vector<JLCui::PixButton *> _linkAllButtons;
// wxButton * _scaleLinkAllButton;
// wxButton * _mashLinkAllButton;
// wxButton * _gateLinkAllButton;
// wxButton * _freqLinkAllButton;
// wxButton * _delayLinkAllButton;
// wxButton * _feedbLinkAllButton;
vector<JLCui::PixButton *> _gridButtons;
// wxButton * _scaleGridButton;
// wxButton * _gateGridButton;
// wxButton * _freqGridButton;
// wxButton * _delayGridButton;
// wxButton * _feedbGridButton;
vector<JLCui::PixButton *> _gridSnapButtons;
// wxButton * _scaleGridSnapButton;
// wxButton * _gateGridSnapButton;
// wxButton * _freqGridSnapButton;
// wxButton * _delayGridSnapButton;
// wxButton * _feedbGridSnapButton;
wxButton * _inspecLabelButton;
wxButton * _outspecLabelButton;
vector<wxButton *> _labelButtons;
// wxButton * _scaleLabelButton;
// wxButton * _mashLabelButton;
// wxButton * _gateLabelButton;
// wxButton * _freqLabelButton;
// wxButton * _delayLabelButton;
// wxButton * _feedbLabelButton;
wxButton * _inspecLabelButtonAlt;
wxButton * _outspecLabelButtonAlt;
vector<wxButton *> _altLabelButtons;
// wxButton * _scaleLabelButtonAlt;
// wxButton * _mashLabelButtonAlt;
// wxButton * _gateLabelButtonAlt;
// wxButton * _freqLabelButtonAlt;
// wxButton * _delayLabelButtonAlt;
// wxButton * _feedbLabelButtonAlt;
JLCui::PixButton * _inspecSpecTypeAllButton;
JLCui::PixButton * _inspecPlotSolidTypeAllButton;
JLCui::PixButton * _inspecPlotLineTypeAllButton;
JLCui::PixButton * _outspecSpecTypeAllButton;
JLCui::PixButton * _outspecPlotSolidTypeAllButton;
JLCui::PixButton * _outspecPlotLineTypeAllButton;
wxCheckBox * _linkMixCheck;
//wxButton * _linkMixButton;
// per path panels
wxPanel * _upperPanels[FT_MAXPATHS];
wxPanel * _inspecPanels[FT_MAXPATHS];
vector<wxPanel **> _subrowPanels;
// wxPanel * _freqPanels[FT_MAXPATHS];
// wxPanel * _scalePanels[FT_MAXPATHS];
// wxPanel * _mashPanels[FT_MAXPATHS];
// wxPanel * _gatePanels[FT_MAXPATHS];
// wxPanel * _delayPanels[FT_MAXPATHS];
// wxPanel * _feedbPanels[FT_MAXPATHS];
wxPanel * _outspecPanels[FT_MAXPATHS];
wxPanel * _lowerPanels[FT_MAXPATHS];
// per path buttons
wxButton * _inputButton[FT_MAXPATHS];
wxButton * _outputButton[FT_MAXPATHS];
wxSpinCtrl *_gainSpinCtrl[FT_MAXPATHS];
wxSlider * _mixSlider[FT_MAXPATHS];
//wxButton * _bypassButton[FT_MAXPATHS];
//wxButton * _muteButton[FT_MAXPATHS];
wxCheckBox * _bypassCheck[FT_MAXPATHS];
wxCheckBox * _muteCheck[FT_MAXPATHS];
JLCui::PixButton * _inspecSpecTypeButton[FT_MAXPATHS];
JLCui::PixButton * _inspecPlotSolidTypeButton[FT_MAXPATHS];
JLCui::PixButton * _inspecPlotLineTypeButton[FT_MAXPATHS];
JLCui::PixButton * _outspecSpecTypeButton[FT_MAXPATHS];
JLCui::PixButton * _outspecPlotSolidTypeButton[FT_MAXPATHS];
JLCui::PixButton * _outspecPlotLineTypeButton[FT_MAXPATHS];
vector<JLCui::PixButton **> _bypassButtons;
// wxButton * _scaleBypassButton[FT_MAXPATHS];
// wxButton * _mashBypassButton[FT_MAXPATHS];
// wxButton * _gateBypassButton[FT_MAXPATHS];
// wxButton * _freqBypassButton[FT_MAXPATHS];
// wxButton * _delayBypassButton[FT_MAXPATHS];
// wxButton * _feedbBypassButton[FT_MAXPATHS];
vector<JLCui::PixButton **> _linkButtons;
// wxButton * _scaleLinkButton[FT_MAXPATHS];
// wxButton * _mashLinkButton[FT_MAXPATHS];
// wxButton * _gateLinkButton[FT_MAXPATHS];
// wxButton * _freqLinkButton[FT_MAXPATHS];
// wxButton * _delayLinkButton[FT_MAXPATHS];
// wxButton * _feedbLinkButton[FT_MAXPATHS];
// sizers
wxBoxSizer *_inspecsizer, *_outspecsizer;
wxBoxSizer *_inspecbuttsizer, *_outspecbuttsizer;
vector<wxBoxSizer *> _rowSizers;
vector<wxBoxSizer *> _rowButtSizers;
wxBoxSizer *_lowersizer, *_uppersizer;
wxScrolledWindow *_rowPanel;
vector<wxPanel *> _rowPanels;
wxPanel *_inspecPanel, *_outspecPanel;
vector<wxSashLayoutWindow *> _rowSashes;
wxSashLayoutWindow *_inspecSash, *_outspecSash;
// shown flags
bool _inspecShown;
vector<bool> _shownFlags;
// bool _freqShown;
// bool _scaleShown;
// bool _mashShown;
// bool _gateShown;
// bool _delayShown;
// bool _feedbShown;
bool _outspecShown;
bool _linkedMix;
// bitmap data
wxBitmap * _bypassBitmap;
wxBitmap * _bypassActiveBitmap;
wxBitmap * _linkBitmap;
wxBitmap *_linkActiveBitmap;
wxColour _defaultBg;
wxColour _activeBg;
FTupdateTimer *_eventTimer;
int _updateMS;
bool _superSmooth;
FTrefreshTimer *_refreshTimer;
int _refreshMS;
vector<wxWindow *> _rowItems;
//wxWindow ** _rowItems;
int _pathCount;
int _rowCount;
FTconfigManager _configManager;
wxComboBox * _presetCombo;
wxChoice * _plotSpeedChoice;
wxCheckBox *_superSmoothCheck;
wxCheckBox *_restorePortsCheck;
wxChoice * _maxDelayChoice;
vector<float> _delayList;
wxSpinCtrl * _tempoSpinCtrl;
FTupdateToken * _updateTokens[FT_MAXPATHS];
bool _bypassArray[FT_MAXPATHS];
FTprocOrderDialog * _procmodDialog;
FTpresetBlendDialog * _blendDialog;
FTmodulatorDialog * _modulatorDialog;
int _bwidth;
int _labwidth;
int _bheight;
int _rowh;
wxFont _titleFont;
wxFont _titleAltFont;
wxFont _buttFont;
vector<FTtitleMenuEvent *> _pendingTitleEvents;
friend class FTupdateTimer;
friend class FTrefreshTimer;
friend class FTlinkMenu;
friend class FTgridMenu;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
class FTupdateTimer
: public wxTimer
{
public:
FTupdateTimer(FTmainwin *win) : mwin(win) {}
void Notify() { mwin->checkEvents(); }
FTmainwin *mwin;
};
class FTrefreshTimer
: public wxTimer
{
public:
FTrefreshTimer(FTmainwin *win) : mwin(win) {}
void Notify() { mwin->checkRefreshes(); }
FTmainwin *mwin;
};
class FTlinkMenu
: public wxMenu
{
public:
FTlinkMenu (wxWindow *parent, FTmainwin *win, FTspectralEngine *specmod, SpecModType stype,
unsigned int procmodnum, unsigned int filtnum);
void OnLinkItem(wxCommandEvent &event);
void OnUnlinkItem(wxCommandEvent &event);
FTmainwin *_mwin;
FTspectralEngine *_specengine;
SpecModType _stype;
unsigned int _procmodnum;
unsigned int _filtnum;
class SpecModObject : public wxObject
{
public:
SpecModObject(FTspectralEngine *sm) : specm(sm) {;}
FTspectralEngine *specm;
};
private:
// any class wishing to process wxWindows events must use this macro
// DECLARE_EVENT_TABLE()
};
class FTgridMenu
: public wxMenu
{
public:
FTgridMenu (wxWindow *parent, FTmainwin *win, vector<FTactiveBarGraph*> & graph, FTspectrumModifier::ModifierType mtype);
void OnSelectItem(wxCommandEvent &event);
FTmainwin *_mwin;
vector<FTactiveBarGraph *> _graphlist;
FTspectrumModifier::ModifierType _mtype;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
class FTgridButton
: public wxButton
{
public:
FTgridButton(FTmainwin *mwin, wxWindow * parent, wxWindowID id,
const wxString& label,
const wxPoint& pos,
const wxSize& size = wxDefaultSize,
long style = 0, const wxValidator& validator=wxDefaultValidator, const wxString& name = wxButtonNameStr);
void handleMouse (wxMouseEvent &event);
FTmainwin * _mainwin;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
class FTtitleMenu
: public wxMenu
{
public:
FTtitleMenu (wxWindow *parent, FTmainwin *win, bool minimized);
void OnSelectItem(wxCommandEvent &event);
FTmainwin *_mwin;
wxWindow * _parent;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
class FTtitleButton
: public wxButton
{
public:
FTtitleButton(FTmainwin *mwin, bool minimized, wxWindow * parent, wxWindowID id,
const wxString& label,
const wxPoint& pos,
const wxSize& size = wxDefaultSize,
long style = 0, const wxValidator& validator=wxDefaultValidator, const wxString& name = wxButtonNameStr);
void handleMouse (wxMouseEvent &event);
FTmainwin * _mainwin;
bool _minimized;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
#endif
| 14,752
|
C++
|
.h
| 432
| 31.581019
| 122
| 0.768717
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,961
|
FTprocEQ.hpp
|
essej_freqtweak/src/FTprocEQ.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCEQ_HPP__
#define __FTPROCEQ_HPP__
#include "FTprocI.hpp"
class FTprocEQ
: public FTprocI
{
public:
FTprocEQ(nframes_t samprate, unsigned int fftn);
FTprocEQ (const FTprocEQ & other);
virtual ~FTprocEQ();
FTprocI * clone() { return new FTprocEQ(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
protected:
FTspectrumModifier * _eqfilter;
};
#endif
| 1,211
|
C++
|
.h
| 35
| 32.628571
| 80
| 0.748709
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,962
|
FTprocWarp.hpp
|
essej_freqtweak/src/FTprocWarp.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCWARP_HPP__
#define __FTPROCWARP_HPP__
#include "FTprocI.hpp"
class FTprocWarp
: public FTprocI
{
public:
FTprocWarp(nframes_t samprate, unsigned int fftn);
FTprocWarp (const FTprocWarp & other);
virtual ~FTprocWarp();
FTprocI * clone() { return new FTprocWarp(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
void setFFTsize (unsigned int fftn);
virtual bool useAsDefault() { return false; }
protected:
FTspectrumModifier * _filter;
fft_data *_tmpdata;
};
#endif
| 1,333
|
C++
|
.h
| 38
| 33.052632
| 80
| 0.751956
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,963
|
pixmap_includes.hpp
|
essej_freqtweak/src/pixmap_includes.hpp
|
//
// /bin/ls -1 pixmaps/*.xpm | awk '{}{ printf "#include \"%s\"\n", $1 }'
//
#ifndef __freqtweak_pixmap_includes__
#define __freqtweak_pixmap_includes__
#include "pixmaps/barplot_active.xpm"
#include "pixmaps/barplot_disabled.xpm"
#include "pixmaps/barplot_focus.xpm"
#include "pixmaps/barplot_normal.xpm"
#include "pixmaps/barplot_selected.xpm"
#include "pixmaps/bypass_active.xpm"
#include "pixmaps/bypass_disabled.xpm"
#include "pixmaps/bypass_focus.xpm"
#include "pixmaps/bypass_normal.xpm"
#include "pixmaps/bypass_selected.xpm"
#include "pixmaps/grid_active.xpm"
#include "pixmaps/grid_disabled.xpm"
#include "pixmaps/grid_focus.xpm"
#include "pixmaps/grid_normal.xpm"
#include "pixmaps/grid_selected.xpm"
#include "pixmaps/gridsnap_active.xpm"
#include "pixmaps/gridsnap_disabled.xpm"
#include "pixmaps/gridsnap_focus.xpm"
#include "pixmaps/gridsnap_normal.xpm"
#include "pixmaps/gridsnap_selected.xpm"
#include "pixmaps/lineplot_active.xpm"
#include "pixmaps/lineplot_disabled.xpm"
#include "pixmaps/lineplot_focus.xpm"
#include "pixmaps/lineplot_normal.xpm"
#include "pixmaps/lineplot_selected.xpm"
#include "pixmaps/link_active.xpm"
#include "pixmaps/link_disabled.xpm"
#include "pixmaps/link_focus.xpm"
#include "pixmaps/link_normal.xpm"
#include "pixmaps/link_selected.xpm"
#include "pixmaps/specplot_active.xpm"
#include "pixmaps/specplot_disabled.xpm"
#include "pixmaps/specplot_focus.xpm"
#include "pixmaps/specplot_normal.xpm"
#include "pixmaps/specplot_selected.xpm"
#endif
| 1,499
|
C++
|
.h
| 41
| 35.439024
| 73
| 0.790778
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,964
|
FTmodulatorI.hpp
|
essej_freqtweak/src/FTmodulatorI.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODULATORI_HPP__
#define __FTMODULATORI_HPP__
#include "FTtypes.hpp"
#include <string>
#include <list>
#include <algorithm>
#include <sigc++/sigc++.h>
#include <iostream>
#include "LockMonitor.hpp"
#include "FTspectrumModifier.hpp"
class FTmodulatorI
: public FTspectrumModifier::Listener
{
public:
virtual ~FTmodulatorI();
virtual FTmodulatorI * clone() = 0;
virtual void initialize() = 0;
virtual void modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes) = 0;
virtual void goingAway(FTspectrumModifier * ft);
typedef std::list<FTspectrumModifier *> SpecModList;
virtual void addSpecMod (FTspectrumModifier * specmod);
virtual void removeSpecMod (FTspectrumModifier * specmod);
virtual void clearSpecMods ();
virtual void getSpecMods (SpecModList & mods);
virtual bool hasSpecMod (FTspectrumModifier *specmod);
virtual std::string getUserName() { return _userName; }
virtual void setUserName (std::string username) { _userName = username; }
virtual std::string getName() { return _name; }
virtual void setFFTsize (unsigned int fftn) { _fftN = fftn; }
virtual void setSampleRate (nframes_t rate) { _sampleRate = rate; }
virtual nframes_t getSampleRate() { return _sampleRate; }
virtual const string & getConfName() { return _confname; }
virtual bool getBypassed() { return _bypassed; }
virtual void setBypassed(bool byp) { _bypassed = byp; }
sigc::signal1<void, FTmodulatorI *> GoingAway;
class Control
{
public:
enum Type {
BooleanType = 1,
IntegerType,
FloatType,
StringType,
EnumType
};
Control (Type t, std::string confname, std::string name, std::string units) : _type(t), _confname(confname), _name(name), _units(units) {}
Type getType() { return _type; }
std::string getConfName() { return _confname; }
std::string getName() { return _name; }
std::string getUnits() { return _units; }
inline bool getValue(bool & val);
inline bool getValue(int & val);
inline bool getValue(float & val);
// for string or enum type
inline bool getValue(std::string & val);
inline bool getEnumStrings (std::list<std::string> & vals);
inline bool getBounds(int & lb, int & ub);
inline bool getBounds(float & lb, float & ub);
inline bool setValue(bool val);
inline bool setValue(int val);
inline bool setValue(float val);
// for string or enum type
inline bool setValue(const std::string & val);
int _intLB, _intUB;
float _floatLB, _floatUB;
std::list<std::string> _enumList;
friend class FTmodulatorI;
protected:
Type _type;
std::string _confname;
std::string _name;
std::string _units;
std::string _stringVal;
float _floatVal;
int _intVal;
bool _boolVal;
};
typedef std::list<Control *> ControlList;
virtual void getControls (ControlList & conlist) {
conlist.insert (conlist.begin(), _controls.begin(), _controls.end());
}
protected:
FTmodulatorI(std::string confname, std::string name, nframes_t samplerate, unsigned int fftn);
ControlList _controls;
SpecModList _specMods;
PBD::NonBlockingLock _specmodLock;
bool _inited;
std::string _name;
std::string _confname;
std::string _userName;
bool _bypassed;
nframes_t _sampleRate;
unsigned int _fftN;
int _id;
};
inline bool FTmodulatorI::Control::getValue(bool & val)
{
if (_type != BooleanType) return false;
val = _boolVal;
return true;
}
inline bool FTmodulatorI::Control::getValue(int & val)
{
if (_type != IntegerType) return false;
val = _intVal;
return true;
}
inline bool FTmodulatorI::Control::getValue(float & val)
{
if (_type != FloatType) return false;
val = _floatVal;
return true;
}
// for string or enum type
inline bool FTmodulatorI::Control::getValue(std::string & val)
{
if (_type != StringType && _type != EnumType) return false;
val = _stringVal;
return true;
}
inline bool FTmodulatorI::Control::getEnumStrings (std::list<std::string> & vals)
{
if (_type != EnumType) return false;
vals.insert(vals.begin(), _enumList.begin(), _enumList.end());
return true;
}
inline bool FTmodulatorI::Control::getBounds(int & lb, int & ub)
{
if (_type != IntegerType) return false;
lb = _intLB;
ub = _intUB;
return true;
}
inline bool FTmodulatorI::Control::getBounds(float & lb, float & ub)
{
if (_type != FloatType) return false;
lb = _floatLB;
ub = _floatUB;
return true;
}
inline bool FTmodulatorI::Control::setValue(bool val)
{
if (_type != BooleanType) return false;
_boolVal = val;
return true;
}
inline bool FTmodulatorI::Control::setValue(int val)
{
if (_type != IntegerType) return false;
_intVal = val;
return true;
}
inline bool FTmodulatorI::Control::setValue(float val)
{
if (_type != FloatType) return false;
_floatVal = val;
return true;
}
// for string or enum type
inline bool FTmodulatorI::Control::setValue(const std::string & val)
{
if (_type == StringType) {
_stringVal = val;
return true;
}
else if (_type == EnumType && std::find(_enumList.begin(), _enumList.end(), val) != _enumList.end()) {
_stringVal = val;
return true;
}
return false;
}
#endif
| 5,947
|
C++
|
.h
| 190
| 28.884211
| 140
| 0.728972
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,965
|
FTioSupport.hpp
|
essej_freqtweak/src/FTioSupport.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
/**
* Supports operations concerning I/O with JACK
*/
#ifndef __FTIOSUPPORT_HPP__
#define __FTIOSUPPORT_HPP__
#include <string>
using namespace std;
#include "FTtypes.hpp"
class FTprocessPath;
class FTioSupport
{
public:
virtual ~FTioSupport() {};
virtual bool init() = 0;
virtual bool reinit(bool rebuild=true) = 0;
virtual bool isInited() = 0;
//virtual bool setProcessPath(FTprocessPath *ppath, int index) = 0;
virtual FTprocessPath * getProcessPath(int index) = 0;
virtual FTprocessPath * setProcessPathActive(int index, bool flag) = 0;
virtual int getActivePathCount () = 0;
virtual bool startProcessing() = 0;
virtual bool stopProcessing() = 0;
virtual bool close() = 0;
virtual bool connectPathInput (int index, const char *inname) = 0;
virtual bool connectPathOutput (int index, const char *outname) = 0;
virtual bool disconnectPathInput (int index, const char *inname) = 0;
virtual bool disconnectPathOutput (int index, const char *outname) = 0;
virtual const char ** getConnectedInputPorts(int index) = 0;
virtual const char ** getConnectedOutputPorts(int index) = 0;
virtual const char ** getInputConnectablePorts(int index) = 0;
virtual const char ** getOutputConnectablePorts(int index) = 0;
virtual const char * getInputPortName(int index) = 0;
virtual const char * getOutputPortName(int index) = 0;
virtual const char ** getPhysicalInputPorts() = 0;
virtual const char ** getPhysicalOutputPorts() = 0;
virtual nframes_t getSampleRate() = 0;
virtual nframes_t getTransportFrame() = 0;
virtual bool getPortsChanged() = 0;
virtual void setName (const string & name);
virtual const char * getName() { return _name.c_str(); }
virtual bool inAudioThread() { return false; }
virtual void setProcessingBypassed (bool val) = 0;
enum IOtype
{
IO_JACK,
};
// set io type for this session
// call before the first instance is called
static void setIOtype (IOtype it) { _iotype = it; }
// singleton retrieval
static FTioSupport * instance() { if (!_instance) _instance = createInstance(); return _instance; }
static void setDefaultName(const string & name) { _defaultName = name; }
static void setDefaultServer(const string & dir) { _defaultServ = dir; }
protected:
// this is our singleton
static FTioSupport * _instance;
static IOtype _iotype;
static FTioSupport * createInstance();
static string _defaultName;
static string _defaultServ;
string _name;
};
#endif
| 3,293
|
C++
|
.h
| 81
| 37.91358
| 100
| 0.744546
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,966
|
FTspectrumModifier.hpp
|
essej_freqtweak/src/FTspectrumModifier.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTSPECTRUMMODIFIER_HPP__
#define __FTSPECTRUMMODIFIER_HPP__
#include "FTtypes.hpp"
#include "xml++.hpp"
#include <string>
#include <list>
using namespace std;
class FTspectrumModifier
{
public:
enum ModifierType
{
GAIN_MODIFIER = 0,
TIME_MODIFIER,
UNIFORM_MODIFIER,
RATIO_MODIFIER,
FREQ_MODIFIER,
DB_MODIFIER,
SEMITONE_MODIFIER,
POS_GAIN_MODIFIER,
// must be last!
NULL_MODIFIER,
};
class Listener {
public:
virtual ~Listener() {}
virtual void goingAway(FTspectrumModifier * ft) = 0;
};
FTspectrumModifier(const string & name, const string &configName, int group,
ModifierType mtype, SpecModType smtype, int length=512, float initval=0.0);
virtual ~FTspectrumModifier();
void setId (int id) { _id = id; }
int getId () { return _id; }
void setLength(int length);
int getLength() { return _length; }
string getName() { return _name; }
void setName(const string & name) { _name = name; }
string getConfigName() { return _configName; }
void setConfigName(const string & name) { _configName = name; }
int getGroup() { return _group; }
void setGroup(int grp) { _group = grp; }
float * getValues();
ModifierType getModifierType() { return _modType; }
SpecModType getSpecModifierType() { return _specmodType; }
FTspectrumModifier * getLink() { return _linkedTo; }
bool link (FTspectrumModifier *specmod);
void unlink (bool unlinksources=true);
void setRange(float min, float max) { _min = min; _max = max; }
void getRange(float &min, float &max) { min = _min; max = _max; }
float getMin() const { return _min;}
float getMax() const { return _max;}
void setBypassed (bool flag) { _bypassed = flag; }
bool getBypassed () { return _bypassed; }
void setDirty (bool val) { _dirty = val; }
// this is as close of a test-and-set as I need
bool getDirty (bool tas=false, bool val=false)
{
if (_linkedTo) {
return _linkedTo->getDirty(false);
}
if (_dirty) {
if (tas) {
_dirty = val;
}
return true;
}
return false;
}
// resets all bins to constructed value
void reset();
void copy (FTspectrumModifier *specmod);
list<FTspectrumModifier*> & getLinkedFrom() { return _linkedFrom; }
bool isLinkedFrom (FTspectrumModifier *specmod);
// user notification
void registerListener (Listener * listener);
void unregisterListener (Listener *listener);
XMLNode * getExtraNode();
void setExtraNode(XMLNode * node);
protected:
void addedLinkFrom (FTspectrumModifier * specmod);
void removedLinkFrom (FTspectrumModifier * specmod);
ModifierType _modType;
SpecModType _specmodType;
string _name;
string _configName;
int _group;
// might point to a linked value array
float * _values;
float * _tmpvalues; // used for copying
int _length;
FTspectrumModifier *_linkedTo;
float _min, _max;
float _initval;
list<FTspectrumModifier*> _linkedFrom;
int _id;
bool _bypassed;
bool _dirty;
list<Listener *> _listenerList;
XMLNode * _extra_node;
};
#endif
| 3,818
|
C++
|
.h
| 119
| 29.285714
| 81
| 0.726547
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,967
|
FTpresetBlendDialog.hpp
|
essej_freqtweak/src/FTpresetBlendDialog.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPRESETBLENDDIALOG_HPP__
#define __FTPRESETBLENDDIALOG_HPP__
#include <wx/wx.h>
#include "FTtypes.hpp"
#include <vector>
#include <string>
using namespace std;
class FTmainwin;
class FTconfigManager;
class FTpresetBlender;
class FTspectrumModifier;
class FTpresetBlendDialog
: public wxFrame
{
public:
FTpresetBlendDialog(FTmainwin * parent, FTconfigManager * confman, wxWindowID id, const wxString & title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400,600),
long style = wxDEFAULT_FRAME_STYLE,
const wxString& name = wxT("PresetBlend"));
virtual ~FTpresetBlendDialog();
void update();
void refreshState(const wxString & defname = wxT(""), bool usefirst=false, const wxString & defsec = wxT(""), bool usesec=false);
protected:
void init();
void onClose(wxCloseEvent & ev);
void onSize(wxSizeEvent &ev);
void onPaint(wxPaintEvent &ev);
void onSliders(wxScrollEvent &ev);
void onCombo(wxCommandEvent &ev);
wxBoxSizer * _procSizer;
wxWindow * _procPanel;
wxComboBox * _priPresetBox;
wxComboBox * _secPresetBox;
wxStaticText * _priStatus;
wxStaticText * _secStatus;
wxSlider * _masterBlend;
vector<wxSlider*> _blendSliders;
typedef pair<unsigned int, unsigned int> ProcPair;
vector<ProcPair > _blendPairs;
vector<FTspectrumModifier *> _filtRefs;
FTmainwin * _mainwin;
bool _justResized;
int _namewidth;
FTconfigManager * _configMan;
FTpresetBlender * _presetBlender;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
#endif
| 2,414
|
C++
|
.h
| 69
| 32.318841
| 131
| 0.761077
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,968
|
FTprocLimit.hpp
|
essej_freqtweak/src/FTprocLimit.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCLIMIT_HPP__
#define __FTPROCLIMIT_HPP__
#include "FTprocI.hpp"
class FTprocLimit
: public FTprocI
{
public:
FTprocLimit(nframes_t samprate, unsigned int fftn);
FTprocLimit (const FTprocLimit & other);
virtual ~FTprocLimit();
FTprocI * clone() { return new FTprocLimit(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
virtual bool useAsDefault() { return false; }
protected:
FTspectrumModifier * _threshfilter;
float _dbAdjust;
};
#endif
| 1,303
|
C++
|
.h
| 37
| 33.27027
| 80
| 0.75419
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,969
|
FTmodulatorDialog.hpp
|
essej_freqtweak/src/FTmodulatorDialog.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODULATORDIALOG_HPP__
#define __FTMODULATORDIALOG_HPP__
#include <map>
#include <list>
#include <wx/wx.h>
#include "FTtypes.hpp"
class FTprocI;
class FTmainwin;
class FTmodulatorI;
class FTmodulatorGui;
class FTmodulatorDialog : public wxFrame
{
public:
// ctor(s)
FTmodulatorDialog(FTmainwin * parent, wxWindowID id, const wxString& title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400,600),
long style = wxDEFAULT_FRAME_STYLE,
const wxString& name = wxT("ModulatorDialog"));
virtual ~FTmodulatorDialog();
void OnIdle(wxIdleEvent &ev);
protected:
void init();
void refreshState();
void onClose(wxCloseEvent & ev);
void onCommit(wxCommandEvent & ev);
void onSize(wxSizeEvent &ev);
void onPaint(wxPaintEvent &ev);
void onAddModulator (wxCommandEvent &ev);
void onAddButton (wxCommandEvent &ev);
void onClearButton (wxCommandEvent &ev);
void onModulatorDeath (FTmodulatorI * mod);
void onModulatorAdded (FTmodulatorI * mod, int channel);
void appendModGui(FTmodulatorI * mod, bool layout=true);
// void onAutoCheck (wxCommandEvent &ev);
wxScrolledWindow * _channelScrollers[FT_MAXPATHS];
wxBoxSizer * _channelSizers[FT_MAXPATHS];
wxScrolledWindow * _channelScroller;
wxBoxSizer * _channelSizer;
int _channelCount;
wxBoxSizer * _chanlistSizer;
wxMenu * _popupMenu;
int _clickedChannel;
FTmainwin * _mainwin;
std::map<FTmodulatorI*, FTmodulatorGui*> _modulatorGuis;
std::list<FTmodulatorGui *> _deadGuis;
bool _justResized;
int _lastSelected;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
#endif
| 2,492
|
C++
|
.h
| 71
| 32.492958
| 80
| 0.763147
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,970
|
FTdspManager.hpp
|
essej_freqtweak/src/FTdspManager.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTDSPMANAGER_HPP__
#define __FTDSPMANAGER_HPP__
#include "FTtypes.hpp"
#include <list>
#include <string>
using namespace std;
class FTprocI;
class FTdspManager
{
public:
typedef list<FTprocI*> ModuleList;
FTdspManager();
virtual ~FTdspManager();
static FTdspManager * instance() { if (!_instance) _instance = new FTdspManager(); return _instance; }
void getAvailableModules (ModuleList & outlist);
FTprocI * getModuleByName (const string & name);
FTprocI * getModuleByConfigName (const string & name);
protected:
ModuleList _prototypes;
static FTdspManager* _instance;
};
#endif
| 1,413
|
C++
|
.h
| 40
| 33.325
| 103
| 0.759587
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,971
|
FThelpWindow.hpp
|
essej_freqtweak/src/FThelpWindow.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTHELPWIN_HPP__
#define __FTHELPWIN_HPP__
#include <wx/wx.h>
#include <wx/html/htmlwin.h>
#include "FTtypes.hpp"
#include <vector>
#include <string>
using namespace std;
class FThelpWindow
: public wxFrame
{
public:
FThelpWindow(wxWindow * parent, wxWindowID id, const wxString & title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400,600),
long style = wxDEFAULT_FRAME_STYLE,
const wxString& name = wxT("HelpWin"));
virtual ~FThelpWindow();
protected:
void init();
wxHtmlWindow * _htmlWin;
};
#endif
| 1,378
|
C++
|
.h
| 41
| 31.170732
| 80
| 0.739229
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,972
|
FTprocGate.hpp
|
essej_freqtweak/src/FTprocGate.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCGATE_HPP__
#define __FTPROCGATE_HPP__
#include "FTprocI.hpp"
class FTprocGate
: public FTprocI
{
public:
FTprocGate(nframes_t samprate, unsigned int fftn);
FTprocGate (const FTprocGate & other);
virtual ~FTprocGate();
FTprocI * clone() { return new FTprocGate(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
protected:
FTspectrumModifier * _filter;
FTspectrumModifier * _invfilter;
float _dbAdjust;
};
#endif
| 1,276
|
C++
|
.h
| 37
| 32.513514
| 80
| 0.754286
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,973
|
cycles.h
|
essej_freqtweak/src/cycles.h
|
/*
Copyright (C) 2001 Paul Davis
Code derived from various headers from the Linux kernel
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 2 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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
$Id: cycles.h,v 1.1 2004/04/13 01:17:54 essej Exp $
*/
#ifndef __ardour_cycles_h__
#define __ardour_cycles_h__
#if defined(__i386__) || defined(__x86_64__)
/*
* Standard way to access the cycle counter on i586+ CPUs.
* Currently only used on SMP.
*
* If you really have a SMP machine with i486 chips or older,
* compile for that, and this will just always return zero.
* That's ok, it just means that the nicer scheduling heuristics
* won't work for you.
*
* We only use the low 32 bits, and we'd simply better make sure
* that we reschedule before that wraps. Scheduling at least every
* four billion cycles just basically sounds like a good idea,
* regardless of how fast the machine is.
*/
typedef unsigned long long cycles_t;
extern cycles_t cacheflush_time;
#define rdtscll(val) \
__asm__ __volatile__("rdtsc" : "=A" (val))
static inline cycles_t get_cycles (void)
{
unsigned long long ret;
rdtscll(ret);
return ret;
}
#elif defined(__powerpc__)
#define CPU_FTR_601 0x00000100
typedef unsigned long cycles_t;
/*
* For the "cycle" counter we use the timebase lower half.
* Currently only used on SMP.
*/
extern cycles_t cacheflush_time;
static inline cycles_t get_cycles(void)
{
cycles_t ret = 0;
__asm__ __volatile__(
"98: mftb %0\n"
"99:\n"
".section __ftr_fixup,\"a\"\n"
" .long %1\n"
" .long 0\n"
" .long 98b\n"
" .long 99b\n"
".previous"
: "=r" (ret) : "i" (CPU_FTR_601));
return ret;
}
#elif defined(__ia64__)
/* ia64 */
typedef unsigned long cycles_t;
static inline cycles_t
get_cycles (void)
{
cycles_t ret;
__asm__ __volatile__ ("mov %0=ar.itc" : "=r"(ret));
return ret;
}
#elif defined(__alpha__)
/* alpha */
/*
* Standard way to access the cycle counter.
* Currently only used on SMP for scheduling.
*
* Only the low 32 bits are available as a continuously counting entity.
* But this only means we'll force a reschedule every 8 seconds or so,
* which isn't an evil thing.
*/
typedef unsigned int cycles_t;
static inline cycles_t get_cycles (void)
{
cycles_t ret;
__asm__ __volatile__ ("rpcc %0" : "=r"(ret));
return ret;
}
#elif defined(__s390__)
/* s390 */
typedef unsigned long long cycles_t;
static inline cycles_t get_cycles(void)
{
cycles_t cycles;
__asm__("stck 0(%0)" : : "a" (&(cycles)) : "memory", "cc");
return cycles >> 2;
}
#elif defined(__hppa__)
/* hppa/parisc */
#define mfctl(reg) ({ \
unsigned long cr; \
__asm__ __volatile__( \
"mfctl " #reg ",%0" : \
"=r" (cr) \
); \
cr; \
})
typedef unsigned long cycles_t;
static inline cycles_t get_cycles (void)
{
return mfctl(16);
}
#elif defined(__mips__)
/* mips/mipsel */
/*
* Standard way to access the cycle counter.
* Currently only used on SMP for scheduling.
*
* Only the low 32 bits are available as a continuously counting entity.
* But this only means we'll force a reschedule every 8 seconds or so,
* which isn't an evil thing.
*
* We know that all SMP capable CPUs have cycle counters.
*/
#define __read_32bit_c0_register(source, sel) \
({ int __res; \
if (sel == 0) \
__asm__ __volatile__( \
"mfc0\t%0, " #source "\n\t" \
: "=r" (__res)); \
else \
__asm__ __volatile__( \
".set\tmips32\n\t" \
"mfc0\t%0, " #source ", " #sel "\n\t" \
".set\tmips0\n\t" \
: "=r" (__res)); \
__res; \
})
/* #define CP0_COUNT $9 */
#define read_c0_count() __read_32bit_c0_register($9, 0)
typedef unsigned int cycles_t;
static inline cycles_t get_cycles (void)
{
return read_c0_count();
}
#else
/* debian: sparc, arm, m68k */
#warning You are compiling libardour on a platform for which ardour/cycles.h needs work
#include <sys/time.h>
typedef long cycles_t;
extern cycles_t cacheflush_time;
static inline cycles_t get_cycles(void)
{
struct timeval tv;
gettimeofday (&tv, NULL);
return tv.tv_usec;
}
#endif
#endif /* __ardour_cycles_h__ */
| 5,545
|
C++
|
.h
| 164
| 29.768293
| 87
| 0.574348
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,974
|
FTmodRotate.hpp
|
essej_freqtweak/src/FTmodRotate.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODROTATE_HPP__
#define __FTMODROTATE_HPP__
#include "FTmodulatorI.hpp"
class FTmodRotate
: public FTmodulatorI
{
public:
FTmodRotate(nframes_t samplerate, unsigned int fftn);
FTmodRotate (const FTmodRotate & other);
virtual ~FTmodRotate();
FTmodulatorI * clone() { return new FTmodRotate(*this); }
void initialize();
void modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes);
void setFFTsize (unsigned int fftn);
protected:
Control * _rate;
Control * _minfreq;
Control * _maxfreq;
nframes_t _lastframe;
float * _tmpfilt;
};
#endif
| 1,431
|
C++
|
.h
| 40
| 33.725
| 120
| 0.754003
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,975
|
FTmodRandomize.hpp
|
essej_freqtweak/src/FTmodRandomize.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODRANDOMIZE_HPP__
#define __FTMODRANDOMIZE_HPP__
#include "FTmodulatorI.hpp"
class FTmodRandomize
: public FTmodulatorI
{
public:
FTmodRandomize(nframes_t samplerate, unsigned int fftn);
FTmodRandomize (const FTmodRandomize & other);
virtual ~FTmodRandomize();
FTmodulatorI * clone() { return new FTmodRandomize(*this); }
void initialize();
void modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes);
protected:
Control * _rate;
Control * _minfreq;
Control * _maxfreq;
Control * _minval;
Control * _maxval;
nframes_t _lastframe;
};
#endif
| 1,436
|
C++
|
.h
| 40
| 33.9
| 120
| 0.756698
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,976
|
FTspectragram.hpp
|
essej_freqtweak/src/FTspectragram.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTSPECTRAGRAM_HPP__
#define __FTSPECTRAGRAM_HPP__
#include <wx/wx.h>
#include <wx/image.h>
#include "FTutils.hpp"
#include "FTtypes.hpp"
class FTmainwin;
class FTspectragram
: public wxPanel
{
//DECLARE_DYNAMIC_CLASS(FTspectragram)
public:
enum PlotType
{
SPECTRAGRAM = 0,
AMPFREQ_SOLID,
AMPFREQ_LINES,
};
FTspectragram(FTmainwin *mwin, wxWindow *parent, wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString& name = wxT("Spectragram"),
PlotType pt = SPECTRAGRAM);
// PlotType pt = AMPFREQ_SOLID);
// PlotType pt = AMPFREQ_LINES);
virtual ~FTspectragram();
enum ColorTableType
{
COLOR_GRAYSCALE = 0,
COLOR_BVRYW,
COLOR_GREENSCALE
};
void plotNextData (const float *data, int length);
void setPlotType (PlotType pt);
PlotType getPlotType() { return _ptype; }
void setXscale(XScaleType sc);
XScaleType getXscale() { return _xScaleType; }
void setDataLength(unsigned int len);
void OnPaint ( wxPaintEvent &event);
void OnSize ( wxSizeEvent &event);
void OnMouseActivity ( wxMouseEvent &event );
void OnXscaleMenu (wxCommandEvent &event);
float powerLogScale(float yval);
protected:
void updateSize();
void initColorTable();
void plotNextDataSpectragram (const float *data, int length);
void plotNextDataAmpFreq (const float *data, int length);
void updatePositionLabels (int pX, int pY, bool showreal);
void xToFreqRange(int x, float &fromfreq, float &tofreq, int &frombin, int &tobin);
void xToBinRange(int x, int &frombin, int &tobin);
void binToXRange(int bin, int &fromx, int &tox, int width, int bins);
bool setDiscreteColor(int index, int r, int g, int b) {
if (index < _discreteColorCount)
{
_discreteColors[index][0] = r;
_discreteColors[index][1] = g;
_discreteColors[index][2] = b;
return true;
}
return false;
}
FTmainwin * _mwin;
PlotType _ptype;
int _width, _height;
float _minCutoff;
float _dbAbsMin;
//float _dataRefMax;
float _dbAdjust;
float _yMin, _yMax;
// bitmaps
wxBitmap * _raster;
wxBitmap * _imageBuf;
wxImage * _rasterImage;
unsigned char * _rasterData;
wxPoint *_points;
// color table stuff
ColorTableType _colorTableType;
static int _maxColorCount;
static int _maxDiscreteColorCount;
static int _colorCount;
static int _discreteColorCount;
static unsigned char **_colorMap;
static unsigned char **_discreteColors;
bool _justresized;
wxBrush _fillBrush;
wxColour _fillColor;
wxPen _linePen;
float _maxval;
float _xscale;
int _length;
XScaleType _xScaleType;
wxString _freqstr;
wxMenu * _xscaleMenu;
unsigned int _dataLength;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
#endif
| 3,659
|
C++
|
.h
| 119
| 27.87395
| 84
| 0.742865
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,977
|
FTmodulatorGui.hpp
|
essej_freqtweak/src/FTmodulatorGui.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODULATORGUI_HPP__
#define __FTMODULATORGUI_HPP__
#include <wx/wx.h>
#include <map>
#include <sigc++/sigc++.h>
#include "FTtypes.hpp"
//#include "FTmodulatorI.hpp"
#include "LockMonitor.hpp"
#include "FTspectrumModifier.hpp"
class FTioSupport;
class FTmodulatorI;
class FTspectralEngine;
class FTmodulatorGui : public wxPanel
{
public:
FTmodulatorGui(FTioSupport * iosup, FTmodulatorI * mod,
wxWindow *parent, wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxRAISED_BORDER,
const wxString& name = wxT("ModulatorGui"));
virtual ~FTmodulatorGui();
sigc::signal0<void> RemovalRequest;
protected:
void init();
void onCheckboxChanged(wxCommandEvent &ev);
void onSliderChanged(wxScrollEvent &ev);
void onChoiceChanged(wxCommandEvent &ev);
void onRemoveButton (wxCommandEvent & ev);
void onAttachButton (wxCommandEvent & ev);
void onChannelButton (wxCommandEvent & ev);
void onTextEnter (wxCommandEvent &ev);
void onBypassButton (wxCommandEvent &ev);
void onModulatorDeath (FTmodulatorI * mod);
void onAttachMenu (wxCommandEvent &ev);
void onChannelMenu (wxCommandEvent &ev);
void refreshMenu();
void refreshChannelMenu();
FTmodulatorI * _modulator;
FTioSupport * _iosup;
wxTextCtrl * _nameText;
wxMenu * _popupMenu;
wxMenu * _channelPopupMenu;
// std::map<wxWindow *, FTmodulatorI::Control *> _controlMap;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
#endif
| 2,400
|
C++
|
.h
| 67
| 32.985075
| 80
| 0.753156
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,978
|
FTconfigManager.hpp
|
essej_freqtweak/src/FTconfigManager.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTCONFIGMANAGER_HPP__
#define __FTCONFIGMANAGER_HPP__
#include <wx/wx.h>
#include <wx/textfile.h>
#include "FTtypes.hpp"
#include <string>
#include <list>
#include <vector>
using namespace std;
class FTspectralEngine;
class FTspectrumModifier;
class XMLNode;
class FTprocI;
class FTconfigManager
{
public:
FTconfigManager(const std::string &basedir = "");
virtual ~FTconfigManager();
bool storeSettings (const std::string &name, bool uselast=false);
bool loadSettings (const std::string &name, bool restore_ports=false, bool uselast=false);
bool loadSettings (const std::string &name, bool restore_ports, bool ignore_iosup, vector<vector <FTprocI *> > & procvec, bool uselast);
list<std::string> getSettingsNames();
protected:
void writeFilter (FTspectrumModifier *specmod, wxTextFile & tf);
void loadFilter (FTspectrumModifier *specmod, wxTextFile & tf);
bool lookupFilterLocation (FTspectrumModifier * specmod, int & chan, int & modpos, int & filtpos);
FTspectrumModifier * lookupFilter (int chan, int modpos, int filtpos);
void loadModulators (const XMLNode * modulatorsNode);
XMLNode* find_named_node (const XMLNode * node, string name);
std::string _basedir;
class LinkCache {
public:
LinkCache (unsigned int src, unsigned int dest, unsigned int modn, unsigned int filtn)
: source_chan(src), dest_chan(dest), mod_n(modn), filt_n(filtn) {}
unsigned int source_chan;
unsigned int dest_chan;
unsigned int mod_n;
unsigned int filt_n;
};
list<LinkCache> _linkCache;
};
#endif
| 2,353
|
C++
|
.h
| 60
| 36.883333
| 137
| 0.757951
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,979
|
spin_box.hpp
|
essej_freqtweak/src/spin_box.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __sooperlooper_gui_spin_box__
#define __sooperlooper_gui_spin_box__
#include <wx/wx.h>
#include <sigc++/sigc++.h>
namespace JLCui {
class SpinBox
: public wxWindow
{
public:
// ctor(s)
SpinBox(wxWindow * parent, wxWindowID id=-1, float lb=0.0f, float ub=1.0f, float val=0.5f, bool midibindable=true,
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize);
virtual ~SpinBox();
enum ScaleMode {
LinearMode = 0,
ZeroGainMode
};
enum SnapMode {
NoSnap = 0,
IntegerSnap
};
virtual bool SetFont(const wxFont & fnt);
void set_bounds (float lb, float ub);
void get_bounds (float &lb, float &ub) { lb = _lower_bound; ub = _upper_bound; }
void set_value (float val);
float get_value ();
void set_default_value (float val) { _default_val = val; }
float get_default_value () { return _default_val; }
void set_label (const wxString &label);
wxString get_label () { return _label_str; }
void set_units (const wxString &units);
wxString get_units () { return _units_str; }
void set_scale_mode (ScaleMode mode);
ScaleMode get_scale_mode () { return _scale_mode; }
void set_snap_mode (SnapMode mode);
SnapMode get_snap_mode () { return _snap_mode; }
void set_allow_outside_bounds (bool val) { _oob_flag = val; }
bool get_allow_outside_bounds () { return _oob_flag; }
void set_show_value (bool val) { _showval_flag = val; }
bool get_show_value () { return _showval_flag; }
void set_bg_color (const wxColour & col);
wxColour & get_bg_color () { return _bgcolor; }
void set_bar_color (const wxColour & col);
wxColour & get_bar_color () { return _barcolor; }
void set_text_color (const wxColour & col);
wxColour & get_text_color () { return _textcolor; }
void set_value_color (const wxColour & col);
wxColour & get_value_color () { return _valuecolor; }
void set_border_color (const wxColour & col);
wxColour & get_border_color () { return _bordercolor; }
void set_decimal_digits (int num);
int get_decimal_digits () { return _decimal_digits; }
float get_increment () { return _increment; }
void set_increment (float val) { _increment = val; }
sigc::signal0<void> pressed;
sigc::signal0<void> released;
sigc::signal1<void, float> value_changed;
sigc::signal0<void> bind_request;
protected:
void OnPaint (wxPaintEvent &ev);
void OnSize (wxSizeEvent &ev);
void OnMouseEvents (wxMouseEvent &ev);
void OnFocusEvent (wxFocusEvent &ev);
void draw_area (wxDC & dc);
void update_size();
void update_bar_shape();
void show_text_ctrl ();
void hide_text_ctrl ();
void on_text_event (wxCommandEvent &ev);
void on_menu_events (wxCommandEvent &ev);
void on_update_timer (wxTimerEvent &ev);
void update_value_str();
wxString get_precise_value_str();
int _width, _height;
wxBitmap * _backing_store;
wxMemoryDC _memdc;
wxMenu * _popup_menu;
wxColour _bgcolor;
wxBrush _bgbrush;
wxColour _barcolor;
wxColour _overbarcolor;
wxBrush _barbrush;
wxColour _bordercolor;
wxBrush _borderbrush;
wxPen _borderpen;
wxBrush _linebrush;
wxColour _textcolor;
wxColour _valuecolor;
float _value;
float _default_val;
float _lower_bound, _upper_bound;
float _increment;
float _direction;
wxString _value_str;
wxString _label_str;
wxString _units_str;
class HidingTextCtrl : public wxTextCtrl {
public:
HidingTextCtrl (wxWindow* par, wxWindowID id, const wxString & value = wxT(""), const wxPoint & pos = wxDefaultPosition,
const wxSize & size = wxDefaultSize, long style = 0)
: wxTextCtrl (par, id, value, pos, size, style) {}
virtual ~HidingTextCtrl() {}
void on_focus_event(wxFocusEvent &ev);
private:
DECLARE_EVENT_TABLE()
};
HidingTextCtrl * _text_ctrl;
bool _dragging;
bool _ignoretext;
long _press_time;
float _val_scale;
ScaleMode _scale_mode;
SnapMode _snap_mode;
int _decimal_digits;
bool _oob_flag;
bool _showval_flag;
wxTimer *_update_timer;
float _curr_adjust;
long _curr_timeout;
wxPoint _border_shape[8];
wxPoint _bar_shape[8];
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
};
#endif
| 4,996
|
C++
|
.h
| 145
| 31.751724
| 122
| 0.719228
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,980
|
xml++.hpp
|
essej_freqtweak/src/xml++.hpp
|
/* xml++.h
* libxml++ and this file are copyright (C) 2000 by Ari Johnson, and
* are covered by the GNU Lesser General Public License, which should be
* included with libxml++ as the file COPYING.
*/
#include <string>
#include <list>
#include <map>
#include <cstdio>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <stdarg.h>
#ifndef __XMLPP_H
#define __XMLPP_H
using std::string;
using std::map;
using std::list;
class XMLTree;
class XMLNode;
typedef list<XMLNode *> XMLNodeList;
typedef XMLNodeList::iterator XMLNodeIterator;
typedef XMLNodeList::const_iterator XMLNodeConstIterator;
class XMLProperty;
typedef list<XMLProperty*> XMLPropertyList;
typedef XMLPropertyList::iterator XMLPropertyIterator;
typedef XMLPropertyList::const_iterator XMLPropertyConstIterator;
typedef map<string, XMLProperty*> XMLPropertyMap;
class XMLTree {
private:
string _filename;
XMLNode *_root;
int _compression;
bool _initialized;
public:
XMLTree() : _filename(), _root(0), _compression(0), _initialized(false) { };
XMLTree(const string &fn)
: _filename(fn), _root(0), _compression(0), _initialized(false) { read(); };
XMLTree(const XMLTree *);
~XMLTree();
bool initialized() const { return _initialized; };
XMLNode *root() const { return _root; };
XMLNode *set_root(XMLNode *n) { return _root = n; };
const string & filename() const { return _filename; };
const string & set_filename(const string &fn) { return _filename = fn; };
int compression() const { return _compression; };
int set_compression(int);
bool read();
bool read(const string &fn) { set_filename(fn); return read(); };
bool read_buffer(const string &);
bool write() const;
bool write(const string &fn) { set_filename(fn); return write(); };
const string & write_buffer() const;
};
class XMLNode {
private:
bool _initialized;
string _name;
bool _is_content;
string _content;
XMLNodeList _children;
XMLPropertyList _proplist;
XMLPropertyMap _propmap;
public:
XMLNode(const string &);
XMLNode(const string &, const string &);
XMLNode(const XMLNode&);
~XMLNode();
bool initialized() const { return _initialized; };
const string name() const { return _name; };
bool is_content() const { return _is_content; };
const string & content() const { return _content; };
const string & set_content(const string &);
XMLNode *add_content(const string & = string());
const XMLNodeList & children(const string & = string()) const;
XMLNode *add_child(const string &);
XMLNode *add_child_copy(const XMLNode&);
void add_child_nocopy (XMLNode&);
const XMLPropertyList & properties() const { return _proplist; };
XMLProperty *property(const string &);
const XMLProperty *property(const string &n) const
{ return ((XMLNode *) this)->property(n); };
XMLProperty *add_property(const string &, const string & = string());
void remove_property(const string &);
/** Remove all nodes with the name passed to remove_nodes */
void remove_nodes(const string &);
};
class XMLProperty {
private:
string _name;
string _value;
public:
XMLProperty(const string &n, const string &v = string())
: _name(n), _value(v) { };
const string & name() const { return _name; };
const string & value() const { return _value; };
const string & set_value(const string &v) { return _value = v; };
};
#endif /* __XML_H */
| 3,380
|
C++
|
.h
| 98
| 32.040816
| 78
| 0.715075
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,981
|
RingBuffer.hpp
|
essej_freqtweak/src/RingBuffer.hpp
|
/*
Copyright (C) 2000 Paul Barton-Davis
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 2 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.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301 USA.
$Id: RingBuffer.hpp,v 1.1.1.1 2002/10/13 04:13:34 essej Exp $
*/
#ifndef __pbd_ringbuffer_h__
#define __pbd_ringbuffer_h__
#include <sys/types.h>
class RingBuffer
{
public:
RingBuffer (int sz) {
int power_of_two;
for (power_of_two = 1;
1<<power_of_two < sz;
power_of_two++);
size = 1<<power_of_two;
size_mask = size;
size_mask -= 1;
write_ptr = 0;
read_ptr = 0;
buf = new char[size];
mlocked = false;
};
virtual ~RingBuffer();
void reset () {
/* How can this be thread safe ? */
read_ptr = 0;
write_ptr = 0;
}
void mem_set ( char val);
int mlock ();
size_t read (char *dest, size_t cnt);
size_t write (char *src, size_t cnt);
struct rw_vector {
char *buf;
size_t len;
};
void get_read_vector (rw_vector *);
void get_write_vector (rw_vector *);
void write_advance (size_t cnt) {
write_ptr += cnt;
write_ptr &= size_mask;
}
void read_advance (size_t cnt) {
read_ptr += cnt;
read_ptr &= size_mask;
}
size_t write_space () {
size_t w, r;
w = write_ptr;
r = read_ptr;
if (w > r) {
return ((r - w + size) & size_mask) - 1;
} else if (w < r) {
return (r - w) - 1;
} else {
return size - 1;
}
}
size_t read_space () {
size_t w, r;
w = write_ptr;
r = read_ptr;
if (w > r) {
return w - r;
} else {
return (w - r + size) & size_mask;
}
}
protected:
char *buf;
volatile size_t write_ptr;
volatile size_t read_ptr;
size_t size;
size_t size_mask;
bool mlocked;
};
#endif /* __pbd_ringbuffer_h__ */
| 2,498
|
C++
|
.h
| 90
| 22.422222
| 72
| 0.604132
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,982
|
FTupdateToken.hpp
|
essej_freqtweak/src/FTupdateToken.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTUPDATETOKEN_HPP__
#define __FTUPDATETOKEN_HPP__
class FTupdateToken
{
public:
FTupdateToken() : _updated(false), _ignore(false) {};
virtual ~FTupdateToken(){}
void setUpdated (bool flag) { _updated = flag; }
// this is as close of a test-and-set as I need
bool getUpdated (bool tas=false)
{
if (_updated) {
_updated = tas;
return true;
}
return false;
}
void setIgnore (bool flag) { _ignore = flag; }
bool getIgnore() { return _ignore;}
protected:
volatile bool _updated;
bool _ignore;
};
#endif
| 1,342
|
C++
|
.h
| 42
| 29.761905
| 80
| 0.728261
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,983
|
FTmodValueLFO.hpp
|
essej_freqtweak/src/FTmodValueLFO.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODVALUELFO_HPP__
#define __FTMODVALUELFO_HPP__
#include "FTmodulatorI.hpp"
#include <map>
class FTmodValueLFO
: public FTmodulatorI
{
public:
FTmodValueLFO(nframes_t samplerate, unsigned int fftn);
FTmodValueLFO (const FTmodValueLFO & other);
virtual ~FTmodValueLFO();
FTmodulatorI * clone() { return new FTmodValueLFO(*this); }
void initialize();
void modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes);
void setFFTsize (unsigned int fftn);
void addSpecMod (FTspectrumModifier * specmod);
void removeSpecMod (FTspectrumModifier * specmod);
void clearSpecMods ();
protected:
Control * _rate;
Control * _depth;
Control * _lfotype;
Control * _minfreq;
Control * _maxfreq;
nframes_t _lastframe;
std::map<FTspectrumModifier *, double> _lastshifts;
float * _tmpfilt;
};
#endif
| 1,684
|
C++
|
.h
| 47
| 33.723404
| 120
| 0.758663
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,984
|
FTjackSupport.hpp
|
essej_freqtweak/src/FTjackSupport.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
/**
* Supports operations concerning I/O with JACK
*/
#ifndef __FTJACKSUPPORT_HPP__
#define __FTJACKSUPPORT_HPP__
#include <jack/jack.h>
#include "FTtypes.hpp"
#include "FTioSupport.hpp"
#include <string>
#include <list>
using namespace std;
class FTprocessPath;
struct PathInfo
{
FTprocessPath * procpath;
jack_port_t * inputport;
jack_port_t * outputport;
bool active;
list<string> inconn_list;
list<string> outconn_list;
};
class FTjackSupport
: public FTioSupport
{
public:
FTjackSupport(const char * name="", const char * dir="");
virtual ~FTjackSupport();
bool init();
bool reinit(bool rebuild=true);
bool isInited() { return _inited; }
//bool setProcessPath(FTprocessPath *ppath, int index);
FTprocessPath * setProcessPathActive(int index, bool flag);
FTprocessPath * getProcessPath(int index)
{ if(index >=0 && index<FT_MAXPATHS && _pathInfos[index]) return _pathInfos[index]->procpath;
return 0; }
int getActivePathCount () { return _activePathCount; }
bool startProcessing();
bool stopProcessing();
bool close();
bool connectPathInput (int index, const char *inname);
bool connectPathOutput (int index, const char *outname);
bool disconnectPathInput (int index, const char *inname);
bool disconnectPathOutput (int index, const char *outname);
const char ** getConnectedInputPorts(int index);
const char ** getConnectedOutputPorts(int index);
const char ** getInputConnectablePorts(int index);
const char ** getOutputConnectablePorts(int index);
const char ** getPhysicalInputPorts();
const char ** getPhysicalOutputPorts();
const char * getInputPortName(int index);
const char * getOutputPortName(int index);
bool inAudioThread();
nframes_t getSampleRate() { return _sampleRate; }
nframes_t getTransportFrame();
bool getPortsChanged() { return _portsChanged; }
void setProcessingBypassed (bool val);
protected:
// JACK callbacks are static
static int processCallback (jack_nframes_t nframes, void *arg);
static int srateCallback (jack_nframes_t nframes, void *arg);
static void jackShutdown (void *arg);
static int portsChanged (jack_port_id_t port, int blah, void *arg);
bool _inited;
jack_client_t * _jackClient;
jack_nframes_t _sampleRate;
jack_nframes_t _maxBufsize;
// FIXME: use real data structure
PathInfo* _pathInfos[FT_MAXPATHS];
int _activePathCount;
//char _name[100];
string _jackserv;
bool _portsChanged;
bool _activated;
bool _bypassed;
};
#endif
| 3,317
|
C++
|
.h
| 94
| 32.585106
| 95
| 0.752204
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,985
|
FTprocBoost.hpp
|
essej_freqtweak/src/FTprocBoost.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCBOOST_HPP__
#define __FTPROCBOOST_HPP__
#include "FTprocI.hpp"
class FTprocBoost
: public FTprocI
{
public:
FTprocBoost(nframes_t samprate, unsigned int fftn);
FTprocBoost (const FTprocBoost & other);
virtual ~FTprocBoost();
FTprocI * clone() { return new FTprocBoost(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
virtual bool useAsDefault() { return false; }
protected:
FTspectrumModifier * _eqfilter;
};
#endif
| 1,282
|
C++
|
.h
| 36
| 33.638889
| 80
| 0.753247
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,986
|
FTmodulatorManager.hpp
|
essej_freqtweak/src/FTmodulatorManager.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTMODULATORMANAGER_HPP__
#define __FTMODULATORMANAGER_HPP__
#include "FTtypes.hpp"
#include <list>
#include <string>
using namespace std;
class FTmodulatorI;
class FTmodulatorManager
{
public:
typedef list<FTmodulatorI*> ModuleList;
FTmodulatorManager();
virtual ~FTmodulatorManager();
static FTmodulatorManager * instance() { if (!_instance) _instance = new FTmodulatorManager(); return _instance; }
void getAvailableModules (ModuleList & outlist);
FTmodulatorI * getModuleByName (const string & name);
FTmodulatorI * getModuleByConfigName (const string & name);
FTmodulatorI * getModuleByIndex (unsigned int index);
protected:
ModuleList _prototypes;
static FTmodulatorManager* _instance;
};
#endif
| 1,536
|
C++
|
.h
| 41
| 35.463415
| 115
| 0.772666
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,987
|
FTprocDelay.hpp
|
essej_freqtweak/src/FTprocDelay.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCDELAY_HPP__
#define __FTPROCDELAY_HPP__
#include "FTprocI.hpp"
class RingBuffer;
class FTprocDelay
: public FTprocI
{
public:
FTprocDelay (nframes_t samprate, unsigned int fftn);
FTprocDelay (const FTprocDelay & other);
virtual ~FTprocDelay();
FTprocI * clone() { return new FTprocDelay(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
void reset();
void setMaxDelay(float secs);
protected:
FTspectrumModifier * _delayFilter;
FTspectrumModifier * _feedbackFilter;
// this is a very large ringbuffer
// used to store the fft results over time
// each frame is stored sequentially.
// the length is determined by the maximum delay time
RingBuffer *_frameFifo;
unsigned long _maxDelaySamples;
float _maxDelay;
};
#endif
| 1,600
|
C++
|
.h
| 46
| 32.630435
| 80
| 0.760941
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,988
|
FTtypes.hpp
|
essej_freqtweak/src/FTtypes.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTTYPES_HPP__
#define __FTTYPES_HPP__
#include <inttypes.h>
// these should match jack's types but we'll avoid the include
// for now
typedef float sample_t;
typedef uint32_t nframes_t;
typedef float fft_data;
#define FT_MAXPATHS 4
#define FT_FIFOLENGTH (1 << 18)
#define FT_MAX_FFT_SIZE 16384
#define FT_MAX_FFT_SIZE_HALF (FT_MAX_FFT_SIZE / 2)
#define FT_MAX_AVERAGES 128
#define FT_MAX_OVERSAMP 16
enum SpecModType {
ALL_SPECMOD = 0,
FREQ_SPECMOD,
DELAY_SPECMOD,
FEEDB_SPECMOD,
SCALE_SPECMOD,
GATE_SPECMOD,
SQUELCH_SPECMOD,
MASH_SPECMOD,
WARP_SPECMOD,
EXPAND_SPECMOD,
COMPRESS_SPECMOD,
BOOST_SPECMOD,
RESCUT_SPECMOD,
RESCUTEQ_SPECMOD
};
enum XScaleType
{
XSCALE_1X = 0, // 1:1 plot bin to filter bin
XSCALE_2X, // ~ 2:1 " with last bin representing the entire upper half
XSCALE_3X, // ~ 3:1 " with last 2 bins representing to upper thirds
XSCALE_4X, // ~ 4:1 " with last 3 bins representing each upper 1/4
XSCALE_LOGA, // pseudo-log scale with lower freqs having bigger bins
XSCALE_LOGB, // pseudo-log scale with lower freqs having bigger bins
};
enum YScaleType
{
YSCALE_1X, //
YSCALE_2X, //
YSCALE_3X, //
YSCALE_4X, //
};
#endif
| 1,987
|
C++
|
.h
| 65
| 28.723077
| 80
| 0.745273
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,989
|
FTactiveBarGraph.hpp
|
essej_freqtweak/src/FTactiveBarGraph.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTACTIVEBARGRAPH_HPP__
#define __FTACTIVEBARGRAPH_HPP__
#include <list>
#include <vector>
#include <string>
using namespace std;
#include <wx/wx.h>
#include "FTtypes.hpp"
#include "FTutils.hpp"
#include "FTspectrumModifier.hpp"
class FTmainwin;
class FTactiveBarGraph
: public wxPanel, public FTspectrumModifier::Listener
{
public:
FTactiveBarGraph(FTmainwin *win, wxWindow *parent, wxWindowID id,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString& name = wxT("ActiveBarGraph"));
virtual ~FTactiveBarGraph();
void setSpectrumModifier (FTspectrumModifier *sm);
FTspectrumModifier * getSpectrumModifier() { return _specMod; }
void setTopSpectrumModifier (FTspectrumModifier *sm);
FTspectrumModifier * getTopSpectrumModifier() { return _topSpecMod; }
void setXscale(XScaleType sc, bool writeextra=true);
XScaleType getXscale() { return _xScaleType; }
bool setMinMax(float min, float max);
void getMinMax(float &min, float &max) { min=_min; max=_max; }
void setFixMin (bool flag);
bool getFixMin () { return _fixMin; }
void setGridLines (bool flag, bool writeextra=true);
bool getGridLines() { return _gridFlag; }
void setGridSnap (bool flag, bool writeextra=true);
bool getGridSnap () { return _gridSnapFlag; }
void OnPaint ( wxPaintEvent &event);
void OnSize ( wxSizeEvent &event);
void OnMouseActivity ( wxMouseEvent &event );
void OnXscaleMenu (wxCommandEvent &event);
void setBypassed (bool flag) { _bypassed = flag; Refresh(FALSE);}
bool getBypassed () { return _bypassed; }
const vector<wxString> & getGridChoiceStrings() { return _gridChoices; }
void setGridChoice (unsigned int , bool writeextra=true);
unsigned int getGridChoice () { return _gridChoiceIndex; }
void setTempo(int bpm);
int getTempo() { return _tempo; }
// listener
void goingAway (FTspectrumModifier * specmod);
void refreshBounds();
void recalculate();
void writeExtra(FTspectrumModifier * sp);
void readExtra(FTspectrumModifier * sp);
protected:
void updateSize();
void xToBinRange(int x, int &frombin, int &tobin);
void binToXRange(int bin, int &fromx, int &tox);
int xDeltaToBinDelta(int xdelt);
void xToFreqRange(int x, float &fromfreq, float &tofreq, int &frombin, int &tobin);
int valToY(float val);
float yToVal(int y);
inline float valToDb(float val);
inline float dbToVal(float db);
inline float valToSemi(float val);
inline float semiToVal(float semi);
float yToDb(int y);
float yToSemi(int y);
float valDiffY(float val, int lasty, int newy);
void updatePositionLabels(int pX, int pY, bool showreal=false, FTspectrumModifier *specmod=0);
void paintGridlines(wxDC & dc);
float snapValue(float val);
void makeGridChoices(bool setdefault=false);
int _width, _height;
int _plotWidth, _plotHeight;
int _leftWidth;
int _topHeight;
int _rightWidth;
int _bottomHeight;
FTspectrumModifier * _specMod;
FTspectrumModifier * _topSpecMod;
float _min, _max;
float _absmin, _absmax;
float _xscale;
float _mindb, _maxdb;
float _absmindb, _absmaxdb;
float _absposmindb, _absposmaxdb;
float _minsemi, _maxsemi;
float _absminsemi, _absmaxsemi;
float *_tmpfilt, *_toptmpfilt;
wxColour _barColor0,_barColor1;
wxColour _barColor2,_barColor3, _barColorDead, _tipColor;
wxBrush _barBrush0, _barBrush1, _barBrush2, _barBrush3, _barBrushDead ,_tipBrush;
wxBrush _bypassBrush;
wxBrush _bgBrush;
wxColour _penColor;
wxPen _barPen;
wxColour _gridColor;
wxPen _gridPen;
wxBitmap * _backingMap;
XScaleType _xScaleType;
bool _fixMin;
YScaleType _yScaleType;
// mouse stuff
int _lastX, _lastY;
int _firstX, _firstY;
float _lastVal;
bool _dragging;
bool _firstCtrl, _firstMove;
bool _zooming;
int _topzoomY, _bottomzoomY;
wxString _freqstr, _valstr;
wxMenu * _xscaleMenu;
FTmainwin * _mainwin;
list<int> _gridPoints;
bool _gridFlag;
bool _gridSnapFlag;
bool _mouseCaptured;
bool _bypassed;
vector<wxString> _gridChoices;
vector<float> _gridValues;
float _gridFactor;
unsigned int _gridChoiceIndex;
wxFont _boundsFont;
wxColour _textColor;
FTspectrumModifier::ModifierType _mtype;
wxString _maxstr, _minstr;
// tempo for time only
int _tempo;
unsigned int _beatscutoff;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
inline float FTactiveBarGraph::valToDb(float val)
{
// assumes 0 <= yval <= 1
if (val <= 0.0) {
// negative infinity really
return -200.0;
}
//float nval = (20.0 * FTutils::fast_log10(yval / refmax));
float nval = (20.0 * FTutils::fast_log10(val));
// printf ("scaled value is %g mincut=%g\n", nval, _minCutoff);
return nval;
}
inline float FTactiveBarGraph::dbToVal(float db)
{
//float nval = (20.0 * FTutils::fast_log10(yval / refmax));
float nval = pow ( (float)10.0, db/20);
// printf ("scaled value is %g mincut=%g\n", nval, _minCutoff);
return nval;
}
inline float FTactiveBarGraph::semiToVal(float semi)
{
float val = pow (2.0, semi/12.0);
// printf ("scaled value is %g mincut=%g\n", nval, _minCutoff);
return val;
}
inline float FTactiveBarGraph::valToSemi(float val)
{
// assumes 0 <= yval <= 1
if (val <= 0.0) {
// invalid
return 0.0;
}
float semi = 12.0 * FTutils::fast_log2(val);
return semi;
}
#endif
| 6,194
|
C++
|
.h
| 186
| 30.704301
| 95
| 0.746056
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,990
|
FTprocI.hpp
|
essej_freqtweak/src/FTprocI.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCI_HPP__
#define __FTPROCI_HPP__
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "FTtypes.hpp"
#include "xml++.hpp"
#include <map>
#include <list>
#include <vector>
#include <string>
using namespace std;
#include "FTtypes.hpp"
#include "FTspectrumModifier.hpp"
// Limit a value to be l<=v<=u
#define LIMIT(v,l,u) ((v)<(l)?(l):((v)>(u)?(u):(v)))
// to handle denormals
#define FLUSH_TO_ZERO(fv) (((*(unsigned int*)&(fv))&0x7f800000)==0)?0.0f:(fv)
class FTprocI
{
public:
//typedef map<string, FTspectrumModifier *> FilterMap;
typedef vector<FTspectrumModifier *> FilterList;
virtual ~FTprocI();
virtual FTprocI * clone() = 0;
virtual void initialize() = 0;
virtual void process (fft_data *data, unsigned int fftn) = 0;
virtual void setBypassed (bool flag);
virtual void setId (int id);
//virtual bool getBypassed () { return _bypassed; }
virtual FTspectrumModifier * getFilter(unsigned int n) {
if (n < _filterlist.size()) {
return _filterlist[n];
}
return 0;
}
virtual void getFilters (vector<FTspectrumModifier *> & filtlist) {
filtlist.clear();
for (FilterList::iterator filt = _filterlist.begin();
filt != _filterlist.end(); ++filt)
{
filtlist.push_back ((*filt));
}
}
virtual void setFFTsize (unsigned int fftn) {
_fftN = fftn;
for (FilterList::iterator filt = _filterlist.begin();
filt != _filterlist.end(); ++filt)
{
(*filt)->setLength (fftn/2);
}
}
virtual void setSampleRate (nframes_t rate) { _sampleRate = rate; }
virtual nframes_t getSampleRate() { return _sampleRate; }
virtual void setOversamp (int osamp) { _oversamp = osamp; }
virtual int getOversamp() { return _oversamp; }
virtual void setName (const string & name) { _name = name; }
virtual const string & getName() { return _name; }
virtual const string & getConfName() { return _confname; }
virtual void setMaxDelay(float secs) {}
virtual void reset() {}
virtual bool useAsDefault() { return true; }
protected:
FTprocI (const string & name, nframes_t samprate, unsigned int fftn);
bool _bypassed;
nframes_t _sampleRate;
unsigned int _fftN;
int _oversamp;
bool _inited;
FilterList _filterlist;
int _id;
string _name;
string _confname;
};
#endif
| 3,065
|
C++
|
.h
| 93
| 30.387097
| 80
| 0.714774
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,991
|
FTprocPitch.hpp
|
essej_freqtweak/src/FTprocPitch.hpp
|
/*
** Copyright (C) 2003 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCPITCH_HPP__
#define __FTPROCPITCH_HPP__
#include "FTprocI.hpp"
class FTprocPitch
: public FTprocI
{
public:
FTprocPitch (nframes_t samprate, unsigned int fftn);
FTprocPitch (const FTprocPitch & other);
virtual ~FTprocPitch();
FTprocI * clone() { return new FTprocPitch(*this); }
void initialize();
void process (fft_data *data, unsigned int fftn);
protected:
FTspectrumModifier * _filter;
// stuff for pitchscaling
float *gLastPhase, *gSumPhase, *gAnaFreq, *gSynFreq, *gAnaMagn, *gSynMagn;
};
#endif
| 1,337
|
C++
|
.h
| 37
| 34.135135
| 80
| 0.753307
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,992
|
slider_bar.hpp
|
essej_freqtweak/src/slider_bar.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __sooperlooper_gui_slider_bar__
#define __sooperlooper_gui_slider_bar__
#include <wx/wx.h>
#include <sigc++/sigc++.h>
namespace JLCui {
class SliderBar
: public wxWindow
{
public:
// ctor(s)
SliderBar(wxWindow * parent, wxWindowID id=-1, float lb=0.0f, float ub=1.0f, float val=0.5f, bool midibindable=true,
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize);
virtual ~SliderBar();
enum BarStyle {
FromLeftStyle=0,
CenterStyle,
FromRightStyle,
HiddenStyle
};
enum ScaleMode {
LinearMode = 0,
ZeroGainMode
};
enum SnapMode {
NoSnap = 0,
IntegerSnap
};
virtual bool SetFont(const wxFont & fnt);
void set_style (BarStyle md);
BarStyle get_style () { return _bar_style;}
void set_bounds (float lb, float ub);
void get_bounds (float &lb, float &ub) { lb = _lower_bound; ub = _upper_bound; }
void set_value (float val, bool refresh=true);
float get_value ();
void set_show_indicator_bar (bool flag) { _show_ind_bar = flag; }
bool get_show_indicator_bar () { return _show_ind_bar; }
void set_indicator_value (float val);
float get_indicator_value ();
void set_default_value (float val) { _default_val = val; }
float get_default_value () { return _default_val; }
void set_label (const wxString &label);
wxString get_label () { return _label_str; }
void set_units (const wxString &units);
wxString get_units () { return _units_str; }
void set_scale_mode (ScaleMode mode);
ScaleMode get_scale_mode () { return _scale_mode; }
void set_snap_mode (SnapMode mode);
SnapMode get_snap_mode () { return _snap_mode; }
void set_allow_outside_bounds (bool val) { _oob_flag = val; }
bool get_allow_outside_bounds () { return _oob_flag; }
void set_show_value (bool val) { _showval_flag = val; }
bool get_show_value () { return _showval_flag; }
void set_bg_color (const wxColour & col);
wxColour & get_bg_color () { return _bgcolor; }
void set_bar_color (const wxColour & col);
wxColour & get_bar_color () { return _barcolor; }
void set_text_color (const wxColour & col);
wxColour & get_text_color () { return _textcolor; }
void set_value_color (const wxColour & col);
wxColour & get_value_color () { return _valuecolor; }
void set_border_color (const wxColour & col);
wxColour & get_border_color () { return _bordercolor; }
void set_indicator_bar_color (const wxColour & col);
wxColour & get_indicator_bar_color () { return _indcolor; }
void set_indicator_max_bar_color (const wxColour & col);
wxColour & get_indicator_max_bar_color () { return _indmaxcolor; }
void set_decimal_digits (int num);
int get_decimal_digits () { return _decimal_digits; }
sigc::signal0<void> pressed;
sigc::signal0<void> released;
sigc::signal1<void, float> value_changed;
sigc::signal0<void> bind_request;
protected:
void OnPaint (wxPaintEvent &ev);
void OnSize (wxSizeEvent &ev);
void OnMouseEvents (wxMouseEvent &ev);
void do_redraw ();
void draw_area (wxDC & dc);
void draw_ind (wxDC & dc);
void update_size();
void show_text_ctrl ();
void hide_text_ctrl ();
void on_text_event (wxCommandEvent &ev);
void on_menu_events (wxCommandEvent &ev);
void update_value_str();
wxString get_precise_value_str();
int _width, _height;
wxBitmap * _backing_store;
wxMemoryDC _memdc;
wxMemoryDC _inddc;
wxBitmap * _indbm;
wxMenu * _popup_menu;
wxColour _bgcolor;
wxBrush _bgbrush;
wxColour _barcolor;
wxColour _overbarcolor;
wxBrush _barbrush;
wxColour _bordercolor;
wxBrush _borderbrush;
wxPen _borderpen;
wxBrush _linebrush;
wxColor _indcolor;
wxColor _indmaxcolor;
wxBrush _indbrush;
wxBrush _indmaxbrush;
wxColour _textcolor;
wxColour _valuecolor;
float _value;
float _default_val;
bool _show_ind_bar;
float _ind_value;
float _lower_bound, _upper_bound;
bool _use_pending;
float _pending_val;
wxString _value_str;
wxString _label_str;
wxString _units_str;
BarStyle _bar_style;
class HidingTextCtrl : public wxTextCtrl {
public:
HidingTextCtrl (wxWindow* par, wxWindowID id, const wxString & value = wxT(""), const wxPoint & pos = wxDefaultPosition,
const wxSize & size = wxDefaultSize, long style = 0)
: wxTextCtrl (par, id, value, pos, size, style) {}
virtual ~HidingTextCtrl() {}
void on_focus_event(wxFocusEvent &ev);
private:
DECLARE_EVENT_TABLE()
};
HidingTextCtrl * _text_ctrl;
bool _dragging;
int _last_x;
bool _ignoretext;
float _val_scale;
ScaleMode _scale_mode;
SnapMode _snap_mode;
int _decimal_digits;
bool _oob_flag;
bool _showval_flag;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
};
#endif
| 5,541
|
C++
|
.h
| 162
| 31.493827
| 122
| 0.720038
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,993
|
FTpresetBlender.hpp
|
essej_freqtweak/src/FTpresetBlender.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPRESETBLENDER_HPP__
#define __FTPRESETBLENDER_HPP__
#include "FTtypes.hpp"
#include <string>
#include <list>
#include <vector>
using namespace std;
class FTprocI;
class FTconfigManager;
class FTspectrumModifier;
class FTpresetBlender
{
public:
FTpresetBlender(FTconfigManager * confman);
virtual ~FTpresetBlender();
bool setPreset(const string & name, int index);
string getPreset(int index);
bool setBlend (unsigned int specmod_n, unsigned int filt_n, float val);
float getBlend (unsigned int specmod_n, unsigned int filt_n);
protected:
void blendFilters (FTspectrumModifier * targFilt, FTspectrumModifier *filt0, FTspectrumModifier *filt1, float val);
vector <vector<vector <FTprocI*> > *> _presetList;
vector <string> _presetNames;
FTconfigManager * _configMan;
FTpresetBlender * _presetBlender;
};
#endif
| 1,653
|
C++
|
.h
| 45
| 34.666667
| 116
| 0.77224
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,994
|
pix_button.hpp
|
essej_freqtweak/src/pix_button.hpp
|
/*
** Copyright (C) 2004 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __sooperlooper_gui_pix_button__
#define __sooperlooper_gui_pix_button__
#include <wx/wx.h>
#include <sigc++/sigc++.h>
namespace JLCui {
class PixButton
: public wxWindow
{
public:
// ctor(s)
PixButton(wxWindow * parent, wxWindowID id=-1, bool midibindable=true, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize);
virtual ~PixButton();
void set_normal_bitmap (const wxBitmap & bm);
void set_focus_bitmap (const wxBitmap & bm);
void set_selected_bitmap (const wxBitmap & bm);
void set_disabled_bitmap (const wxBitmap & bm);
void set_active_bitmap (const wxBitmap & bm);
wxBitmap & get_normal_bitmap() { return _normal_bitmap;}
wxBitmap & get_focus_bitmap() { return _focus_bitmap; }
wxBitmap & get_selected_bitmap() { return _selected_bitmap; }
wxBitmap & get_disabled_bitmap() { return _disabled_bitmap; }
wxBitmap & get_active_bitmap() { return _active_bitmap; }
void set_active(bool flag);
bool get_active() { return _active; }
void set_bg_color (const wxColour & col);
wxColour & get_bg_color () { return _bgcolor; }
enum MouseButton {
LeftButton=1,
MiddleButton,
RightButton
};
// int argument is mouse button as above
sigc::signal1<void,int> pressed;
sigc::signal1<void,int> released;
sigc::signal1<void,int> clicked;
sigc::signal0<void> enter;
sigc::signal0<void> leave;
sigc::signal0<void> bind_request;
protected:
enum ButtonState {
Normal,
Selected,
Disabled
};
enum EnterState {
Inside,
Outside
};
void OnPaint (wxPaintEvent &ev);
void OnSize (wxSizeEvent &ev);
void OnMouseEvents (wxMouseEvent &ev);
void on_menu_events (wxCommandEvent &ev);
void draw_area (wxDC & dc);
void update_size();
wxBitmap _normal_bitmap;
wxBitmap _focus_bitmap;
wxBitmap _selected_bitmap;
wxBitmap _disabled_bitmap;
wxBitmap _active_bitmap;
ButtonState _bstate;
EnterState _estate;
bool _active;
int _width, _height;
wxColour _bgcolor;
wxBrush _bgbrush;
wxBitmap * _backing_store;
wxMemoryDC _memdc;
wxMenu * _popup_menu;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
};
#endif
| 2,978
|
C++
|
.h
| 92
| 29.880435
| 148
| 0.742777
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,532,995
|
FTprocOrderDialog.hpp
|
essej_freqtweak/src/FTprocOrderDialog.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPROCORDERDIALOG_HPP__
#define __FTPROCORDERDIALOG_HPP__
#include <list>
using namespace std;
#include <wx/wx.h>
#include "FTtypes.hpp"
class FTprocI;
class FTmainwin;
class wxListCtrl;
class FTprocOrderDialog : public wxFrame
{
public:
// ctor(s)
FTprocOrderDialog(FTmainwin * parent, wxWindowID id, const wxString& title,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400,600),
long style = wxDEFAULT_FRAME_STYLE,
const wxString& name = wxT("ProcOrderDialog"));
virtual ~FTprocOrderDialog();
void refreshState();
protected:
class ModAction
{
public:
ModAction (FTprocI *pm, int frm , int toi, bool rem)
: from(frm), to(toi), remove(rem), procmod(pm) {}
ModAction (const ModAction & o)
: from(o.from), to(o.to), remove(o.remove), procmod(o.procmod) {}
int from;
int to;
bool remove;
FTprocI * procmod;
};
void init();
void onClose(wxCloseEvent & ev);
void onCommit(wxCommandEvent & ev);
void onSize(wxSizeEvent &ev);
void onPaint(wxPaintEvent &ev);
void onTargetButtons(wxCommandEvent & ev);
void onAddButton(wxCommandEvent & ev);
void onAutoCheck (wxCommandEvent &ev);
wxListCtrl * _sourceList;
wxListCtrl * _targetList;
wxCheckBox * _autoCheck;
wxStaticText * _modifiedText;
FTmainwin * _mainwin;
list<ModAction> _actions;
bool _justResized;
int _lastSelected;
private:
// any class wishing to process wxWindows events must use this macro
DECLARE_EVENT_TABLE()
};
#endif
| 2,300
|
C++
|
.h
| 72
| 29.430556
| 80
| 0.746472
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,996
|
FTapp.hpp
|
essej_freqtweak/src/FTapp.hpp
|
/*
** Copyright (C) 2002 Jesse Chappell <jesse@essej.net>
**
** 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 2 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
**
*/
#ifndef __FTPAPPHPP__
#define __FTPAPPHPP__
#include <wx/wx.h>
#include "FTtypes.hpp"
class FTmainwin;
class FTprocessPath;
class FTapp : public wxApp
{
public:
// override base class virtuals
// ----------------------------
FTapp();
// this one is called on application startup and is a good place for the app
// initialization (doing it here and not in the ctor allows to have an error
// return: if OnInit() returns false, the application terminates)
virtual bool OnInit();
FTmainwin * getMainwin() { return _mainwin; }
//FTprocessPath * getProcessPath(int index);
void setupSignals();
protected:
FTmainwin * _mainwin;
};
DECLARE_APP(FTapp);
#endif
| 1,482
|
C++
|
.h
| 42
| 33.190476
| 80
| 0.736248
|
essej/freqtweak
| 34
| 4
| 3
|
GPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,997
|
test.cpp
|
AllWize_mbus-payload/test/aunit/test.cpp
|
/*
MBUS Payload Encoder / Decoder
Unit Tests
Copyright (C) 2019 by AllWize
Copyright (C) 2019 by Xose Pérez <xose at allwize dot io>
The MBUSPayload library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The MBUSPayload library 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the MBUSPayload library. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Arduino.h>
#include "MBUSPayload.h"
#include <AUnit.h>
using namespace aunit;
#define MBUS_PAYLOAD_TEST_VERBOSE 1
#if defined(ARDUINO_ARCH_SAMD)
#define PC_SERIAL SerialUSB
#else
#define PC_SERIAL Serial
#endif
// -----------------------------------------------------------------------------
// Wrapper class
// -----------------------------------------------------------------------------
class MBUSPayloadWrap: public MBUSPayload {
public:
MBUSPayloadWrap() : MBUSPayload() {}
MBUSPayloadWrap(uint8_t size) : MBUSPayload(size) {}
int8_t findDefinition(uint32_t vif) { return _findDefinition(vif); }
uint32_t getVIF(uint8_t code, int8_t scalar) { return _getVIF(code, scalar); }
};
// -----------------------------------------------------------------------------
// Helper methods
// -----------------------------------------------------------------------------
class EncoderTest: public TestOnce {
protected:
virtual void setup() override {
mbuspayload = new MBUSPayloadWrap();
mbuspayload->reset();
}
virtual void teardown() override {
delete mbuspayload;
}
virtual void compare(unsigned char depth, uint8_t * expected) {
uint8_t * actual = mbuspayload->getBuffer();
#if MBUS_PAYLOAD_TEST_VERBOSE
PC_SERIAL.println();
char buff[6];
PC_SERIAL.print("Expected: ");
for (unsigned char i=0; i<depth; i++) {
snprintf(buff, sizeof(buff), "%02X ", expected[i]);
PC_SERIAL.print(buff);
}
PC_SERIAL.println();
PC_SERIAL.print("Actual : ");
for (unsigned char i=0; i<mbuspayload->getSize(); i++) {
snprintf(buff, sizeof(buff), "%02X ", actual[i]);
PC_SERIAL.print(buff);
}
PC_SERIAL.println();
#endif
assertEqual(depth, mbuspayload->getSize());
for (unsigned char i=0; i<depth; i++) {
assertEqual(expected[i], actual[i]);
}
}
MBUSPayloadWrap * mbuspayload;
};
class DecoderTest: public TestOnce {
protected:
virtual void setup() override {
mbuspayload = new MBUSPayloadWrap(10);
mbuspayload->reset();
}
virtual void teardown() override {
delete mbuspayload;
}
virtual void compare(uint8_t * buffer, unsigned char len, uint8_t fields, uint8_t code = 0xFF, int8_t scalar = 0, uint32_t value = 0) {
DynamicJsonDocument jsonBuffer(256);
JsonArray root = jsonBuffer.createNestedArray();
assertEqual(fields, mbuspayload->decode(buffer, len, root));
assertEqual(fields, (uint8_t) root.size());
#if MBUS_PAYLOAD_TEST_VERBOSE
PC_SERIAL.println();
serializeJsonPretty(root, PC_SERIAL);
PC_SERIAL.println();
#endif
if (code != 0xFF) {
assertEqual(code, (uint8_t) root[0]["code"]);
assertEqual(scalar, (int8_t) root[0]["scalar"]);
assertEqual(value, (uint32_t) root[0]["value_raw"]);
}
}
MBUSPayloadWrap * mbuspayload;
};
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
testF(EncoderTest, Empty) {
mbuspayload->reset();
assertEqual(0, mbuspayload->getSize());
}
testF(EncoderTest, Unsupported_Coding) {
mbuspayload->addRaw(0x0F, 0x06, 14);
assertEqual(MBUS_ERROR::UNSUPPORTED_CODING, mbuspayload->getError());
assertEqual(MBUS_ERROR::NO_ERROR, mbuspayload->getError());
}
testF(EncoderTest, Add_Raw_8bit) {
uint8_t expected[] = { 0x01, 0x06, 0x0E};
mbuspayload->addRaw(MBUS_CODING::BIT_8, 0x06, 14);
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Raw_16bit) {
uint8_t expected[] = { 0x02, 0x06, 0x0E, 0x00};
mbuspayload->addRaw(MBUS_CODING::BIT_16, 0x06, 14);
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Raw_32bit) {
uint8_t expected[] = { 0x04, 0x06, 0x0E, 0x00, 0x00, 0x00};
mbuspayload->addRaw(MBUS_CODING::BIT_32, 0x06, 14);
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Raw_2bcd) {
uint8_t expected[] = { 0x09, 0x06, 0x14};
mbuspayload->addRaw(MBUS_CODING::BCD_2, 0x06, 14);
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Raw_8bcd) {
uint8_t expected[] = { 0x0C, 0x13, 0x13, 0x20, 0x00, 0x00};
mbuspayload->addRaw(MBUS_CODING::BCD_8, 0x13, 2013);
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Raw_VIFE) {
uint8_t expected[] = { 0x01, 0xFB, 0x8C, 0x74, 0x0E};
mbuspayload->addRaw(MBUS_CODING::BIT_8, 0xFB8C74, 14);
compare(sizeof(expected), expected);
}
testF(EncoderTest, Find_Definition) {
assertEqual((int8_t) 0, mbuspayload->findDefinition(0x03));
}
testF(EncoderTest, Get_VIF) {
assertEqual((uint32_t) 0xFF , mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, -4));
assertEqual((uint32_t) 0x00 , mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, -3));
assertEqual((uint32_t) 0x03 , mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, 0));
assertEqual((uint32_t) 0x06 , mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, 3));
assertEqual((uint32_t) 0x07 , mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, 4));
assertEqual((uint32_t) 0xFB00, mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, 5));
assertEqual((uint32_t) 0xFB01, mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, 6));
assertEqual((uint32_t) 0xFF , mbuspayload->getVIF(MBUS_CODE::ENERGY_WH, 7));
}
testF(EncoderTest, Add_Field_1a) {
uint8_t expected[] = { 0x02, 0x06, 0x78, 0x05 };
mbuspayload->addField(MBUS_CODE::ENERGY_WH, 3, 1400); // 1400 kWh
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_1b) {
uint8_t expected[] = { 0x01, 0x07, 0x8C };
mbuspayload->addField(MBUS_CODE::ENERGY_WH, 4, 140); // 1400 kWh
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_2) {
uint8_t expected[] = { 0x01, 0xFB, 0x01, 0xC8 };
mbuspayload->addField(MBUS_CODE::ENERGY_WH, 6, 200); // 200 MWh
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_3) {
uint8_t expected[] = { 0x01, 0x0D, 0x24 };
mbuspayload->addField(MBUS_CODE::ENERGY_J, 5, 36); // 3.6 MJ
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_4) {
uint8_t expected[] = { 0x01, 0x13, 0x39 };
mbuspayload->addField(MBUS_CODE::VOLUME_M3, -3, 57); // 57 l
compare(sizeof(expected), expected);
}
testF(EncoderTest, MultiField) {
uint8_t expected[] = { 0x01, 0x13, 0x39, 0x01, 0x0D, 0x24 };
mbuspayload->addField(MBUS_CODE::VOLUME_M3, -3, 57); // 57 l
mbuspayload->addField(MBUS_CODE::ENERGY_J, 5, 36); // 3.6 MJ
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_Compact_1) {
uint8_t expected[] = { 0x01, 0x13, 0x39 };
mbuspayload->addField(MBUS_CODE::VOLUME_M3, 0.057); // 57 l
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_Compact_2) {
uint8_t expected[] = { 0x01, 0x0D, 0x24 };
mbuspayload->addField(MBUS_CODE::ENERGY_J, 36e5); // 3.6 MJ
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_Compact_3) {
uint8_t expected[] = { 0x02, 0x2A, 0x06, 0x05 };
mbuspayload->addField(MBUS_CODE::POWER_W, 128.6); // 128.6 W
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_Compact_Zero) {
uint8_t expected[] = { 0x01, 0x2B, 0x00 };
mbuspayload->addField(MBUS_CODE::POWER_W, 0); // 0 W
compare(sizeof(expected), expected);
}
testF(EncoderTest, Add_Field_Compact_Infinite_Decimals) {
uint8_t expected[] = { 0x01, 0x69, 0x67 };
mbuspayload->addField(MBUS_CODE::PRESSURE_BAR, 1.02999999999999999); // 1.03 bars
compare(sizeof(expected), expected);
}
// -----------------------------------------------------------------------------
testF(DecoderTest, Number_1) {
uint8_t buffer[] = { 0x01, 0xFB, 0x01, 0xC8};
compare(buffer, sizeof(buffer), 1, MBUS_CODE::ENERGY_WH, 6, 200);
}
testF(DecoderTest, Number_2) {
uint8_t buffer[] = { 0x01, 0x13, 0x39 };
compare(buffer, sizeof(buffer), 1, MBUS_CODE::VOLUME_M3, -3, 57);
}
testF(DecoderTest, Number_3) {
uint8_t buffer[] = { 0x02, 0x06, 0x78, 0x05 };
compare(buffer, sizeof(buffer), 1, MBUS_CODE::ENERGY_WH, 3, 1400);
}
testF(DecoderTest, Number_4) {
uint8_t buffer[] = { 0x01, 0x07, 0x8C };
compare(buffer, sizeof(buffer), 1, MBUS_CODE::ENERGY_WH, 4, 140);
}
testF(DecoderTest, Number_5) {
uint8_t buffer[] = { 0x01, 0xFB, 0x01, 0xC8 };
compare(buffer, sizeof(buffer), 1, MBUS_CODE::ENERGY_WH, 6, 200);
}
testF(DecoderTest, Number_6) {
uint8_t buffer[] = { 0x01, 0x2B, 0x00 };
compare(buffer, sizeof(buffer), 1, MBUS_CODE::POWER_W, 0, 0);
}
testF(DecoderTest, MultiField) {
uint8_t buffer[] = { 0x01, 0x13, 0x39, 0x01, 0x0D, 0x24 };
compare(buffer, sizeof(buffer), 2, MBUS_CODE::VOLUME_M3, -3, 57);
}
testF(DecoderTest, Decode_2bcd) {
uint8_t buffer[] = { 0x09, 0x06, 0x14};
compare(buffer, sizeof(buffer), 1, MBUS_CODE::ENERGY_WH, 3, 14);
}
testF(DecoderTest, Decode_8bcd) {
uint8_t buffer[] = { 0x0C, 0x13, 0x13, 0x20, 0x00, 0x00};
compare(buffer, sizeof(buffer), 1, MBUS_CODE::VOLUME_M3, -3, 2013);
}
// -----------------------------------------------------------------------------
// Main
// -----------------------------------------------------------------------------
void setup() {
PC_SERIAL.begin(115200);
while (!PC_SERIAL && millis() < 5000);
Printer::setPrinter(&PC_SERIAL);
//TestRunner::setVerbosity(Verbosity::kAll);
}
void loop() {
TestRunner::run();
delay(1);
}
| 10,870
|
C++
|
.cpp
| 261
| 35.846743
| 143
| 0.605575
|
AllWize/mbus-payload
| 33
| 4
| 4
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,998
|
MBUSPayload.cpp
|
AllWize_mbus-payload/src/MBUSPayload.cpp
|
/*
MBUS Payload Encoder / Decoder
Copyright (C) 2019 by AllWize
Copyright (C) 2019 by Xose Pérez <xose at allwize dot io>
The MBUSPayload library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The MBUSPayload library 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the MBUSPayload library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MBUSPayload.h"
// ----------------------------------------------------------------------------
MBUSPayload::MBUSPayload(uint8_t size) : _maxsize(size) {
_buffer = (uint8_t *) malloc(size);
_cursor = 0;
}
MBUSPayload::~MBUSPayload(void) {
free(_buffer);
}
void MBUSPayload::reset(void) {
_cursor = 0;
}
uint8_t MBUSPayload::getSize(void) {
return _cursor;
}
uint8_t *MBUSPayload::getBuffer(void) {
return _buffer;
}
uint8_t MBUSPayload::copy(uint8_t *dst) {
memcpy(dst, _buffer, _cursor);
return _cursor;
}
uint8_t MBUSPayload::getError() {
uint8_t error = _error;
_error = MBUS_ERROR::NO_ERROR;
return error;
}
// ----------------------------------------------------------------------------
uint8_t MBUSPayload::addRaw(uint8_t dif, uint32_t vif, uint32_t value) {
// Check supported codings (1 to 4 bytes o 2-8 BCD)
bool bcd = ((dif & 0x08) == 0x08);
uint8_t len = (dif & 0x07);
if ((len < 1) || (4 < len)) {
_error = MBUS_ERROR::UNSUPPORTED_CODING;
return 0;
}
// Calculate VIF(E) size
uint8_t vif_len = 0;
uint32_t vif_copy = vif;
while (vif_copy > 0) {
vif_len++;
vif_copy >>= 8;
}
// Check buffer overflow
if ((_cursor + 1 + vif_len + len) > _maxsize) {
_error = MBUS_ERROR::BUFFER_OVERFLOW;
return 0;
}
// Store DIF
_buffer[_cursor++] = dif;
// Store VIF
for (uint8_t i = 0; i<vif_len; i++) {
_buffer[_cursor + vif_len - i - 1] = (vif & 0xFF);
vif >>= 8;
}
_cursor += vif_len;
// Value Information Block - Data
if (bcd) {
for (uint8_t i = 0; i<len; i++) {
_buffer[_cursor++] = ((value / 10) % 10) * 16 + (value % 10);
value = value / 100;
}
} else {
for (uint8_t i = 0; i<len; i++) {
_buffer[_cursor++] = value & 0xFF;
value >>= 8;
}
}
return _cursor;
}
uint8_t MBUSPayload::addField(uint8_t code, int8_t scalar, uint32_t value) {
// Find the closest code-scalar match
uint32_t vif = _getVIF(code, scalar);
if (0xFF == vif) {
_error = MBUS_ERROR::UNSUPPORTED_RANGE;
return 0;
}
// Calculate coding length
uint32_t copy = value >> 8;
uint8_t coding = 1;
while (copy > 0) {
copy >>= 8;
coding++;
}
if (coding > 4) {
coding = 4;
}
// Add value
return addRaw(coding, vif, value);
}
uint8_t MBUSPayload::addField(uint8_t code, float value) {
// Does not support negative values
if (value < 0) {
_error = MBUS_ERROR::NEGATIVE_VALUE;
return 0;
}
// Special case fot value == 0
if (value < ARDUINO_FLOAT_MIN) {
return addField(code, 0, value);
}
// Get the size of the integer part
int8_t int_size = 0;
uint32_t tmp = value;
while (tmp > 10) {
tmp /= 10;
int_size++;
}
// Calculate scale
int8_t scalar = 0;
// If there is a fractional part, move up 8-int_size positions
float frac = value - int(value);
if (frac > ARDUINO_FLOAT_MIN) {
scalar = int_size - ARDUINO_FLOAT_DECIMALS;
for (int8_t i=scalar; i<0; i++) {
value *= 10.0;
}
}
// Check validity when no decimals
bool valid = (_getVIF(code, scalar) != 0xFF);
// Now move down
uint32_t scaled = round(value);
while ((scaled % 10) == 0) {
scalar++;
scaled /= 10;
if (_getVIF(code, scalar) == 0xFF) {
if (valid) {
scalar--;
scaled *= 10;
break;
}
} else {
valid = true;
}
}
// Convert to integer
return addField(code, scalar, scaled);
}
uint8_t MBUSPayload::decode(uint8_t *buffer, uint8_t size, JsonArray& root) {
uint8_t count = 0;
uint8_t index = 0;
while (index < size) {
count++;
// Decode DIF
uint8_t dif = buffer[index++];
bool bcd = ((dif & 0x08) == 0x08);
uint8_t len = (dif & 0x07);
if ((len < 1) || (4 < len)) {
_error = MBUS_ERROR::UNSUPPORTED_CODING;
return 0;
}
// Get VIF(E)
uint32_t vif = 0;
do {
if (index == size) {
_error = MBUS_ERROR::BUFFER_OVERFLOW;
return 0;
}
vif = (vif << 8) + buffer[index++];
} while ((vif & 0x80) == 0x80);
// Find definition
int8_t def = _findDefinition(vif);
if (def < 0) {
_error = MBUS_ERROR::UNSUPPORTED_VIF;
return 0;
}
// Check buffer overflow
if (index + len > size) {
_error = MBUS_ERROR::BUFFER_OVERFLOW;
return 0;
}
// read value
uint32_t value = 0;
if (bcd) {
for (uint8_t i = 0; i<len; i++) {
uint8_t byte = buffer[index + len - i - 1];
value = (value * 100) + ((byte >> 4) * 10) + (byte & 0x0F);
}
} else {
for (uint8_t i = 0; i<len; i++) {
value = (value << 8) + buffer[index + len - i - 1];
}
}
index += len;
// scaled value
int8_t scalar = vif_defs[def].scalar + vif - vif_defs[def].base;
double scaled = value;
for (int8_t i=0; i<scalar; i++) scaled *= 10;
for (int8_t i=scalar; i<0; i++) scaled /= 10;
// Init object
JsonObject data = root.createNestedObject();
data["vif"] = vif;
data["code"] = vif_defs[def].code;
data["scalar"] = scalar;
data["value_raw"] = value;
data["value_scaled"] = scaled;
//data["units"] = String(getCodeUnits(vif_defs[def].code));
}
return count;
}
const char * MBUSPayload::getCodeUnits(uint8_t code) {
switch (code) {
case MBUS_CODE::ENERGY_WH:
return "Wh";
case MBUS_CODE::ENERGY_J:
return "J";
case MBUS_CODE::VOLUME_M3:
return "m3";
case MBUS_CODE::MASS_KG:
return "s";
case MBUS_CODE::ON_TIME_S:
case MBUS_CODE::OPERATING_TIME_S:
case MBUS_CODE::AVG_DURATION_S:
case MBUS_CODE::ACTUAL_DURATION_S:
return "s";
case MBUS_CODE::ON_TIME_MIN:
case MBUS_CODE::OPERATING_TIME_MIN:
case MBUS_CODE::AVG_DURATION_MIN:
case MBUS_CODE::ACTUAL_DURATION_MIN:
return "min";
case MBUS_CODE::ON_TIME_H:
case MBUS_CODE::OPERATING_TIME_H:
case MBUS_CODE::AVG_DURATION_H:
case MBUS_CODE::ACTUAL_DURATION_H:
return "h";
case MBUS_CODE::ON_TIME_DAYS:
case MBUS_CODE::OPERATING_TIME_DAYS:
case MBUS_CODE::AVG_DURATION_DAYS:
case MBUS_CODE::ACTUAL_DURATION_DAYS:
return "days";
case MBUS_CODE::POWER_W:
case MBUS_CODE::MAX_POWER_W:
return "W";
case MBUS_CODE::POWER_J_H:
return "J/h";
case MBUS_CODE::VOLUME_FLOW_M3_H:
return "m3/h";
case MBUS_CODE::VOLUME_FLOW_M3_MIN:
return "m3/min";
case MBUS_CODE::VOLUME_FLOW_M3_S:
return "m3/s";
case MBUS_CODE::MASS_FLOW_KG_H:
return "kg/h";
case MBUS_CODE::FLOW_TEMPERATURE_C:
case MBUS_CODE::RETURN_TEMPERATURE_C:
case MBUS_CODE::EXTERNAL_TEMPERATURE_C:
case MBUS_CODE::TEMPERATURE_LIMIT_C:
return "C";
case MBUS_CODE::TEMPERATURE_DIFF_K:
return "K";
case MBUS_CODE::PRESSURE_BAR:
return "bar";
case MBUS_CODE::BAUDRATE_BPS:
return "bps";
case MBUS_CODE::VOLTS:
return "V";
case MBUS_CODE::AMPERES:
return "A";
case MBUS_CODE::VOLUME_FT3:
return "ft3";
case MBUS_CODE::VOLUME_GAL:
return "gal";
case MBUS_CODE::VOLUME_FLOW_GAL_M:
return "gal/min";
case MBUS_CODE::VOLUME_FLOW_GAL_H:
return "gal/h";
case MBUS_CODE::FLOW_TEMPERATURE_F:
case MBUS_CODE::RETURN_TEMPERATURE_F:
case MBUS_CODE::TEMPERATURE_DIFF_F:
case MBUS_CODE::EXTERNAL_TEMPERATURE_F:
case MBUS_CODE::TEMPERATURE_LIMIT_F:
return "F";
default:
break;
}
return "";
}
const char * MBUSPayload::getCodeName(uint8_t code) {
switch (code) {
case MBUS_CODE::ENERGY_WH:
case MBUS_CODE::ENERGY_J:
return "energy";
case MBUS_CODE::VOLUME_M3:
case MBUS_CODE::VOLUME_FT3:
case MBUS_CODE::VOLUME_GAL:
return "volume";
case MBUS_CODE::MASS_KG:
return "mass";
case MBUS_CODE::ON_TIME_S:
case MBUS_CODE::ON_TIME_MIN:
case MBUS_CODE::ON_TIME_H:
case MBUS_CODE::ON_TIME_DAYS:
return "on_time";
case MBUS_CODE::OPERATING_TIME_S:
case MBUS_CODE::OPERATING_TIME_MIN:
case MBUS_CODE::OPERATING_TIME_H:
case MBUS_CODE::OPERATING_TIME_DAYS:
return "operating_time";
case MBUS_CODE::AVG_DURATION_S:
case MBUS_CODE::AVG_DURATION_MIN:
case MBUS_CODE::AVG_DURATION_H:
case MBUS_CODE::AVG_DURATION_DAYS:
return "avg_duration";
case MBUS_CODE::ACTUAL_DURATION_S:
case MBUS_CODE::ACTUAL_DURATION_MIN:
case MBUS_CODE::ACTUAL_DURATION_H:
case MBUS_CODE::ACTUAL_DURATION_DAYS:
return "actual_duration";
case MBUS_CODE::POWER_W:
case MBUS_CODE::MAX_POWER_W:
case MBUS_CODE::POWER_J_H:
return "power";
case MBUS_CODE::VOLUME_FLOW_M3_H:
case MBUS_CODE::VOLUME_FLOW_M3_MIN:
case MBUS_CODE::VOLUME_FLOW_M3_S:
case MBUS_CODE::VOLUME_FLOW_GAL_M:
case MBUS_CODE::VOLUME_FLOW_GAL_H:
return "volume_flow";
case MBUS_CODE::MASS_FLOW_KG_H:
return "mass_flow";
case MBUS_CODE::FLOW_TEMPERATURE_C:
case MBUS_CODE::FLOW_TEMPERATURE_F:
return "flow_temperature";
case MBUS_CODE::RETURN_TEMPERATURE_C:
case MBUS_CODE::RETURN_TEMPERATURE_F:
return "return_temperature";
case MBUS_CODE::EXTERNAL_TEMPERATURE_C:
case MBUS_CODE::EXTERNAL_TEMPERATURE_F:
return "external_temperature";
case MBUS_CODE::TEMPERATURE_LIMIT_C:
case MBUS_CODE::TEMPERATURE_LIMIT_F:
return "temperature_limit";
case MBUS_CODE::TEMPERATURE_DIFF_K:
case MBUS_CODE::TEMPERATURE_DIFF_F:
return "temperature_diff";
case MBUS_CODE::PRESSURE_BAR:
return "pressure";
case MBUS_CODE::BAUDRATE_BPS:
return "baudrate";
case MBUS_CODE::VOLTS:
return "voltage";
case MBUS_CODE::AMPERES:
return "current";
case MBUS_CODE::FABRICATION_NUMBER:
return "fab_number";
case MBUS_CODE::BUS_ADDRESS:
return "bus_address";
case MBUS_CODE::CREDIT:
return "credit";
case MBUS_CODE::DEBIT:
return "debit";
case MBUS_CODE::ACCESS_NUMBER:
return "access_number";
case MBUS_CODE::MANUFACTURER:
return "manufacturer";
case MBUS_CODE::MODEL_VERSION:
return "model_version";
case MBUS_CODE::HARDWARE_VERSION:
return "hardware_version";
case MBUS_CODE::FIRMWARE_VERSION:
return "firmware_version";
case MBUS_CODE::CUSTOMER:
return "customer";
case MBUS_CODE::ERROR_FLAGS:
return "error_flags";
case MBUS_CODE::ERROR_MASK:
return "error_mask";
case MBUS_CODE::DIGITAL_OUTPUT:
return "digital_output";
case MBUS_CODE::DIGITAL_INPUT:
return "digital_input";
case MBUS_CODE::RESPONSE_DELAY_TIME:
return "response_delay";
case MBUS_CODE::RETRY:
return "retry";
case MBUS_CODE::GENERIC:
return "generic";
case MBUS_CODE::RESET_COUNTER:
case MBUS_CODE::CUMULATION_COUNTER:
return "counter";
default:
break;
}
return "";
}
// ----------------------------------------------------------------------------
int8_t MBUSPayload::_findDefinition(uint32_t vif) {
for (uint8_t i=0; i<MBUS_VIF_DEF_NUM; i++) {
vif_def_type vif_def = vif_defs[i];
if ((vif_def.base <= vif) && (vif < (vif_def.base + vif_def.size))) {
return i;
}
}
return -1;
}
uint32_t MBUSPayload::_getVIF(uint8_t code, int8_t scalar) {
for (uint8_t i=0; i<MBUS_VIF_DEF_NUM; i++) {
vif_def_type vif_def = vif_defs[i];
if (code == vif_def.code) {
if ((vif_def.scalar <= scalar) && (scalar < (vif_def.scalar + vif_def.size))) {
return vif_def.base + (scalar - vif_def.scalar);
}
}
}
return 0xFF; // this is not a valid VIF
}
| 12,838
|
C++
|
.cpp
| 420
| 24.92381
| 85
| 0.608828
|
AllWize/mbus-payload
| 33
| 4
| 4
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,532,999
|
MBUSPayload.h
|
AllWize_mbus-payload/src/MBUSPayload.h
|
/*
MBUS Payload Encoder / Decoder
Copyright (C) 2019 by AllWize
Copyright (C) 2019 by Xose Pérez <xose at allwize dot io>
The MBUSPayload library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The MBUSPayload library 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the MBUSPayload library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MBUS_PAYLOAD_H
#define MBUS_PAYLOAD_H
#include <Arduino.h>
#include <ArduinoJson.h>
#define MBUS_DEFAULT_BUFFER_SIZE 32
#define ARDUINO_FLOAT_MIN 1e-6 // Assume 0 if less than this
#define ARDUINO_FLOAT_DECIMALS 6 // 6 decimals is just below the limit for Arduino float maths
// Supported code types
enum MBUS_CODE {
// no VIFE
ENERGY_WH,
ENERGY_J,
VOLUME_M3,
MASS_KG,
ON_TIME_S,
ON_TIME_MIN,
ON_TIME_H,
ON_TIME_DAYS,
OPERATING_TIME_S,
OPERATING_TIME_MIN,
OPERATING_TIME_H,
OPERATING_TIME_DAYS,
POWER_W,
POWER_J_H,
VOLUME_FLOW_M3_H,
VOLUME_FLOW_M3_MIN,
VOLUME_FLOW_M3_S,
MASS_FLOW_KG_H,
FLOW_TEMPERATURE_C,
RETURN_TEMPERATURE_C,
TEMPERATURE_DIFF_K,
EXTERNAL_TEMPERATURE_C,
PRESSURE_BAR,
//TIME_POINT_DATE,
//TIME_POINT_DATETIME,
//HCA,
AVG_DURATION_S,
AVG_DURATION_MIN,
AVG_DURATION_H,
AVG_DURATION_DAYS,
ACTUAL_DURATION_S,
ACTUAL_DURATION_MIN,
ACTUAL_DURATION_H,
ACTUAL_DURATION_DAYS,
FABRICATION_NUMBER,
BUS_ADDRESS,
// VIFE 0xFD
CREDIT,
DEBIT,
ACCESS_NUMBER,
//MEDIUM,
MANUFACTURER,
//PARAMETER_SET_ID,
MODEL_VERSION,
HARDWARE_VERSION,
FIRMWARE_VERSION,
//SOFTWARE_VERSION,
//CUSTOMER_LOCATION,
CUSTOMER,
//ACCESS_CODE_USER,
//ACCESS_CODE_OPERATOR,
//ACCESS_CODE_SYSOP,
//ACCESS_CODE_DEVELOPER,
//PASSWORD,
ERROR_FLAGS,
ERROR_MASK,
DIGITAL_OUTPUT,
DIGITAL_INPUT,
BAUDRATE_BPS,
RESPONSE_DELAY_TIME,
RETRY,
GENERIC,
VOLTS,
AMPERES,
RESET_COUNTER,
CUMULATION_COUNTER,
// VIFE 0xFB
VOLUME_FT3,
VOLUME_GAL,
VOLUME_FLOW_GAL_M,
VOLUME_FLOW_GAL_H,
FLOW_TEMPERATURE_F,
RETURN_TEMPERATURE_F,
TEMPERATURE_DIFF_F,
EXTERNAL_TEMPERATURE_F,
TEMPERATURE_LIMIT_F,
TEMPERATURE_LIMIT_C,
MAX_POWER_W,
};
// Supported encodings
enum MBUS_CODING {
BIT_8 = 0x01,
BIT_16,
BIT_24,
BIT_32,
BCD_2 = 0x09,
BCD_4,
BCD_6,
BCD_8,
};
// Error codes
enum MBUS_ERROR {
NO_ERROR,
BUFFER_OVERFLOW,
UNSUPPORTED_CODING,
UNSUPPORTED_RANGE,
UNSUPPORTED_VIF,
NEGATIVE_VALUE,
};
// VIF codes
#define MBUS_VIF_DEF_NUM 73
typedef struct {
uint8_t code;
uint32_t base;
uint8_t size;
int8_t scalar;
} vif_def_type;
static const vif_def_type vif_defs[MBUS_VIF_DEF_NUM] = {
// No VIFE
{ MBUS_CODE::ENERGY_WH , 0x00 , 8, -3},
{ MBUS_CODE::ENERGY_J , 0x08 , 8, 0},
{ MBUS_CODE::VOLUME_M3 , 0x10 , 8, -6},
{ MBUS_CODE::MASS_KG , 0x18 , 8, -3},
{ MBUS_CODE::ON_TIME_S , 0x20 , 1, 0},
{ MBUS_CODE::ON_TIME_MIN , 0x21 , 1, 0},
{ MBUS_CODE::ON_TIME_H , 0x22 , 1, 0},
{ MBUS_CODE::ON_TIME_DAYS , 0x23 , 1, 0},
{ MBUS_CODE::OPERATING_TIME_S , 0x24 , 1, 0},
{ MBUS_CODE::OPERATING_TIME_MIN , 0x25 , 1, 0},
{ MBUS_CODE::OPERATING_TIME_H , 0x26 , 1, 0},
{ MBUS_CODE::OPERATING_TIME_DAYS , 0x27 , 1, 0},
{ MBUS_CODE::POWER_W , 0x28 , 8, -3},
{ MBUS_CODE::POWER_J_H , 0x30 , 8, 0},
{ MBUS_CODE::VOLUME_FLOW_M3_H , 0x38 , 8, -6},
{ MBUS_CODE::VOLUME_FLOW_M3_MIN , 0x40 , 8, -7},
{ MBUS_CODE::VOLUME_FLOW_M3_S , 0x48 , 8, -9},
{ MBUS_CODE::MASS_FLOW_KG_H , 0x50 , 8, -3},
{ MBUS_CODE::FLOW_TEMPERATURE_C , 0x58 , 4, -3},
{ MBUS_CODE::RETURN_TEMPERATURE_C , 0x5C , 4, -3},
{ MBUS_CODE::TEMPERATURE_DIFF_K , 0x60 , 4, -3},
{ MBUS_CODE::EXTERNAL_TEMPERATURE_C , 0x64 , 4, -3},
{ MBUS_CODE::PRESSURE_BAR , 0x68 , 4, -3},
//{ MBUS_CODE::TIME_POINT_DATE , 0x6C , 1, 0},
//{ MBUS_CODE::TIME_POINT_DATETIME , 0x6D , 1, 0},
//{ MBUS_CODE::HCA , 0x6E , 1, 0},
{ MBUS_CODE::AVG_DURATION_S , 0x70 , 1, 0},
{ MBUS_CODE::AVG_DURATION_MIN , 0x71 , 1, 0},
{ MBUS_CODE::AVG_DURATION_H , 0x72 , 1, 0},
{ MBUS_CODE::AVG_DURATION_DAYS , 0x73 , 1, 0},
{ MBUS_CODE::ACTUAL_DURATION_S , 0x74 , 1, 0},
{ MBUS_CODE::ACTUAL_DURATION_MIN , 0x75 , 1, 0},
{ MBUS_CODE::ACTUAL_DURATION_H , 0x76 , 1, 0},
{ MBUS_CODE::ACTUAL_DURATION_DAYS , 0x77 , 1, 0},
{ MBUS_CODE::FABRICATION_NUMBER , 0x78 , 1, 0},
{ MBUS_CODE::BUS_ADDRESS , 0x7A , 1, 0},
{ MBUS_CODE::VOLUME_M3 , 0x933A , 1, -3},
{ MBUS_CODE::VOLUME_M3 , 0x943A , 1, -2},
// VIFE 0xFD
{ MBUS_CODE::CREDIT , 0xFD00 , 4, -3},
{ MBUS_CODE::DEBIT , 0xFD04 , 4, -3},
{ MBUS_CODE::ACCESS_NUMBER , 0xFD08 , 1, 0},
//{ MBUS_CODE::MEDIUM , 0xFD09 , 1, 0},
{ MBUS_CODE::MANUFACTURER , 0xFD0A , 1, 0},
//{ MBUS_CODE::PARAMETER_SET_ID , 0xFD0B , 1, 0},
{ MBUS_CODE::MODEL_VERSION , 0xFD0C , 1, 0},
{ MBUS_CODE::HARDWARE_VERSION , 0xFD0D , 1, 0},
{ MBUS_CODE::FIRMWARE_VERSION , 0xFD0E , 1, 0},
//{ MBUS_CODE::SOFTWARE_VERSION , 0xFD0F , 1, 0},
//{ MBUS_CODE::CUSTOMER_LOCATION , 0xFD10 , 1, 0},
{ MBUS_CODE::CUSTOMER , 0xFD11 , 1, 0},
//{ MBUS_CODE::ACCESS_CODE_USER , 0xFD12 , 1, 0},
//{ MBUS_CODE::ACCESS_CODE_OPERATOR , 0xFD13 , 1, 0},
//{ MBUS_CODE::ACCESS_CODE_SYSOP , 0xFD14 , 1, 0},
//{ MBUS_CODE::ACCESS_CODE_DEVELOPER , 0xFD15 , 1, 0},
//{ MBUS_CODE::PASSWORD , 0xFD16 , 1, 0},
{ MBUS_CODE::ERROR_FLAGS , 0xFD17 , 1, 0},
{ MBUS_CODE::ERROR_MASK , 0xFD18 , 1, 0},
{ MBUS_CODE::DIGITAL_OUTPUT , 0xFD1A , 1, 0},
{ MBUS_CODE::DIGITAL_INPUT , 0xFD1B , 1, 0},
{ MBUS_CODE::BAUDRATE_BPS , 0xFD1C , 1, 0},
{ MBUS_CODE::RESPONSE_DELAY_TIME , 0xFD1D , 1, 0},
{ MBUS_CODE::RETRY , 0xFD1E , 1, 0},
{ MBUS_CODE::GENERIC , 0xFD3A , 1, 0},
{ MBUS_CODE::VOLTS , 0xFD40 , 16, -9},
{ MBUS_CODE::AMPERES , 0xFD50 , 16, -12},
{ MBUS_CODE::RESET_COUNTER , 0xFD60 , 16, -12},
{ MBUS_CODE::CUMULATION_COUNTER , 0xFD61 , 16, -12},
// VIFE 0xFB
{ MBUS_CODE::ENERGY_WH , 0xFB00 , 2, 5},
{ MBUS_CODE::ENERGY_J , 0xFB08 , 2, 8},
{ MBUS_CODE::VOLUME_M3 , 0xFB10 , 2, 2},
{ MBUS_CODE::MASS_KG , 0xFB18 , 2, 5},
{ MBUS_CODE::VOLUME_FT3 , 0xFB21 , 1, -1},
{ MBUS_CODE::VOLUME_GAL , 0xFB22 , 2, -1},
{ MBUS_CODE::VOLUME_FLOW_GAL_M , 0xFB24 , 1, -3},
{ MBUS_CODE::VOLUME_FLOW_GAL_M , 0xFB25 , 1, 0},
{ MBUS_CODE::VOLUME_FLOW_GAL_H , 0xFB26 , 1, 0},
{ MBUS_CODE::POWER_W , 0xFB28 , 2, 5},
{ MBUS_CODE::POWER_J_H , 0xFB30 , 2, 8},
{ MBUS_CODE::FLOW_TEMPERATURE_F , 0xFB58 , 4, -3},
{ MBUS_CODE::RETURN_TEMPERATURE_F , 0xFB5C , 4, -3},
{ MBUS_CODE::TEMPERATURE_DIFF_F , 0xFB60 , 4, -3},
{ MBUS_CODE::EXTERNAL_TEMPERATURE_F , 0xFB64 , 4, -3},
{ MBUS_CODE::TEMPERATURE_LIMIT_F , 0xFB70 , 4, -3},
{ MBUS_CODE::TEMPERATURE_LIMIT_C , 0xFB74 , 4, -3},
{ MBUS_CODE::MAX_POWER_W , 0xFB78 , 8, -3},
};
class MBUSPayload {
public:
MBUSPayload(uint8_t size = MBUS_DEFAULT_BUFFER_SIZE);
~MBUSPayload();
void reset(void);
uint8_t getSize(void);
uint8_t * getBuffer(void);
uint8_t copy(uint8_t * buffer);
uint8_t getError();
uint8_t addRaw(uint8_t dif, uint32_t vif, uint32_t value);
uint8_t addField(uint8_t code, int8_t scalar, uint32_t value);
uint8_t addField(uint8_t code, float value);
uint8_t decode(uint8_t *buffer, uint8_t size, JsonArray& root);
const char * getCodeName(uint8_t code);
const char * getCodeUnits(uint8_t code);
protected:
int8_t _findDefinition(uint32_t vif);
uint32_t _getVIF(uint8_t code, int8_t scalar);
uint8_t * _buffer;
uint8_t _maxsize;
uint8_t _cursor;
uint8_t _error = NO_ERROR;
};
#endif
| 9,187
|
C++
|
.h
| 246
| 34.414634
| 109
| 0.562423
|
AllWize/mbus-payload
| 33
| 4
| 4
|
LGPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,001
|
Main.cpp
|
sarthak-gupta-sg_Geometric-Match-OpenCV/Main.cpp
|
// GeoMatchNew.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
//#include "pch.h"
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include "GeoMatch.h"
using namespace std;
using namespace cv;
class CommandParser
{
char **argList; //point to hold argument list
int numArgs; // no of arguments in the list
public:
CommandParser(void);
CommandParser(int, char**);
~CommandParser(void);
char* GetParameter(const char *key);
};
// default constucter
CommandParser::CommandParser(void)
{
numArgs = 0;
argList = NULL;
}
CommandParser::~CommandParser(void)
{
}
//constructer to initialize with number of argument and argument list
CommandParser::CommandParser(int _numArgs, char** _argList)
{
numArgs = _numArgs;
argList = _argList;
}
//return argument that curresponds to the key
char* CommandParser::GetParameter(const char *key)
{
for (int currArg = 0; currArg < numArgs; currArg++)
{
if (strcmp(key, argList[currArg]) == 0)
return argList[currArg + 1];
}
return NULL;
}
void WrongUsage()
{
cout << "\n Edge Based Template Matching Program\n";
cout << " ------------------------------------\n";
cout << "\nProgram arguments:\n\n";
cout << " -t Template image name (image to be searched)\n\n";
cout << " -h High Threshold (High threshold for creating template model)\n\n";
cout << " -l Low Threshold (Low threshold for creating template model)\n\n";
cout << " -s Search image name (image we are trying to find)\n\n";
cout << " -m Minumum score (Minimum score required to proceed with search [0.0 to 1.0])\n\n";
cout << " -g greediness (heuistic parameter to terminate search [0.0 to 1.0] )\n\n";
cout << "Example: GeoMatch -t Template.jpg -h 100 -l 10 -s Search1.jpg -m 0.7 -g 0.5 \n\n";
}
int main(int argc, char** argv)
{
void WrongUsage();
CommandParser cp(argc, argv);
GeoMatch GM; // object to implent geometric matching
int lowThreshold = 10; //deafult value
int highThreashold = 100; //deafult value
double minScore = 0.7; //deafult value
double greediness = 0.8; //deafult value
double total_time = 0;
double score = 0;
Point result;
//Load Template image
char* param;
param = cp.GetParameter("-t");
if (param == NULL)
{
cout << "ERROR: Template image argument missing";
WrongUsage();
return -1;
}
Mat templateImage = imread(param, IMREAD_GRAYSCALE);
if (templateImage.data == NULL)
{
cout << "\nERROR: Could not load Template Image.\n" << param;
return 0;
}
param = cp.GetParameter("-s");
if (param == NULL)
{
cout << "ERROR: source image argument missing";
WrongUsage();
return -1;
}
//Load Search Image
Mat searchImage = imread(param, IMREAD_GRAYSCALE);
if (searchImage.data == NULL)
{
cout << "\nERROR: Could not load Search Image." << param;
return 0;
}
param = cp.GetParameter("-l"); //get Low threshold
if (param != NULL)
lowThreshold = atoi(param);
param = cp.GetParameter("-h");
if (param != NULL)
highThreashold = atoi(param);//get high threshold
param = cp.GetParameter("-m"); // get minimum score
if (param != NULL)
minScore = atof(param);
param = cp.GetParameter("-g");//get greediness
if (param != NULL)
greediness = atof(param);
//Size templateSize = ; //Size(templateImage.width, templateImage->height);
Mat grayTemplateImg; //(templateImage.size(), CV_8U, 1);
templateImage.copyTo(grayTemplateImg);
cout << "\n Edge Based Template Matching Program\n";
cout << " ------------------------------------\n";
if (!GM.CreateGeoMatchModel(grayTemplateImg, lowThreshold, highThreashold))
{
cout << "ERROR: could not create model...";
return 0;
}
cout << " Shape model created.." << "with Low Threshold = " << lowThreshold << " High Threshold = " << highThreashold << endl;
//CvSize searchSize = cvSize(searchImage->width, searchImage->height);
Mat graySearchImg; //= cvCreateImage(searchSize, IPL_DEPTH_8U, 1);
// Convert color image to gray image.
searchImage.copyTo(graySearchImg);
cout << " Finding Shape Model.." << " Minumum Score = " << minScore << " Greediness = " << greediness << "\n";
cout << " ------------------------------------\n";
clock_t start_time1 = clock();
score = GM.FindGeoMatchModel(graySearchImg, minScore, greediness, &result);
clock_t finish_time1 = clock();
total_time = ((double)finish_time1 - (double)start_time1) / CLOCKS_PER_SEC;
Mat rgb;
if (score > minScore) // if score is atleast 0.4
{
cout << " Found at [" << result.x << ", " << result.y << "]\n Score = " << score << "\n Searching Time = " << total_time * 1000 << "ms";
cvtColor(searchImage, rgb, COLOR_GRAY2BGR);
GM.DrawContours(rgb, result, Scalar(0, 255, 0), 1);
}
else
cout << " Object Not found";
//////////////////////////////////
cout << "\n ------------------------------------\n\n";
cout << "\n Press any key to exit!";
//Display result
Mat dispTemplate;
cvtColor(templateImage, dispTemplate, COLOR_GRAY2BGR);
GM.DrawContours(dispTemplate, CV_RGB(255, 0, 0), 1);
namedWindow("Template", WINDOW_AUTOSIZE);
imshow("Template", dispTemplate);
namedWindow("Search Image", WINDOW_AUTOSIZE);
imshow("Search Image", rgb);
// wait for both windows to be closed before releasing images
waitKey(0);
destroyWindow("Search Image");
destroyWindow("Template");
searchImage.release();
graySearchImg.release();
templateImage.release();
grayTemplateImg.release();
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| 6,415
|
C++
|
.cpp
| 172
| 33.726744
| 139
| 0.663457
|
sarthak-gupta-sg/Geometric-Match-OpenCV
| 32
| 22
| 1
|
GPL-3.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,003
|
main.cpp
|
Bakkes_CPPRP/loadoutextractor/main.cpp
|
#pragma comment(lib, "CPPRP.lib")
#include "../CPPRP/ReplayFile.h"
#include "../CPPRP/exceptions/ReplayException.h"
#include <string>
#include "bmloadout.h"
#include <iostream>
#include "helper_classes.h"
#include <map>
#include "bmloadout.h"
#include "bakkesmodloadoutlib.h"
#include "../CPPRP/data/NetworkData.h"
std::map<int, std::string> actorNameMap;
std::map<int, BMLoadout> processed;
std::map<int, CPPRP::CameraSettings> cameras;
//std::map<int, int> cameraSettingsMapping;
// void on_playername_set(Frame* frame, ActorState* actor, const char* playername)
// {
// //printf("Player %i got name %s\n", actor->actor_id, playername);
// actorNameMap[actor->actor_id] = std::string(playername);
// }
// void on_camerasettings_map(Frame* frame, ActorState* actor, ActiveActor* aactor)
// {
// //printf("Player %i\n", aactor->actor_id);
// //int w = 5;
// cameraSettingsMapping[aactor->actor_id] = actor->actor_id;
// }
// void SetCameraSettings(Frame* frame, ActorState* actor, CameraSettings* cameraSettings)
// {
// //printf("Player %i got name %s\n", actor->actor_id, playername);
// cameras[actor->actor_id] = *cameraSettings;
// }
void SetClientLoadouts(const CPPRP::ActorStateData& actor, const CPPRP::ClientLoadouts& loadouts)
{
BMLoadout customLoadout = processed[actor.actorId];
customLoadout.body.blue_is_orange = false; //Two seperate loadouts
customLoadout.body.blue_loadout[SLOT_BODY].product_id = (uint16_t)loadouts.loadout_one.body;
customLoadout.body.blue_loadout[SLOT_SKIN].product_id = (uint16_t)loadouts.loadout_one.skin;
customLoadout.body.blue_loadout[SLOT_WHEELS].product_id = (uint16_t)loadouts.loadout_one.wheels;
customLoadout.body.blue_loadout[SLOT_BOOST].product_id = (uint16_t)loadouts.loadout_one.boost;
customLoadout.body.blue_loadout[SLOT_ANTENNA].product_id = (uint16_t)loadouts.loadout_one.antenna;
customLoadout.body.blue_loadout[SLOT_HAT].product_id = (uint16_t)loadouts.loadout_one.hat;
customLoadout.body.blue_loadout[SLOT_ENGINE_AUDIO].product_id = (uint16_t)loadouts.loadout_one.engine_audio;
customLoadout.body.blue_loadout[SLOT_SUPERSONIC_TRAIL].product_id = (uint16_t)loadouts.loadout_one.trail;
customLoadout.body.blue_loadout[SLOT_GOALEXPLOSION].product_id = (uint16_t)loadouts.loadout_one.goal_explosion;
customLoadout.body.orange_loadout[SLOT_BODY].product_id = (uint16_t)loadouts.loadout_two.body;
customLoadout.body.orange_loadout[SLOT_SKIN].product_id = (uint16_t)loadouts.loadout_two.skin;
customLoadout.body.orange_loadout[SLOT_WHEELS].product_id = (uint16_t)loadouts.loadout_two.wheels;
customLoadout.body.orange_loadout[SLOT_BOOST].product_id = (uint16_t)loadouts.loadout_two.boost;
customLoadout.body.orange_loadout[SLOT_ANTENNA].product_id = (uint16_t)loadouts.loadout_two.antenna;
customLoadout.body.orange_loadout[SLOT_HAT].product_id = (uint16_t)loadouts.loadout_two.hat;
customLoadout.body.orange_loadout[SLOT_ENGINE_AUDIO].product_id = (uint16_t)loadouts.loadout_two.engine_audio;
customLoadout.body.orange_loadout[SLOT_SUPERSONIC_TRAIL].product_id = (uint16_t)loadouts.loadout_two.trail;
customLoadout.body.orange_loadout[SLOT_GOALEXPLOSION].product_id = (uint16_t)loadouts.loadout_two.goal_explosion;
processed[actor.actorId] = customLoadout;
}
template<class... Ts> struct overload : Ts... { using Ts::operator()...; };
template<class... Ts> overload(Ts...) -> overload<Ts...>;
void SetClientLoadoutsOnline(const CPPRP::ActorStateData& actor, const CPPRP::ClientLoadoutsOnline& loadouts)
{
if (processed.find(actor.actorId) == processed.end())
return;
BMLoadout customLoadout = processed[actor.actorId];
for (int slot = 0; slot < loadouts.online_one.attributes_list.size(); slot++)
{
for (int j = 0; j < loadouts.online_one.attributes_list[slot].product_attributes.size(); j++)
{
CPPRP::AttributeType pa = loadouts.online_one.attributes_list[slot].product_attributes[j];
std::visit(
//overload(
[&customLoadout, slot](const CPPRP::ProductAttributePainted&& paint)
{
customLoadout.body.blue_loadout[slot].paint_index = (uint8_t)(paint.value);
}
//)
,
pa);
/*std::shared_ptr<CPPRP::ProductAttributePainted> paPainted = std::dynamic_pointer_cast<CPPRP::ProductAttributePainted>(pa);
if (paPainted)
{
customLoadout.body.blue_loadout[slot].paint_index = (uint8_t)(pa->value);
}*/
}
}
for (int slot = 0; slot < loadouts.online_two.attributes_list.size(); slot++)
{
for (int j = 0; j < loadouts.online_two.attributes_list[slot].product_attributes.size(); j++)
{
std::shared_ptr<CPPRP::ProductAttribute> pa = loadouts.online_two.attributes_list[slot].product_attributes[j];
std::shared_ptr<CPPRP::ProductAttributePainted> paPainted = std::dynamic_pointer_cast<CPPRP::ProductAttributePainted>(pa);
if (paPainted)
{
customLoadout.body.orange_loadout[slot].paint_index = (uint8_t)(pa->value);
}
}
}
processed[actor.actorId] = customLoadout;
}
std::map<int, std::string> carNames = {
{21, "Backfire"},
{22, "Breakout"},
{23, "Octane"},
{24, "Paladin"},
{25, "Roadhog"},
{26, "Gizmo"},
{27, "Sweet Tooth"},
{28, "X-Devil"},
{29, "Hotshot"},
{30, "Merc"},
{31, "Venom"},
{402, "Takumi"},
{403, "Dominus"},
{404, "Scarab"},
{523, "Zippy"},
{597, "Delorean"},
{600, "Ripper"},
{607, "Grog"},
{625, "Armadillo"},
{723, "Hogsticker"},
{803, "'16 Batmobile"},
{1018, "Dominus GT"},
{1159, "X-Devil Mk2"},
{1171, "Masamune"},
{1172, "Marauder"},
{1286, "Aftershock"},
{1295, "Takumi RX-T"},
{1300, "Roadhog XL"},
{1317, "Esper"},
{1416, "Breakout Type-S"},
{1475, "Proteus"},
{1478, "Triton"},
{1533, "Vulcan"},
{1568, "Octane ZSR"},
{1603, "Twinmill III"},
{1623, "Bone Shaker"},
{1624, "Endo"},
{1675, "Ice Charger"},
{1691, "Mantis"},
{1856, "Jager 619"},
{1883, "Imperator DT5"},
{1919, "Centio V17"},
{1932, "Animus GP"},
{2070, "Werewolf"},
{2268, "Dodge Charger R/T"},
{2269, "Skyline GT-R"},
{2298, "Samus' Gunship"},
{2313, "Mario NSR"},
{2665, "TDK Tumbler"},
{2666, "'89 Batmobile"},
{2853, "Twinzer"},
{2919, "Jurassic Jeep Wrangler"},
{3031, "Cyclone"},
{3155, "Maverick"},
{3156, "Maverick G1"},
{3157, "Maverick GXT"},
{3265, "McLaren 570S"},
{3426, "Diestro"},
{3451, "Nimbus"},
{3594, "Artemis G1"},
{3614, "Artemis"},
{3622, "Artemis GXT"},
{3875, "Guardian GXT"},
{3879, "Guardian"},
{3880, "Guardian G1"},
};
int main(int argc, char *argv[])
{
auto replayFile = std::make_shared<CPPRP::ReplayFile>(argv[1]);
replayFile->Load();
replayFile->DeserializeHeader();
replayFile->actorDeleteCallbacks.push_back([&](const CPPRP::ActorStateData& actor)
{
std::shared_ptr<CPPRP::TAGame::Car_TA> car = std::dynamic_pointer_cast<CPPRP::TAGame::Car_TA>(actor.actorObject);
if(car)
{
if(replayFile->actorStates.find(car->PlayerReplicationInfo.actor_id) == replayFile->actorStates.end())
{
return;
}
CPPRP::ActorStateData& priActor = replayFile->actorStates[car->PlayerReplicationInfo.actor_id];
std::shared_ptr<CPPRP::TAGame::PRI_TA> pri = std::dynamic_pointer_cast<CPPRP::TAGame::PRI_TA>(priActor.actorObject);
if (pri)
{
actorNameMap[priActor.actorId] = pri->PlayerName;
cameras[priActor.actorId] = pri->CameraSettings;
SetClientLoadouts(priActor, pri->ClientLoadouts);
SetClientLoadoutsOnline(priActor, pri->ClientLoadoutsOnline);
}
}
else
{
std::shared_ptr<CPPRP::TAGame::CameraSettingsActor_TA> camera = std::dynamic_pointer_cast<CPPRP::TAGame::CameraSettingsActor_TA>(actor.actorObject);
//TAGame.CameraSettingsActor_TA:ProfileSettings
if(camera)
{
cameras[camera->PRI.actor_id] = camera->ProfileSettings;
}
}
//printf("%s\n", typeid(*actor.actorObject).name());
});
replayFile->Parse();
//Engine.PlayerReplicationInfo:PlayerName
// crp_register_updated_callback("Engine.PlayerReplicationInfo:PlayerName", (callback_updated)&on_playername_set);
// crp_register_updated_callback("TAGame.PRI_TA:ClientLoadouts", (callback_updated)&on_loadout_set);
// crp_register_updated_callback("TAGame.PRI_TA:ClientLoadoutsOnline", (callback_updated)&on_onlineloadout_set);
// crp_register_updated_callback("TAGame.CameraSettingsActor_TA:PRI", (callback_updated)&on_camerasettings_map);
// crp_register_updated_callback("TAGame.PRI_TA:CameraSettings", (callback_updated)&on_camerasettings_set);
// crp_register_updated_callback("TAGame.CameraSettingsActor_TA:ProfileSettings", (callback_updated)&on_camerasettings_set);
// //
// crp_parse_replay();
//FILE * pFile;
//pFile = fopen("loadout.txt", "w");
for (auto a : processed)
{
std::string loadout = save(a.second);
std::string body = carNames[a.second.body.blue_loadout[SLOT_BODY].product_id].c_str();
//printf("%i", a.second.body.blue_loadout[SLOT_BODY].product_id);
printf("%s (%s): %s\n", actorNameMap[a.first].c_str(), body.c_str(), loadout.c_str());
}
printf("\n");
for (auto a : processed)
{
int actual_actor = a.first;
auto cam = cameras[actual_actor];
printf("%s: FOV: %i, height: %i, pitch: %i, distance: %i, stiffness: %.1f, swivel: %.1f, transition: %.1f \n",
actorNameMap[a.first].c_str(),
(int)cam.FOV,
(int) cam.height,
(int) cam.pitch,
(int) cam.distance,
cam.stiffness,
cam.swivelspeed,
cam.transitionspeed);
}
//fclose(pFile);
//crp_free_replay();
//getchar();
return 0;
}
| 9,781
|
C++
|
.cpp
| 238
| 36.785714
| 160
| 0.688492
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,004
|
main.cpp
|
Bakkes_CPPRP/CPPRPTest/main.cpp
|
//#define _CRTDBG_MAP_ALLOC
//#include <stdlib.h>
//#include <crtdbg.h>
//#include <omp.h>
#pragma comment(lib, "CPPRP.lib")
#include "../CPPRP/ReplayFile.h"
#include "../CPPRP/exceptions/ReplayException.h"
#include <iostream>
#include "bench.h"
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>
#include <algorithm>
#include <map>
#include <filesystem>
#include <queue>
#include <unordered_map>
#include "../CPPRPJSON/OptionsParser.h"
#undef max
int main(int argc, char *argv[])
{
if constexpr (true) {
auto replayFile = std::make_shared<CPPRP::ReplayFile>(R"(C:\Users\m4rti\Documents\My Games\Rocket League\TAGame\Demos\48238C814A7BF02F8A219BB9C77C2F6E.replay)");
replayFile->Load();
replayFile->DeserializeHeader();
for (auto it : replayFile->GetProperty<std::vector<std::unordered_map<std::string, std::shared_ptr<CPPRP::Property>>>>("PlayerStats"))
{
for (auto it2 : it)
{
printf("%s\n", it2.first.c_str());
}
}
std::map<uint32_t, std::unordered_map<uint32_t, uint32_t>> scores;
struct TestData
{
CPPRP::OnlineID id;
uint32_t match_Score;
};
std::map<uint32_t, CPPRP::TAGame::PRI_TA> pris;
replayFile->updatedCallbacks.push_back([&](const CPPRP::ActorStateData& asd, const std::vector<uint32_t>& props)
{
if (auto pri = std::dynamic_pointer_cast<CPPRP::TAGame::PRI_TA>(asd.actorObject))
{
pris[asd.actorId] = *pri;
}
});
replayFile->tickables.push_back([&](const CPPRP::Frame frame, const std::unordered_map<uint32_t, CPPRP::ActorStateData>& actorStats)
{
for (auto& actor : actorStats)
{
auto pri = std::dynamic_pointer_cast<CPPRP::TAGame::PRI_TA>(actor.second.actorObject);
if (pri)
{
scores[frame.frameNumber][actor.first] = pri->MatchScore;
}
}
});
replayFile->Parse();
auto replay_name = replayFile->GetProperty<std::string>("ReplayName");
auto replay_date = replayFile->GetProperty<std::string>("Date");
auto replay_match_type = replayFile->GetProperty<std::string>("MatchType");
auto replay_id = replayFile->GetProperty<std::string>("Id");
auto replay_team_size = replayFile->GetProperty<int>("TeamSize");
auto replay_map_name = replayFile->GetProperty<std::string>("MapName");
for(auto& [id, pri]: pris)
{
if (pri.Team.active)
{
const auto team_object = replayFile->actorStates[pri.Team.actor_id];
const auto team_archetype = replayFile->replayFile->names[team_object.typeId];
}
}
int fdfsd = 5;
return 0;
}
//printf("hi");
std::queue<std::filesystem::path> replayFilesToLoad;
{
std::filesystem::path p(argv[1]);
if (std::filesystem::is_regular_file(p))
{
if (argc > 2)
{
int amnt = std::stoi(argv[2]);
for(int i = 0; i < amnt; ++i)
replayFilesToLoad.push(p);
}
else
{
replayFilesToLoad.push(p);
}
}
else
{
for (const auto & entry : std::filesystem::recursive_directory_iterator(argv[1]))
{
if (entry.path().filename().u8string().find(".replay") == std::string::npos)
continue;
if (replayFilesToLoad.size() >= 5335345)
break;
replayFilesToLoad.push(entry.path());
}
}
}
static const size_t numReplays = replayFilesToLoad.size();
printf("Attempt to parse %i replays\n", numReplays);
std::atomic<uint32_t> success = 0;
std::atomic<uint32_t> fail = 0;
std::atomic<uint32_t> corrupt = 0;
std::mutex queueMutex;
std::mutex filesMutex;
//td::atomic<uint32_t>
std::atomic<bool> allLoaded = false;
std::queue<std::shared_ptr<CPPRP::ReplayFile>> replayFileQueue;
auto parseReplay = [&success, &fail, &allLoaded, &queueMutex, &replayFileQueue]()
{
while (true)
{
std::shared_ptr<CPPRP::ReplayFile> replayFile{ nullptr };
{
std::lock_guard<std::mutex> lockGuard(queueMutex);
if (!replayFileQueue.empty())
{
replayFile = replayFileQueue.front();
replayFileQueue.pop();
}
else if (allLoaded)
{
break;
}
else
{
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
}
if (replayFile != nullptr)
{
try
{
replayFile->VerifyCRC(CPPRP::CRC_Both);
replayFile->DeserializeHeader();
replayFile->Parse();
success++;
//printf("Parsed\n");
}
catch (...) {
fail++;
printf("[%i/%i] %s\n", fail.load(), success.load() + fail.load(), replayFile->path.filename().u8string().c_str());
}
}
}
};
auto loadReplay = [&filesMutex, &queueMutex, &replayFilesToLoad, &replayFileQueue]()
{
while (true)
{
std::filesystem::path replayName;
{
std::lock_guard<std::mutex> fileLockGuard(filesMutex);
if (!replayFilesToLoad.empty())
{
replayName = replayFilesToLoad.front();
replayFilesToLoad.pop();
}
else
{
break;
}
}
std::shared_ptr<CPPRP::ReplayFile> rf = std::make_shared<CPPRP::ReplayFile>(replayName);
if (rf->Load())
{
std::lock_guard<std::mutex> lockGuard(queueMutex);
replayFileQueue.push(std::move(rf));
}
else
{
printf("Failed loading replay file\n");
}
}
};
OptionsParser op(argc, argv);
auto loadAndParseReplay = [&success, &queueMutex, &replayFilesToLoad]()
{
while (true)
{
std::filesystem::path replayName;
{
std::lock_guard<std::mutex> lockGuard(queueMutex);
if (!replayFilesToLoad.empty())
{
replayName = replayFilesToLoad.front();
replayFilesToLoad.pop();
}
else
{
break;
}
}
try
{
std::shared_ptr<CPPRP::ReplayFile> replayFile = std::make_shared<CPPRP::ReplayFile>(replayName);
replayFile->Load();
//replayFile->VerifyCRC(CPPRP::CRC_Both);
replayFile->DeserializeHeader();
replayFile->Parse();
// struct t
// {
// uint32_t filepos;
// uint32_t framenumber;
// };
// const auto& kf = replayFile->replayFile->keyframes;
// std::vector<t> positions;
// for (size_t i = 0; i < kf.size(); ++i)
// {
// positions.push_back({ kf[i].filepos, kf[i].frame });
// }
// t ow = { replayFile->replayFile->netstream_size * 8, static_cast<uint32_t>(replayFile->GetProperty<int32_t>("NumFrames")) };
// positions.push_back(ow);
// const size_t posCount = positions.size() - 1;
// for (size_t i = 0; i < posCount; ++i)
// {
// auto wot1 = positions[i];
// auto wot2 = positions[i + 1];
// uint32_t frameCount = wot2.framenumber - wot1.framenumber;
// replayFile->Parse(wot1.filepos, wot2.filepos, frameCount);
// }
success++;
//printf("Parsed\n");
}
catch (...) {
printf("err\n");
}
}
};
const int bothReplayThreadsCount = op.GetIntValue({"both"}, 1);
const int loadThreads = op.GetIntValue({"loads"}, 0);
const int parseThreads = op.GetIntValue({"parses"}, 0);
if (loadThreads == 0 || parseThreads == 0)
{
//constexpr size_t bothReplayThreadCount = 50;
printf("Loading&parsing using %i thread(s)\n", bothReplayThreadsCount);
auto start = std::chrono::steady_clock::now();
if (bothReplayThreadsCount == 1)
{
loadAndParseReplay();
}
else
{
std::vector<std::thread> bothReplayThreads;
for (size_t i = 0; i < bothReplayThreadsCount; ++i)
{
std::thread bothReplayThread = std::thread{
loadAndParseReplay
};
bothReplayThreads.emplace_back(std::move(bothReplayThread));
}
for (auto& t : bothReplayThreads)
{
t.join();
}
}
auto end = std::chrono::steady_clock::now();
printf("Done parsing\n");
std::cout << "Elapsed time in nanoseconds : "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
<< " ns" << std::endl;
std::cout << "Elapsed time in microseconds : "
<< std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< " µs" << std::endl;
std::cout << "Elapsed time in milliseconds : "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
<< " ms" << std::endl;
float totalMs = (float)std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "Average " << (totalMs/success) << std::endl;
}
else
{
printf("Loading threads: %i. Parsing using %i thread(s)\n", loadThreads, parseThreads);
auto start = std::chrono::steady_clock::now();
//constexpr size_t loadReplayThreadCount = 4;
//constexpr size_t parseReplayThreadCount = 6;
std::vector<std::thread> loadReplayThreads;
std::vector<std::thread> parseReplayThreads;
for (size_t i = 0; i < loadThreads; ++i)
{
std::thread loadReplayThread = std::thread{
loadReplay
};
loadReplayThreads.emplace_back(std::move(loadReplayThread));
}
for (size_t i = 0; i < parseThreads; i++)
{
std::thread parseReplayThread = std::thread{
parseReplay
};
parseReplayThreads.emplace_back(std::move(parseReplayThread));
}
for (auto& t : loadReplayThreads)
{
t.join();
}
printf("Loaded all files, waiting for parse to end\n");
allLoaded = true;
for (auto& t : parseReplayThreads)
{
t.join();
}
printf("Done parsing\n");
auto end = std::chrono::steady_clock::now();
std::cout << "Elapsed time in nanoseconds : "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count()
<< " ns" << std::endl;
std::cout << "Elapsed time in microseconds : "
<< std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< " �s" << std::endl;
std::cout << "Elapsed time in milliseconds : "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
<< " ms" << std::endl;
float totalMs = (float)std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "Average " << (totalMs/success) << std::endl;
std::cout << "Success: " << success.load() << ", fail: " << fail.load() << std::endl;
}
{
/*printf("Test %s\n", name);
printf("Attempted to parse %i replays in %.5f ms \n", success + fail + corrupt, elapsed);
printf("Success: %i, fail: %i (%.2f%%) corrupt: %i Average parse time %.5f ms (totaltime/successfulparses)\n", (success.load()), fail.load(), ((double)success.load() / (double)((success.load()) + fail.load())) * 100, corrupt.load(), (elapsed / (double)success.load()));*/
}
system("pause");
return 0;
}
| 10,294
|
C++
|
.cpp
| 332
| 27.036145
| 273
| 0.653433
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,005
|
ReplayFile.cpp
|
Bakkes_CPPRP/CPPRP/ReplayFile.cpp
|
#include "ReplayFile.h"
#include <fstream>
#include "./data/GameClasses.h"
#include "./data/NetworkData.h"
#include <set>
#include "./data/ArcheTypes.h"
#include "./generated/ClassExtensions.h"
#include "./exceptions/ParseException.h"
#include "./exceptions/ReplayException.h"
#include "CRC.h"
#include <functional>
#include "NetworkDataParsers.h"
#include "PropertyParser.h"
#include <format>
namespace CPPRP
{
#ifdef PARSELOG_ENABLED
constexpr bool IncludeParseLog = true;
#else
constexpr bool IncludeParseLog = false;
#endif
constexpr uint32_t ParseLogSize = 100;
ReplayFile::ReplayFile(std::filesystem::path path_) : path(path_)
{
}
ReplayFile::ReplayFile(std::vector<char>& fileData)
{
this->data = fileData;
}
ReplayFile::~ReplayFile()
{
}
const bool ReplayFile::Load()
{
if (!std::filesystem::exists(path))
return false;
std::ifstream file(path, std::ios::binary | std::ios::ate);
const std::streamsize size = file.tellg();
data.resize((size_t)size);
file.seekg(0, std::ios::beg);
if (file.bad())
return false;
return (bool)file.read(data.data(), size);
}
template<typename T>
T ReadHeaderStruct(std::shared_ptr<CPPBitReader<BitReaderType>>& bitReader)
{
return bitReader->read<T>();
}
template<>
KeyFrame ReadHeaderStruct(std::shared_ptr<CPPBitReader<BitReaderType>>& bitReader)
{
return KeyFrame {
bitReader->read<float>(), //Time
bitReader->read<uint32_t>(), //Frame
bitReader->read<uint32_t>() //File position
};
}
template<>
DebugString ReadHeaderStruct(std::shared_ptr<CPPBitReader<BitReaderType>>& bitReader)
{
return DebugString {
bitReader->read<uint32_t>(), //Time
bitReader->read<std::string>(), //Frame
bitReader->read<std::string>() //File position
};
}
template<>
ReplayTick ReadHeaderStruct(std::shared_ptr<CPPBitReader<BitReaderType>>& bitReader)
{
return ReplayTick {
bitReader->read<std::string>(), //Type
bitReader->read<uint32_t>() //Frame
};
}
template<>
ClassIndex ReadHeaderStruct(std::shared_ptr<CPPBitReader<BitReaderType>>& bitReader)
{
return ClassIndex{
bitReader->read<std::string>(), //Class_name
bitReader->read<uint32_t>() //Index
};
}
template<typename T>
void ReadVector(std::shared_ptr<CPPBitReader<BitReaderType>>& bitReader, std::vector<T>& inVec)
{
const uint32_t vectorCount = bitReader->read<uint32_t>();
if (vectorCount * sizeof(T) > bitReader->size) throw 0; //TODO: throw proper exception
inVec.resize(vectorCount);
for (uint32_t i = 0; i < vectorCount; ++i)
{
inVec[i] = ReadHeaderStruct<T>(bitReader);
}
}
void ReplayFile::DeserializeHeader()
{
const size_t dataSizeBits = data.size() * 8;
replayFile = std::make_shared<ReplayFileData>();
fullReplayBitReader = std::make_shared<CPPBitReader<BitReaderType>>((const BitReaderType*)data.data(), dataSizeBits, replayFile);
replayFile->header = {
fullReplayBitReader->read<uint32_t>(), //Size
fullReplayBitReader->read<uint32_t>(), //CRC
fullReplayBitReader->read<uint32_t>(), //engineVersion
fullReplayBitReader->read<uint32_t>() //licenseeVersion
};
if (replayFile->header.engineVersion >= 868 && replayFile->header.licenseeVersion >= 18)
{
replayFile->header.netVersion = fullReplayBitReader->read<uint32_t>();
}
//Reconstruct because we have version info now, find something better for this
size_t bitPos = fullReplayBitReader->GetAbsoluteBitPosition();
fullReplayBitReader = std::make_shared<CPPBitReader<BitReaderType>>((const BitReaderType*)data.data(), dataSizeBits, replayFile);
fullReplayBitReader->skip(bitPos);
replayFile->replayType = fullReplayBitReader->read<std::string>(); //Not sure what this is
while (true)
{
if (auto baseProperty = std::make_shared<Property>(); ParseProperty(baseProperty))
{
replayFile->properties[baseProperty->property_name] = baseProperty;
}
else
{
break;
}
}
//TODO: clean this up
const std::string buildVersion = GetPropertyOrDefault<std::string>("BuildVersion", "");
replayFile->header.buildVersion = buildVersion;
this->header.buildVersion = buildVersion;
fullReplayBitReader->buildVersion = buildVersion;
replayFile->body_size = fullReplayBitReader->read<uint32_t>();
replayFile->crc2 = fullReplayBitReader->read<uint32_t>();
ReadVector(fullReplayBitReader, replayFile->levels);
ReadVector(fullReplayBitReader, replayFile->keyframes);
const uint32_t netstreamCount = static_cast<uint32_t>(fullReplayBitReader->read<int32_t>());
replayFile->netstream_data = data.data() + fullReplayBitReader->GetAbsoluteBytePosition(); //We know this is always aligned, so valid
const uint32_t netstreamSizeInBytes = netstreamCount * 8;
fullReplayBitReader->skip(netstreamSizeInBytes); //Skip netstream data for now
replayFile->netstream_size = netstreamCount;
if (!fullReplayBitReader->canRead())
{
//Replay is corrupt
const std::string exceptionText = "ReplayFile corrupt. header + netstream_size > filesize";
throw GeneralParseException(exceptionText, *fullReplayBitReader);
}
ReadVector(fullReplayBitReader, replayFile->debugstrings);
ReadVector(fullReplayBitReader, replayFile->replayticks);
ReadVector(fullReplayBitReader, replayFile->replicated_packages);
ReadVector(fullReplayBitReader, replayFile->objects);
ReadVector(fullReplayBitReader, replayFile->names);
ReadVector(fullReplayBitReader, replayFile->class_indices);
const uint32_t classNetsCount = fullReplayBitReader->read<uint32_t>();
replayFile->classnets.resize(classNetsCount);
for (uint32_t i = 0; i < classNetsCount; ++i)
{
ClassNet cn = {
fullReplayBitReader->read<int32_t>(), //Index
fullReplayBitReader->read<int32_t>(), //Parent
NULL, //Parent class, not known yet
fullReplayBitReader->read<int32_t>(), //Id
fullReplayBitReader->read<int32_t>(), //Prop_indexes_size
std::vector<PropIndexId>(), //Empty propindexid array
0, //Max_prop_id
std::vector<uint16_t>() //Property_id_cache
};
const uint32_t newSize = cn.prop_indexes_size;
cn.prop_indexes.resize(newSize);
for (uint32_t j = 0; j < newSize; ++j)
{
cn.prop_indexes[j] = (
PropIndexId{
fullReplayBitReader->read<int32_t>(), //Prop_index
fullReplayBitReader->read<int32_t>() //Prop_id
});
}
std::shared_ptr<ClassNet> classNet = std::make_shared<ClassNet>(cn);
replayFile->classnets[i] = (classNet);
//Set parent class if exists
for (int32_t k = static_cast<int32_t>(i) - 1; k >= 0; --k)
{
if (replayFile->classnets[i]->parent == replayFile->classnets[k]->id)
{
replayFile->classnets[i]->parent_class = replayFile->classnets[k];
break;
}
}
}
if (replayFile->header.netVersion >= 10)
{
fullReplayBitReader->read<int32_t>();
}
header = replayFile->header;
this->FixParents();
}
const bool ReplayFile::VerifyCRC(CrcCheck verifyWhat)
{
if ((verifyWhat & CRC_Both) == 0) return false; //User supplied invalid value, < 0 or >= 4
const size_t dataSizeBits = data.size() * 8;
//Replay not loaded, less than 8 bytes
if (dataSizeBits < sizeof(uint32_t) * 2 * 8)
{
return false;
}
CPPBitReader<BitReaderType> bitReader((const BitReaderType*)data.data(),
dataSizeBits, replayFile, 0, 0, 0, "");
const uint32_t headerSize = bitReader.read<uint32_t>();
const uint32_t headerReadCrc = bitReader.read<uint32_t>();
//File is lying about its size
if (bitReader.GetAbsoluteBytePosition() + headerSize > data.size())
{
return false;
}
constexpr uint32_t CRC_SEED = 0xEFCBF201;
if (verifyWhat & CRC_Header)
{
const uint32_t headerCalculatedCRC2 = CalculateCRC_SB16(*reinterpret_cast<std::vector<uint8_t>*>(&data),
static_cast<size_t>(bitReader.GetAbsoluteBytePosition()),
static_cast<size_t>(headerSize), CRC_SEED);
const bool result = headerCalculatedCRC2 == headerReadCrc;
//If only verify header, or if already failed here
if (!(verifyWhat & CRC_Body) || !result)
{
return result;
}
}
bitReader.skip(headerSize * 8);
if (bitReader.GetAbsoluteBytePosition() + 2 > data.size())
{
//Won't be able to read body size and crc, so false
return false;
}
const uint32_t bodySize = bitReader.read<uint32_t>();
const uint32_t bodyReadCrc = bitReader.read<uint32_t>();
if (bitReader.GetAbsoluteBytePosition() + bodySize > data.size())
{
return false;
}
//cast is ugly but works
const uint32_t bodyCalculatedCRC2 = CalculateCRC_SB16(*reinterpret_cast<std::vector<uint8_t>*>(&data),
static_cast<size_t>(bitReader.GetAbsoluteBytePosition()),
static_cast<size_t>(bodySize), CRC_SEED);
return bodyReadCrc == bodyCalculatedCRC2;
}
void ReplayFile::FixParents()
{
for (size_t i = 0; i < replayFile->classnets.size(); ++i)
{
const uint32_t index = replayFile->classnets.at(i)->index;
const std::string objectName = replayFile->objects.at(index);
if (classnetMap.find(objectName) != classnetMap.end())
{
auto newClassnet = replayFile->classnets.at(i);
auto originalClassnet = classnetMap[objectName];
//Kind of a cheap hack, just insert map with higher ID properties to start of array so we don't have to find and replace existing ones
//This way the property index cacher will find these newer properties before the old ones thus making the old ones obsolete
originalClassnet->prop_indexes.insert(originalClassnet->prop_indexes.begin(), newClassnet->prop_indexes.begin(), newClassnet->prop_indexes.end());
}
else
{
classnetMap[objectName] = replayFile->classnets.at(i);
}
}
for (auto& archetypeMapping : archetypeMap)
{
if (const auto found = classnetMap.find(archetypeMapping.first); found != classnetMap.end())
{
std::shared_ptr<ClassNet>& headClassnet = found->second;
for (auto& archetype : archetypeMapping.second)
{
classnetMap[archetype] = headClassnet;
}
}
}
//TODO: derive this from gameclasses
for (const auto& [child_name, parent_name] : class_extensions)
{
std::shared_ptr<ClassNet> childClass = GetClassnetByNameWithLookup(child_name);
std::shared_ptr<ClassNet> parentClass = GetClassnetByNameWithLookup(parent_name);
if (parentClass != nullptr && childClass != nullptr
&& (childClass->parent_class == nullptr || (childClass->parent_class->index != parentClass->index)))
{
childClass->parent_class = parentClass;
}
}
for (const auto& cn : replayFile->classnets)
{
uint16_t i = 0;
uint16_t result = GetPropertyIndexById(cn, i);
while (result != 0)
{
cn->property_id_cache.push_back(result);
result = GetPropertyIndexById(cn, ++i);
}
}
const size_t objectsSize = replayFile->objects.size();
parseFunctions.resize(objectsSize);
createFunctions.resize(objectsSize);
for(size_t i = 0; i < objectsSize; i++)
{
const std::string& name = replayFile->objects.at(i);
if(auto found = parsePropertyFuncs.find(name); found != parsePropertyFuncs.end())
{
parseFunctions[i] = found->second;
}
if(auto found = createObjectFuncs.find(name); found != createObjectFuncs.end())
{
createFunctions[i] = found->second;
}
}
const std::vector<std::string> position_names = {
"TAGame.CrowdActor_TA", "TAGame.VehiclePickup_Boost_TA", "TAGame.InMapScoreboard_TA",
"TAGame.BreakOutActor_Platform_TA", "Engine.WorldInfo", "TAGame.HauntedBallTrapTrigger_TA",
"Engine.KActor", "TAGame.CrowdManager_TA", "TAGame.PlayerStart_Platform_TA"
};
const std::vector<std::string> rotation_names = {
"TAGame.Ball_TA", "TAGame.Car_TA", "TAGame.Car_KnockOut_TA", "TAGame.Car_Season_TA",
"TAGame.Ball_Breakout_TA", "TAGame.Ball_Haunted_TA", "TAGame.Ball_God_TA"
};
for(size_t i = 0; i < objectsSize; i++)
{
const std::string& name = replayFile->objects.at(i);
if(std::find(position_names.begin(), position_names.end(), name) != position_names.end())
{
positionIDs.push_back(i);
}
if(std::find(rotation_names.begin(), rotation_names.end(), name) != rotation_names.end())
{
rotationIDs.push_back(i);
}
classnetCache.push_back(GetClassnetByNameWithLookup(name));
if(classnetCache[i])
GetMaxPropertyId(classnetCache[i].get());
}
const size_t size = replayFile->objects.size();
for (uint32_t i = 0; i < size; ++i)
{
objectToId[replayFile->objects.at(i)] = i;
}
const std::vector<std::string> attributeNames =
{
"TAGame.ProductAttribute_UserColor_TA",
"TAGame.ProductAttribute_Painted_TA",
"TAGame.ProductAttribute_TeamEdition_TA",
"TAGame.ProductAttribute_SpecialEdition_TA",
"TAGame.ProductAttribute_TitleID_TA"
};
for(size_t i = 0; i < attributeNames.size(); ++i)
{
const uint32_t attributeID = objectToId[attributeNames.at(i)];
attributeIDs.push_back(attributeID);
}
}
std::string ReplayFile::GetParseLog(size_t amount)
{
std::stringstream ss;
ss << "Parse log: ";
for (size_t i = amount > parseLog.size() ? 0 : parseLog.size() - amount; i < parseLog.size(); i++)
{
ss <<"\n\t" + parseLog.at(i);
}
return ss.str();
}
void ReplayFile::Parse(const uint32_t startPos, int32_t endPos, const uint32_t frameCount)
{
/*
Replay is corrupt, no way we'll parse this correctly
Parsing header is fine though, so only throw this in parse
*/
if (replayFile->header.engineVersion == 0 &&
replayFile->header.licenseeVersion == 0 &&
replayFile->header.netVersion == 0)
{
throw InvalidVersionException(0, 0, 0);
}
if (endPos < 0)
{
endPos = replayFile->netstream_size * 8;
}
CPPBitReader<BitReaderType> networkReader((BitReaderType*)(replayFile->netstream_data), static_cast<size_t>(endPos), replayFile);
try
{
int first = 0;
networkReader.skip(startPos);
//Get some const data we're gonna need repeatedly during parsing and store for performance reasons
const uint32_t numFrames = frameCount > 0 ? frameCount : static_cast<uint32_t>(GetProperty<int32_t>("NumFrames"));
const int32_t maxChannels = GetProperty<int32_t>("MaxChannels");
const bool isLan = GetProperty<std::string>("MatchType") == "Lan";
const size_t namesSize = replayFile->names.size();
const size_t objectsSize = replayFile->objects.size();
const uint32_t engineVersion = replayFile->header.engineVersion;
const uint32_t licenseeVersion = replayFile->header.licenseeVersion;
const bool parseNameId = engineVersion > 868 || (engineVersion == 868 && licenseeVersion >= 20) || (engineVersion == 868 && licenseeVersion >= 14 && !isLan) || ((engineVersion == 868 && licenseeVersion == 17 && isLan));
networkReader.attributeIDs = attributeIDs;
frames.resize(numFrames);
std::vector<uint32_t> updatedProperties;
updatedProperties.reserve(100);
uint32_t currentFrame = 0;
while (
#ifndef PARSE_UNSAFE
networkReader.canRead() &&
#endif
currentFrame < numFrames)
{
Frame& f = frames[currentFrame];
f.frameNumber = currentFrame;
f.position = networkReader.GetAbsoluteBitPosition();
f.time = networkReader.read<float>();
f.delta = networkReader.read<float>();
if constexpr (IncludeParseLog)
{
parseLog.push_back("New frame " + std::to_string(currentFrame) + " at " + std::to_string(f.time) + ", pos " + std::to_string(f.position));
}
#ifndef PARSE_UNSAFE
if (f.time < 0 || f.delta < 0
|| (f.time > 0 && f.time < 1E-10)
|| (f.delta > 0 && f.delta < 1E-10))
{
std::string exceptionText = "Frame time incorrect (parser at wrong position)\n" + GetParseLog(ParseLogSize);
throw GeneralParseException(exceptionText, networkReader);
}
#endif
for (const auto& newFrame : newFrameCallbacks)
{
newFrame(f);
}
//While there are actors in buffer (this frame)
while (networkReader.read<bool>())
{
const uint32_t actorId = networkReader.readBitsMax<uint32_t>(maxChannels);
if (networkReader.read<bool>())
{
//Is new state
if (networkReader.read<bool>())
{
uint32_t name_id;
if (parseNameId)
{
const uint32_t nameId = networkReader.read<uint32_t>();
name_id = nameId;
#ifndef PARSE_UNSAFE
if (nameId > namesSize)
{
throw GeneralParseException("nameId not in replayFile->objects " + std::to_string(nameId) + " > " + std::to_string(namesSize), networkReader);
}
#endif
}
else
{
name_id = 0;
}
const bool unknownBool = networkReader.read<bool>();
const uint32_t typeId = networkReader.read<uint32_t>();
#ifndef PARSE_UNSAFE
if (typeId > objectsSize)
{
throw GeneralParseException("Typeid not in replayFile->objects " + std::to_string(typeId) + " > " + std::to_string(objectsSize), networkReader);
}
#endif
auto& classNet = classnetCache[typeId];
#ifndef PARSE_UNSAFE
if (classNet == nullptr)
{
const std::string typeName = replayFile->objects.at(typeId);
throw GeneralParseException("Classnet for " + typeName + " not found", networkReader);
}
#endif
const uint32_t classId = classNet->index;
const auto& funcPtr = createFunctions[classId];
#ifndef PARSE_UNSAFE
if (funcPtr == nullptr)
{
const std::string className = replayFile->objects.at(classId);
throw GeneralParseException("Could not find class " + className , networkReader);
return;
}
#endif
std::shared_ptr<Engine::Actor> actorObject = funcPtr();
//ActorStateData asd =
if constexpr (IncludeParseLog)
{
const std::string_view typeName = replayFile->objects.at(typeId);
const std::string_view className = replayFile->objects.at(classId);
parseLog.push_back(std::format("New actor for {}, classname {}", typeName, className));
}
if (HasInitialPosition(classId))
{
actorObject->Location = networkReader.read<Vector3I>();
}
if (HasRotation(classId))
{
actorObject->Rotation = networkReader.read<Rotator>();
}
auto [inserted, insert_result] = actorStates.emplace(actorId, ActorStateData{ std::move(actorObject), classNet, actorId, name_id, classId, typeId });
for(const auto& createdFunc : createdCallbacks)
{
createdFunc(inserted->second);
}
}
else //Is existing state
{
ActorStateData& actorState = actorStates[actorId];
updatedProperties.clear();
//While there's data for this state to be updated
while (networkReader.read<bool>())
{
const uint16_t maxPropId = GetMaxPropertyId(actorState.classNet.get());
const uint32_t propertyId = networkReader.readBitsMax<uint32_t>(maxPropId + 1);
const uint32_t propertyIndex = actorState.classNet->property_id_cache[propertyId];
if constexpr (IncludeParseLog)
{
char buff[1024];
snprintf(buff, sizeof(buff), "Calling parser for %s (%i, %i, %s)", replayFile->objects[propertyIndex].c_str(), propertyIndex, actorId, actorState.nameId >= namesSize ? "unknown" : replayFile->names[actorState.nameId].c_str());
parseLog.emplace_back(buff);
}
{
updatedProperties.push_back(propertyIndex);
const auto& funcPtr = parseFunctions[propertyIndex];
/*if (b)
{
printf("Calling parser for %s (%i, %i, %s)\n", replayFile->objects[propertyIndex].c_str(), propertyIndex, actorId, actorState.nameId >= namesSize ? "unknown" : replayFile->names[actorState.nameId].c_str());
}*/
#ifndef PARSE_UNSAFE
if (funcPtr == nullptr)
{
const std::string& objName = replayFile->objects[propertyIndex];
//std::cout << "Property " << objName << " is undefined\n";
std::string exceptionText = "Property " + objName + " is undefined\n" + GetParseLog(ParseLogSize);
throw GeneralParseException(exceptionText, networkReader);
}
#endif
funcPtr(actorState.actorObject.get(), networkReader);
}
}
for(const auto& updateFunc : updatedCallbacks)
{
updateFunc(actorState, updatedProperties);
}
}
}
else
{
ActorStateData& actorState = actorStates[actorId];
for(const auto& deleteFunc : actorDeleteCallbacks)
{
deleteFunc(actorState);
}
actorStates.erase(actorId);
}
}
for (const auto& tick : tickables)
{
tick(f, actorStates);
}
currentFrame++;
}
if (numFrames != currentFrame)
{
throw GeneralParseException("Number of expected frames does not match number of parsed frames. Expected: " + std::to_string(numFrames) + ", parsed: " + std::to_string(currentFrame), networkReader);
}
if (networkReader.size - networkReader.GetAbsoluteBitPosition() > 8192)
{
//Unsure how big RL buffer sizes are, 8192 seems fair
throw GeneralParseException("Not enough bytes parsed! Expected ~" + std::to_string(networkReader.size) + ", parsed: " + std::to_string(networkReader.GetAbsoluteBitPosition()) + ". Diff(" + std::to_string(networkReader.size - networkReader.GetAbsoluteBitPosition()) + ")", networkReader);
}
}
catch (...)
{
printf("Caught ex\n");
//Parse(startPos, endPos);
//fclose(fp);
throw;
}
}
const bool ReplayFile::HasInitialPosition(const uint32_t id) const
{
return std::find(positionIDs.begin(), positionIDs.end(), id) == positionIDs.end();
/*
const uint32_t classId = classNet->index;
const std::string className = replayFile->objects.at(classId);
//auto found = createObjectFuncs.find(className);
const auto& funcPtr = createFunctions[classId];
*/
// return !(name.compare("TAGame.CrowdActor_TA") == 0
// || name.compare("TAGame.VehiclePickup_Boost_TA") == 0
// || name.compare("TAGame.InMapScoreboard_TA") == 0
// || name.compare("TAGame.BreakOutActor_Platform_TA") == 0
// || name.compare("Engine.WorldInfo") == 0
// || name.compare("TAGame.HauntedBallTrapTrigger_TA") == 0
// || name.compare("Engine.KActor") == 0
// || name.compare("TAGame.CrowdManager_TA") == 0);
}
const bool ReplayFile::HasRotation(const uint32_t id) const
{
return std::find(rotationIDs.begin(), rotationIDs.end(), id) != rotationIDs.end();
// return name.compare("TAGame.Ball_TA") == 0
// || name.compare("TAGame.Car_TA") == 0
// || name.compare("TAGame.Car_Season_TA") == 0
// || name.compare("TAGame.Ball_Breakout_TA") == 0
// || name.compare("TAGame.Ball_Haunted_TA") == 0
// || name.compare("TAGame.Ball_God_TA") == 0;
}
const std::pair<const uint32_t, const KeyFrame> ReplayFile::GetNearestKeyframe(uint32_t frame) const
{
if (replayFile->keyframes.size() == 0)
{
return std::make_pair<const uint32_t, KeyFrame>(0, { 0.f, 0,0 });
}
const size_t size = replayFile->keyframes.size();
size_t currentKeyframeIndex = 0;
for (currentKeyframeIndex; currentKeyframeIndex < size; ++currentKeyframeIndex)
{
if (replayFile->keyframes.at(currentKeyframeIndex).frame > frame)
{
break;
}
}
const KeyFrame nearestKeyFrame = replayFile->keyframes.at(currentKeyframeIndex);
const uint32_t frameNumber = nearestKeyFrame.frame;
return std::make_pair(frameNumber, nearestKeyFrame);
}
const bool ReplayFile::ParseProperty(const std::shared_ptr<Property>& currentProperty)
{
currentProperty->property_name = fullReplayBitReader->read<std::string>();
if (currentProperty->property_name.compare("None") == 0) //We're done parsing this prop
{
return false;
}
currentProperty->property_type = fullReplayBitReader->read<std::string>();
const uint32_t propertySize = fullReplayBitReader->read<uint32_t>();
const uint32_t idk = fullReplayBitReader->read<uint32_t>(); //Seems to be index of array
//Not sure why I'm doing these micro optimizations here, kinda hurts readability and its only like a nanosecond
//Update october 2024, this came back to bite me in the ass, good job 2018 me
switch (currentProperty->property_type[0])
{
case 'N':
{
if (currentProperty->property_type[1] == 'o') //Type is "None"
{
return false;
}
else //Type is "Name"
{
currentProperty->value = fullReplayBitReader->read<std::string>();
}
}
break;
case 'I': //IntProperty
{
currentProperty->value = fullReplayBitReader->read<int32_t>();
}
break;
case 'S': //StrProperty / StructProperty
{
if (currentProperty->property_type[3] == 'u') //Type is "StructProperty"
{
auto structName = fullReplayBitReader->read<std::string>();
std::vector<std::shared_ptr<Property>> structFields;
while (true)
{
auto prop = std::make_shared<Property>();
const bool moreToParse = ParseProperty(prop);
if (!moreToParse)
{
break;
}
structFields.push_back(prop);
}
currentProperty->value = StructProperty{ .name = structName, .fields = structFields };
}
else if (currentProperty->property_type[3] == 'P') //Type is "StrProperty"
{
currentProperty->value = fullReplayBitReader->read<std::string>();
}
else
{
assert(1==2);
}
}
break;
case 'B':
{
if (currentProperty->property_type[1] == 'y') //Type is "ByteProperty"
{
EnumProperty ep;
ep.type = fullReplayBitReader->read<std::string>();
if (ep.type.compare("OnlinePlatform_Steam") == 0 || ep.type.compare("OnlinePlatform_PS4") == 0) //for some reason if string is this, there's no value.
{
ep.value = "";
}
else if (ep.type.compare("None") == 0)
{
//TODO: Regression test on older replays
//I guess this just means its a normal char type (int8)
ep.value = fullReplayBitReader->read<uint8_t>(8);
}
else
{
ep.value = fullReplayBitReader->read<std::string>(); //Value
}
currentProperty->value = ep;
}
else //Type is "BoolProperty", but unlike network data, is stored as entire byte
{
if (replayFile->header.engineVersion == 0 &&
replayFile->header.licenseeVersion == 0 &&
replayFile->header.netVersion == 0)
{
currentProperty->value = fullReplayBitReader->read<uint32_t>();
}
else
{
currentProperty->value = fullReplayBitReader->read<uint8_t>();
}
}
}
break;
case 'Q': //QWordProperty
{
currentProperty->value = fullReplayBitReader->read<uint64_t>();
}
break;
case 'F': //FloatProperty
{
currentProperty->value = fullReplayBitReader->read<float>();
}
break;
case 'A': //ArrayProperty
{
const int32_t count = fullReplayBitReader->read<int32_t>();
std::vector<std::unordered_map<std::string, std::shared_ptr<Property>>> properties;
properties.resize(count);
for (int32_t i = 0; i < count; ++i)
{
std::unordered_map<std::string, std::shared_ptr<Property>> props;
while (true)
{
auto baseProperty = std::make_shared<Property>();
const bool moreToParse = ParseProperty(baseProperty);
if (!moreToParse)
{
break;
}
props[baseProperty->property_name] = baseProperty;
}
properties[i] = props;
}
currentProperty->value = properties;
}
break;
default: //Die
//assert(1 == 2);
break;
}
return true;
}
const std::shared_ptr<ClassNet>& ReplayFile::GetClassnetByNameWithLookup(const std::string & name) const
{
static std::shared_ptr<ClassNet> notfound = std::shared_ptr<ClassNet>(nullptr);
static const std::map<std::string, std::string> classnetNamesLookups = {
{"CrowdActor_TA", "TAGame.CrowdActor_TA"},
{"VehiclePickup_Boost_TA", "TAGame.VehiclePickup_Boost_TA"},
{"CrowdManager_TA", "TAGame.CrowdManager_TA"},
{"BreakOutActor_Platform_TA", "TAGame.BreakOutActor_Platform_TA"},
{"WorldInfo", "Engine.WorldInfo"},
{"Archetypes.Teams.TeamWhite", "TAGame.Team_Soccar_TA"},
{"PersistentLevel.KActor", "Engine.KActor"},
{"PlayerStart_Platform_TA", "TAGame.PlayerStart_Platform_TA"},
{"InMapScoreboard_TA", "TAGame.InMapScoreboard_TA"}
};
for (const auto& kv : classnetNamesLookups)
{
if (name.find(kv.first) != std::string::npos)
{
auto found = classnetMap.find(kv.second);
if (found == classnetMap.end())
{
return notfound;
}
return (*found).second;
}
}
auto found = classnetMap.find(name);
if (found == classnetMap.end())
return notfound;
return found->second;
}
const uint16_t ReplayFile::GetPropertyIndexById(const std::shared_ptr<ClassNet>& cn, const int32_t id) const
{
for (int32_t i = 0; i < cn->prop_indexes_size; i++)
{
if (cn->prop_indexes[i].prop_id == id)
{
return cn->prop_indexes[i].prop_index;
}
}
if (cn->parent_class)
{
const std::shared_ptr<ClassNet>& parentNet = cn->parent_class;
if (parentNet == NULL) //Is root?
{
return cn->index;
}
return this->GetPropertyIndexById(parentNet, id);
}
return 0;
}
const uint16_t ReplayFile::GetMaxPropertyId(ClassNet* cn)
{
if (cn == nullptr)
{
throw std::runtime_error("ClassNet is nullptr");
}
if (cn->max_prop_id == 0)
{
cn->max_prop_id = FindMaxPropertyId(cn, 0);
}
return cn->max_prop_id;
}
const uint16_t ReplayFile::FindMaxPropertyId(const ClassNet* cn, uint16_t maxProp) const
{
if (cn == nullptr)
{
return maxProp;
}
for (int32_t i = 0; i < cn->prop_indexes_size; ++i)
{
if (cn->prop_indexes[i].prop_id > maxProp)
{
maxProp = cn->prop_indexes[i].prop_id;
}
}
if (cn->parent_class)
{
return FindMaxPropertyId(cn->parent_class.get(), maxProp);
}
return maxProp;
}
const bool ReplayFile::HasProperty(const std::string & key) const
{
return replayFile->properties.find(key) != replayFile->properties.end();
}
}
| 29,923
|
C++
|
.cpp
| 842
| 31.064133
| 291
| 0.685133
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,006
|
ReplayException.cpp
|
Bakkes_CPPRP/CPPRP/exceptions/ReplayException.cpp
|
#include "ReplayException.h"
#include <sstream>
namespace CPPRP
{
InvalidVersionException::InvalidVersionException(const uint32_t engine, const uint32_t licensee, const uint32_t net) : engineVersion(engine), licenseeVersion(licensee), netVersion(net)
{
std::stringstream ss;
ss << "Invalid version (" << std::to_string(engineVersion) << ", " << std::to_string(licenseeVersion) << ", " << std::to_string(netVersion) << ")";
errorMsg = ss.str();
}
InvalidVersionException::~InvalidVersionException() {}
const char * InvalidVersionException::what() const throw()
{
return errorMsg.c_str();
}
};
| 609
|
C++
|
.cpp
| 16
| 36
| 185
| 0.730964
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,007
|
ParseException.cpp
|
Bakkes_CPPRP/CPPRP/exceptions/ParseException.cpp
|
#include "ParseException.h"
namespace CPPRP
{
PropertyDoesNotExistException::PropertyDoesNotExistException(const std::string& propertyName_) : propertyName(propertyName_)
{
std::stringstream ss;
ss << "Property with key \"" << propertyName << "\" does not exist in properties map.";
errorMsg = ss.str().c_str();
}
PropertyDoesNotExistException::~PropertyDoesNotExistException() {}
const char * PropertyDoesNotExistException::what() const throw()
{
return errorMsg.c_str();
}
};
| 497
|
C++
|
.cpp
| 15
| 30.866667
| 125
| 0.757322
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,008
|
simpleplaythrough.cpp
|
Bakkes_CPPRP/examples/simpleplaythrough.cpp
|
#include "../CPPRP/ReplayFile.h"
#include "../CPPRP/ReplayException.h"
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <atomic>
#include <algorithm>
#include <map>
#include <filesystem>
#include <queue>
#include <unordered_map>
#undef max
int main(int argc, char *argv[])
{
auto replayFile = std::make_shared<CPPRP::ReplayFile>("/windows2/alpaca/2F6924754EEC41B468694D9537E4C1D7.replay");
replayFile->Load();
replayFile->DeserializeHeader();
for (auto it : replayFile->GetProperty<std::vector<std::unordered_map<std::string, std::shared_ptr<CPPRP::Property>>>>("PlayerStats"))
{
for (auto it2 : it)
{
//printf("%s\n", it2.first.c_str());
}
}
std::vector<CPPRP::TAGame::Car_TA> cars;
replayFile->createdCallbacks.push_back([&](const CPPRP::ActorStateData& asd)
{
//std::cout << "New actor created " << typeid(*asd.actorObject).name() << "\n";
});
std::map<uint32_t, std::unordered_map<uint32_t, CPPRP::Vector3>> locations;
replayFile->tickables.push_back([&](const uint32_t frameNumber, const std::unordered_map<int, CPPRP::ActorStateData>& actorStats)
{
for (auto& actor : actorStats)
{
std::shared_ptr<CPPRP::TAGame::Car_TA> car = std::dynamic_pointer_cast<CPPRP::TAGame::Car_TA>(actor.second.actorObject);
if (car)
{
//printf("%i\n", actor.first);
locations[frameNumber][actor.first] = car->ReplicatedRBState.position;
}
}
});
replayFile->updatedCallbacks.push_back([&](const CPPRP::ActorStateData& actor, const std::vector<uint32_t>& updatedProperties)
{
std::shared_ptr<CPPRP::Engine::PlayerReplicationInfo> gameEvent = std::dynamic_pointer_cast<CPPRP::Engine::PlayerReplicationInfo>(actor.actorObject);
if(gameEvent)
{
const uint32_t replicatedIndex = replayFile->objectToId["Engine.PlayerReplicationInfo:PlayerName"];
// std::string wot = "";
// for(auto prop : updatedProperties)
// {
// wot += std::to_string(prop) + ", ";
// }
//printf("Test: (%i) -> (%s): %i - ", replicatedIndex, wot.c_str(), (int)(std::find(updatedProperties.begin(), updatedProperties.end(), replicatedIndex) != updatedProperties.end()));
if((std::find(updatedProperties.begin(), updatedProperties.end(), replicatedIndex) != updatedProperties.end()))
{
printf("SkillTier %s\n", gameEvent->PlayerName.c_str());
//printf("%s\n", gameEvent->DodgeTorque.ToString().c_str());
//if(gameEvent->ReplicatedStatEvent.object_id >= 0)
//printf("New winner %s\n", replayFile->replayFile->objects[gameEvent->ReplicatedStatEvent.object_id].c_str());
//printf("New state name [%i] %s\n", gameEvent->ReplicatedStateName, replayFile->replayFile->names[gameEvent->ReplicatedStateName].c_str());
}
}
});
replayFile->PreprocessTables();
replayFile->Parse();
int fdfsd = 5;
system("pause");
return 0;
}
| 3,179
|
C++
|
.cpp
| 71
| 37.014085
| 194
| 0.62674
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,009
|
CPPBM.cpp
|
Bakkes_CPPRP/CPPRPBM/CPPBM.cpp
|
#include "CPPBM.h"
#include <math.h>
BAKKESMOD_PLUGIN(CPPBM, "CPPBM", "0.1", 0);
Quat normalize(Quat q) {
double n = sqrt(q.X*q.X + q.Y * q.Y + q.Z * q.Z + q.W * q.W);
q.X /= n;
q.Y /= n;
q.Z /= n;
q.W /= n;
return q;
}
Quat minusQuat(Quat v0, Quat v1)
{
return { v0.X - v1.X, v0.Y - v1.Y, v0.Z - v1.Z, v0.W - v1.W };
}
Quat mulQuat(Quat lhs, Quat rhs)
{
return { (lhs.W * rhs.X) + (lhs.X * rhs.W) + (lhs.Y * rhs.Z) - (lhs.Z * rhs.Y),
(lhs.W * rhs.Y) + (lhs.Y * rhs.W) + (lhs.Z * rhs.X) - (lhs.X * rhs.Z),
(lhs.W * rhs.Z) + (lhs.Z * rhs.W) + (lhs.X * rhs.Y) - (lhs.Y * rhs.X),
(lhs.W * rhs.W) - (lhs.X * rhs.X) - (lhs.Y * rhs.Y) - (lhs.Z * rhs.Z) };
}
Quat mulQuat(float t, Quat v1)
{
return { t * v1.X, t * v1.Y, t * v1.Z, t * v1.W };
}
Quat plusQuat(Quat v0, Quat v1)
{
return { v0.X + v1.X, v0.Y + v1.Y, v0.Z + v1.Z, v0.W + v1.W };
}
//
//Quat slerp(Quat qa, Quat qb, float t) {
//
// Quat qm = Quat();
// // Calculate angle between them.
// double cosHalfTheta = qa.W * qb.W + qa.X * qb.X + qa.Y * qb.Y + qa.Z * qb.Z;
// // if qa=qb or qa=-qb then theta = 0 and we can return qa
// if (abs(cosHalfTheta) >= 1.0f) {
// qm.W = qa.W; qm.X = qa.X; qm.Y = qa.Y; qm.Z = qa.Z;
// return qm;
// }
// // Calculate temporary values.
// double halfTheta = acos(cosHalfTheta);
// double sinHalfTheta = sqrt(1.0 - cosHalfTheta * cosHalfTheta);
// // if theta = 180 degrees then result is not fully defined
// // we could rotate around any a.Xis normal to qa or qb
// if (fabs(sinHalfTheta) < 0.001f) { // fabs is floating point absolute
// qm.W = (qa.W * 0.5f + qb.W * 0.5f);
// qm.X = (qa.X * 0.5f + qb.X * 0.5f);
// qm.Y = (qa.Y * 0.5f + qb.Y * 0.5f);
// qm.Z = (qa.Z * 0.5f + qb.Z * 0.5f);
// return qm;
// }
// double ratioA = sin((1.f - t) * halfTheta) / sinHalfTheta;
// double ratioB = sin(t * halfTheta) / sinHalfTheta;
// //calculate Quaternion.
// qm.W = (qa.W * ratioA + qb.W * ratioB);
// qm.X = (qa.X * ratioA + qb.X * ratioB);
// qm.Y = (qa.Y * ratioA + qb.Y * ratioB);
// qm.Z = (qa.Z * ratioA + qb.Z * ratioB);
// return qm;
//
// // Only unit quaternions are valid rotations.
// // Normalize to avoid undefined behavior.
// //v0 = normalize(v0);
// //v1 = normalize(v1);
//
// //// Compute the cosine of the angle between the two vectors.
// //double dot = v0.X * v1.X + v0.Y * v1.Y + v0.Z * v1.Z + v0.W * v1.W ;
//
// //// If the dot product is negative, slerp won't take
// //// the shorter path. Note that v1 and -v1 are equivalent when
// //// the negation is applied to all four components. Fix by
// //// reversing one quaternion.
// //if (dot < 0.0f) {
// // v1 = v1.conjugate();
// // v1 = mulQuat(1 / v1.X*v1.X + v1.Y * v1.Y + v1.Z * v1.Z + v1.W * v1.W, v1);
// // dot = -dot;
// //}
//
// //const double DOT_THRESHOLD = 0.9995;
// //if (dot > DOT_THRESHOLD) {
// // // If the inputs are too close for comfort, linearly interpolate
// // // and normalize the result.
//
// // Quat result = plusQuat(v0, mulQuat(t, minusQuat(v1, v0)));
// // result = normalize(result);
// // return result;
// //}
//
// //// Since dot is in range [0, DOT_THRESHOLD], acos is safe
// //double theta_0 = acos(dot); // theta_0 = angle between input vectors
// //double theta = theta_0 * t; // theta = angle between v0 and result
// //double sin_theta = sin(theta); // compute this value only once
// //double sin_theta_0 = sin(theta_0); // compute this value only once
//
// //double s0 = cos(theta) - dot * sin_theta / sin_theta_0; // == sin(theta_0 - theta) / sin(theta_0)
// //double s1 = sin_theta / sin_theta_0;
//
// //return plusQuat(mulQuat(s0, v0), mulQuat(s1 , v1));
//}
Quat slerp(Quat q1, Quat q2, float t)
{
float w1, x1, y1, z1, w2, x2, y2, z2, w3, x3, y3, z3;
Quat q2New;
float theta, mult1, mult2;
w1 = q1.W; x1 = q1.X; y1 = q1.Y; z1 = q1.Z;
w2 = q2.W; x2 = q2.X; y2 = q2.Y; z2 = q2.Z;
// Reverse the sign of q2 if q1.q2 < 0.
if (w1*w2 + x1 * x2 + y1 * y2 + z1 * z2 < 0)
{
w2 = -w2; x2 = -x2; y2 = -y2; z2 = -z2;
}
theta = acos(w1*w2 + x1 * x2 + y1 * y2 + z1 * z2);
if (theta > 0.000001)
{
mult1 = sin((1 - t)*theta) / sin(theta);
mult2 = sin(t*theta) / sin(theta);
}
// To avoid division by 0 and by very small numbers the approximation of sin(angle)
// by angle is used when theta is small (0.000001 is chosen arbitrarily).
else
{
mult1 = 1.f - t;
mult2 = t;
}
w3 = mult1 * w1 + mult2 * w2;
x3 = mult1 * x1 + mult2 * x2;
y3 = mult1 * y1 + mult2 * y2;
z3 = mult1 * z1 + mult2 * z2;
return Quat(w3, x3, y3, z3);
}
void CPPBM::onLoad()
{
replayFile = std::make_shared<CPPRP::ReplayFile>("K:/Alpaca1000/0E42C57743B81717DBD855B1085F2D79.replay");
gameWrapper->HookEventWithCaller<CarWrapper>("Function TAGame.Car_TA.SetVehicleInput",
bind(&CPPBM::OnTick, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
gameWrapper->HookEvent("Function Engine.GameViewportClient.Tick",
bind(&CPPBM::GVCTick, this, std::placeholders::_1));
replayFile->Load();
replayFile->DeserializeHeader();
//for (auto it : replayFile->GetProperty<std::vector<std::unordered_map<std::string, std::shared_ptr<CPPRP::Property>>>>("PlayerStats"))
{
//for (auto it2 : it)
{
// printf("%s\n", it2.first.c_str());
}
}
replayFile->tickables.push_back([&](const CPPRP::Frame f, const std::unordered_map<int, CPPRP::ActorStateData>& actorStats)
{
for (auto& actor : actorStats)
{
std::shared_ptr<CPPRP::TAGame::Car_TA> car = std::dynamic_pointer_cast<CPPRP::TAGame::Car_TA>(actor.second.actorObject);
if (car)
{
cvarManager->log("replicatedsteer " + std::to_string((int)car->ReplicatedSteer));
ReplicationData rd;
rd.rbState = car->ReplicatedRBState;
rd.steer = car->ReplicatedSteer;
rd.throttle = car->ReplicatedThrottle;
rd.handbrake = car->bReplicatedHandbrake;
rd.delta = replayFile->frames[f.frameNumber].time - replayFile->frames[0].time;
locations[f.frameNumber][actor.first] = rd;
cvarManager->log("replicatedsteer " + std::to_string(car->ReplicatedRBState.position.x) + "|" + std::to_string(car->ReplicatedRBState.position.y) + "|" + std::to_string(car->ReplicatedRBState.position.z) + "|" + std::to_string(rd.steer) );
}
}
});
replayFile->Parse();
const uint32_t numFrames = static_cast<uint32_t>(replayFile->GetProperty<int32_t>("NumFrames"));
for (auto& act : locations[0])
{
for (uint32_t frame = 0; frame < numFrames; )
{
//cvarManager->log("test");
auto foundHere = locations[frame].find(act.first);
if (foundHere != locations[frame].end())
{
int framesAdd = 1;
while (true)
{
auto foundNext = locations[frame + framesAdd].find(act.first);
if (foundNext == locations[frame + framesAdd].end())
{
--foundNext;
--framesAdd;
break;
}
if (abs(foundNext->second.rbState.position.x - foundHere->second.rbState.position.x) > .1
|| abs(foundNext->second.rbState.position.y - foundHere->second.rbState.position.y) > .1
|| abs(foundNext->second.rbState.position.z - foundHere->second.rbState.position.z) > .1)
break;
framesAdd++;
}
auto start = locations[frame][act.first];
auto end = locations[frame + framesAdd][act.first];
float diff = end.delta - start.delta;
for (int i = frame + 1; i < frame + framesAdd; i++)
{
float elaps = locations[i][act.first].delta - start.delta;
float ff = (elaps / diff);
Quat oldQuat(start.rbState.rotation.w, start.rbState.rotation.x, start.rbState.rotation.y, start.rbState.rotation.z);
Quat nextQuat(end.rbState.rotation.w, end.rbState.rotation.x, end.rbState.rotation.y, end.rbState.rotation.z);
Quat slerped = slerp(oldQuat, nextQuat, 1.f - ff);
locations[i][act.first].rbState.position = {
start.rbState.position.x + (end.rbState.position.x - start.rbState.position.x) * ff,
start.rbState.position.y + (end.rbState.position.y - start.rbState.position.y) * ff,
start.rbState.position.z + (end.rbState.position.z - start.rbState.position.z) * ff,
};
locations[i][act.first].rbState.linear_velocity = {
start.rbState.linear_velocity.x * (1.f - ff) + end.rbState.linear_velocity.x * (ff),
start.rbState.linear_velocity.y * (1.f - ff) + end.rbState.linear_velocity.y * (ff),
start.rbState.linear_velocity.z * (1.f - ff) + end.rbState.linear_velocity.z * (ff)
};
locations[i][act.first].rbState.angular_velocity = {
start.rbState.angular_velocity.x * (1.f - ff) + end.rbState.angular_velocity.x * (ff),
start.rbState.angular_velocity.y * (1.f - ff) + end.rbState.angular_velocity.y * (ff),
start.rbState.angular_velocity.z * (1.f - ff) + end.rbState.angular_velocity.z * (ff)
};
//locations[i][act.first].rbState.rotation = { slerped.X, slerped.Y, slerped.Z, slerped.W };
}
cvarManager->log("diff: " + std::to_string(framesAdd));
frame += framesAdd == 0 ? 1 : framesAdd;
}
else
{
frame++;
}
}
}
for (auto& act : locations[0])
{
for (uint32_t frame = 0; frame < numFrames; )
{
//cvarManager->log("test");
auto foundHere = locations[frame].find(act.first);
if (foundHere != locations[frame].end())
{
int framesAdd = 1;
while (true)
{
auto foundNext = locations[frame + framesAdd].find(act.first);
if (foundNext == locations[frame + framesAdd].end())
{
--foundNext;
--framesAdd;
break;
}
if (abs(foundNext->second.rbState.rotation.x - foundHere->second.rbState.rotation.x) > .001
|| abs(foundNext->second.rbState.rotation.y - foundHere->second.rbState.rotation.y) > .001
|| abs(foundNext->second.rbState.rotation.z - foundHere->second.rbState.rotation.z) > .001
|| abs(foundNext->second.rbState.rotation.w - foundHere->second.rbState.rotation.w) > .001)
break;
framesAdd++;
}
auto start = locations[frame][act.first];
auto end = locations[frame + framesAdd][act.first];
float diff = end.delta - start.delta;
for (int i = frame + 1; i < frame + framesAdd; i++)
{
float elaps = locations[i][act.first].delta - start.delta;
float ff = (elaps / diff);
Quat oldQuat(start.rbState.rotation.w, start.rbState.rotation.x, start.rbState.rotation.y, start.rbState.rotation.z);
Quat nextQuat(end.rbState.rotation.w, end.rbState.rotation.x, end.rbState.rotation.y, end.rbState.rotation.z);
Quat slerped = slerp(oldQuat, nextQuat, ff);
locations[i][act.first].rbState.position = {
start.rbState.position.x + (end.rbState.position.x - start.rbState.position.x) * ff,
start.rbState.position.y + (end.rbState.position.y - start.rbState.position.y) * ff,
start.rbState.position.z + (end.rbState.position.z - start.rbState.position.z) * ff,
};
locations[i][act.first].rbState.linear_velocity = {
start.rbState.linear_velocity.x * (1.f - ff) + end.rbState.linear_velocity.x * (ff),
start.rbState.linear_velocity.y * (1.f - ff) + end.rbState.linear_velocity.y * (ff),
start.rbState.linear_velocity.z * (1.f - ff) + end.rbState.linear_velocity.z * (ff)
};
locations[i][act.first].rbState.angular_velocity = {
start.rbState.angular_velocity.x * (1.f - ff) + end.rbState.angular_velocity.x * (ff),
start.rbState.angular_velocity.y * (1.f - ff) + end.rbState.angular_velocity.y * (ff),
start.rbState.angular_velocity.z * (1.f - ff) + end.rbState.angular_velocity.z * (ff)
};
//locations[i][act.first].rbState.rotation = { slerped.X, slerped.Y, slerped.Z, slerped.W };
}
cvarManager->log("diff: " + std::to_string(framesAdd));
frame += framesAdd == 0 ? 1 : framesAdd;
}
else
{
frame++;
}
}
}
currentFrame = locations.begin()->first;
currentFrameIngame = 0;
}
void CPPBM::onUnload()
{
}
void CPPBM::GVCTick(std::string name)
{
auto found = locations.find(currentFrame);
auto nextFound = locations.find(currentFrame + 1);
if (found == locations.end() || nextFound == locations.end())
return;
//for (auto loc2 : found->second)
//{
// cvarManager->log(" - " + std::to_string(loc2.second.steer));
//}
auto actorToGetLoc = ++found->second.begin();
auto nextActorToGetLoc = ++nextFound->second.begin();
if (actorToGetLoc == found->second.end() || nextActorToGetLoc == nextFound->second.end())
return;
cvarManager->log(std::to_string(actorToGetLoc->second.steer));
CPPRP::ReplicatedRBState rbState = actorToGetLoc->second.rbState;
CPPRP::ReplicatedRBState nextRbState = nextActorToGetLoc->second.rbState;
if (gameWrapper->GetGameEventAsServer().GetCars().Count() == 0)return;
auto cw = gameWrapper->GetGameEventAsServer().GetCars().Get(0);
auto carRbState = cw.GetCurrentRBState();
float delta = nextActorToGetLoc->second.delta - actorToGetLoc->second.delta;
std::chrono::duration<float, std::milli> applied2 = std::chrono::system_clock::now() - timeApplied;
float applied = applied2.count() / 1000.f;
float diff = applied - actorToGetLoc->second.delta;
float ff = (diff / delta);
//float ff = applied / .33f;
//cvarManager->log("Perc:" + std::to_string(ff) + "|" + std::to_string(currentFrame));
Quat oldQuat(rbState.rotation.w, rbState.rotation.x, rbState.rotation.y, rbState.rotation.z);
Quat nextQuat(nextRbState.rotation.w, nextRbState.rotation.x, nextRbState.rotation.y, nextRbState.rotation.z);
carRbState.Quaternion = slerp(oldQuat, nextQuat, ff);
//{ rbState.rotation.w * ff + nextRbState.rotation.w * (1.f - ff),
// rbState.rotation.x * ff + nextRbState.rotation.x * (1.f - ff),
// rbState.rotation.y * ff + nextRbState.rotation.y * (1.f - ff) ,
// rbState.rotation.z * ff + nextRbState.rotation.z * (1.f - ff) };
carRbState.Location = {
rbState.position.x + (nextRbState.position.x - rbState.position.x ) * ff,
rbState.position.y + (nextRbState.position.y - rbState.position.y) * ff,
rbState.position.z + (nextRbState.position.z - rbState.position.z) * ff
};
cvarManager->log("Interped " + std::to_string(ff) + " | " + std::to_string(carRbState.Quaternion.W) + " > " + std::to_string(carRbState.Quaternion.X) + "|" + std::to_string(carRbState.Quaternion.Y) + "|" + std::to_string(carRbState.Quaternion.Z) + "|" + std::to_string(carRbState.Location.X) + "|" + std::to_string(carRbState.Location.Y) + "|" + std::to_string(carRbState.Location.Z) /*+ std::to_string(framesAdd)*/);
carRbState.LinearVelocity = {
rbState.linear_velocity.x * ff + nextRbState.linear_velocity.x * (1.f - ff),
rbState.linear_velocity.y * ff + nextRbState.linear_velocity.y * (1.f - ff),
rbState.linear_velocity.z * ff + nextRbState.linear_velocity.z * (1.f - ff)
};
carRbState.AngularVelocity = {
rbState.angular_velocity.x * ff + nextRbState.angular_velocity.x * (1.f - ff),
rbState.angular_velocity.y * ff + nextRbState.angular_velocity.y * (1.f - ff),
rbState.angular_velocity.z * ff + nextRbState.angular_velocity.z * (1.f - ff)
};
//cw.SetLocation(carRbState.Location);
//cw.GetCollisionComponent().SetbDisableAllRigidBody(true);
//cw.SetRBState(carRbState);
if (diff + (1.f / 150.f) > delta) currentFrame++;
//cw.SetLocation(carRbState.Location);
}
void CPPBM::OnTick(CarWrapper cw, void * params, std::string funcName)
{
static bool b = false;
if (!b)
{
b = true;
for (auto loc : locations)
{
for (auto loc2 : loc.second)
{
cvarManager->log(std::to_string(loc.first) + " - " + std::to_string(loc2.second.steer));
}
}
}
auto found = locations.find(currentFrame);
auto nextFound = locations.find(currentFrame + 1);
if (found == locations.end() || nextFound == locations.end())
return;
for (auto loc2 : found->second)
{
//cvarManager->log(" - " + std::to_string(loc2.second.steer));
}
auto actorToGetLoc = (++found->second.begin());
auto nextActorToGetLoc = (++nextFound->second.begin());
if (actorToGetLoc == found->second.end() || nextActorToGetLoc == nextFound->second.end())
return;
//cvarManager->log(std::to_string(actorToGetLoc->second.steer));
CPPRP::ReplicatedRBState rbState = actorToGetLoc->second.rbState;
CPPRP::ReplicatedRBState nextRbState = nextActorToGetLoc->second.rbState;
//cw.SetLocation({ cppRPvec.x, cppRPvec.y, cppRPvec.z});
auto carRbState = cw.GetCurrentRBState();
float ff = 1.f - (1.f / (float)((currentFrameIngame % 4) + 1));
//cvarManager->log(std::to_string(ff));
/*carRbState.Quaternion = { rbState.rotation.w * ff + rbState.rotation.w * (1.f - ff),
rbState.rotation.x * ff + nextRbState.rotation.x * (1.f - ff),
rbState.rotation.y * ff + nextRbState.rotation.y * (1.f - ff) ,
rbState.rotation.z * ff + nextRbState.rotation.z * (1.f - ff) };*/
//carRbState.Quaternion = slerp(rbState.rotation, nextRbState.rotation, ff);
carRbState.Location = {
rbState.position.x * ff + nextRbState.position.x * (1.f -ff),
rbState.position.y * ff + nextRbState.position.y * (1.f - ff),
rbState.position.z * ff + nextRbState.position.z * (1.f - ff)
};
carRbState.LinearVelocity = {
rbState.linear_velocity.x * ff + nextRbState.linear_velocity.x * (1.f - ff),
rbState.linear_velocity.y * ff + nextRbState.linear_velocity.y * (1.f - ff),
rbState.linear_velocity.z * ff + nextRbState.linear_velocity.z * (1.f - ff)
};
carRbState.AngularVelocity = {
rbState.angular_velocity.x * ff + nextRbState.angular_velocity.x * (1.f - ff),
rbState.angular_velocity.y * ff + nextRbState.angular_velocity.y * (1.f - ff),
rbState.angular_velocity.z * ff + nextRbState.angular_velocity.z * (1.f - ff)
};
cw.SetRBState(carRbState);
/*carRbState.Quaternion = { rbState.rotation.w, rbState.rotation.x, rbState.rotation.y, rbState.rotation.z };
carRbState.Location = { rbState.position.x, rbState.position.y, rbState.position.z };
carRbState.LinearVelocity = { rbState.linear_velocity.x, rbState.linear_velocity.y, rbState.linear_velocity.z };
carRbState.AngularVelocity = { rbState.angular_velocity.x, rbState.angular_velocity.y, rbState.angular_velocity.z };
*/
//cw.SetLocation(carRbState.Location);
//cw.SetVelocity(carRbState.LinearVelocity);
//cw.SetAngularVelocity(carRbState.AngularVelocity, 0);
/*cvarManager->log("Old throttle: " + std::to_string((int)(actorToGetLoc->second.throttle)));
cvarManager->log("Throttle " + std::to_string(((float)(actorToGetLoc->second.throttle - 128) / 128.f)));
cvarManager->log("Old steer: " + std::to_string((int)(actorToGetLoc->second.steer)));
cvarManager->log("Steer " + std::to_string(((float)(actorToGetLoc->second.steer - 128) / 128.f)));*/
ControllerInput* input = (ControllerInput*)params;
input->Steer = ((float)(actorToGetLoc->second.steer - 128) / 128.f) * ff + ((float)(nextActorToGetLoc->second.steer - 128) / 128.f) * (1.f-ff);
input->Throttle = ((float)(actorToGetLoc->second.throttle - 128) / 128.f) * ff + ((float)(nextActorToGetLoc->second.throttle - 128) / 128.f) * (1.f - ff);
input->Handbrake = (actorToGetLoc->second.handbrake);
//cw.SetInput(inp);
//
//cw.SetbUpdateSimulatedPosition(true);
//cw.SetbReplayActor(true);
//cw.SetbReplicateRigidBodyLocation(true);
//cw.SetReplicatedRBState(carRbState);
//cw.SetRBState(carRbState);
//cw.SetOldRBState(carRbState);
//cw.SetClientCorrectionRBState(carRbState);
if (currentFrameIngame == 0)
{
timeApplied = std::chrono::system_clock::now();
//timeApplied = gameWrapper->GetGameEventAsServer().GetSecondsElapsed();
}
if (currentFrameIngame% 4 == 0)
{
//cw.SetPhysicsState(carRbState);
/*cw.SetLocation(carRbState.Location);
cw.SetVelocity(carRbState.LinearVelocity);
cw.SetAngularVelocity(carRbState.AngularVelocity, 0);*/
//cw.SetPhysicsState(carRbState);
//currentFrame++;
}
currentFrameIngame++;
//cvarManager->log("Tick");
}
| 19,709
|
C++
|
.cpp
| 448
| 40.850446
| 418
| 0.665397
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,010
|
main.cpp
|
Bakkes_CPPRP/CPPRPPlayer/main.cpp
|
#include "IReplayPlayer.h"
#include <string>
#include <queue>
class Timer
{
private:
std::chrono::time_point<std::chrono::steady_clock> start;
std::chrono::time_point<std::chrono::steady_clock> end;
bool ended = false;
std::string name;
public:
Timer(std::string timerName) : name(timerName)
{
start = std::chrono::steady_clock::now();
}
void Stop()
{
end = std::chrono::steady_clock::now();
ended = true;
}
~Timer()
{
if (!ended) Stop();
std::cout << name << " duration in microseconds : "
<< std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< "\n";
/*std::cout << "Elapsed time in milliseconds : "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
<< " ms\n";*/
}
};
struct FK
{
float time;
std::string name;
};
struct GT
{
float speed;
std::string name;
};
std::mutex kickoffMutex;
std::vector<FK> kickoffs;
std::vector<GT> fastgoals;
std::vector<GT> slowgoals;
std::mutex queueMutex;
//static std::string fastestKickoffFile = "";
//static float fastestKickoff = 10.f;
void AnalyzeReplay(std::filesystem::path& replayPath)
{
using namespace CPPRP::ReplayPlaying;
auto replayFile = std::make_shared<CPPRP::ReplayFile>(replayPath);
replayFile->Load();
replayFile->DeserializeHeader();
replayFile->PreprocessTables();
IReplayPlayer p(replayFile);
replayFile->Parse();
//float k = p.GetFastestKickoff();
//float fastestGoal = p.GetFastestGoal();
std::lock_guard<std::mutex> mtx(kickoffMutex);
kickoffs.push_back({p.GetFastestKickoff(), replayPath.string()});
fastgoals.push_back({ p.GetFastestGoal(), replayPath.string() });
slowgoals.push_back({ p.GetSlowestGoal(), replayPath.string() });
//if (k < fastestKickoff)
//{
// fastestKickoff = k;
// fastestKickoffFile = replayPath.string();
//}
printf("Fastest goal that replay was: %.3f\n", p.GetFastestGoal());
}
int main(int argc, char* argv[])
{
std::queue<std::filesystem::path> replayFilesToLoad;
{
//std::filesystem::path p("C:\\Users\\Bakkes\\Documents\\My Games\\Rocket League\\TAGame\\Demos\\");
std::filesystem::path p;
if (argc > 1)
p = std::filesystem::path(argv[1]);
else
p = std::filesystem::path("C:\\Users\\Bakkes\\Downloads\\RLCS Season 9-20200723T230751Z-001\\RLCS Season 9\\");
printf("Reading path %s\n", p.u8string().c_str());
if (std::filesystem::is_regular_file(p))
{
replayFilesToLoad.push(p);
}
else
{
for (const auto& entry : std::filesystem::recursive_directory_iterator(p))
{
if (entry.path().filename().u8string().find(".replay") == std::string::npos)
continue;
if (replayFilesToLoad.size() >= 5335345)
break;
replayFilesToLoad.push(entry.path());
}
}
}
auto analyzeLambda = [&replayFilesToLoad]()
{
while (true)
{
std::filesystem::path replayF;
{
std::lock_guard<std::mutex> lockGuard(queueMutex);
if (replayFilesToLoad.empty())
{
break;
}
replayF = replayFilesToLoad.front();
replayFilesToLoad.pop();
}
try
{
AnalyzeReplay(replayF);
}
catch (...) {}
}
};
{
Timer t("Analyze");
const int bothReplayThreadsCount = 8;
if (bothReplayThreadsCount == 1)
{
analyzeLambda();
}
else
{
std::vector<std::thread> bothReplayThreads;
for (size_t i = 0; i < bothReplayThreadsCount; ++i)
{
std::thread bothReplayThread = std::thread{
analyzeLambda
};
bothReplayThreads.emplace_back(std::move(bothReplayThread));
}
for (auto& t : bothReplayThreads)
{
t.join();
}
}
}
printf("Kickoffs\n");
std::sort(kickoffs.begin(), kickoffs.end(), [](auto lhs, auto rhs) { return lhs.time < rhs.time; });
for (int i = 0; i < 5; ++i)
{
printf("%s: %.4f\n", kickoffs.at(i).name.c_str(), kickoffs.at(i).time);
}
//printf("%s: %.4f", fastestKickoffFile.c_str(), fastestKickoff);
printf("\n\nFastest goals\n");
std::sort(fastgoals.begin(), fastgoals.end(), [](auto lhs, auto rhs) { return lhs.speed > rhs.speed; });
for (int i = 0; i < 5; ++i)
{
printf("%s: %.4f km/h\n", fastgoals.at(i).name.c_str(), fastgoals.at(i).speed);
}
printf("\n\nSlowest goals\n");
std::sort(slowgoals.begin(), slowgoals.end(), [](auto lhs, auto rhs) { return lhs.speed < rhs.speed; });
for (int i = 0; i < 5; ++i)
{
printf("%s: %.4f km/h\n", slowgoals.at(i).name.c_str(), slowgoals.at(i).speed);
}
return 0;
}
| 4,389
|
C++
|
.cpp
| 162
| 24.216049
| 114
| 0.667381
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,011
|
IReplayPlayer.cpp
|
Bakkes_CPPRP/CPPRPPlayer/IReplayPlayer.cpp
|
#include "IReplayPlayer.h"
namespace CPPRP
{
namespace ReplayPlaying
{
float IReplayPlayer::GetFastestKickoff()
{
if (kickoffSpeeds.size() == 0) return 9999.f;
return *kickoffSpeeds.begin();
}
float IReplayPlayer::GetFastestGoal()
{
if (scoreSpeeds.size() == 0) return -1.f;
return *scoreSpeeds.begin();
}
float IReplayPlayer::GetSlowestGoal()
{
if (scoreSpeeds.size() == 0) return 10000.f;
return *scoreSpeeds.rbegin();
}
IReplayPlayer::IReplayPlayer(std::shared_ptr<CPPRP::ReplayFile> replay) : replay_(replay)
{
using namespace std::placeholders;
replay->tickables.push_back(std::bind(&IReplayPlayer::OnTick, this, _1, _2));
replay->newFrameCallbacks.push_back(std::bind(&IReplayPlayer::OnNewFrame, this, _1));
replay->createdCallbacks.push_back(std::bind(&IReplayPlayer::OnActorCreated, this, _1));
replay->updatedCallbacks.push_back(std::bind(&IReplayPlayer::OnActorUpdated, this, _1, _2));
replay->actorDeleteCallbacks.push_back(std::bind(&IReplayPlayer::OnActorDeleted, this, _1));
RegisterActorUpdate<ProjectX::GRI_X>(FIELD(ProjectX::GRI_X::bGameStarted),
[](const std::shared_ptr<ProjectX::GRI_X>& actor, std::string& propertyName)
{
//printf("Game has started: %s\n", actor->MatchGUID.c_str());
});
RegisterActorUpdate<TAGame::GameEvent_Soccar_TA>(FIELD(TAGame::GameEvent_Soccar_TA::SecondsRemaining),
[](const std::shared_ptr<TAGame::GameEvent_Soccar_TA>& actor, std::string& propertyName)
{
//printf("GameTime: %i\n", actor->SecondsRemaining);
});
RegisterActorUpdate<TAGame::GameEvent_TA>(FIELD(TAGame::GameEvent_TA::ReplicatedRoundCountDownNumber),
[¤tGameState_ = currentGameState_](const std::shared_ptr<TAGame::GameEvent_TA>& actor, std::string& propertyName)
{
//printf("Countdown: %i\n", actor->ReplicatedRoundCountDownNumber);
currentGameState_ = actor->ReplicatedRoundCountDownNumber == 0 ? GameState::Playing : GameState::Countdown;
});
RegisterActorUpdate<TAGame::GameEvent_Soccar_TA>(FIELD(TAGame::GameEvent_Soccar_TA::bBallHasBeenHit),
[&timeSinceBallHit = timeSinceBallHit,
&lastVal = lastVal,
&kickoffSpeeds = kickoffSpeeds](const std::shared_ptr<TAGame::GameEvent_Soccar_TA>& actor, std::string& propertyName)
{
if (actor->bBallHasBeenHit == lastVal)
return;
//Time between kickoff and ball hit
if (!actor->bBallHasBeenHit)
{
timeSinceBallHit = 0.f;
}
else
{
kickoffSpeeds.insert(timeSinceBallHit);
//printf("Time since ball hit: %.3f\n", timeSinceBallHit);
}
lastVal = actor->bBallHasBeenHit;
//printf("Ball has been hit: %i\n", actor->bBallHasBeenHit);
});
RegisterActorUpdate<TAGame::Team_TA>(FIELD(TAGame::Team_TA::CustomTeamName), [](const std::shared_ptr<TAGame::Team_TA>& actor, std::string& propertyName)
{
//printf("Score update: %s\n", actor->CustomTeamName.c_str());
});
RegisterActorUpdate<TAGame::GameEvent_Soccar_TA>(FIELD(TAGame::GameEvent_Soccar_TA::ReplicatedScoredOnTeam), [&](const std::shared_ptr<TAGame::GameEvent_Soccar_TA>& actor, std::string& propertyName)
{
bool hasbol = false;
//printf("AAAAAAAAA: %i\n", actor->MatchGoals);
for (const auto& act : replay_->actorStates)
{
if (auto c = std::dynamic_pointer_cast<CPPRP::TAGame::Ball_TA>(act.second.actorObject))
{
auto lin_vel = c->ReplicatedRBState.linear_velocity;
float abc = powf(lin_vel.x, 2) + powf(lin_vel.y, 2) + powf(lin_vel.z, 2);
abc = sqrt(abc);
if (abc > .001f)
{
const float kmh = (abc * 60 * 60) / 100000;
scoreSpeeds.insert(kmh);
//printf("Score speed: %.2f\n", abc);
}
}
}
if (hasbol == false)
{
//printf("No bol!!\n");
}
});
}
void IReplayPlayer::OnTick(const Frame frame, const std::unordered_map<int, ActorStateData>& actorData)
{
timeSinceBallHit += frame.delta;
//printf("[%i] Hit frame: %i\n", currentGameState_, frame.frameNumber);
}
void IReplayPlayer::OnNewFrame(const Frame frame)
{
}
void IReplayPlayer::OnActorCreated(const ActorStateData& createdActor)
{
}
void IReplayPlayer::OnActorUpdated(const ActorStateData& updatedActor, const std::vector<uint32_t>& updatedProperties)
{
for (auto prop : updatedProperties)
{
for (auto& cb : variableUpdates_[prop])
{
std::string abc = "";
cb(updatedActor.actorObject, abc);
}
}
}
void IReplayPlayer::OnActorDeleted(const ActorStateData& deletedActor)
{//
}
}
}
| 4,631
|
C++
|
.cpp
| 120
| 33.508333
| 201
| 0.684705
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,012
|
main.cpp
|
Bakkes_CPPRP/CPPRPJSON/main.cpp
|
#include "CPPRPJSON.h"
class Timer
{
private:
std::chrono::time_point<std::chrono::steady_clock> start;
std::chrono::time_point<std::chrono::steady_clock> end;
bool ended = false;
std::string name;
public:
Timer(std::string timerName) : name(timerName)
{
start = std::chrono::steady_clock::now();
}
void Stop()
{
end = std::chrono::steady_clock::now();
ended = true;
}
~Timer()
{
if (!ended) Stop();
std::cout << name << " duration in microseconds : "
<< std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()
<< "\n";
/*std::cout << "Elapsed time in milliseconds : "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
<< " ms\n";*/
}
};
int main(int argc, char* argv[])
{
OptionsParser op(argc, argv);
std::string inputFile = op.looseOption;
if (inputFile.size() == 0)
{
inputFile = op.GetStringValue({ "i", "input" });
}
if (inputFile.size() == 0)
{
std::cerr << "No input file given! Pass path to replay file as default argument via -i or --input\n";
return 1;
}
if (!std::filesystem::exists(inputFile))
{
std::cerr << "Failed to open file " << inputFile << "\n";
return 1;
}
auto replayFile = std::make_shared<CPPRP::ReplayFile>(inputFile);
if (!replayFile->Load())
{
std::cerr << "Cannot open file, it exists but cannot open? " << inputFile << "\n";
return 1;
}
{
//std::cout << "File size: " << replayFile->data.size() << " bytes\n";
}
{
//Timer crcTimer("CRC");
int crc = op.GetIntValue({ "crc", "verify" }, 0);
if (crc < 0 || crc > CPPRP::CrcCheck::CRC_Both)
{
std::cerr << "Invalid value given for crc check (0 = no check, 1 = verify header, 2 = verify body, 3 = verify both)\n";
return 1;
}
if (crc != 0 && !replayFile->VerifyCRC((CPPRP::CrcCheck)crc))
{
std::cerr << "CRC check failed! Replay file " << inputFile << " is probably corrupt or has been tampered with!";
return 1;
}
}
//Timer t("Time including header deserialization");
try
{
replayFile->DeserializeHeader();
}
catch (CPPRP::GeneralParseException<BitReaderType>& gpe)
{
std::cerr << "DeserializeHeader threw exception: " << gpe.errorMsg << "\n";
return 1;
}
const bool parseBody = !op.GetBoolValue({ "ho", "header" }, false);
const bool doDryRun = op.GetBoolValue({ "dry" }, false);
//Timer t2("Time without header deserialization");
if (doDryRun)
{
if (parseBody)
{
replayFile->Parse();
}
}
else
{
rapidjson::StringBuffer s(0, 20000000); //Allocate 20mb
/*FILE* fp = NULL;
fopen_s(&fp, "test.json", "wb");
char writeBuffer[65536];
rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));*/
const int precision = op.GetIntValue({ "p", "precision" }, 0);
bool result = 0;
if (false) {}
#ifdef CPPRP_PRETTYSUPPORT
else if (const bool writePretty = op.GetBoolValue({ "pretty", "prettify" }, false); writePretty)
{
auto writer = rapidjson::PrettyWriter<rapidjson::StringBuffer>(s);
result = ParseBodyAndSerializeReplay(writer, replayFile, parseBody, precision);
}
#endif
else
{
auto writer = rapidjson::Writer<rapidjson::StringBuffer>(s);
result = ParseBodyAndSerializeReplay(writer, replayFile, parseBody, precision);
}
if (result != 0) //we got an error
{
return result;
}
std::string outJsonString = s.GetString();
std::string outFile = op.GetStringValue({ "o", "output" });
if (outFile.size() > 0)
{
std::ofstream outFileStream(outFile);
outFileStream << outJsonString;
}
if ((outFile.size() > 0 && op.GetBoolValue({ "stdout", "print" }, false)) || (outFile.size() == 0 && op.GetBoolValue({ "stdout", "print" }, true)))
{
std::cout << outJsonString;
}
}
//t.Stop();
//t2.Stop();
}
| 3,736
|
C++
|
.cpp
| 131
| 25.824427
| 149
| 0.657939
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,014
|
bakkesmodloadoutlib.h
|
Bakkes_CPPRP/loadoutextractor/bakkesmodloadoutlib.h
|
#pragma once
#include <map>
#include "bmloadout.h"
#include <iostream>
#include "helper_classes.h"
static inline void print_loadout(BMLoadout loadout)
{
std::cout << "HEADER " << std::endl << "\tVersion: " << unsigned(loadout.header.version) << std::endl;
std::cout << "\tSize in bytes: " << loadout.header.code_size << std::endl;
std::cout << "\tCRC: " << unsigned(loadout.header.crc) << std::endl << std::endl;
std::cout << "Blue is orange: " << (loadout.body.blue_is_orange ? "true" : "false") << std::endl;
std::cout << "Blue: " << std::endl;
for (auto body : loadout.body.blue_loadout)
{
std::cout << "\tSlot: " << unsigned(body.first) << ", ID: " << body.second.product_id << ", paint: " << unsigned(body.second.paint_index) << std::endl;
}
if (loadout.body.blueColor.should_override) {
std::cout << "Color Primary (" << unsigned(loadout.body.blueColor.primary_colors.r) << ", " << unsigned(loadout.body.blueColor.primary_colors.g) << ", " << unsigned(loadout.body.blueColor.primary_colors.b) << ")";
std::cout << " Secondary (" << unsigned(loadout.body.blueColor.secondary_colors.r) << ", " << unsigned(loadout.body.blueColor.secondary_colors.g) << ", " << unsigned(loadout.body.blueColor.secondary_colors.b) << ")";
}
if (!loadout.body.blue_is_orange)
{
std::cout << std::endl << "Orange: " << std::endl;
for (auto body : loadout.body.orange_loadout)
{
std::cout << "\tSlot: " << unsigned(body.first) << ", ID: " << body.second.product_id << ", paint: " << unsigned(body.second.paint_index) << std::endl;
}
if (loadout.body.orangeColor.should_override) {
std::cout << "Color Primary (" << unsigned(loadout.body.orangeColor.primary_colors.r) << ", " << unsigned(loadout.body.orangeColor.primary_colors.g) << ", " << unsigned(loadout.body.orangeColor.primary_colors.b) << ")";
std::cout << " Secondary (" << unsigned(loadout.body.orangeColor.secondary_colors.r) << ", " << unsigned(loadout.body.orangeColor.secondary_colors.g) << ", " << unsigned(loadout.body.orangeColor.secondary_colors.b) << ")";
}
}
std::cout << std::endl << std::endl;
}
static inline std::map<uint8_t, Item> read_items_from_buffer(BitBinaryReader<unsigned char>& reader)
{
std::map<uint8_t, Item> items;
int itemsSize = reader.ReadBits<int>(4); //Read the length of the item array
for (int i = 0; i < itemsSize; i++)
{
Item option;
int slotIndex = reader.ReadBits<int>(5); //Read slot of item
int productId = reader.ReadBits<int>(13); //Read product ID
bool isPaintable = reader.ReadBool(); //Read whether item is paintable or not
if (isPaintable)
{
int paintID = reader.ReadBits<int>(6); //Read paint index
option.paint_index = paintID;
}
option.product_id = productId;
option.slot_index = slotIndex;
items.insert_or_assign(slotIndex, option); //Add item to loadout at its selected slot
}
return items;
}
static inline RGB read_colors_from_buffer(BitBinaryReader<unsigned char>& reader)
{
RGB col;
col.r = reader.ReadBits<uint8_t>(8);
col.g = reader.ReadBits<uint8_t>(8);
col.b = reader.ReadBits<uint8_t>(8);
return col;
}
static inline BMLoadout load(std::string loadoutString)
{
BitBinaryReader<unsigned char> reader(loadoutString);
BMLoadout loadout;
/*
Reads header
VERSION (6 bits)
SIZE_IN_BYTES (10 bits)
CRC (8 BITS)
*/
loadout.header.version = reader.ReadBits<uint8_t>(6);
loadout.header.code_size = reader.ReadBits<uint16_t>(10);
loadout.header.crc = reader.ReadBits<uint8_t>(8);
/* Verification (can be skipped if you already know the code is correct) */
/*
Calculate whether code_size converted to base64 is actually equal to the given input string
Mostly done so we don't end up with invalid buffers, but this step is not required.
*/
int stringSizeCalc = ((int)ceil((4 * (float)loadout.header.code_size / 3)) + 3) & ~3;
int stringSize = loadoutString.size();
if (abs(stringSizeCalc - stringSize) > 6) //Diff may be at most 4 (?) because of base64 padding, but we check > 6 because IDK
{
//Given input string is probably invalid, handle
std::cout << "Invalid input string size!";
exit(0);
}
/*
Verify CRC, aka check if user didn't mess with the input string to create invalid loadouts
*/
if (!reader.VerifyCRC(loadout.header.crc, 3, loadout.header.code_size))
{
//User changed characters in input string, items isn't valid! handle here
std::cout << "Invalid input string! CRC check failed";
exit(0);
}
//At this point we know the input string is probably correct, time to parse the body
loadout.body.blue_is_orange = reader.ReadBool(); //Read single bit indicating whether blue = orange
loadout.body.blue_loadout = read_items_from_buffer(reader); //Read loadout
loadout.body.blueColor.should_override = reader.ReadBool(); //Read whether custom colors is on
if (loadout.body.blueColor.should_override) {
/* Read rgb for primary colors (0-255)*/
loadout.body.blueColor.primary_colors = read_colors_from_buffer(reader);
/* Read rgb for secondary colors (0-255)*/
loadout.body.blueColor.secondary_colors = read_colors_from_buffer(reader);
}
if (loadout.body.blue_is_orange) //User has same loadout for both teams
{
loadout.body.orange_loadout = loadout.body.blue_loadout;
}
else {
loadout.body.orange_loadout = read_items_from_buffer(reader);
loadout.body.orangeColor.should_override = reader.ReadBool(); //Read whether custom colors is on
if (loadout.body.blueColor.should_override) {
/* Read rgb for primary colors (0-255)*/
loadout.body.orangeColor.primary_colors = read_colors_from_buffer(reader);
/* Read rgb for secondary colors (0-255)*/
loadout.body.orangeColor.secondary_colors = read_colors_from_buffer(reader);
}
}
return loadout;
}
static inline void write_loadout(BitBinaryWriter<unsigned char>& writer, std::map<uint8_t, Item> loadout)
{
//Save current position so we can write the length here later
const int amountStorePos = writer.current_bit;
//Reserve 4 bits to write size later
writer.WriteBits(0, 4);
//Counter that keeps track of size
int loadoutSize = 0;
for (auto opt : loadout)
{
//In bakkesmod, when unequipping the productID gets set to 0 but doesn't
//get removed, so we do this check here.
if (opt.second.product_id <= 0)
continue;
loadoutSize++;
writer.WriteBits(opt.first, 5); //Slot index, 5 bits so we get slot upto 31
writer.WriteBits(opt.second.product_id, 13); //Item id, 13 bits so upto 8191 should be enough
writer.WriteBool(opt.second.paint_index > 0); //Bool indicating whether item is paintable or not
if (opt.second.paint_index > 0) //If paintable
{
writer.WriteBits(opt.second.paint_index, 6); //6 bits, allow upto 63 paints
}
}
//Save current position of writer
const int amountStorePos2 = writer.current_bit;
writer.current_bit = amountStorePos;
//Write the size of the loadout to the spot we allocated earlier
writer.WriteBits(loadoutSize, 4); //Gives us a max of 15 customizable slots per team
writer.current_bit = amountStorePos2; //Set back reader to original position
}
static inline void write_color(BitBinaryWriter<unsigned char>& writer, RGB color)
{
writer.WriteBits(color.r, 8);
writer.WriteBits(color.g, 8);
writer.WriteBits(color.b, 8);
}
static inline std::string save(BMLoadout loadout)
{
//Allocate buffer thats big enough
BitBinaryWriter<unsigned char> writer(10000);
writer.WriteBits(CURRENT_LOADOUT_VERSION, 6); //Write current version
/*
We write 18 empty bits here, because we determine size and CRC after writing the whole loadout
but we still need to allocate this space in advance
*/
writer.WriteBits(0, 18);
writer.WriteBool(loadout.body.blue_is_orange); //Write blue == orange?
write_loadout(writer, loadout.body.blue_loadout);
writer.WriteBool(loadout.body.blueColor.should_override); //Write override blue car colors or not
if (loadout.body.blueColor.should_override)
{
write_color(writer, loadout.body.blueColor.primary_colors); // write primary colors RGB (R = 0-255, G = 0-255, B = 0-255)
write_color(writer, loadout.body.blueColor.secondary_colors); //write secondary
}
if (!loadout.body.blue_is_orange)
{
write_loadout(writer, loadout.body.orange_loadout);
writer.WriteBool(loadout.body.orangeColor.should_override);//Write override orange car colors or not
if (loadout.body.orangeColor.should_override)
{
write_color(writer, loadout.body.orangeColor.primary_colors); //write primary
write_color(writer, loadout.body.orangeColor.secondary_colors); //write secondary
}
}
const int currentBit = writer.current_bit; //Save current location of writer
int sizeInBytes = currentBit / 8 + (currentBit % 8 == 0 ? 0 : 1); //Calculate how many bytes are used
writer.current_bit = 6; //Set writer to header (bit 6)
writer.WriteBits(sizeInBytes, 10); //Write size
writer.WriteBits(writer.CalculateCRC(3, sizeInBytes), 8); //Write calculated CRC
writer.current_bit = currentBit; //Set writer back to original position
return writer.ToHex();
}
| 9,211
|
C++
|
.h
| 196
| 43.362245
| 226
| 0.711347
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,017
|
bench.h
|
Bakkes_CPPRP/CPPRPTest/bench.h
|
#pragma once
//https://stackoverflow.com/questions/2349776/how-can-i-benchmark-c-code-easily
#ifdef _WIN32
#include <windows.h>
double get_time()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart / (double)f.QuadPart;
}
#else
#include <sys/time.h>
#include <sys/resource.h>
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#endif
#define BENCHMARK(name, func, iterations) \
{\
double start_time = get_time();\
for(int aaaa = 0; aaaa < iterations; aaaa++) {\
func;\
}\
double end_time = get_time();\
double elapsed = (end_time-start_time) * 1000.f;\
printf("[%s] Ran %i iterations in %.5f ms (avg: %.5f ms)\n", name, iterations, elapsed, (elapsed/(double)iterations));\
}
| 813
|
C++
|
.h
| 32
| 23.96875
| 119
| 0.72
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,018
|
CRC.h
|
Bakkes_CPPRP/CPPRP/CRC.h
|
#pragma once
#include <stdint.h>
#include <string>
#include <vector>
#include <memory>
#include <array>
namespace CPPRP
{
enum { Crc32Poly = 0x04c11db7 };
constexpr static inline uint32_t swap(uint32_t x)
{
#if defined(__GNUC__) || defined(__clang__)
return __builtin_bswap32(x);
#else
return (x >> 24) | ((x >> 8) & 0x0000FF00) |
((x << 8) & 0x00FF0000) | (x << 24);
#endif
}
/*
Generate lookup tables at compile time
*/
template<uint32_t SIZE>
constexpr std::array<std::array<uint32_t, 256>, SIZE> GenerateTable(const uint32_t poly)
{
std::array<std::array<uint32_t, 256>, SIZE> crcLookupTable{};
for (uint32_t cell = 0; cell != 256; ++cell)
{
uint32_t crc = cell << 24;
for (uint32_t repeat = 8; repeat; --repeat)
{
crc = (crc & 0x80000000) ? (crc << 1) ^ poly : (crc << 1);
}
if constexpr (SIZE == 1) //Special case for 1, don't swap crc. Dont need to do it in 2nd loop since we only fill [0] when SIZE=1
{
crcLookupTable[0][cell] = crc;
}
else
{
crcLookupTable[0][cell] = swap(crc);
}
}
for (uint32_t cell = 0; cell != 256; ++cell)
{
uint32_t crc = swap(crcLookupTable[0][cell]);
for (uint32_t table = 1; table < SIZE; ++table)
{
crc = swap(crcLookupTable[0][crc >> 24]) ^ (crc << 8);
crcLookupTable[table][cell] = swap(crc);
}
}
return crcLookupTable;
}
template<typename T>
static const uint32_t CalculateCRC_SB1(const std::vector<T>& data, const size_t startPosition, const size_t length, uint32_t crc)
{
constexpr auto CRCTableSB1 = GenerateTable<1>(Crc32Poly);
crc = ~crc;
for (size_t i = startPosition; i < startPosition + length; ++i)
{
crc = (crc << 8) ^ CRCTableSB1[0][static_cast<uint8_t>(data[i]) ^ (crc >> 24)];
}
return ~crc;
}
template<typename T>
static const uint32_t CalculateCRC_SB8(const std::vector<T>& data, const size_t startPosition, size_t length, uint32_t crc)
{
constexpr auto CRCTableSB8 = GenerateTable<8>(Crc32Poly);
crc = ~swap(crc);
const uint8_t* __restrict currentData = (uint8_t*)(data.data() + startPosition);
// Align 4 bytes
uint32_t preProcessBytes = ((reinterpret_cast<std::uintptr_t>(currentData) + 3) & ~(3)) - reinterpret_cast<std::uintptr_t>(currentData);
if (length > preProcessBytes)
{
length -= preProcessBytes;
while (preProcessBytes--)
{
crc = (crc >> 8) ^ CRCTableSB8[0][*currentData++ ^ (crc & 0xFF)];
}
const uint32_t* processBy8 = (const uint32_t*)currentData;
uint32_t times = length >> 3;//divide by 8
while (times--)
{
uint32_t one = *processBy8++ ^ crc;
uint32_t two = *processBy8++;
crc =
CRCTableSB8[7][one & 0xFF] ^
CRCTableSB8[6][(one >> 8) & 0xFF] ^
CRCTableSB8[5][(one >> 16) & 0xFF] ^
CRCTableSB8[4][one >> 24] ^
CRCTableSB8[3][two & 0xFF] ^
CRCTableSB8[2][(two >> 8) & 0xFF] ^
CRCTableSB8[1][(two >> 16) & 0xFF] ^
CRCTableSB8[0][two >> 24];
}
currentData = (const uint8_t*)processBy8;
length &= 7; //mod 8
}
//process remaining bits
while (length--)
{
crc = (crc >> 8) ^ CRCTableSB8[0][*currentData++ ^ (crc & 0xFF)];
}
return swap(~crc);
};
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <xmmintrin.h>
#ifdef __MINGW32__
#define PREFETCH(location) __builtin_prefetch(location)
#else
#define PREFETCH(location) _mm_prefetch(location, _MM_HINT_T0)
#endif
#else
#ifdef __GNUC__
#define PREFETCH(location) __builtin_prefetch(location)
#else
#define PREFETCH(location) ;
#endif
#endif
//Based on SB8 and crc32_16bytes_prefetch in crc32.cpp from https://create.stephan-brumme.com/crc32
template<typename T>
static const uint32_t CalculateCRC_SB16(const std::vector<T>& data, const size_t startPosition, size_t length, uint32_t crc)
{
constexpr auto CRCTableSB16 = GenerateTable<16>(Crc32Poly);
crc = ~swap(crc);
const uint8_t* __restrict currentData = (uint8_t*)(data.data() + startPosition);
// Align 8 bytes
uint32_t preProcessBytes = ((reinterpret_cast<std::uintptr_t>(currentData) + 3) & ~(3)) - reinterpret_cast<std::uintptr_t>(currentData);
if (length > preProcessBytes)
{
length -= preProcessBytes;
while (preProcessBytes--)
{
crc = (crc >> 8) ^ CRCTableSB16[0][*currentData++ ^ (crc & 0xFF)];
}
const uint32_t* processBy8 = (const uint32_t*)currentData;
uint32_t times = length >> 4;//divide by 16
constexpr size_t unrollSize = 4;
constexpr size_t bytesAtOnce = 16 * unrollSize;
constexpr size_t prefetchAhead = 256;
while (length >= bytesAtOnce)
{
PREFETCH(((const char*)processBy8) + prefetchAhead);
for (size_t unroll = 0; unroll < unrollSize; unroll++) //let compiler unroll this
{
uint32_t one = *processBy8++ ^ crc;
uint32_t two = *processBy8++;
uint32_t three = *processBy8++;
uint32_t four = *processBy8++;
crc =
CRCTableSB16[0][(four >> 24) & 0xFF] ^
CRCTableSB16[1][(four >> 16) & 0xFF] ^
CRCTableSB16[2][(four >> 8) & 0xFF] ^
CRCTableSB16[3][four & 0xFF] ^
CRCTableSB16[4][(three >> 24) & 0xFF] ^
CRCTableSB16[5][(three >> 16) & 0xFF] ^
CRCTableSB16[6][(three >> 8) & 0xFF] ^
CRCTableSB16[7][three & 0xFF] ^
CRCTableSB16[8][(two >> 24) & 0xFF] ^
CRCTableSB16[9][(two >> 16) & 0xFF] ^
CRCTableSB16[10][(two >> 8) & 0xFF] ^
CRCTableSB16[11][two & 0xFF] ^
CRCTableSB16[12][(one >> 24) & 0xFF] ^
CRCTableSB16[13][(one >> 16) & 0xFF] ^
CRCTableSB16[14][(one >> 8) & 0xFF] ^
CRCTableSB16[15][one & 0xFF];
}
length -= bytesAtOnce;
}
currentData = (const uint8_t*)processBy8;
//length &= (16-1); //mod 16 not needed since we substract from length above
}
//process remaining bits
while (length--)
{
crc = (crc >> 8) ^ CRCTableSB16[0][*currentData++ ^ (crc & 0xFF)];
}
return swap(~crc);
};
};
| 5,865
|
C++
|
.h
| 179
| 29.03352
| 138
| 0.640495
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,019
|
PropertyParser.h
|
Bakkes_CPPRP/CPPRP/PropertyParser.h
|
#pragma once
#include <unordered_map>
#include <functional>
#include <memory>
#include "./data/GameClasses.h"
namespace CPPRP
{
typedef std::function<std::shared_ptr<Engine::Actor>()> createObjectFunc;
typedef std::function<void(Engine::Actor*, CPPBitReader<BitReaderType>& br)> parsePropertyFunc;
static std::unordered_map<std::string, createObjectFunc> createObjectFuncs;
static std::unordered_map<std::string, parsePropertyFunc> parsePropertyFuncs;
template<typename T1>
inline static std::shared_ptr<Engine::Actor> createObject()
{
return std::make_shared<T1>();
}
template<typename T1>
inline static void RegisterClass(std::string className)
{
createObjectFuncs[className] = &createObject<T1>;
}
template<typename T>
inline static void RegisterField(const std::string& str, T callback)
{
parsePropertyFuncs[str] = callback;
}
template<typename T>
inline static T Initializor()
{
#define GAMECLASS(namesp, classn) RegisterClass<namesp::classn>(xstr(namesp) "." xstr(classn));
#define fulln(namesp, classn, propname) xstr(namesp) "." xstr(classn) ":" xstr(propname)
#define GAMEFIELD(namesp, classn, propname, nameoftype) \
RegisterField(fulln(namesp, classn, propname), [](Engine::Actor* struc, CPPBitReader<BitReaderType>& br) { ((CPPRP::namesp::classn*)(struc))->propname = Consume<nameoftype>(br); })
#include "./generated/GameClassMacros.h"
#undef GAMECLASS
#undef fulln
#undef GAMEFIELD
return 0;
}
static int T = Initializor<int>();
}
| 1,490
|
C++
|
.h
| 41
| 34.243902
| 181
| 0.766875
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,020
|
NetworkDataParsers.h
|
Bakkes_CPPRP/CPPRP/NetworkDataParsers.h
|
#pragma once
#include "./data/NetworkData.h"
#include <vector>
#include <sstream>
#include "./exceptions/ParseException.h"
#include "CPPBitReader.h"
#include <variant>
/*
File responsible for parsing network data, which are the fields in the game classes
Basically means it should parse all structs defined in data/NetworkData.h.
This file parses all which need special treatment (for example when stuff has changed in a version, and we need to do version checks)
Others are auto generated and written to ./generated/NetworkDataParserGenerated.h
*/
namespace CPPRP
{
template<typename T>
inline const T Consume(CPPBitReader<BitReaderType>& reader) { return reader.read<T>(); }
template<typename T>
inline const std::vector<T> ConsumeVector(CPPBitReader<BitReaderType>& reader) {
uint8_t size = reader.read<uint8_t>();
std::vector<T> vec;
vec.resize(size);
for (uint8_t i = 0; i < size; i++)
{
vec[i] = Consume<T>(reader);
}
return vec;
}
template<>
inline const AttributeType Consume(CPPBitReader<BitReaderType>& reader) {
//Make sure this matches attributeNames in the preprocess function
enum class AttributeTypes : size_t
{
UserColor = 0,
Painted,
TeamEdition,
SpecialEdition,
TitleID,
MAX
};
AttributeType att;
bool unknown1 = reader.read<bool>();
uint32_t class_index = reader.read<uint32_t>();
size_t index = std::distance(reader.attributeIDs.begin(),
std::find(reader.attributeIDs.begin(), reader.attributeIDs.end(), class_index));
switch((AttributeTypes)index)
{
case AttributeTypes::UserColor:
{
if (reader.licenseeVersion >= 23)
{
auto tmp = ProductAttributeUserColorRGB();
{
tmp.r = reader.read<uint8_t>();
tmp.g = reader.read<uint8_t>();
tmp.b = reader.read<uint8_t>();
tmp.a = reader.read<uint8_t>();
att = tmp;
}
}
else
{
auto tmp = ProductAttributeUserColorSingle();
tmp.has_value = reader.read<bool>();
if (tmp.has_value)
{
tmp.value = reader.read<uint32_t>(31);
}
else
{
tmp.value = 0;
}
att = tmp;
}
}
break;
case AttributeTypes::Painted:
{
auto tmp = ProductAttributePainted();
if (reader.engineVersion >= 868 && reader.licenseeVersion >= 18)
{
tmp.value = reader.read<uint32_t>(31);
}
else
{
tmp.value = reader.readBitsMax<uint32_t>(14);
}
att = tmp;
}
break;
case AttributeTypes::TeamEdition:
{
auto tmp = ProductAttributeTeamEdition();
tmp.value = reader.read<uint32_t>(31);
att = tmp;
}
break;
case AttributeTypes::SpecialEdition:
{
auto tmp = ProductAttributeSpecialEdition();
tmp.value = reader.read<uint32_t>(31);
att = tmp;
}
break;
case AttributeTypes::TitleID:
{
auto tmp = ProductAttributeTitle();
tmp.title = reader.read<std::string>();
att = tmp;
}
break;
default:
case AttributeTypes::MAX:
{
throw AttributeParseException<BitReaderType>("Unable to parse attribute with ID: " + std::to_string(class_index), reader);
}
break;
}
std::visit(
[unknown1, class_index](ProductAttribute& base)
{
base.unknown1 = unknown1;
base.class_index = class_index;
},
att);
//std::get<ProductAttribute>(att).unknown1 = unknown1;
//std::get<ProductAttribute>(att).class_index = class_index;
return att;
}
template<>
inline const ClientLoadout Consume(CPPBitReader<BitReaderType>& reader) {
ClientLoadout item;
item.version = reader.read<uint8_t>();
item.body = reader.read<uint32_t>();
item.skin = reader.read<uint32_t>();
item.wheels = reader.read<uint32_t>();
item.boost = reader.read<uint32_t>();
item.antenna = reader.read<uint32_t>();
item.hat = reader.read<uint32_t>();
item.unknown2 = reader.read<uint32_t>();
if (item.version > 10)
{
item.unknown3 = reader.read<uint32_t>();
}
if (item.version >= 16)
{
item.engine_audio = reader.read<uint32_t>();
item.trail = reader.read<uint32_t>();
item.goal_explosion = reader.read<uint32_t>();
}
if (item.version >= 17)
{
item.banner = reader.read<uint32_t>();
}
if (item.version >= 19)
{
item.unknown4 = reader.read<uint32_t>();
}
if (item.version >= 22)
{
item.unknown5 = reader.read<uint32_t>();
item.unknown6 = reader.read<uint32_t>();
item.unknown7 = reader.read<uint32_t>();
}
return item;
}
template<>
inline const ReplicatedRBState Consume(CPPBitReader<BitReaderType>& reader) {
ReplicatedRBState item;
const uint32_t netVersion = reader.netVersion;
//PREFETCH((char*)(reader.data));
item.sleeping = reader.read<bool>();
if (netVersion >= 5)
{
item.position = reader.read<Vector3>();
if (netVersion < 7)
{
item.position = { item.position.x * 10, item.position.y * 10, item.position.z * 10 };
}
}
else
{
item.position = static_cast<Vector3>(reader.read<Vector3I>());
}
if (netVersion >= 7)
{
item.rotation = reader.read<Quat>();
}
else
{
item.rotation.x = reader.readFixedCompressedFloat(1, 16);
item.rotation.y = reader.readFixedCompressedFloat(1, 16);
item.rotation.z = reader.readFixedCompressedFloat(1, 16);
item.rotation.w = 0;
}
if (!item.sleeping)
{
item.linear_velocity = reader.read<Vector3>();
item.angular_velocity = reader.read<Vector3>();
}
else
{
item.linear_velocity = { 0 };
item.angular_velocity = { 0 };
}
return item;
}
template<>
inline const PartyLeader Consume(CPPBitReader<BitReaderType>& reader) {
PartyLeader item;
uint8_t test = reader.read<uint8_t>();
if (test != 0)
{
reader.goback(8);
item.id = reader.read<OnlineID>();
}
else
{
UniqueId ui;
ui.platform = 0;
ui.splitscreenID = 0;
item.id = ui;
}
return item;
}
template<>
inline const GameMode Consume(CPPBitReader<BitReaderType>& reader) {
GameMode item;
if (reader.engineVersion >= 868 && reader.licenseeVersion >= 12)
{
item.gamemode = reader.read<uint8_t>();
}
else
{
item.gamemode = reader.read<uint8_t>(2);
}
return item;
}
template<>
inline const PickupInfo_TA Consume(CPPBitReader<BitReaderType>& reader)
{
PickupInfo_TA item;
ActiveActor itemz;
itemz.active = reader.read<bool>();
itemz.actor_id = reader.read<int32_t>();
item.AvailablePickups = itemz;
item.bItemsArePreview = reader.read<bool>();
item.unknown = reader.read<bool>();
return item;
}
template<>
inline const Reservation Consume(CPPBitReader<BitReaderType>& reader) {
Reservation item;
item.number = reader.read<uint8_t>(3);
item.player_id = reader.read<OnlineID>();
//Is always an unique ID
if (reinterpret_cast<UniqueId*>(&item.player_id)->platform == Platform_Unknown && (reader.licenseeVersion <= 18 || reader.netVersion != 0))
{
}
else
{
item.player_name = reader.read<std::string>();
}
if (reader.engineVersion >= 868 && reader.licenseeVersion >= 12)
{
item.status = reader.read<uint8_t>();
}
else
{
item.status = reader.read<uint8_t>(2);
}
return item;
}
template<>
inline const GameServer Consume(CPPBitReader<BitReaderType>& reader)
{
GameServer item = GameServer {0, ""};
//Update >= "221120.42953.406184" use a string for buildID, lower uses uint64_t
if (reader.buildVersion < std::string("221120.42953.406184"))
{
item.GameServerID = reader.read<uint64_t>();
}
else
{
item.GameServerIDString = reader.read<std::string>();
}
return item;
}
#include "./generated/NetworkDataParsersGenerated.h"
}
| 7,583
|
C++
|
.h
| 290
| 22.537931
| 141
| 0.681153
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,021
|
CPPBitReader.h
|
Bakkes_CPPRP/CPPRP/CPPBitReader.h
|
#pragma once
#include <string>
#include <sstream>
#include <stdint.h>
#include <assert.h>
//#include "ParseException.h"
#include "./data/ReplayFileData.h"
//#include "ReplayFile.h"
#include "./exceptions/ReplayException.h"
#include <cmath>
#include <memory>
#include <xmmintrin.h>
//#define USESIMD
#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
#include <locale>
#include <codecvt>
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef _WIN32
static inline std::string ws2s(const std::wstring& wstr)
{
if (wstr.empty())
{
return std::string();
}
int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &wstr[0], wstr.size(), NULL, 0, NULL, NULL);
std::string ret = std::string(size, 0);
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &wstr[0], wstr.size(), &ret[0], size, NULL, NULL);
return ret;
}
#else
static inline std::string ws2s(const std::u16string& wstr)
{
if (wstr.empty())
{
return std::string();
}
using convert_typeX = std::codecvt_utf8<char16_t>;
std::wstring_convert<convert_typeX, char16_t> converterX;
return converterX.to_bytes(wstr);
//char buf[2048] = { 0 };
//const ssize_t res = std::wcstombs(buf, wstr.c_str(), 2048);
//return std::string(buf);
}
#endif
#undef _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
#define QUAT_NUM_BITS (18)
#define MAX_QUAT_VALUE (0.7071067811865475244f)
#define MAX_QUAT_VALUE_INVERSE (1.0f / MAX_QUAT_VALUE)
typedef uint32_t BitReaderType;
namespace CPPRP
{
static inline float uncompress_quat(uint32_t val)
{
constexpr float MaxValue = (float)(1 << QUAT_NUM_BITS) - 1;
float positiveRangedValue = val / MaxValue;
float rangedValue = (positiveRangedValue - 0.50f) * 2.0f;
return rangedValue * MAX_QUAT_VALUE;
}
//TODO: memoize?
static inline const uint32_t msbDeBruijn32(uint32_t v)
{
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
v |= v >> 1; // first round down to one less than a power of 2
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return static_cast<uint32_t>(MultiplyDeBruijnBitPosition[(const uint32_t)(v * 0x07C4ACDDU) >> 27]);
}
typedef struct
{
const uint8_t* data;
uint64_t cachedVal;
uint32_t validBits;
size_t len;
size_t bytes_read;
} bitreader_t;
static inline void bitreader_load_cache(bitreader_t* b)
{
uint64_t val = *(uint64_t*)&b->data[b->bytes_read];
b->bytes_read += 8;
b->cachedVal = (val);// (val >> 32) | (val << 32);
b->validBits = 64;
}
static inline void bitreader_init(bitreader_t* b, const uint8_t* data, size_t len)
{
b->data = data;
b->len = len;
b->bytes_read = 0;
bitreader_load_cache(b);
}
static inline uint64_t bitreader_read_bits(bitreader_t* b, uint8_t bits)
{
uint32_t validBits = b->validBits;
uint64_t result = 0;
uint8_t overflow = 0;
if (bits >= validBits)
{
overflow = validBits;
bits -= validBits;
//Need special case for validBits == 0, since >> 64 is UB, but is a little ugly imo
//result = validBits == 0 ? 0 : (b->cachedVal >> (64 - validBits));
result = (b->cachedVal >> (64 - validBits));
bitreader_load_cache(b);
validBits = 64;
}
validBits -= bits;
//result |= ((bt >> (bit_position))& ((1ULL << n) - 1)) << bit_pos;
//(((b->cachedVal) >> 8) & (((1ULL << bits) - 1)))
result |= (((b->cachedVal) >> (64 - validBits - bits)) & ((1ULL << bits) - 1)) << overflow;// >> (validBits);
//result |= ((b->cachedVal >> (64 - validBits))& ((1ull << (64 - validBits)) - 1));
b->validBits = validBits;
return (result);
}
//Attempt at writing a fast bitreader for RL replays
template<typename T>
class CPPBitReader
{
public:
bitreader_t b;
const int size;
const int t_position = 0;
const int bit_position = 0;
//Let's store this data in here, saves a call to owner.
//Use during network stream parsing
const uint16_t engineVersion;
const uint8_t licenseeVersion;
const uint8_t netVersion;
std::string buildVersion;
std::vector<uint32_t> attributeIDs;
private:
template<typename X>
inline const X get_bits(uint16_t n)
{
#ifndef PARSE_UNSAFE
if (GetAbsoluteBitPosition() + n > b.len)
{
throw std::runtime_error("Attempted to read beyond buffer");
}
#endif
uint64_t res = bitreader_read_bits(&b, n);
return *(X*)(&res);
}
template<typename X>
inline const X get_bits_max(const X maxValue, const uint8_t max_bits)
{
X result = 0;
result = read<X>(max_bits);
if ((result + (1 << max_bits)) < maxValue)
{
result |= ((b.cachedVal >> (64 - b.validBits)) & 1) << max_bits;
if (b.validBits == 1)
{
read<X>(1);
}
else
{
b.validBits -= 1;
}
}
return result;
}
template<typename X>
inline const X get_bits_max(const X maxValue)
{
return get_bits_max(maxValue, msbDeBruijn32(maxValue));
}
public:
CPPBitReader(const T * data, size_t size, std::shared_ptr<ReplayFileData> owner_);
CPPBitReader(const T * data, size_t size, std::shared_ptr<ReplayFileData> owner_,
const uint32_t engineV, const uint32_t licenseeV, const uint32_t netV, const std::string buildV);
CPPBitReader(const CPPBitReader& other);
CPPBitReader();
template<typename U>
const U read();
template<typename U>
const U read(uint16_t customSize);
/*
Source from this is from the C# replay parser
*/
const float readFixedCompressedFloat(const int32_t maxValue, int32_t numBits);
template<typename U>
inline const U readBitsMax(const uint32_t max);
inline const bool canRead() const noexcept;
inline const bool canRead(int bits) const noexcept;
void goback(int32_t num);
void skip(uint32_t num);
const size_t GetAbsoluteBytePosition() const noexcept;
const size_t GetAbsoluteBitPosition() const noexcept;
};
template<>
template<>
inline const bool CPPBitReader<BitReaderType>::read<bool>()
{
return get_bits<uint8_t>(1);
}
//Float requires special casting since bit operations aren't allowed
template<>
template<>
inline const float CPPBitReader<BitReaderType>::read<float>()
{
static_assert(sizeof(float) == sizeof(uint32_t));
const uint32_t value = read<uint32_t>();
return reinterpret_cast<const float&>(value);
}
template<>
template<>
inline const Vector3I CPPBitReader<BitReaderType>::read<Vector3I>()
{
//PREFETCH((char*)(this->data));
const uint32_t max_value = 20 + (2 * (netVersion >= 7));
const uint32_t num_bits = get_bits_max<uint32_t>(max_value, 4); //Saves a debruijn call since its 4 for both 22 and 20
const int32_t bias = 1 << (int32_t)(num_bits + 1);
const int16_t max = (int16_t)num_bits + 2;
if (max < 22) //if it fits in 64 bits, read it all at once (3*21 < 64)
{
const uint64_t test = read<uint64_t>(max * 3);
const uint64_t rightShift = static_cast<uint64_t>(64 - max);
const int32_t dx = static_cast<int32_t>((test << rightShift) >> rightShift);
const int32_t dy = static_cast<int32_t>((test << (64UL - max * 2UL)) >> rightShift);
const int32_t dz = static_cast<int32_t>((test << (64UL - max * 3UL)) >> rightShift);
return { (dx - bias), (dy - bias), (dz - bias) };
}
//happens in 3 out of 10000 replays, so we still need it i guess
const int32_t dx = read<int32_t>(max);
const int32_t dy = read<int32_t>(max);
const int32_t dz = read<int32_t>(max);
return { (dx - bias), (dy - bias), (dz - bias) };
}
template<>
template<>
inline const Vector3 CPPBitReader<BitReaderType>::read<Vector3>()
{
Vector3I v = read<Vector3I>();
return { v.x / 100.f, v.y / 100.f, v.z / 100.f };
}
template<>
template<>
inline const Rotator CPPBitReader<BitReaderType>::read<Rotator>()
{
constexpr float conversion = 360.f / 256.f;
Rotator ret{ 0 };
if (read<bool>())
{
ret.pitch = static_cast<int>(read<int8_t>() * conversion);
}
if (read<bool>())
{
ret.yaw = static_cast<int>(read<int8_t>() * conversion);
}
if (read<bool>())
{
ret.roll = static_cast<int>(read<int8_t>() * conversion);
}
return ret;
}
#ifdef USESIMD
#include <immintrin.h>
template<>
template<>
inline const Quat CPPBitReader<BitReaderType>::read<Quat>()
{
constexpr uint16_t BitsReadForQuat = 2 + (3 * QUAT_NUM_BITS);
const uint64_t readQuat = read<uint64_t>(BitsReadForQuat);
const uint8_t largest = readQuat & 0b11; //Read 2 lsb
constexpr uint64_t QuatMask = (1 << QUAT_NUM_BITS) - 1; //(2^QUAT_NUM_BITS) - 1
const __m128 first = _mm_set_ps(0, (readQuat & (QuatMask << 2ULL)) >> 2ULL, (readQuat & (QuatMask << 20ULL)) >> 20ULL, (readQuat & (QuatMask << 38ULL)) >> 38ULL);
const __m128 second = _mm_set_ps(QuatMask, QuatMask, QuatMask, QuatMask);
const __m128 minus = _mm_set_ps(0.5f, 0.5f, 0.5f, 0.5f);
constexpr float TwoTimesMaxQuat = 2.f * MAX_QUAT_VALUE;
const __m128 timestwo = _mm_set_ps(TwoTimesMaxQuat, TwoTimesMaxQuat, TwoTimesMaxQuat, TwoTimesMaxQuat);
const __m128 divd = _mm_div_ps(first, second);
const __m128 mind = _mm_sub_ps(divd, minus);
const __m128 result = _mm_mul_ps(mind, timestwo);
const float* res = (float*)&result;
const float extra = _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ps1(1.f - (res[0] * res[0]) - (res[1] * res[1]) - (res[2] * res[2]))));
Quat q = { 0 };
switch (largest)
{
case 0:
q = { extra, res[2], res[1], res[0] };
break;
case 1:
q = { res[2], extra, res[1], res[0] };
break;
case 2:
q = { res[2], res[1], extra, res[0] };
break;
case 3:
default:
q = { res[2], res[1], res[0], extra };
break;
};
return q;
}
#else
template<>
template<>
inline const Quat CPPBitReader<BitReaderType>::read<Quat>()
{
const uint8_t largest = read<uint8_t>(2);
const float a = uncompress_quat(read<uint32_t>(QUAT_NUM_BITS));
const float b = uncompress_quat(read<uint32_t>(QUAT_NUM_BITS));
const float c = uncompress_quat(read<uint32_t>(QUAT_NUM_BITS));
float extra = std::sqrt(1.f - (a * a) - (b * b) - (c * c));
if (std::isnan(extra))
{
extra = .0f;
}
Quat q = { 0 };
switch (largest)
{
case 0:
q = { extra, a, b, c };
break;
case 1:
q = { a, extra, b, c };
break;
case 2:
q = { a, b, extra, c };
break;
case 3:
default:
q = { a, b, c, extra };
break;
};
return q;
}
#endif
template<>
template<>
inline const std::string CPPBitReader<BitReaderType>::read<std::string>()
{
const int32_t length = read<int32_t>();
const size_t final_length = static_cast<size_t>(length) * (length > 0 ? 1 : -2);
if (final_length == 0)
{
return "";
}
#ifndef PARSE_UNSAFE
if (final_length > 1024)
{
if (engineVersion == 0
&& licenseeVersion == 0
&& netVersion == 0)
{
throw InvalidVersionException(0, 0, 0);
}
else
{
throw std::runtime_error("Got unwanted string length, read value " + std::to_string(length) + ", reading bytes " + std::to_string(final_length) + ". (" + std::to_string(this->bit_position) + ")");
}
}
#endif
if (length < 0)
{
char test[2048];
for (size_t i = 0; i < final_length; ++i)
{
test[i] = read<uint8_t>();
}
#ifdef _WIN32
std::wstring test_ws(reinterpret_cast<wchar_t*>(test));
#else
std::u16string test_ws(reinterpret_cast<char16_t*>(test));
#endif
return ws2s(test_ws);
}
std::string str;
if (b.validBits % 8 == 0)
{
const char* text = ((char*)&b.data[b.bytes_read - ((b.validBits) / 8)]);
str = std::string(text);
skip(final_length * 8);
}
else
{
str.resize(final_length - 1);
int todo = final_length;
while (todo > 7)
{
*reinterpret_cast<uint64_t*>(&str[final_length - todo]) = read<uint64_t>();
todo -= 8;
}
if (todo > 3)
{
*reinterpret_cast<uint64_t*>(&str[final_length - todo]) = read<uint32_t>();
todo -= 4;
}
for (size_t i = final_length - todo; i < final_length; ++i)
{
str[i] = read<uint8_t>();
}
}
return str;
}
template<>
template<>
inline const OnlineID CPPBitReader<BitReaderType>::read<OnlineID>()
{
OnlineID uniqueId;
const uint8_t platform = read<uint8_t>();
switch (platform)
{
case Platform_Steam:
{
auto tmp = SteamID();
tmp.steamID = read<uint64_t>(sizeof(uint64_t) * 8);
uniqueId = tmp;
break;
}
case Platform_Dingo:
{
auto tmp = XBoxID();
tmp.xboxID = read<uint64_t>(sizeof(uint64_t) * 8);
uniqueId = tmp;
break;
}
case Platform_QQ:
{
auto tmp = QQID();
tmp.qqID = read<uint64_t>(sizeof(uint64_t) * 8);
uniqueId = tmp;
break;
}
case Platform_PS4:
{
auto tmp = PS4ID();
#define PSY4_MAX_NAME_LENGTH 16
char playerNameTemp[PSY4_MAX_NAME_LENGTH];
//Psynet names are always length 16, so optimize by interpreting 128 bits
*reinterpret_cast<uint64_t*>(&playerNameTemp) = read<uint64_t>();
*reinterpret_cast<uint64_t*>(&playerNameTemp[8]) = read<uint64_t>();
/*for (uint32_t i = 0; i < PSY4_MAX_NAME_LENGTH; ++i)
{
playerNameTemp[i] = read<char>();
}*/
tmp.playerName = std::string(playerNameTemp, PSY4_MAX_NAME_LENGTH);
tmp.unknown1 = read<uint64_t>();
if (netVersion >= 1)
{
tmp.unknown2 = read<uint64_t>();
}
tmp.psId = read<uint64_t>();
uniqueId = tmp;
break;
}
case Platform_Switch:
{
auto tmp = SwitchID();
tmp.a = read<uint64_t>(64);
tmp.b = read<uint64_t>(64);
tmp.c = read<uint64_t>(64);
tmp.d = read<uint64_t>(64);
uniqueId = tmp;
}
break;
case Platform_PsyNet:
{
auto tmp = PsyNetID();
if (engineVersion >= 868 && licenseeVersion >= 24 && netVersion >= 10)
{
tmp.a = read<uint64_t>(64);
}
else
{
tmp.a = read<uint64_t>(64);
tmp.b = read<uint64_t>(64);
tmp.c = read<uint64_t>(64);
tmp.d = read<uint64_t>(64);
}
uniqueId = tmp;
}
break;
case Platform_Epic:
{
auto epicID = EpicID();
epicID.epicId = read<std::string>();
uniqueId = epicID;
}
break;
case Platform_Unknown:
{
auto tmp = UnknownId();
if (licenseeVersion > 18 && netVersion == 0)
{
tmp.unknown = 0;
}
else
{
tmp.unknown = read<uint32_t>(3 * 8);
}
uniqueId = tmp;
}
//printf("Unknown platform found!\n");
break;
default:
//printf("Unknown platform %i", id.platform);
//assert(1 == 2);
break;
}
uint8_t splitscreenID = read<uint8_t>();
std::visit(
[platform, splitscreenID](UniqueId& base)
{
base.platform = platform;
base.splitscreenID = splitscreenID;
},
uniqueId);
return uniqueId;
}
template<typename T>
template<typename U>
inline const U CPPBitReader<T>::readBitsMax(const uint32_t max)
{
return get_bits_max<U>(max);
}
template<typename T>
inline CPPBitReader<T>::CPPBitReader(const T * data, size_t sizee, std::shared_ptr<ReplayFileData> owner_)
: engineVersion(owner_->header.engineVersion), licenseeVersion(owner_->header.licenseeVersion),
netVersion(owner_->header.netVersion), size(sizee), buildVersion(owner_->header.buildVersion)
{
bitreader_init(&b, (uint8_t*)data, sizee);
}
template<typename T>
inline CPPBitReader<T>::CPPBitReader(const T * data, size_t sizee, std::shared_ptr<ReplayFileData> owner_,
const uint32_t engineV, const uint32_t licenseeV, const uint32_t netV, const std::string buildV) : engineVersion(engineV),
licenseeVersion(licenseeV), netVersion(netV), size(sizee), buildVersion(buildV)
{
bitreader_init(&b, (uint8_t*)data, sizee);
}
template<typename T>
inline CPPBitReader<T>::CPPBitReader(const CPPBitReader& other)
: engineVersion(other.engineVersion), licenseeVersion(other.licenseeVersion), netVersion(other.netVersion), size(other.size), buildVersion(other.buildVersion)
{
bitreader_init(&b, other.b.data, other.b.len);
}
template<typename T>
inline CPPBitReader<T>::CPPBitReader() : engineVersion(0), licenseeVersion(0), netVersion(0), buildVersion("")
{
}
template<typename T>
inline const float CPPBitReader<T>::readFixedCompressedFloat(const int32_t maxValue, const int32_t numBits)
{
const int32_t maxBitValue = (1 << (numBits - 1)) - 1;
const int32_t bias = (1 << (numBits - 1));
const int32_t serIntMax = (1 << (numBits - 0));
const int32_t delta = readBitsMax<int32_t>(serIntMax);
const float unscaledValue = static_cast<float>(delta - bias);
if (maxValue > maxBitValue)
{
// We have to scale down, scale needs to be a float:
const float invScale = maxValue / (float)maxBitValue;
return unscaledValue * invScale;
}
const float scale = maxBitValue / (float)maxValue;
const float invScale = 1.0f / (float)scale;
return unscaledValue * invScale;
}
template <typename T>
inline const bool CPPBitReader<T>::canRead() const noexcept
{
return GetAbsoluteBitPosition() < b.len;
}
template <typename T>
inline const bool CPPBitReader<T>::canRead(int bits) const noexcept
{
return GetAbsoluteBitPosition() + bits < b.len;
}
template <typename T>
void CPPBitReader<T>::goback(int32_t num)
{
if (b.validBits + num > 64)
{
//num -= b.validBits;
int old = b.validBits;
if (old + num > 64)
int dfsdf = 5;
//num -= b.validBits;
b.validBits = 0;
b.bytes_read -= ((num / 64) + 2) * 8;
bitreader_load_cache(&b);
b.validBits = ((num + old) % 64);
//b.validBits = 64 - (num % 64);
}
else
{
b.validBits += num; //no need to reset cache
}
/*constexpr uint32_t SIZE_IN_BITS = (sizeof(T) * 8);
if (static_cast<int32_t>(bit_position) - num < 0)
{
num -= bit_position;
bit_position = SIZE_IN_BITS - (num % SIZE_IN_BITS);
t_position -= (abs(num)) / SIZE_IN_BITS + 1;
}
else
{
bit_position -= num;
}
data = start + t_position;*/
}
template<typename T>
inline void CPPBitReader<T>::skip(uint32_t num)
{
/*for(int i = 0; i < num; ++i)
read<uint64_t>(1);*/
//b.bytes_read += (num / 64) * 8;
//bitreader_t br2 = b;
//uint32_t num2 = num;
if (b.validBits <= num)
{
num -= b.validBits;
b.validBits = 0;
b.bytes_read += ((num / 64)) * 8;
bitreader_load_cache(&b);
b.validBits = (64 - (num % 64));
}
else
{
b.validBits -= num;
}
}
template<typename T>
const size_t CPPBitReader<T>::GetAbsoluteBytePosition() const noexcept
{
return (b.bytes_read) - (b.validBits / 8);
}
template<typename T>
const size_t CPPBitReader<T>::GetAbsoluteBitPosition() const noexcept
{
return (b.bytes_read * 8) - (b.validBits);
};
template<typename T>
template<typename U>
inline const U CPPBitReader<T>::read()
{
return get_bits<U>(sizeof(U) * 8);
}
template<typename T>
template<typename U>
inline const U CPPBitReader<T>::read(uint16_t customSize)
{
return get_bits<U>(customSize);
}
}
| 18,704
|
C++
|
.h
| 652
| 25.470859
| 200
| 0.658159
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,022
|
ReplayFile.h
|
Bakkes_CPPRP/CPPRP/ReplayFile.h
|
#pragma once
#include <stdint.h>
#include <string>
#include <filesystem>
#include <any>
#include <map>
#include <vector>
#include <unordered_map>
#include <mutex>
#include <functional>
#include "CPPBitReader.h"
#include "./data/NetworkData.h"
#include "./exceptions/ParseException.h"
#include "./exceptions/ReplayException.h"
#include "NetworkDataParsers.h"
#include "./data/ReplayFileData.h"
#include "PropertyParser.h"
#ifdef _WIN32
#define DllExport __declspec( dllexport )
#else
#define DllExport
#endif
namespace CPPRP
{
enum CrcCheck
{
CRC_Header = 0x1,
CRC_Body = 0x02,
CRC_Both = CRC_Header | CRC_Body
};
struct ActorStateData
{
std::shared_ptr<Engine::Actor> actorObject;
std::shared_ptr<ClassNet> classNet;
uint32_t actorId{0};
uint32_t nameId{ 0 };
uint32_t classNameId{ 0 };
uint32_t typeId{ 0 }; // Used for checking archetypes
};
typedef std::function<void(const Frame&, const std::unordered_map<decltype(ActorStateData::actorId), ActorStateData>&)> tickable;
typedef std::function<void(const Frame&)> onNewFrame;
typedef std::function<void(const ActorStateData&)> actorCreated;
typedef std::function<void(const ActorStateData&, const std::vector<uint32_t>&)> actorUpdated;
typedef std::function<void(const ActorStateData&)> actorDeleted;
typedef std::function<void(uint32_t, const ActorStateData&)> propertyUpdated;
class DllExport ReplayFile
{
private:
std::shared_ptr<CPPBitReader<BitReaderType>> fullReplayBitReader;
std::map<std::string, std::shared_ptr<ClassNet>> classnetMap;
public:
std::vector<char> data;
std::filesystem::path path;
std::vector<Frame> frames;
std::unordered_map<decltype(ActorStateData::actorId), ActorStateData> actorStates;
std::shared_ptr<ReplayFileData> replayFile;
FileHeader header;
std::vector<parsePropertyFunc> parseFunctions;
std::vector<createObjectFunc> createFunctions;
std::vector<std::string> parseLog;
public:
std::vector<tickable> tickables;
std::vector<onNewFrame> newFrameCallbacks;
std::vector<actorCreated> createdCallbacks;
std::vector<actorUpdated> updatedCallbacks;
std::vector<actorDeleted> actorDeleteCallbacks;
std::vector<uint32_t> positionIDs;
std::vector<uint32_t> rotationIDs;
std::vector<uint32_t> attributeIDs;
std::vector<std::shared_ptr<ClassNet>> classnetCache;
std::unordered_map<std::string, uint32_t> objectToId;
public:
ReplayFile(std::filesystem::path path_);
ReplayFile(std::vector<char>& fileData);
~ReplayFile();
const bool Load();
void DeserializeHeader();
const bool VerifyCRC(CrcCheck verifyWhat);
void Parse(const uint32_t startPos = 0, int32_t endPos = -1, const uint32_t frameCount = 0);
std::string GetParseLog(size_t amount);
protected:
void MergeDuplicates();
void FixParents();
const std::pair<const uint32_t, const KeyFrame> GetNearestKeyframe(uint32_t frame) const;
const bool ParseProperty(const std::shared_ptr<Property>& currentProperty);
const std::shared_ptr<ClassNet>& GetClassnetByNameWithLookup(const std::string& name) const;
const uint16_t GetPropertyIndexById(const std::shared_ptr<ClassNet>& cn, const int32_t id) const;
const uint16_t GetMaxPropertyId(ClassNet* cn);
const uint16_t FindMaxPropertyId(const ClassNet* cn, uint16_t maxProp) const;
public:
const bool HasProperty(const std::string& key) const;
const bool HasInitialPosition(const uint32_t name) const;
const bool HasRotation(const uint32_t name) const;
template<typename T>
const T GetProperty(const std::string& key) const;
template<typename T>
const T GetPropertyOrDefault(const std::string& key, const T defaultt) const;
template<typename T>
const std::shared_ptr<T> GetActiveActor(const ActiveActor& key) const;
};
template<typename T>
inline const T ReplayFile::GetPropertyOrDefault(const std::string& key, const T defaultt) const
{
if (auto it = replayFile->properties.find(key); it != replayFile->properties.end())
{
auto& value = it->second->value;
return std::get<T>(value);
}
return defaultt;
}
template<typename T>
inline const T ReplayFile::GetProperty(const std::string& key) const
{
if (auto it = replayFile->properties.find(key); it != replayFile->properties.end())
{
auto& value = it->second->value;
return std::get<T>(value);
// could throw a custom "bad type exception" after checking or just use the std::bad_variant_access std::get throws
//if (std::holds_alternative<T>(value))
//{
//
//}
}
throw PropertyDoesNotExistException(key);
}
template<typename T>
inline const std::shared_ptr<T> ReplayFile::GetActiveActor(const ActiveActor& key) const
{
if (auto found = actorStates.find(key.actor_id); found != actorStates.end())
{
return std::dynamic_pointer_cast<T>(found->second.actorObject);
}
return nullptr;
}
}
| 4,832
|
C++
|
.h
| 135
| 33.133333
| 130
| 0.758237
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,023
|
NetworkDataParsersGenerated.h
|
Bakkes_CPPRP/CPPRP/generated/NetworkDataParsersGenerated.h
|
template<>
inline const LogoData Consume(CPPBitReader<BitReaderType>& reader)
{
LogoData item;
item.swap_colors = reader.read<bool>();
item.logo_id = reader.read<uint32_t>();
return item;
}
template<>
inline const ActiveActor Consume(CPPBitReader<BitReaderType>& reader)
{
ActiveActor item;
item.active = reader.read<bool>();
item.actor_id = reader.read<int32_t>();
return item;
}
template<>
inline const ObjectTarget Consume(CPPBitReader<BitReaderType>& reader)
{
ObjectTarget item;
item.unknown = reader.read<bool>();
item.object_index = reader.read<int32_t>();
return item;
}
template<>
inline const CameraSettings Consume(CPPBitReader<BitReaderType>& reader)
{
CameraSettings item;
item.FOV = reader.read<float>();
item.height = reader.read<float>();
item.pitch = reader.read<float>();
item.distance = reader.read<float>();
item.stiffness = reader.read<float>();
item.swivelspeed = reader.read<float>();
if(reader.engineVersion >= 868
&& reader.licenseeVersion >= 20) {
item.transitionspeed = reader.read<float>();
} else {
item.transitionspeed = 0;
}
return item;
}
template<>
inline const ReplicatedPickupData Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedPickupData item;
item.unknown1 = reader.read<bool>();
item.actor_id = reader.read<int32_t>();
item.picked_up = reader.read<bool>();
return item;
}
template<>
inline const ReplicatedPickupData2 Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedPickupData2 item;
item.unknown1 = reader.read<bool>();
item.actor_id = reader.read<int32_t>();
item.picked_up = reader.read<uint8_t>();
return item;
}
template<>
inline const TeamPaint Consume(CPPBitReader<BitReaderType>& reader)
{
TeamPaint item;
item.team_number = reader.read<uint8_t>();
item.team_color_id = reader.read<uint8_t>();
item.custom_color_id = reader.read<uint8_t>();
item.team_finish_id = reader.read<uint32_t>();
item.custom_finish_id = reader.read<uint32_t>();
return item;
}
template<>
inline const ReplicatedDemolish Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedDemolish item;
item.attacker_flag = reader.read<bool>();
item.attacker_actor_id = reader.read<int32_t>();
item.victim_flag = reader.read<bool>();
item.victim_actor_id = reader.read<int32_t>();
item.attacker_velocity = reader.read<Vector3>();
item.victim_velocity = reader.read<Vector3>();
return item;
}
template<>
inline const ReplicatedDemolish2 Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedDemolish2 item;
item.custom_demo_flag = reader.read<bool>();
item.custom_demo_id = reader.read<int32_t>();
item.attacker_flag = reader.read<bool>();
item.attacker_actor_id = reader.read<int32_t>();
item.victim_flag = reader.read<bool>();
item.victim_actor_id = reader.read<int32_t>();
item.attacker_velocity = reader.read<Vector3>();
item.victim_velocity = reader.read<Vector3>();
return item;
}
template<>
inline const DemolishDataGoalExplosion Consume(CPPBitReader<BitReaderType>& reader)
{
DemolishDataGoalExplosion item;
item.goal_explosion_owner_flag = reader.read<bool>();
item.goal_explosion_owner = reader.read<int32_t>();
item.attacker_flag = reader.read<bool>();
item.attacker_actor_id = reader.read<int32_t>();
item.victim_flag = reader.read<bool>();
item.victim_actor_id = reader.read<int32_t>();
item.attacker_velocity = reader.read<Vector3>();
item.victim_velocity = reader.read<Vector3>();
return item;
}
template<>
inline const ReplicatedMusicStringer Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedMusicStringer item;
item.unknown1 = reader.read<bool>();
item.object_index = reader.read<uint32_t>();
item.trigger = reader.read<uint8_t>();
return item;
}
template<>
inline const ReplicatedStateIndex Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedStateIndex item;
item.value = reader.readBitsMax<uint32_t>(140);
return item;
}
template<>
inline const PrivateMatchSettings Consume(CPPBitReader<BitReaderType>& reader)
{
PrivateMatchSettings item;
item.mutators = reader.read<std::string>();
item.map_name = reader.read<uint32_t>();
item.max_player_count = reader.read<uint32_t>();
item.game_name = reader.read<std::string>();
item.password = reader.read<std::string>();
item.is_public = reader.read<bool>();
return item;
}
template<>
inline const ActorBase Consume(CPPBitReader<BitReaderType>& reader)
{
ActorBase item;
item.value = reader.read<uint32_t>();
item.unknown1 = reader.read<bool>();
item.unknown2 = reader.read<bool>();
return item;
}
template<>
inline const Attributes Consume(CPPBitReader<BitReaderType>& reader)
{
Attributes item;
item.product_attributes = ConsumeVector<AttributeType>(reader);
return item;
}
template<>
inline const OnlineLoadout Consume(CPPBitReader<BitReaderType>& reader)
{
OnlineLoadout item;
item.attributes_list = ConsumeVector<Attributes>(reader);
return item;
}
template<>
inline const ClientLoadoutsOnline Consume(CPPBitReader<BitReaderType>& reader)
{
ClientLoadoutsOnline item;
item.online_one = Consume<OnlineLoadout>(reader);
item.online_two = Consume<OnlineLoadout>(reader);
item.loadout_set = reader.read<bool>();
item.is_deprecated = reader.read<bool>();
return item;
}
template<>
inline const ClientLoadouts Consume(CPPBitReader<BitReaderType>& reader)
{
ClientLoadouts item;
item.loadout_one = Consume<ClientLoadout>(reader);
item.loadout_two = Consume<ClientLoadout>(reader);
return item;
}
template<>
inline const ClubColors Consume(CPPBitReader<BitReaderType>& reader)
{
ClubColors item;
item.team_color_set = reader.read<bool>();
item.team_color_id = reader.read<uint8_t>();
item.custom_color_set = reader.read<bool>();
item.custom_color_id = reader.read<uint8_t>();
return item;
}
template<>
inline const WeldedInfo Consume(CPPBitReader<BitReaderType>& reader)
{
WeldedInfo item;
item.active = reader.read<bool>();
item.actor_id = reader.read<int32_t>();
item.offset = reader.read<Vector3>();
item.mass = reader.read<float>();
item.rotation = reader.read<Rotator>();
return item;
}
template<>
inline const ReplicatedBoostData Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedBoostData item;
item.grant_count = reader.read<uint8_t>();
item.boost_amount = reader.read<uint8_t>();
item.unused1 = reader.read<uint8_t>();
item.unused2 = reader.read<uint8_t>();
return item;
}
template<>
inline const DamageState Consume(CPPBitReader<BitReaderType>& reader)
{
DamageState item;
item.damage_state = reader.read<uint8_t>();
item.unknown2 = reader.read<bool>();
item.causer_actor_id = reader.read<int32_t>();
item.damage_location = reader.read<Vector3>();
item.direct_damage = reader.read<bool>();
item.immediate = reader.read<bool>();
return item;
}
template<>
inline const AppliedDamage Consume(CPPBitReader<BitReaderType>& reader)
{
AppliedDamage item;
item.id = reader.read<uint8_t>();
item.position = reader.read<Vector3>();
item.damage_index = reader.read<int32_t>();
item.total_damage = reader.read<int32_t>();
return item;
}
template<>
inline const ReplicatedExplosionData Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedExplosionData item;
item.unknown1 = reader.read<bool>();
item.actor_id = reader.read<uint32_t>();
item.position = reader.read<Vector3>();
return item;
}
template<>
inline const ReplicatedExplosionDataExtended Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedExplosionDataExtended item;
item.unknown1 = reader.read<bool>();
item.actor_id = reader.read<int32_t>();
item.position = reader.read<Vector3>();
item.unknown3 = reader.read<bool>();
item.secondary_actor_id = reader.read<int32_t>();
return item;
}
template<>
inline const ReplicatedTitle Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedTitle item;
item.unknown1 = reader.read<bool>();
item.unknown2 = reader.read<bool>();
item.unknown3 = reader.read<uint32_t>();
item.unknown4 = reader.read<uint32_t>();
item.unknown5 = reader.read<uint32_t>();
item.unknown6 = reader.read<uint32_t>();
item.unknown7 = reader.read<uint32_t>();
item.unknown8 = reader.read<bool>();
return item;
}
template<>
inline const ImpulseData Consume(CPPBitReader<BitReaderType>& reader)
{
ImpulseData item;
item.CompressedRotation = reader.read<int>();
item.ImpulseSpeed = reader.read<float>();
return item;
}
template<>
inline const HistoryKey Consume(CPPBitReader<BitReaderType>& reader)
{
HistoryKey item;
item.data = reader.read<uint16_t>(14);
return item;
}
template<>
inline const ReplicatedStatEvent Consume(CPPBitReader<BitReaderType>& reader)
{
ReplicatedStatEvent item;
item.unknown1 = reader.read<bool>();
item.object_id = reader.read<int32_t>();
return item;
}
template<>
inline const RepStatTitle Consume(CPPBitReader<BitReaderType>& reader)
{
RepStatTitle item;
item.unknown1 = reader.read<bool>();
item.name = reader.read<std::string>();
item.object_target = Consume<ObjectTarget>(reader);
item.value = reader.read<uint32_t>();
return item;
}
template<>
inline const SkillTier Consume(CPPBitReader<BitReaderType>& reader)
{
SkillTier item;
item.tier = reader.readBitsMax<uint32_t>(500);
return item;
}
template<>
inline const RigidBodyState Consume(CPPBitReader<BitReaderType>& reader)
{
RigidBodyState item;
item.position = reader.read<Vector3>();
item.lin_vel = reader.read<Vector3>();
item.quaternion = reader.read<Quat>();
item.ang_vel = reader.read<Vector3>();
item.flags = reader.read<uint32_t>();
return item;
}
| 9,522
|
C++
|
.h
| 318
| 28.028302
| 90
| 0.76488
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,024
|
ClassExtensions.h
|
Bakkes_CPPRP/CPPRP/generated/ClassExtensions.h
|
#pragma once
#include <unordered_map>
#include <string>
namespace CPPRP {
static const std::unordered_map<std::string, std::string> class_extensions =
{
{"Engine.Actor", "Core.Object"}
, {"Engine.ReplicatedActor_ORS","Engine.Actor"}
, {"Engine.Info","Engine.Actor"}
, {"Engine.ReplicationInfo","Engine.Info"}
, {"Engine.GameReplicationInfo","Engine.ReplicationInfo"}
, {"Engine.Pawn","Engine.Actor"}
, {"Engine.PlayerReplicationInfo","Engine.ReplicationInfo"}
, {"Engine.TeamInfo","Engine.ReplicationInfo"}
, {"Engine.WorldInfo","Engine.Info"}
, {"Engine.DynamicSMActor","Engine.Actor"}
, {"Engine.KActor","Engine.DynamicSMActor"}
, {"ProjectX.GRI_X","Engine.GameReplicationInfo"}
, {"ProjectX.NetModeReplicator_X","Engine.ReplicationInfo"}
, {"ProjectX.Pawn_X","Engine.Pawn"}
, {"ProjectX.PRI_X","Engine.PlayerReplicationInfo"}
, {"TAGame.PRI_TA","ProjectX.PRI_X"}
, {"TAGame.PRI_KnockOut_TA","TAGame.PRI_TA"}
, {"TAGame.RBActor_TA","ProjectX.Pawn_X"}
, {"TAGame.CarComponent_TA","Engine.ReplicationInfo"}
, {"TAGame.CarComponent_AirActivate_TA","TAGame.CarComponent_TA"}
, {"TAGame.CarComponent_Jump_TA","TAGame.CarComponent_TA"}
, {"TAGame.CarComponent_DoubleJump_TA","TAGame.CarComponent_AirActivate_TA"}
, {"TAGame.CarComponent_DoubleJump_KO_TA","TAGame.CarComponent_DoubleJump_TA"}
, {"TAGame.CarComponent_Boost_TA","TAGame.CarComponent_AirActivate_TA"}
, {"TAGame.CarComponent_Boost_KO_TA","TAGame.CarComponent_Boost_TA"}
, {"TAGame.CarComponent_Dodge_TA","TAGame.CarComponent_AirActivate_TA"}
, {"TAGame.CarComponent_Dodge_KO_TA","TAGame.CarComponent_Dodge_TA"}
, {"TAGame.CarComponent_FlipCar_TA","TAGame.CarComponent_TA"}
, {"TAGame.CarComponent_Torque_TA","TAGame.CarComponent_TA"}
, {"TAGame.Ball_TA","TAGame.RBActor_TA"}
, {"TAGame.Team_TA","Engine.TeamInfo"}
, {"TAGame.Team_Soccar_TA","TAGame.Team_TA"}
, {"TAGame.BreakOutActor_Platform_TA","Engine.Actor"}
, {"TAGame.SpecialPickup_TA","TAGame.CarComponent_TA"}
, {"TAGame.SpecialPickup_Targeted_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.SpecialPickup_Tornado_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.SpecialPickup_HauntedBallBeam_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.SpecialPickup_BallVelcro_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.SpecialPickup_Rugby_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.SpecialPickup_BallFreeze_TA","TAGame.SpecialPickup_Targeted_TA"}
, {"TAGame.SpecialPickup_Spring_TA","TAGame.SpecialPickup_Targeted_TA"}
, {"TAGame.SpecialPickup_BallCarSpring_TA","TAGame.SpecialPickup_Spring_TA"}
, {"TAGame.SpecialPickup_BallGravity_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.SpecialPickup_GrapplingHook_TA","TAGame.SpecialPickup_Targeted_TA"}
, {"TAGame.SpecialPickup_BallLasso_TA","TAGame.SpecialPickup_GrapplingHook_TA"}
, {"TAGame.SpecialPickup_BoostOverride_TA","TAGame.SpecialPickup_Targeted_TA"}
, {"TAGame.SpecialPickup_Batarang_TA","TAGame.SpecialPickup_BallLasso_TA"}
, {"TAGame.SpecialPickup_HitForce_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.SpecialPickup_Swapper_TA","TAGame.SpecialPickup_Targeted_TA"}
, {"TAGame.SpecialPickup_Football_TA","TAGame.SpecialPickup_TA"}
, {"TAGame.CrowdManager_TA","Engine.ReplicationInfo"}
, {"TAGame.CrowdActor_TA","Engine.ReplicationInfo"}
, {"TAGame.InMapScoreboard_TA","Engine.Actor"}
, {"TAGame.Vehicle_TA","TAGame.RBActor_TA"}
, {"TAGame.Car_TA","TAGame.Vehicle_TA"}
, {"TAGame.Car_Season_TA","TAGame.Car_TA"}
, {"TAGame.Car_KnockOut_TA","TAGame.Car_TA"}
, {"TAGame.CameraSettingsActor_TA","Engine.ReplicationInfo"}
, {"TAGame.GRI_TA","ProjectX.GRI_X"}
, {"TAGame.Ball_Breakout_TA","TAGame.Ball_TA"}
, {"TAGame.Ball_God_TA","TAGame.Ball_TA"}
, {"TAGame.VehiclePickup_TA","Engine.ReplicationInfo"}
, {"TAGame.VehiclePickup_Boost_TA","TAGame.VehiclePickup_TA"}
, {"TAGame.VehiclePickup_Item_TA","TAGame.VehiclePickup_TA"}
, {"TAGame.Ball_Haunted_TA","TAGame.Ball_TA"}
, {"TAGame.GameEvent_TA","Engine.ReplicationInfo"}
, {"TAGame.GameEvent_Team_TA","TAGame.GameEvent_TA"}
, {"TAGame.GameEvent_Soccar_TA","TAGame.GameEvent_Team_TA"}
, {"TAGame.GameEvent_KnockOut_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEvent_Breakout_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEvent_Football_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEvent_GodBall_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEvent_Season_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEvent_SoccarPrivate_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEvent_SoccarSplitscreen_TA","TAGame.GameEvent_SoccarPrivate_TA"}
, {"TAGame.GameEvent_Tutorial_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEvent_Tutorial_Goalie_TA","TAGame.GameEvent_Tutorial_TA"}
, {"TAGame.GameEvent_Tutorial_Striker_TA","TAGame.GameEvent_Tutorial_TA"}
, {"TAGame.GameEvent_GameEditor_TA","TAGame.GameEvent_Soccar_TA"}
, {"TAGame.GameEditor_Pawn_TA","ProjectX.Pawn_X"}
, {"TAGame.GameEvent_TrainingEditor_TA","TAGame.GameEvent_GameEditor_TA"}
, {"TAGame.HauntedBallTrapTrigger_TA","Engine.Actor"}
, {"TAGame.MaxTimeWarningData_TA","Engine.ReplicatedActor_ORS"}
, {"TAGame.RumblePickups_TA","Engine.Actor"}
, {"TAGame.PickupTimer_TA","TAGame.CarComponent_TA"}
, {"TAGame.Cannon_TA","Engine.Actor"}
, {"TAGame.Stunlock_TA","Engine.Actor"}
, {"TAGame.PlayerStart_Platform_TA","Engine.Actor"}
};
};
| 5,367
|
C++
|
.h
| 96
| 53.010417
| 81
| 0.733397
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,025
|
GameClassMacros.h
|
Bakkes_CPPRP/CPPRP/generated/GameClassMacros.h
|
#define xstr(a) DEFINESTR(a)
#define DEFINESTR(a) #a
#ifndef GAMECLASS
#define GAMECLASS(...)
#endif
#ifndef GAMEFIELD
#define GAMEFIELD(...)
#endif
GAMECLASS(Engine, Actor);
GAMEFIELD(Engine, Actor, DrawScale, float);
GAMEFIELD(Engine, Actor, bCollideActors, bool);
GAMEFIELD(Engine, Actor, bCollideWorld, bool);
GAMEFIELD(Engine, Actor, bNetOwner, bool);
GAMEFIELD(Engine, Actor, Base, struct ActorBase);
GAMEFIELD(Engine, Actor, bBlockActors, bool);
GAMEFIELD(Engine, Actor, bHidden, bool);
GAMEFIELD(Engine, Actor, bTearOff, bool);
GAMEFIELD(Engine, Actor, Location, struct Vector3I);
GAMEFIELD(Engine, Actor, Rotation, struct Rotator);
GAMEFIELD(Engine, Actor, Physics, uint8_t);
GAMEFIELD(Engine, Actor, RemoteRole, uint8_t);
GAMEFIELD(Engine, Actor, Role, uint8_t);
GAMEFIELD(Engine, Actor, ReplicatedCollisionType, uint8_t);
GAMEFIELD(Engine, Actor, Owner, ActiveActor);
GAMEFIELD(Engine, Actor, bHardAttach, bool);
GAMEFIELD(Engine, Actor, Instigator, ActiveActor);
GAMEFIELD(Engine, Actor, RelativeLocation, Vector3I);
GAMEFIELD(Engine, Actor, RelativeRotation, Rotator);
GAMEFIELD(Engine, Actor, bRootMotionFromInterpCurve, bool);
GAMECLASS(Engine, ReplicatedActor_ORS);
GAMEFIELD(Engine, ReplicatedActor_ORS, ReplicatedOwner, ActiveActor);
GAMECLASS(Engine, Info);
GAMECLASS(Engine, ReplicationInfo);
GAMECLASS(Engine, GameReplicationInfo);
GAMEFIELD(Engine, GameReplicationInfo, ServerName, std::string);
GAMEFIELD(Engine, GameReplicationInfo, GameClass, struct ObjectTarget);
GAMEFIELD(Engine, GameReplicationInfo, bStopCountDown, bool);
GAMEFIELD(Engine, GameReplicationInfo, bMatchIsOver, bool);
GAMEFIELD(Engine, GameReplicationInfo, bMatchHasBegun, bool);
GAMEFIELD(Engine, GameReplicationInfo, RemainingTime, int);
GAMEFIELD(Engine, GameReplicationInfo, ElapsedTime, int);
GAMEFIELD(Engine, GameReplicationInfo, RemainingMinute, int);
GAMEFIELD(Engine, GameReplicationInfo, GoalScore, int);
GAMEFIELD(Engine, GameReplicationInfo, TimeLimit, int);
GAMEFIELD(Engine, GameReplicationInfo, Winner, ActiveActor);
GAMECLASS(Engine, Pawn);
GAMEFIELD(Engine, Pawn, PlayerReplicationInfo, struct ActiveActor);
GAMEFIELD(Engine, Pawn, HealthMax, uint32_t);
GAMEFIELD(Engine, Pawn, bIsCrouched, bool);
GAMEFIELD(Engine, Pawn, bIsWalking, bool);
GAMEFIELD(Engine, Pawn, bSimulateGravity, bool);
GAMEFIELD(Engine, Pawn, bCanSwatTurn, bool);
GAMEFIELD(Engine, Pawn, bUsedByMatinee, bool);
GAMEFIELD(Engine, Pawn, bRootMotionFromInterpCurve, bool);
GAMEFIELD(Engine, Pawn, bFastAttachedMove, bool);
GAMEFIELD(Engine, Pawn, RemoteViewPitch, uint8_t);
GAMEFIELD(Engine, Pawn, GroundSpeed, float);
GAMEFIELD(Engine, Pawn, AirSpeed, float);
GAMEFIELD(Engine, Pawn, AccelRate, float);
GAMEFIELD(Engine, Pawn, JumpZ, float);
GAMEFIELD(Engine, Pawn, AirControl, float);
GAMEFIELD(Engine, Pawn, RootMotionInterpRate, float);
GAMEFIELD(Engine, Pawn, RootMotionInterpCurrentTime, float);
GAMEFIELD(Engine, Pawn, RootMotionInterpCurveLastValue, Vector3I);
GAMECLASS(Engine, PlayerReplicationInfo);
GAMEFIELD(Engine, PlayerReplicationInfo, Team, struct ActiveActor);
GAMEFIELD(Engine, PlayerReplicationInfo, bReadyToPlay, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, PlayerName, std::string);
GAMEFIELD(Engine, PlayerReplicationInfo, RemoteUserData, std::string);
GAMEFIELD(Engine, PlayerReplicationInfo, bWaitingPlayer, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, Score, uint32_t);
GAMEFIELD(Engine, PlayerReplicationInfo, PlayerID, uint32_t);
GAMEFIELD(Engine, PlayerReplicationInfo, bBot, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, bIsSpectator, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, bTimedOut, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, bAdmin, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, bIsInactive, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, bOnlySpectator, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, Ping, uint8_t);
GAMEFIELD(Engine, PlayerReplicationInfo, UniqueId, OnlineID);
GAMEFIELD(Engine, PlayerReplicationInfo, Deaths, uint32_t);
GAMEFIELD(Engine, PlayerReplicationInfo, TTSSpeaker, uint8_t);
GAMEFIELD(Engine, PlayerReplicationInfo, bOutOfLives, bool);
GAMEFIELD(Engine, PlayerReplicationInfo, bFromPreviousLevel, bool);
GAMECLASS(Engine, TeamInfo);
GAMEFIELD(Engine, TeamInfo, Score, uint32_t);
GAMECLASS(Engine, WorldInfo);
GAMEFIELD(Engine, WorldInfo, WorldGravityZ, float);
GAMEFIELD(Engine, WorldInfo, TimeDilation, float);
GAMEFIELD(Engine, WorldInfo, bHighPriorityLoading, bool);
GAMEFIELD(Engine, WorldInfo, Pauser, ActiveActor);
GAMECLASS(Engine, DynamicSMActor);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMesh, ObjectTarget);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMaterial0, ObjectTarget);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMaterial1, ObjectTarget);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMaterial2, ObjectTarget);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMaterial3, ObjectTarget);
GAMEFIELD(Engine, DynamicSMActor, bForceStaticDecals, bool);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMeshTranslation, Vector3);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMeshRotation, Rotator);
GAMEFIELD(Engine, DynamicSMActor, ReplicatedMeshScale3D, Vector3);
GAMECLASS(Engine, KActor);
GAMEFIELD(Engine, KActor, bWakeOnLevelStart, bool);
GAMEFIELD(Engine, KActor, RBState, RigidBodyState);
GAMEFIELD(Engine, KActor, ReplicatedDrawScale3D, Vector3);
GAMECLASS(ProjectX, GRI_X);
GAMEFIELD(ProjectX, GRI_X, MatchGUID, std::string);
GAMEFIELD(ProjectX, GRI_X, MatchGuid, std::string);
GAMEFIELD(ProjectX, GRI_X, ReplicatedServerRegion, std::string);
GAMEFIELD(ProjectX, GRI_X, ReplicatedGameMutatorIndex, int);
GAMEFIELD(ProjectX, GRI_X, bGameStarted, bool);
GAMEFIELD(ProjectX, GRI_X, bGameEnded, bool);
GAMEFIELD(ProjectX, GRI_X, ReplicatedGamePlaylist, uint32_t);
GAMEFIELD(ProjectX, GRI_X, GameServerID, GameServer);
GAMEFIELD(ProjectX, GRI_X, Reservations, struct Reservation);
GAMECLASS(ProjectX, NetModeReplicator_X);
GAMECLASS(ProjectX, Pawn_X);
GAMECLASS(ProjectX, PRI_X);
GAMECLASS(TAGame, PRI_TA);
GAMEFIELD(TAGame, PRI_TA, MatchShots, uint32_t);
GAMEFIELD(TAGame, PRI_TA, PersistentCamera, struct ActiveActor);
GAMEFIELD(TAGame, PRI_TA, SkillTier, struct SkillTier);
GAMEFIELD(TAGame, PRI_TA, bUsingBehindView, bool);
GAMEFIELD(TAGame, PRI_TA, MatchAssists, uint32_t);
GAMEFIELD(TAGame, PRI_TA, RespawnTimeRemaining, int);
GAMEFIELD(TAGame, PRI_TA, bOnlineLoadoutSet, bool);
GAMEFIELD(TAGame, PRI_TA, MatchGoals, uint32_t);
GAMEFIELD(TAGame, PRI_TA, ReplicatedGameEvent, struct ActiveActor);
GAMEFIELD(TAGame, PRI_TA, TotalXP, uint32_t);
GAMEFIELD(TAGame, PRI_TA, MatchScore, uint32_t);
GAMEFIELD(TAGame, PRI_TA, MatchSaves, uint32_t);
GAMEFIELD(TAGame, PRI_TA, Title, uint32_t);
GAMEFIELD(TAGame, PRI_TA, ClubID, uint64_t);
GAMEFIELD(TAGame, PRI_TA, MaxTimeTillItem, int);
GAMEFIELD(TAGame, PRI_TA, PickupTimer, ActiveActor);
GAMEFIELD(TAGame, PRI_TA, MatchBreakoutDamage, uint32_t);
GAMEFIELD(TAGame, PRI_TA, BotProductName, uint32_t);
GAMEFIELD(TAGame, PRI_TA, BotBannerProductID, uint32_t);
GAMEFIELD(TAGame, PRI_TA, bReady, bool);
GAMEFIELD(TAGame, PRI_TA, SpectatorShortcut, uint32_t);
GAMEFIELD(TAGame, PRI_TA, bUsingSecondaryCamera, bool);
GAMEFIELD(TAGame, PRI_TA, PlayerHistoryValid, bool);
GAMEFIELD(TAGame, PRI_TA, bIsInSplitScreen, bool);
GAMEFIELD(TAGame, PRI_TA, bMatchMVP, bool);
GAMEFIELD(TAGame, PRI_TA, RepStatTitles, struct RepStatTitle);
GAMEFIELD(TAGame, PRI_TA, bOnlineLoadoutsSet, bool);
GAMEFIELD(TAGame, PRI_TA, bUsingItems, bool);
GAMEFIELD(TAGame, PRI_TA, PrimaryTitle, struct ReplicatedTitle);
GAMEFIELD(TAGame, PRI_TA, bMatchAdmin, bool);
GAMEFIELD(TAGame, PRI_TA, bBusy, bool);
GAMEFIELD(TAGame, PRI_TA, bVoteToForfeitDisabled, bool);
GAMEFIELD(TAGame, PRI_TA, bUsingFreecam, bool);
GAMEFIELD(TAGame, PRI_TA, ClientLoadoutOnline, struct OnlineLoadout);
GAMEFIELD(TAGame, PRI_TA, CameraYaw, uint8_t);
GAMEFIELD(TAGame, PRI_TA, CameraPitch, uint8_t);
GAMEFIELD(TAGame, PRI_TA, PawnType, uint8_t);
GAMEFIELD(TAGame, PRI_TA, ReplicatedWorstNetQualityBeyondLatency, uint8_t);
GAMEFIELD(TAGame, PRI_TA, SteeringSensitivity, float);
GAMEFIELD(TAGame, PRI_TA, PartyLeader, struct PartyLeader);
GAMEFIELD(TAGame, PRI_TA, TimeTillItem, int);
GAMEFIELD(TAGame, PRI_TA, ClientLoadoutsOnline, struct ClientLoadoutsOnline);
GAMEFIELD(TAGame, PRI_TA, ClientLoadouts, struct ClientLoadouts);
GAMEFIELD(TAGame, PRI_TA, ClientLoadout, struct ClientLoadout);
GAMEFIELD(TAGame, PRI_TA, CameraSettings, struct CameraSettings);
GAMEFIELD(TAGame, PRI_TA, SecondaryTitle, struct ReplicatedTitle);
GAMEFIELD(TAGame, PRI_TA, PlayerHistoryKey, struct HistoryKey);
GAMEFIELD(TAGame, PRI_TA, bIdleBanned, bool);
GAMEFIELD(TAGame, PRI_TA, bIsDistracted, bool);
GAMEFIELD(TAGame, PRI_TA, ReplacingBotPRI, ActiveActor);
GAMEFIELD(TAGame, PRI_TA, CurrentVoiceRoom, std::string);
GAMECLASS(TAGame, PRI_KnockOut_TA);
GAMEFIELD(TAGame, PRI_KnockOut_TA, Knockouts, int);
GAMEFIELD(TAGame, PRI_KnockOut_TA, KnockoutDeaths, int);
GAMEFIELD(TAGame, PRI_KnockOut_TA, DamageCaused, int);
GAMEFIELD(TAGame, PRI_KnockOut_TA, Hits, int);
GAMEFIELD(TAGame, PRI_KnockOut_TA, Grabs, int);
GAMEFIELD(TAGame, PRI_KnockOut_TA, Blocks, int);
GAMEFIELD(TAGame, PRI_KnockOut_TA, bIsActiveMVP, bool);
GAMECLASS(TAGame, RBActor_TA);
GAMEFIELD(TAGame, RBActor_TA, ReplicatedRBState, struct ReplicatedRBState);
GAMEFIELD(TAGame, RBActor_TA, bReplayActor, bool);
GAMEFIELD(TAGame, RBActor_TA, bFrozen, bool);
GAMEFIELD(TAGame, RBActor_TA, WeldedInfo, struct WeldedInfo);
GAMEFIELD(TAGame, RBActor_TA, bIgnoreSyncing, bool);
GAMEFIELD(TAGame, RBActor_TA, MaxLinearSpeed, float);
GAMEFIELD(TAGame, RBActor_TA, MaxAngularSpeed, float);
GAMEFIELD(TAGame, RBActor_TA, TeleportCounter, uint8_t);
GAMECLASS(TAGame, CarComponent_TA);
GAMEFIELD(TAGame, CarComponent_TA, Vehicle, struct ActiveActor);
GAMEFIELD(TAGame, CarComponent_TA, ReplicatedActive, uint8_t);
GAMEFIELD(TAGame, CarComponent_TA, ReplicatedActivityTime, float);
GAMECLASS(TAGame, CarComponent_AirActivate_TA);
GAMEFIELD(TAGame, CarComponent_AirActivate_TA, AirActivateCount, int);
GAMECLASS(TAGame, CarComponent_Jump_TA);
GAMECLASS(TAGame, CarComponent_DoubleJump_TA);
GAMEFIELD(TAGame, CarComponent_DoubleJump_TA, DoubleJumpImpulse, struct Vector3I);
GAMECLASS(TAGame, CarComponent_DoubleJump_KO_TA);
GAMECLASS(TAGame, CarComponent_Boost_TA);
GAMEFIELD(TAGame, CarComponent_Boost_TA, RechargeDelay, float);
GAMEFIELD(TAGame, CarComponent_Boost_TA, bUnlimitedBoost, bool);
GAMEFIELD(TAGame, CarComponent_Boost_TA, UnlimitedBoostRefCount, uint32_t);
GAMEFIELD(TAGame, CarComponent_Boost_TA, bNoBoost, bool);
GAMEFIELD(TAGame, CarComponent_Boost_TA, ReplicatedBoostAmount, uint8_t);
GAMEFIELD(TAGame, CarComponent_Boost_TA, ReplicatedBoost, ReplicatedBoostData);
GAMEFIELD(TAGame, CarComponent_Boost_TA, RechargeRate, float);
GAMEFIELD(TAGame, CarComponent_Boost_TA, BoostModifier, float);
GAMEFIELD(TAGame, CarComponent_Boost_TA, StartBoostAmount, float);
GAMEFIELD(TAGame, CarComponent_Boost_TA, CurrentBoostAmount, float);
GAMEFIELD(TAGame, CarComponent_Boost_TA, bRechargeGroundOnly, bool);
GAMECLASS(TAGame, CarComponent_Boost_KO_TA);
GAMECLASS(TAGame, CarComponent_Dodge_TA);
GAMEFIELD(TAGame, CarComponent_Dodge_TA, DodgeTorque, struct Vector3I);
GAMEFIELD(TAGame, CarComponent_Dodge_TA, DodgeImpulse, struct Vector3I);
GAMECLASS(TAGame, CarComponent_Dodge_KO_TA);
GAMEFIELD(TAGame, CarComponent_Dodge_KO_TA, DodgeRotationCompressed, int32_t);
GAMECLASS(TAGame, CarComponent_FlipCar_TA);
GAMEFIELD(TAGame, CarComponent_FlipCar_TA, bFlipRight, bool);
GAMEFIELD(TAGame, CarComponent_FlipCar_TA, FlipCarTime, float);
GAMECLASS(TAGame, CarComponent_Torque_TA);
GAMEFIELD(TAGame, CarComponent_Torque_TA, TorqueScale, float);
GAMEFIELD(TAGame, CarComponent_Torque_TA, ReplicatedTorqueInput, int32_t);
GAMECLASS(TAGame, Ball_TA);
GAMEFIELD(TAGame, Ball_TA, GameEvent, struct ActiveActor);
GAMEFIELD(TAGame, Ball_TA, ReplicatedPhysMatOverride, struct ObjectTarget);
GAMEFIELD(TAGame, Ball_TA, ReplicatedBallGravityScale, float);
GAMEFIELD(TAGame, Ball_TA, ReplicatedBallScale, float);
GAMEFIELD(TAGame, Ball_TA, HitTeamNum, unsigned char);
GAMEFIELD(TAGame, Ball_TA, ReplicatedWorldBounceScale, float);
GAMEFIELD(TAGame, Ball_TA, ReplicatedAddedCarBounceScale, float);
GAMEFIELD(TAGame, Ball_TA, ReplicatedExplosionData, struct ReplicatedExplosionData);
GAMEFIELD(TAGame, Ball_TA, ReplicatedBallMaxLinearSpeedScale, float);
GAMEFIELD(TAGame, Ball_TA, ReplicatedExplosionDataExtended, struct ReplicatedExplosionDataExtended);
GAMEFIELD(TAGame, Ball_TA, MagnusCoefficient, Vector3I);
GAMEFIELD(TAGame, Ball_TA, bEndOfGameHidden, bool);
GAMECLASS(TAGame, Team_TA);
GAMEFIELD(TAGame, Team_TA, LogoData, struct LogoData);
GAMEFIELD(TAGame, Team_TA, GameEvent, struct ActiveActor);
GAMEFIELD(TAGame, Team_TA, CustomTeamName, std::string);
GAMEFIELD(TAGame, Team_TA, ClubID, uint64_t);
GAMEFIELD(TAGame, Team_TA, Difficulty, int32_t);
GAMEFIELD(TAGame, Team_TA, ClubColors, struct ClubColors);
GAMECLASS(TAGame, Team_Soccar_TA);
GAMEFIELD(TAGame, Team_Soccar_TA, GameScore, uint32_t);
GAMECLASS(TAGame, BreakOutActor_Platform_TA);
GAMEFIELD(TAGame, BreakOutActor_Platform_TA, DamageState, struct DamageState);
GAMECLASS(TAGame, SpecialPickup_TA);
GAMECLASS(TAGame, SpecialPickup_Targeted_TA);
GAMEFIELD(TAGame, SpecialPickup_Targeted_TA, Targeted, struct ActiveActor);
GAMECLASS(TAGame, SpecialPickup_Tornado_TA);
GAMECLASS(TAGame, SpecialPickup_HauntedBallBeam_TA);
GAMECLASS(TAGame, SpecialPickup_BallVelcro_TA);
GAMEFIELD(TAGame, SpecialPickup_BallVelcro_TA, bHit, bool);
GAMEFIELD(TAGame, SpecialPickup_BallVelcro_TA, bBroken, bool);
GAMEFIELD(TAGame, SpecialPickup_BallVelcro_TA, AttachTime, float);
GAMEFIELD(TAGame, SpecialPickup_BallVelcro_TA, BreakTime, float);
GAMECLASS(TAGame, SpecialPickup_Rugby_TA);
GAMEFIELD(TAGame, SpecialPickup_Rugby_TA, bBallWelded, bool);
GAMECLASS(TAGame, SpecialPickup_BallFreeze_TA);
GAMEFIELD(TAGame, SpecialPickup_BallFreeze_TA, RepOrigSpeed, float);
GAMECLASS(TAGame, SpecialPickup_Spring_TA);
GAMECLASS(TAGame, SpecialPickup_BallCarSpring_TA);
GAMECLASS(TAGame, SpecialPickup_BallGravity_TA);
GAMECLASS(TAGame, SpecialPickup_GrapplingHook_TA);
GAMECLASS(TAGame, SpecialPickup_BallLasso_TA);
GAMECLASS(TAGame, SpecialPickup_BoostOverride_TA);
GAMECLASS(TAGame, SpecialPickup_Batarang_TA);
GAMECLASS(TAGame, SpecialPickup_HitForce_TA);
GAMECLASS(TAGame, SpecialPickup_Swapper_TA);
GAMECLASS(TAGame, SpecialPickup_Football_TA);
GAMEFIELD(TAGame, SpecialPickup_Football_TA, WeldedBall, struct ActiveActor);
GAMECLASS(TAGame, CrowdManager_TA);
GAMEFIELD(TAGame, CrowdManager_TA, GameEvent, struct ActiveActor);
GAMEFIELD(TAGame, CrowdManager_TA, ReplicatedGlobalOneShotSound, struct ObjectTarget);
GAMECLASS(TAGame, CrowdActor_TA);
GAMEFIELD(TAGame, CrowdActor_TA, GameEvent, struct ActiveActor);
GAMEFIELD(TAGame, CrowdActor_TA, ReplicatedOneShotSound, struct ObjectTarget);
GAMEFIELD(TAGame, CrowdActor_TA, ReplicatedRoundCountDownNumber, uint32_t);
GAMEFIELD(TAGame, CrowdActor_TA, ReplicatedCountDownNumber, uint32_t);
GAMEFIELD(TAGame, CrowdActor_TA, ModifiedNoise, float);
GAMECLASS(TAGame, InMapScoreboard_TA);
GAMECLASS(TAGame, Vehicle_TA);
GAMEFIELD(TAGame, Vehicle_TA, ReplicatedThrottle, unsigned char);
GAMEFIELD(TAGame, Vehicle_TA, bReplicatedHandbrake, bool);
GAMEFIELD(TAGame, Vehicle_TA, bDriving, bool);
GAMEFIELD(TAGame, Vehicle_TA, ReplicatedSteer, unsigned char);
GAMEFIELD(TAGame, Vehicle_TA, bHasPostMatchCelebration, bool);
GAMEFIELD(TAGame, Vehicle_TA, bPodiumMode, bool);
GAMECLASS(TAGame, Car_TA);
GAMEFIELD(TAGame, Car_TA, AttachedPickup, struct ActiveActor);
GAMEFIELD(TAGame, Car_TA, RumblePickups, struct ActiveActor);
GAMEFIELD(TAGame, Car_TA, AddedCarForceMultiplier, float);
GAMEFIELD(TAGame, Car_TA, ReplicatedCarScale, float);
GAMEFIELD(TAGame, Car_TA, AddedBallForceMultiplier, float);
GAMEFIELD(TAGame, Car_TA, TeamPaint, struct TeamPaint);
GAMEFIELD(TAGame, Car_TA, ReplicatedDemolish, struct ReplicatedDemolish);
GAMEFIELD(TAGame, Car_TA, ReplicatedDemolish_CustomFX, struct ReplicatedDemolish2);
GAMEFIELD(TAGame, Car_TA, ReplicatedDemolishGoalExplosion, struct DemolishDataGoalExplosion);
GAMEFIELD(TAGame, Car_TA, ClubColors, struct ClubColors);
GAMECLASS(TAGame, Car_Season_TA);
GAMECLASS(TAGame, Car_KnockOut_TA);
GAMEFIELD(TAGame, Car_KnockOut_TA, ReplicatedStateName, uint32_t);
GAMEFIELD(TAGame, Car_KnockOut_TA, ReplicatedStateChanged, unsigned char);
GAMEFIELD(TAGame, Car_KnockOut_TA, ReplicatedImpulse, ImpulseData);
GAMEFIELD(TAGame, Car_KnockOut_TA, UsedAttackComponent, ActiveActor);
GAMECLASS(TAGame, CameraSettingsActor_TA);
GAMEFIELD(TAGame, CameraSettingsActor_TA, PRI, struct ActiveActor);
GAMEFIELD(TAGame, CameraSettingsActor_TA, bMouseCameraToggleEnabled, bool);
GAMEFIELD(TAGame, CameraSettingsActor_TA, bUsingSecondaryCamera, bool);
GAMEFIELD(TAGame, CameraSettingsActor_TA, bUsingBehindView, bool);
GAMEFIELD(TAGame, CameraSettingsActor_TA, ProfileSettings, struct CameraSettings);
GAMEFIELD(TAGame, CameraSettingsActor_TA, bUsingSwivel, bool);
GAMEFIELD(TAGame, CameraSettingsActor_TA, bUsingFreecam, bool);
GAMEFIELD(TAGame, CameraSettingsActor_TA, bHoldMouseCamera, bool);
GAMEFIELD(TAGame, CameraSettingsActor_TA, bResetCamera, bool);
GAMEFIELD(TAGame, CameraSettingsActor_TA, CameraPitch, uint8_t);
GAMEFIELD(TAGame, CameraSettingsActor_TA, CameraYaw, uint8_t);
GAMECLASS(TAGame, GRI_TA);
GAMEFIELD(TAGame, GRI_TA, NewDedicatedServerIP, std::string);
GAMECLASS(TAGame, Ball_Breakout_TA);
GAMEFIELD(TAGame, Ball_Breakout_TA, DamageIndex, uint32_t);
GAMEFIELD(TAGame, Ball_Breakout_TA, AppliedDamage, struct AppliedDamage);
GAMEFIELD(TAGame, Ball_Breakout_TA, LastTeamTouch, unsigned char);
GAMECLASS(TAGame, Ball_God_TA);
GAMEFIELD(TAGame, Ball_God_TA, TargetSpeed, float);
GAMECLASS(TAGame, VehiclePickup_TA);
GAMEFIELD(TAGame, VehiclePickup_TA, bNoPickup, bool);
GAMEFIELD(TAGame, VehiclePickup_TA, ReplicatedPickupData, struct ReplicatedPickupData);
GAMEFIELD(TAGame, VehiclePickup_TA, NewReplicatedPickupData, struct ReplicatedPickupData2);
GAMECLASS(TAGame, VehiclePickup_Boost_TA);
GAMECLASS(TAGame, VehiclePickup_Item_TA);
GAMEFIELD(TAGame, VehiclePickup_Item_TA, ReplicatedFXActorArchetype, ActiveActor);
GAMECLASS(TAGame, Ball_Haunted_TA);
GAMEFIELD(TAGame, Ball_Haunted_TA, DeactivatedGoalIndex, unsigned char);
GAMEFIELD(TAGame, Ball_Haunted_TA, bIsBallBeamed, bool);
GAMEFIELD(TAGame, Ball_Haunted_TA, ReplicatedBeamBrokenValue, unsigned char);
GAMEFIELD(TAGame, Ball_Haunted_TA, LastTeamTouch, unsigned char);
GAMEFIELD(TAGame, Ball_Haunted_TA, TotalActiveBeams, unsigned char);
GAMECLASS(TAGame, GameEvent_TA);
GAMEFIELD(TAGame, GameEvent_TA, ReplicatedRoundCountDownNumber, uint32_t);
GAMEFIELD(TAGame, GameEvent_TA, ActivatorCar, struct ActiveActor);
GAMEFIELD(TAGame, GameEvent_TA, ReplicatedGameStateTimeRemaining, uint32_t);
GAMEFIELD(TAGame, GameEvent_TA, ReplicatedStateName, uint32_t);
GAMEFIELD(TAGame, GameEvent_TA, MatchTypeClass, struct ObjectTarget);
GAMEFIELD(TAGame, GameEvent_TA, BotSkill, float);
GAMEFIELD(TAGame, GameEvent_TA, bHasLeaveMatchPenalty, bool);
GAMEFIELD(TAGame, GameEvent_TA, bCanVoteToForfeit, bool);
GAMEFIELD(TAGame, GameEvent_TA, bAllowReadyUp, bool);
GAMEFIELD(TAGame, GameEvent_TA, GameMode, struct GameMode);
GAMEFIELD(TAGame, GameEvent_TA, ReplicatedStateIndex, struct ReplicatedStateIndex);
GAMEFIELD(TAGame, GameEvent_TA, GameOwner, struct ActiveActor);
GAMEFIELD(TAGame, GameEvent_TA, bIsBotMatch, bool);
GAMEFIELD(TAGame, GameEvent_TA, MatchStartEpoch, uint64_t);
GAMECLASS(TAGame, GameEvent_Team_TA);
GAMEFIELD(TAGame, GameEvent_Team_TA, MaxTeamSize, uint32_t);
GAMEFIELD(TAGame, GameEvent_Team_TA, bForfeit, bool);
GAMEFIELD(TAGame, GameEvent_Team_TA, bDisableMutingOtherTeam, bool);
GAMECLASS(TAGame, GameEvent_Soccar_TA);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, bOverTime, bool);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, GameTime, uint32_t);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, MVP, struct ActiveActor);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, MatchWinner, struct ActiveActor);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, GameWinner, struct ActiveActor);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, SubRulesArchetype, struct ObjectTarget);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, SecondsRemaining, uint32_t);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, RoundNum, uint32_t);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, SeriesLength, uint32_t);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, ReplicatedMusicStinger, struct ReplicatedMusicStringer);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, bBallHasBeenHit, bool);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, bUnlimitedTime, bool);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, ReplicatedStatEvent, struct ReplicatedStatEvent);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, bShowIntroScene, bool);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, bClubMatch, bool);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, ReplicatedScoredOnTeam, unsigned char);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, bMatchEnded, bool);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, ReplicatedServerPerformanceState, unsigned char);
GAMEFIELD(TAGame, GameEvent_Soccar_TA, MaxScore, uint32_t);
GAMECLASS(TAGame, GameEvent_KnockOut_TA);
GAMEFIELD(TAGame, GameEvent_KnockOut_TA, PlayerLives, int);
GAMECLASS(TAGame, GameEvent_Breakout_TA);
GAMECLASS(TAGame, GameEvent_Football_TA);
GAMECLASS(TAGame, GameEvent_GodBall_TA);
GAMECLASS(TAGame, GameEvent_Season_TA);
GAMECLASS(TAGame, GameEvent_SoccarPrivate_TA);
GAMEFIELD(TAGame, GameEvent_SoccarPrivate_TA, MatchSettings, struct PrivateMatchSettings);
GAMECLASS(TAGame, GameEvent_SoccarSplitscreen_TA);
GAMECLASS(TAGame, GameEvent_Tutorial_TA);
GAMECLASS(TAGame, GameEvent_Tutorial_Goalie_TA);
GAMECLASS(TAGame, GameEvent_Tutorial_Striker_TA);
GAMECLASS(TAGame, GameEvent_GameEditor_TA);
GAMECLASS(TAGame, GameEditor_Pawn_TA);
GAMECLASS(TAGame, GameEvent_TrainingEditor_TA);
GAMECLASS(TAGame, HauntedBallTrapTrigger_TA);
GAMECLASS(TAGame, MaxTimeWarningData_TA);
GAMEFIELD(TAGame, MaxTimeWarningData_TA, EndGameEpochTime, uint64_t);
GAMEFIELD(TAGame, MaxTimeWarningData_TA, EndGameWarningEpochTime, uint64_t);
GAMECLASS(TAGame, RumblePickups_TA);
GAMEFIELD(TAGame, RumblePickups_TA, AttachedPickup, ActiveActor);
GAMEFIELD(TAGame, RumblePickups_TA, ConcurrentItemCount, int);
GAMEFIELD(TAGame, RumblePickups_TA, PickupInfo, PickupInfo_TA);
GAMECLASS(TAGame, PickupTimer_TA);
GAMEFIELD(TAGame, PickupTimer_TA, TimeTillItem, int);
GAMEFIELD(TAGame, PickupTimer_TA, MaxTimeTillItem, int);
GAMECLASS(TAGame, Cannon_TA);
GAMEFIELD(TAGame, Cannon_TA, Pitch, float);
GAMEFIELD(TAGame, Cannon_TA, FireCount, uint8_t);
GAMECLASS(TAGame, Stunlock_TA);
GAMEFIELD(TAGame, Stunlock_TA, Car, ActiveActor);
GAMEFIELD(TAGame, Stunlock_TA, MaxStunTime, float);
GAMEFIELD(TAGame, Stunlock_TA, StunTimeRemaining, float);
GAMECLASS(TAGame, PlayerStart_Platform_TA);
GAMEFIELD(TAGame, PlayerStart_Platform_TA, bActive, bool);
| 22,779
|
C++
|
.h
| 411
| 54.406326
| 100
| 0.825426
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,533,026
|
tostring.h
|
Bakkes_CPPRP/CPPRP/utils/tostring.h
|
#pragma once
#include <string>
#include <vector>
#include <memory>
#include "../data/"
template<typename T>
inline const std::string ToString(const T& item) {
std::stringstream ss;
ss << "ERR. ToString not declared for " << typeid(T).name() << "\n";
return ss.str();
}
template<typename T>
inline const std::string ToString(const std::vector<T>& item) {
std::stringstream ss;
const size_t size = item.size();
for (size_t i = 0; i < size; ++i)
{
ss << "\t[" << i << "] - " << ToString(item.at(i)) << "\n";
}
//ss << "ERR. ToString not declared for " << typeid(T).name() << "\n";
return ss.str();
}
template<>
inline const std::string ToString(const std::shared_ptr<UniqueId>& item)
{
return "ERR";
}
template<>
inline const std::string ToString(const Vector3I& item) { return item.ToString(); }
template<>
inline const std::string ToString(const Vector3& item) { return item.ToString(); }
template<>
inline const std::string ToString(const Quat& item) { return item.ToString(); }
template<>
inline const std::string ToString(const Rotator& item) { return item.ToString(); }
template<>
inline const std::string ToString(const std::string& item) { return item; }
template<>
inline const std::string ToString(const bool& item) { return item ? "true" : "false"; }
template<>
inline const std::string ToString(const uint8_t& item) { return std::to_string((int)item); }
template<>
inline const std::string ToString(const float& item) { return std::to_string(item); }
template<>
inline const std::string ToString(const uint64_t& item) { return std::to_string(item); }
#define ToStringStd(type)\
template<>\
inline const std::string ToString(const type & item) { return std::to_string(item); }
ToStringStd(uint16_t);
ToStringStd(uint32_t);
ToStringStd(int);
}
| 1,773
|
C++
|
.h
| 52
| 32.673077
| 92
| 0.709696
|
Bakkes/CPPRP
| 32
| 9
| 2
|
MPL-2.0
|
9/20/2024, 10:43:54 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.