hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a2c9d1f01f2381e62d83070eac23d802a34f568e
2,122
cpp
C++
backup/2/interviewbit/c++/pretty-json.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/interviewbit/c++/pretty-json.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/interviewbit/c++/pretty-json.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/interviewbit/pretty-json.html . string prefix(int ind) { string res; for (int i = 0; i < ind; i++) { res += "\t"; } return res; } vector<string> clean(vector<string> words) { vector<string> res; for (string word : words) { if (word.length() <= 0) { continue; } bool valid = false; for (int i = 0; i < word.length(); i++) { if (word[i] != '\t') { valid = true; break; } } if (valid) { res.push_back(word); } } return res; } vector<string> Solution::prettyJSON(string A) { vector<string> res; int ind = 0, len = A.length(); char pre = '\0'; string delimiter = "{}[]"; string line; for (int i = 0; i < len; i++) { char ch = A[i]; if (pre == ',') { res.push_back(line); line = prefix(ind); } if (delimiter.find(ch) != string::npos) { res.push_back(line); if (ch == '{' || ch == '[') { line = prefix(ind) + ch; ind++; res.push_back(line); line = prefix(ind); } else { ind--; line = prefix(ind) + ch; if (i + 1 < len && A[i + 1] == ',') { } else { res.push_back(line); line = prefix(ind); } } } else { line += ch; } pre = ch; } return clean(res); }
30.753623
345
0.48115
yangyanzhan
a2cc38e8bd5593054465e1ac57e2340c62535cd8
895
cpp
C++
src/OpenHydro/mainwindow.cpp
glabmoris/OpenHydrography
41492e8fe94254d8cdd81bb032df2649464736c8
[ "MIT" ]
null
null
null
src/OpenHydro/mainwindow.cpp
glabmoris/OpenHydrography
41492e8fe94254d8cdd81bb032df2649464736c8
[ "MIT" ]
null
null
null
src/OpenHydro/mainwindow.cpp
glabmoris/OpenHydrography
41492e8fe94254d8cdd81bb032df2649464736c8
[ "MIT" ]
null
null
null
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { buildUI(); } MainWindow::~MainWindow() { } void MainWindow::buildUI(){ buildMainMenu(); buildDocks(); } void MainWindow::buildMainMenu(){ menuBar = new QMenuBar(); //TODO: add menu items this->setMenuBar(menuBar); } void MainWindow::buildDocks(){ this->setTabPosition(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea|Qt::BottomDockWidgetArea,QTabWidget::North); projectWindow = new ProjectWindow(this); this->addDockWidget(Qt::LeftDockWidgetArea,projectWindow); //TODO: connect(ui->actionShowProjectWindow,&QAction::triggered,projectWindow,&ProjectWindow::show); viewerWindow = new ViewerWindow(this); this->setCentralWidget(viewerWindow); //TODO: connect(ui->actionShowProjectWindow,&QAction::triggered,projectWindow,&ProjectWindow::show); }
21.829268
116
0.727374
glabmoris
a2cc68bb94ff35f052fcee5cc345f80efed3d234
14,064
cpp
C++
src/obstruction_free_dictionary.cpp
cconklin/nonblocking-tables
82acacbb16342ad36156931b9969674d85114d21
[ "MIT" ]
null
null
null
src/obstruction_free_dictionary.cpp
cconklin/nonblocking-tables
82acacbb16342ad36156931b9969674d85114d21
[ "MIT" ]
null
null
null
src/obstruction_free_dictionary.cpp
cconklin/nonblocking-tables
82acacbb16342ad36156931b9969674d85114d21
[ "MIT" ]
null
null
null
#include <obstruction_free_dictionary.hpp> namespace nonblocking { template<> versioned<obstruction_free_dictionary::bucket_state>::versioned(unsigned int version, obstruction_free_dictionary::bucket_state value) : _version{version} { switch (value) { case obstruction_free_dictionary::bucket_state::empty: _value = 0; break; case obstruction_free_dictionary::bucket_state::busy: _value = 1; break; case obstruction_free_dictionary::bucket_state::inserting: _value = 2; break; case obstruction_free_dictionary::bucket_state::member: _value = 3; break; case obstruction_free_dictionary::bucket_state::updating: _value = 4; break; } } template <> versioned<obstruction_free_dictionary::bucket_state>::versioned() noexcept : _version{0}, _value{0} {} template <> bool versioned<obstruction_free_dictionary::bucket_state>::operator==(versioned<obstruction_free_dictionary::bucket_state> other) { return (_version == other._version) && (_value == other._value); } template<> obstruction_free_dictionary::bucket_state versioned<obstruction_free_dictionary::bucket_state>::value() { switch (_value) { case 0: return obstruction_free_dictionary::bucket_state::empty; case 1: return obstruction_free_dictionary::bucket_state::busy; case 2: return obstruction_free_dictionary::bucket_state::inserting; case 3: return obstruction_free_dictionary::bucket_state::member; case 4: return obstruction_free_dictionary::bucket_state::updating; default: return obstruction_free_dictionary::bucket_state::busy; } } template<> unsigned int versioned<obstruction_free_dictionary::bucket_state>::version() { return _version; } obstruction_free_dictionary::bucket::bucket(unsigned int key, unsigned int value, unsigned int version, bucket_state state) : key{key}, state(versioned<obstruction_free_dictionary::bucket_state>(version, state)), value(versioned<unsigned int>(version, value)), copy(versioned<unsigned int>(version, 0)) {} obstruction_free_dictionary::bucket::bucket() : key{0}, state(versioned<obstruction_free_dictionary::bucket_state>()), value(versioned<unsigned int>()), copy(versioned<unsigned int>()) {} obstruction_free_dictionary::bucket::bucket(unsigned int key, versioned<unsigned int> value, versioned<unsigned int> copy, versioned<bucket_state> state) : key{key}, value{value}, copy{copy}, state{state} {} obstruction_free_dictionary::bucket* obstruction_free_dictionary::bucket_at(unsigned int h, int index) { return &buckets[(h+index*(index+1)/2)%size]; } obstruction_free_dictionary::bucket::bucket(const obstruction_free_dictionary::bucket& b) { key.store(b.key.load(std::memory_order_relaxed), std::memory_order_relaxed); state.store(b.state.load(std::memory_order_relaxed), std::memory_order_relaxed); value.store(b.value.load(std::memory_order_relaxed), std::memory_order_relaxed); copy.store(b.copy.load(std::memory_order_relaxed), std::memory_order_relaxed); } bool obstruction_free_dictionary::does_bucket_contain_collision(unsigned int h, int index) { versioned<bucket_state> state; versioned<bucket_state> later_state; unsigned int key; do { bucket* bkt_at = bucket_at(h, index); state = bkt_at->state.load(std::memory_order_acquire); key = bkt_at->key.load(std::memory_order_acquire); later_state = bkt_at->state.load(std::memory_order_relaxed); } while (!(state == later_state)); if ((state.value() == inserting) || (state.value() == member) || (state.value() == updating)) { if (hash(key) == h) { return true; } } return false; } obstruction_free_dictionary::obstruction_free_dictionary(unsigned int size) : base(size) { buckets = new bucket[size]; } obstruction_free_dictionary::~obstruction_free_dictionary() { delete buckets; } std::pair<obstruction_free_dictionary::bucket*, obstruction_free_dictionary::bucket> obstruction_free_dictionary::read_bucket(unsigned int key) { unsigned int h = hash(key); auto max = get_probe_bound(h); for (unsigned int i = 0; i <= max; ++i) { versioned<bucket_state> state; versioned<bucket_state> later_state; versioned<unsigned int> value; versioned<unsigned int> copy; unsigned int bkt_key; do { state = bucket_at(h, i)->state.load(std::memory_order_acquire); bkt_key = bucket_at(h, i)->key.load(std::memory_order_acquire); if (bkt_key != key) { break; } if ((state.value() == busy) || (state.value() == inserting) || (state.value() == empty)) { break; } value = bucket_at(h, i)->value.load(std::memory_order_acquire); copy = bucket_at(h, i)->copy.load(std::memory_order_acquire); later_state = bucket_at(h, i)->state.load(std::memory_order_relaxed); } while (!(state == later_state)); if (bkt_key == key) { if ((state.value() == member) || (state.value() == updating)) { return std::make_pair(bucket_at(h, i), bucket(key, value, copy, state)); } } } return std::make_pair(nullptr, bucket()); } std::pair<bool, unsigned int> obstruction_free_dictionary::lookup(unsigned int key) { std::pair<bucket*, bucket> bkt = read_bucket(key); if (std::get<0>(bkt)) { auto bkt_at = std::get<1>(bkt); if (bkt_at.state.load(std::memory_order_relaxed).value() == member) { return std::make_pair(true, bkt_at.value.load(std::memory_order_relaxed).value()); } else if (bkt_at.state.load(std::memory_order_relaxed).value() == updating) { return std::make_pair(true, bkt_at.copy.load(std::memory_order_relaxed).value()); } } return std::make_pair(false, 0); } bool obstruction_free_dictionary::erase(unsigned int key) { unsigned int h = hash(key); auto max = get_probe_bound(h); for (unsigned int i = 0; i <= max; ++i) { while (true) { auto* bkt_at = bucket_at(h, i); auto state = bkt_at->state.load(std::memory_order_acquire); auto bkt_key = bkt_at->key.load(std::memory_order_acquire); if (((state.value() == member) || (state.value() == updating)) && (bkt_key == key)) { if (std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &state, versioned<bucket_state>(state.version(), busy), std::memory_order_release, std::memory_order_acquire)) { conditionally_lower_bound(h, i); bkt_at->state.store(versioned<bucket_state>(state.version()+1, empty), std::memory_order_release); return true; } // Some other operation (delete/update) got in our way -- try again continue; } // No match: try another bucket break; } } return false; } void obstruction_free_dictionary::set(unsigned int key, unsigned int value) { while (true) { bool aborted = false; std::pair<bucket*, bucket> bkt = read_bucket(key); if (auto* bkt_at = std::get<0>(bkt)) { // Update auto bkt_value = std::get<1>(bkt); auto state = bkt_value.state.load(std::memory_order_relaxed); if (state.value() == member) { // Copy value to copy auto old_copy = bkt_value.copy.load(); if (!std::atomic_compare_exchange_strong_explicit(&bkt_at->copy, &old_copy, bkt_value.value.load(std::memory_order_relaxed), std::memory_order_release, std::memory_order_relaxed)) { // Failed to copy -- another updater is present: abort continue; } } auto new_state = versioned<bucket_state>(state.version() + 1, updating); if (!std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &state, new_state, std::memory_order_release, std::memory_order_relaxed)) { // Status modified: abort continue; } // Ensure that ALL the previous happened before modifying the value std::atomic_thread_fence(std::memory_order_acquire); // Update the value auto old_value = bkt_value.value.load(std::memory_order_relaxed); if (!std::atomic_compare_exchange_strong_explicit(&bkt_at->value, &old_value, versioned<unsigned int>(state.version() + 1, value), std::memory_order_relaxed, std::memory_order_relaxed)) { // Value modified: abort continue; } // Move back to member status if (std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &new_state, versioned<bucket_state>(state.version() + 1, member), std::memory_order_release, std::memory_order_relaxed)) { return; } } else { // Insert unsigned int h = hash(key); int i = -1; unsigned int version; versioned<bucket_state> old_state; versioned<bucket_state> new_state; do { if (++i > size) { throw "Table full"; } version = bucket_at(h, i)->state.load(std::memory_order_acquire).version(); old_state = versioned<bucket_state>(version, empty); new_state = versioned<bucket_state>(version, busy); } while (!std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->state, &old_state, new_state, std::memory_order_release, std::memory_order_relaxed)); unsigned int new_version = version+1; bucket_at(h, i)->key.store(key, std::memory_order_relaxed); bucket_at(h, i)->value.store(versioned<unsigned int>(new_version, value), std::memory_order_relaxed); versioned<bucket_state> inserting_state; do { inserting_state = versioned<bucket_state>(new_version, inserting); bucket_at(h, i)->state.store(inserting_state, std::memory_order_release); conditionally_raise_bound(h, i); auto max = get_probe_bound(h); for (unsigned int j = 0; j <= max; ++j) { if (j != i) { auto* bkt_at = bucket_at(h, j); unsigned int bkt_key; do { old_state = bkt_at->state.load(std::memory_order_acquire); bkt_key = bkt_at->key.load(std::memory_order_acquire); if ((bkt_key != key) || (old_state.value() == busy) || (old_state.value() == empty)) { break; } new_state = bkt_at->state.load(std::memory_order_relaxed); } while (!(old_state == new_state)); if (bkt_key == key) { if (old_state.value() == inserting) { auto j_insert = versioned<bucket_state>(old_state.version(), inserting); std::atomic_compare_exchange_strong_explicit(&bkt_at->state, &j_insert, versioned<bucket_state>(old_state.version(), busy), std::memory_order_release, std::memory_order_relaxed); } else if ((old_state.value() == member) || (old_state.value() == updating)) { bucket_at(h, i)->state.store(versioned<bucket_state>(version, busy)); conditionally_lower_bound(h, i); bucket_at(h, i)->state.store(versioned<bucket_state>(version, empty)); aborted = true; break; } } } } if (aborted) { break; } } while (!std::atomic_compare_exchange_strong_explicit(&bucket_at(h, i)->state, &inserting_state, versioned<bucket_state>(new_version, member), std::memory_order_release, std::memory_order_relaxed)); if (!aborted) { return; } } } } }
46.88
309
0.539676
cconklin
a2d06373c54b5876208d9a6ef81c7f4ae347e232
1,944
cpp
C++
algoritma-dan-struktur-data/linked_list.cpp
kodeaqua/script-praktikum
807000b053ff2e0765ee28f7a5decb676131238d
[ "MIT" ]
3
2021-12-25T06:08:42.000Z
2022-01-04T01:22:45.000Z
algoritma-dan-struktur-data/linked_list.cpp
kodeaqua/script-praktikum
807000b053ff2e0765ee28f7a5decb676131238d
[ "MIT" ]
3
2022-01-04T05:09:06.000Z
2022-03-10T07:33:41.000Z
algoritma-dan-struktur-data/linked_list.cpp
kodeaqua/script-praktikum
807000b053ff2e0765ee28f7a5decb676131238d
[ "MIT" ]
12
2021-12-04T12:28:41.000Z
2022-03-31T02:29:21.000Z
/* Praktikum Struktur Data Laboratorium Komputer Universitas Pakuan 2022 */ #include <iostream> using namespace std; struct Node { string nama; Node* next; }; void print(Node* head) { while (head != NULL) { cout << head->nama << "->"; head = head->next; } cout << endl << endl; } int main() { cout << " >>> CONTOH LINKED LIST <<<" << endl << endl; Node* node1 = NULL; Node* node2 = NULL; Node* node3 = NULL; // Membuat 3 node node1 = new Node(); node2 = new Node(); node3 = new Node(); // Menginputkan nilai ke dalam node node1->nama = "Fahmi"; node2->nama = "Noor"; node3->nama = "Fiqri"; // Sambungkan node-node node1->next = node2; node2->next = node3; node3->next = NULL; // --- menampilkan linked list awal cout << "Linked List Awal" << endl; print(node1); // --- menambahkan elemen pada akhir linked list Node* node4 = new Node(); node4->nama = "Fauzan"; node3->next = node4; cout << "Menambahkan elemen pada akhir linked list" << endl; print(node1); // --- menambahkan elemen pada awal linked list Node* node0 = new Node(); node0->nama = "Adam"; node0->next = node1; cout << "Menambahkan elemen pada awal linked list" << endl; print(node0); // --- menambahkan elemen setelah elemen kedua pada linked list Node* node12 = new Node(); node12->nama = "Reyhan"; node12->next = node2; node1->next = node12; cout << "Menambahkan elemen pada awal linked list" << endl; print(node0); // -- mengambil elemen ke-i pada linked list cout << "Mengambil elemen ke-2 pada linked list" << endl; string nilai_dicari; Node* nodeDicari = node0; for (auto i = 0; i < 1; i++) { nodeDicari = nodeDicari->next; }; cout << nodeDicari->nama << endl << endl; // --- menghapus elemen pada akhir linked list node3->next = NULL; cout << "Menghapus elemen pada akhir linked list" << endl; print(node0); return 0; }
20.25
65
0.618827
kodeaqua
a2d09c4da54aee783bd4db43a6ec6cd07ffdb4b7
10,600
cpp
C++
Source/PluginProcessor.cpp
SilvinWillemsen/TrombonePlugin
9096be4fa064855c53f7d94695167b41108776f9
[ "MIT" ]
null
null
null
Source/PluginProcessor.cpp
SilvinWillemsen/TrombonePlugin
9096be4fa064855c53f7d94695167b41108776f9
[ "MIT" ]
null
null
null
Source/PluginProcessor.cpp
SilvinWillemsen/TrombonePlugin
9096be4fa064855c53f7d94695167b41108776f9
[ "MIT" ]
null
null
null
/* ============================================================================== This file contains the basic framework code for a JUCE plugin processor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" //============================================================================== TrombonePluginAudioProcessor::TrombonePluginAudioProcessor() #ifndef JucePlugin_PreferredChannelConfigurations : AudioProcessor (BusesProperties() #if ! JucePlugin_IsMidiEffect #if ! JucePlugin_IsSynth .withInput ("Input", juce::AudioChannelSet::stereo(), true) #endif .withOutput ("Output", juce::AudioChannelSet::stereo(), true) #endif ) #endif { #ifdef NOEDITOR addParameter (tubeLength = new AudioParameterFloat ("tubelength", // parameter ID "Tube Length", // parameter name Global::LnonExtended, // minimum value Global::Lextended, // maximum value Global::LnonExtended)); // default value addParameter (lipFrequency = new AudioParameterFloat ("lipFrequency", // parameter ID "Lip Frequency", // parameter name 20.0f, // minimum value 1000.0f, // maximum value Global::nonExtendedLipFreq)); // default value addParameter (pressure = new AudioParameterFloat ("pressure", // parameter ID "Pressure", // parameter name 0.0f, // minimum value 6000.0f, // maximum value 0.0f)); // default value #endif } TrombonePluginAudioProcessor::~TrombonePluginAudioProcessor() { } //============================================================================== const juce::String TrombonePluginAudioProcessor::getName() const { return JucePlugin_Name; } bool TrombonePluginAudioProcessor::acceptsMidi() const { #if JucePlugin_WantsMidiInput return true; #else return false; #endif } bool TrombonePluginAudioProcessor::producesMidi() const { #if JucePlugin_ProducesMidiOutput return true; #else return false; #endif } bool TrombonePluginAudioProcessor::isMidiEffect() const { #if JucePlugin_IsMidiEffect return true; #else return false; #endif } double TrombonePluginAudioProcessor::getTailLengthSeconds() const { return 0.0; } int TrombonePluginAudioProcessor::getNumPrograms() { return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs, // so this should be at least 1, even if you're not really implementing programs. } int TrombonePluginAudioProcessor::getCurrentProgram() { return 0; } void TrombonePluginAudioProcessor::setCurrentProgram (int index) { } const juce::String TrombonePluginAudioProcessor::getProgramName (int index) { return {}; } void TrombonePluginAudioProcessor::changeProgramName (int index, const juce::String& newName) { } //============================================================================== void TrombonePluginAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock) { if (sampleRate != 44100) std::cout << "sampleRate is not 44100 Hz!!" << std::endl; fs = sampleRate; NamedValueSet parameters; //// Tube //// parameters.set ("T", 26.85); parameters.set ("LnonExtended", Global::LnonExtended); parameters.set ("Lextended", Global::Lextended); parameters.set ("L", Global::LnonExtended); // Geometric information including formula from bell taken from T. Smyth "Trombone synthesis by model and measurement" geometry = { {0.708, 0.177, 0.711, 0.241, 0.254, 0.502}, // lengths {0.0069, 0.0072, 0.0069, 0.0071, 0.0075, 0.0107} // radii }; parameters.set ("flare", 0.7); // flare (exponent coeff) parameters.set ("x0", 0.0174); // position of bell mouth (exponent coeff) parameters.set ("b", 0.0063); // fitting parameter parameters.set ("bellL", 0.21); // bell (length ratio) //// Lip //// double f0 = 300; double H0 = 2.9e-4; parameters.set("f0", f0); // fundamental freq lips parameters.set("Mr", 5.37e-5); // mass lips parameters.set("omega0", 2.0 * double_Pi * f0); // angular freq parameters.set("sigmaR", 5); // damping parameters.set("H0", H0); // equilibrium parameters.set("barrier", -H0); // equilibrium parameters.set("w", 1e-2); // lip width parameters.set("Sr", 1.46e-5); // lip area parameters.set ("Kcol", 10000); parameters.set ("alphaCol", 3); //// Input //// parameters.set ("Pm", (Global::exciteFromStart ? 300 : 0) * Global::pressureMultiplier); // LVal = (*parameters.getVarPointer ("Lextended")); trombone = std::make_shared<Trombone> (parameters, 1.0 / fs, geometry); pressureVal = 0; LVal = (*parameters.getVarPointer ("LnonExtended")); // start by contracting lipFreqVal = 2.4 * trombone->getTubeC() / (trombone->getTubeRho() * LVal); LValPrev = LVal; lipFreqValPrev = lipFreqVal; trombone->setExtVals (0, lipFreqVal, LVal, true); lowPass = std::make_unique<LowPass> (std::vector<double> { 0.0001343, 0.0005374, 0.0008060, 0.0005374, 0.0001343 }, std::vector<double> {1, -3.3964, 4.3648, -2.5119, 0.5456 }); } void TrombonePluginAudioProcessor::releaseResources() { // When playback stops, you can use this as an opportunity to free up any // spare memory, etc. } #ifndef JucePlugin_PreferredChannelConfigurations bool TrombonePluginAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const { #if JucePlugin_IsMidiEffect juce::ignoreUnused (layouts); return true; #else // This is the place where you check if the layout is supported. // In this template code we only support mono or stereo. // Some plugin hosts, such as certain GarageBand versions, will only // load plugins that support stereo bus layouts. if (layouts.getMainOutputChannelSet() != juce::AudioChannelSet::mono() && layouts.getMainOutputChannelSet() != juce::AudioChannelSet::stereo()) return false; // This checks if the input layout matches the output layout #if ! JucePlugin_IsSynth if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet()) return false; #endif return true; #endif } #endif void TrombonePluginAudioProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages) { juce::ScopedNoDenormals noDenormals; auto totalNumInputChannels = getTotalNumInputChannels(); auto totalNumOutputChannels = getTotalNumOutputChannels(); // In case we have more outputs than inputs, this code clears any output // channels that didn't contain input data, (because these aren't // guaranteed to be empty - they may contain garbage). // This is here to avoid people getting screaming feedback // when they first compile a plugin, but obviously you don't need to keep // this code if your algorithm always overwrites all the output channels. for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i) buffer.clear (i, 0, buffer.getNumSamples()); // This is the place where you'd normally do the guts of your plugin's // audio processing... // Make sure to reset the state if your inner loop is processing // the samples and the outer loop is handling the channels. // Alternatively, you can process the samples with the channels // interleaved by keeping the same state. float output = 0.0; auto* channelData = buffer.getWritePointer(0); for (int i = 0; i < buffer.getNumSamples(); ++i) { trombone->calculate(); output = trombone->getOutput() * 0.001 * Global::oOPressureMultiplier; output = lowPass->filter (output); trombone->updateStates(); channelData[i] = Global::outputClamp (output); } if (totalNumOutputChannels > 1) { auto* channelDataL = buffer.getReadPointer(0); auto* channelDataR = buffer.getWritePointer(1); for (int i = 0; i < buffer.getNumSamples(); ++i) channelDataR[i] = channelDataL[i]; } #ifdef NOEDITOR // double fineTuneRange = 0.5; // double fineTune = fineTuneRange * 2 * (e.y - controlY - controlHeight * 0.5) / controlHeight; LVal = *tubeLength; lipFreqVal = *lipFrequency; lipFreqVal = Global::limit (lipFreqVal, 20, 1000); pressureVal = *pressure; trombone->setExtVals (pressureVal, lipFreqVal, LVal); #endif trombone->refreshLipModelInputParams(); LValPrev = LVal; } //============================================================================== bool TrombonePluginAudioProcessor::hasEditor() const { #ifdef NOEDITOR return false; // (change this to false if you choose to not supply an editor) #else return true; #endif } juce::AudioProcessorEditor* TrombonePluginAudioProcessor::createEditor() { return new TrombonePluginAudioProcessorEditor (*this); } //============================================================================== void TrombonePluginAudioProcessor::getStateInformation (juce::MemoryBlock& destData) { // You should use this method to store your parameters in the memory block. // You could do that either as raw data, or use the XML or ValueTree classes // as intermediaries to make it easy to save and load complex data. } void TrombonePluginAudioProcessor::setStateInformation (const void* data, int sizeInBytes) { // You should use this method to restore your parameters from this memory block, // whose contents will have been created by the getStateInformation() call. } //============================================================================== // This creates new instances of the plugin.. juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new TrombonePluginAudioProcessor(); }
36.30137
123
0.600755
SilvinWillemsen
a2d2627dae9849dea59e2d46467e2478af70ee31
1,589
cc
C++
src/orthog/CLP.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/orthog/CLP.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/orthog/CLP.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*-----------------------------------// /** * @file CLP.cc * @brief CLP member definitions * @note Copyright (C) 2013 Jeremy Roberts */ //----------------------------------------------------------------------------// #include "CLP.hh" #include "utilities/DBC.hh" #ifdef DETRAN_ENABLE_BOOST #include <boost/math/special_functions/legendre.hpp> #endif namespace detran_orthog { //----------------------------------------------------------------------------// CLP::CLP(const Parameters &p) : ContinuousOrthogonalBasis(p) { #ifndef DETRAN_ENABLE_BOOST THROW("CLP needs boost to be enabled."); #else // Allocate the basis matrix d_basis = new callow::MatrixDense(d_size, d_order + 1, 0.0); // Allocate the normalization array d_a = Vector::Create(d_order + 1, 0.0); // The weights are just the qw's. double L = d_upper_bound - d_lower_bound; for (size_t i = 0; i < d_w->size(); ++i) { d_x[i] = 2.0*(d_x[i] - d_lower_bound)/L - 1.0; (*d_w)[i] = d_qw[i]; } // Build the basis for (size_t l = 0; l <= d_order; ++l) { for (size_t i = 0; i < d_size; ++i) { (*d_basis)(i, l) = boost::math::legendre_p(l, d_x[i]); } // Inverse of normalization coefficient. (*d_a)[l] = (2.0 * l + 1.0) / 2.0; } //d_orthonormal = true; //compute_a(); #endif } } // end namespace detran_orthog //----------------------------------------------------------------------------// // end of file CLP.cc //----------------------------------------------------------------------------//
26.04918
80
0.458779
baklanovp
a2d287905820c7c2c0439ca043d8006003de8419
4,004
cpp
C++
RoiSelector/RoiSelector.cpp
valerydol/drone_vision
ecb4ea9c17159c7cf72d1f3ab8b1ee9bf2adda71
[ "MIT" ]
3
2019-11-19T13:50:18.000Z
2020-01-15T11:50:22.000Z
RoiSelector/RoiSelector.cpp
valerydol/drone_vision
ecb4ea9c17159c7cf72d1f3ab8b1ee9bf2adda71
[ "MIT" ]
null
null
null
RoiSelector/RoiSelector.cpp
valerydol/drone_vision
ecb4ea9c17159c7cf72d1f3ab8b1ee9bf2adda71
[ "MIT" ]
null
null
null
#include "RoiSelector.h" RoiSelector::RoiSelector(float _offset_roi_x, float _offset_roi_y, float _width_roi_x, float _height_roi_y, bool _isEmptyFlag) : offset_roi_x(_offset_roi_x), offset_roi_y(_offset_roi_y), width_roi_x(_width_roi_x), height_roi_y(_height_roi_y), isEmptyFlag(true), roiNotCroped(), roiCroped() { } RoiSelector::~RoiSelector() { } //if ROI was detected? //step B.0 bool RoiSelector::isEmpty() { return isEmptyFlag; } //select ROI with new data and crope //step A.3 void RoiSelector::cropeNewROI(Mat &src, Mat &dstNotCroped, Mat &dstCroped) { // Define the roi Rect roi((int)getOffsetRoi_X(), (int)getOffsetRoi_Y(), (int)getRoiWidth_X(), (int)getRoiHeight_Y()); // Crop clone dstCroped = src(roi); dstNotCroped = src.clone(); //copy croped roi roiCroped = dstCroped.clone(); //copy src roi roiNotCroped = src.clone(); //change isEmptyFlag isEmptyFlag = false; } //set new ROI offsets , new roi boarder sizes //where is X / Y of start ROI //step A.2.4 void RoiSelector:: setNewRoiOffsets(int src_cols_width, int src_rows_height, float &startOnX, float &startOnY) { setOffsetRoi_X((src_cols_width / 2) - (getRoiWidth_X() / 2.0F)); //setOffsetRoi_Y((src_rows_height / 2) - (getRoiHeight_Y() / 2)); setOffsetRoi_Y((src_rows_height ) - (getRoiHeight_Y())-15.0F); startOnX = getOffsetRoi_X(); startOnY = getOffsetRoi_Y(); } //calculate ROI Width Height //do bigger //step A.2.3 void RoiSelector::doBigger(int src_cols_width, int src_rows_height) { //check if we can do our ROI bigger if (((getRoiWidth_X() + ROI_DELTA) < src_cols_width) && ((getRoiHeight_Y() + ROI_DELTA) < src_rows_height)) { setRoiWidth_X((float)(getRoiWidth_X() + ROI_DELTA)); //set Width_X setRoiHeight_Y((float)(getRoiHeight_Y() + ROI_DELTA));//set Height_Y } else//set max size { setRoiWidth_X((float)src_cols_width);//set Width_X setRoiHeight_Y((float)src_rows_height);//set Height_Y } } //calculate ROI Width Height //do smaller //step A.2.3 void RoiSelector::doSmaller(int src_cols_width, int src_rows_height) { //check if we can do our ROI smaller if (((getRoiWidth_X() - ROI_DELTA) > ROI_MIN_SIZE_WIDTH) && ((getRoiHeight_Y() - ROI_DELTA) > ROI_MIN_SIZE_HEIGTH)) { if (getRoiWidth_X() != src_cols_width) { setRoiWidth_X((float)(getRoiWidth_X() - ROI_DELTA)); //set Width_X setRoiHeight_Y((float)(getRoiHeight_Y() - ROI_DELTA));//set Height_Y } else //if last roi.size equel src.size { //set width equels to height setRoiWidth_X((float)src_rows_height);//set Width_X setRoiHeight_Y((float)src_rows_height);//set Height_Y } } else // we can`t do ROI SMALLER , set ROI_SIZE_X1 { setRoiWidth_X((float)ROI_DEFAULT_SIZE_WIDTH); setRoiHeight_Y((float)ROI_DEFAULT_SIZE_HEIGTH); } } //we need calculate roi size or get DEFAULT_SIZE //step A.2.2 void RoiSelector:: getNewRoiSize(const Mat &src, float &width_frame_cols, float &height_frame_rows, COMMAND roi_size) { int w = src.cols; int h = src.rows; if (roi_size == ROI_NEW) { setRoiWidth_X((float)ROI_DEFAULT_SIZE_WIDTH); setRoiHeight_Y((float)ROI_DEFAULT_SIZE_HEIGTH); } else if ((roi_size == ROI_BIGGER) || (roi_size == ROI_SMALLER)) { if (roi_size == ROI_BIGGER) { doBigger(w, h); } else { doSmaller(w, h); } } width_frame_cols = getRoiWidth_X(); height_frame_rows = getRoiHeight_Y(); } //return croped Mat // Define the roi and Crop img to ROI new size //step A.2 void RoiSelector::GetRoiFromImg(Mat &src, Mat &dstNotCroped , Mat &dstCroped, float &startOnX, float &startOnY, float &width_frame_cols, float &height_frame_rows, COMMAND roi_size) { //get new roi size getNewRoiSize(src, width_frame_cols, height_frame_rows, roi_size); //set start points for ROI setNewRoiOffsets(src.cols, src.rows, startOnX, startOnY); //crope ROI cropeNewROI(src, dstNotCroped, dstCroped); }
27.054054
181
0.697053
valerydol
a2d2afe1a5c2c4b5d9b78ae5898e3948814d9744
994
cpp
C++
TCPsrv/TCPsrv/main.cpp
yu-s/_code_bak
08308f7c836d05a9c4d610def19fc1a3e7c6ecf4
[ "MIT" ]
null
null
null
TCPsrv/TCPsrv/main.cpp
yu-s/_code_bak
08308f7c836d05a9c4d610def19fc1a3e7c6ecf4
[ "MIT" ]
null
null
null
TCPsrv/TCPsrv/main.cpp
yu-s/_code_bak
08308f7c836d05a9c4d610def19fc1a3e7c6ecf4
[ "MIT" ]
1
2020-05-05T12:28:45.000Z
2020-05-05T12:28:45.000Z
#include <Winsock2.h> #include <stdio.h> void main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 1, 1 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { return; } if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 ) { WSACleanup( ); return; } SOCKET sockets = socket(AF_INET,SOCK_STREAM,0); SOCKADDR_IN addrsrv; addrsrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrsrv.sin_family = AF_INET; addrsrv.sin_port = htons(6666); bind(sockets,(sockaddr*)&addrsrv,sizeof(SOCKADDR)); listen(sockets,5); SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); while(true) { SOCKET sockcoen = accept(sockets,(SOCKADDR*)&addrClient,&len); char sendbuf[100]; sprintf(sendbuf,"welcome %s to this",inet_ntoa(addrClient.sin_addr)); send(sockcoen,sendbuf,strlen(sendbuf)+1,0); char recvbuf[100]; recv(sockcoen,recvbuf,100,0); printf("%s\n",recvbuf); closesocket(sockcoen); } }
20.708333
71
0.690141
yu-s
a2d4de27027e955cb9a41693af9ab7a6f90c5a57
2,984
cpp
C++
samples/snippets/cpp/VS_Snippets_IIS/IIS7/IMapHandlerProviderSetScriptName/cpp/IMapHandlerProviderSetScriptName.cpp
mitchelsellers/iis-docs
376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429
[ "CC-BY-4.0", "MIT" ]
90
2017-06-13T19:56:04.000Z
2022-03-15T16:42:09.000Z
samples/snippets/cpp/VS_Snippets_IIS/IIS7/IMapHandlerProviderSetScriptName/cpp/IMapHandlerProviderSetScriptName.cpp
mitchelsellers/iis-docs
376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429
[ "CC-BY-4.0", "MIT" ]
453
2017-05-22T18:00:05.000Z
2022-03-30T21:07:55.000Z
samples/snippets/cpp/VS_Snippets_IIS/IIS7/IMapHandlerProviderSetScriptName/cpp/IMapHandlerProviderSetScriptName.cpp
mitchelsellers/iis-docs
376c5b4a1b88b807eb8dbe7c63ba7cd9c59f7429
[ "CC-BY-4.0", "MIT" ]
343
2017-05-26T08:57:30.000Z
2022-03-25T23:05:04.000Z
// <Snippet1> #define _WINSOCKAPI_ #include <windows.h> #include <sal.h> #include <httpserv.h> // Create the module class. class MyHttpModule : public CHttpModule { public: REQUEST_NOTIFICATION_STATUS OnMapRequestHandler( IN IHttpContext * pHttpContext, IN IMapHandlerProvider * pProvider ) { // Create an HRESULT to receive return values from methods. HRESULT hr; // Retrieve a pointer to the URL. DWORD cchScriptName = 0; PCWSTR pwszUrl = pHttpContext->GetScriptName(&cchScriptName); // Test for an error. if ((NULL != pwszUrl) && (cchScriptName>0)) { // Compare the request URL to limit the module's scope. if (0 == wcscmp(pwszUrl,L"/default.htm")) { // Create a buffer to contain the script name. PCWSTR pszScriptName = L"/example/default.htm"; // Retrive the length of the script name. cchScriptName = (DWORD) wcslen(pszScriptName); // Specify the file name. hr = pProvider->SetScriptName(pszScriptName,cchScriptName); // Test for an error. if (FAILED(hr)) { // Specify the error condition to return. pProvider->SetErrorStatus( hr ); // End additional processing. return RQ_NOTIFICATION_FINISH_REQUEST; } } } // Return processing to the pipeline. return RQ_NOTIFICATION_CONTINUE; } }; // Create the module's class factory. class MyHttpModuleFactory : public IHttpModuleFactory { public: HRESULT GetHttpModule( OUT CHttpModule ** ppModule, IN IModuleAllocator * pAllocator ) { UNREFERENCED_PARAMETER( pAllocator ); // Create a new instance. MyHttpModule * pModule = new MyHttpModule; // Test for an error. if (!pModule) { // Return an error if the factory cannot create the instance. return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); } else { // Return a pointer to the module. *ppModule = pModule; pModule = NULL; // Return a success status. return S_OK; } } void Terminate() { // Remove the class from memory. delete this; } }; // Create the module's exported registration function. HRESULT __stdcall RegisterModule( DWORD dwServerVersion, IHttpModuleRegistrationInfo * pModuleInfo, IHttpServer * pGlobalInfo ) { UNREFERENCED_PARAMETER( dwServerVersion ); UNREFERENCED_PARAMETER( pGlobalInfo ); // Set the request notifications and exit. return pModuleInfo->SetRequestNotifications( new MyHttpModuleFactory, RQ_MAP_REQUEST_HANDLER, 0 ); } // </Snippet1>
26.882883
75
0.580764
mitchelsellers
a2d75b15fedfdb232f50064e81df8bd18c0dbed4
1,077
cpp
C++
Software/lib/motor.cpp
JiaxunHong/Smart-Pets-Feeder
4204c669880377d7dc79d194f1d0e2a60c666e67
[ "MIT" ]
12
2021-04-10T16:03:04.000Z
2021-04-27T08:14:59.000Z
Software/lib/motor.cpp
JiaxunHong/Smart-Pets-Feeder
4204c669880377d7dc79d194f1d0e2a60c666e67
[ "MIT" ]
4
2021-04-15T11:33:45.000Z
2021-04-18T07:02:23.000Z
Software/lib/motor.cpp
JiaxunHong/Smart-Pets-Feeder
4204c669880377d7dc79d194f1d0e2a60c666e67
[ "MIT" ]
6
2021-04-10T16:03:36.000Z
2021-04-19T12:07:51.000Z
#include "motor.h" #include <iostream> //C++ Standard library #include <wiringPi.h> //GPIO library using namespace std; //Namespace Declarations void motor::motor_init() { for(auto i:m)pinMode(i, OUTPUT); //Initialising stepper motor pins } void motor::motopa(int zf) { auto di=0; int jnum = 0; if(zf == 1) { while(1){ for(auto j=0;j<4;++j){ if(di==j) digitalWrite(m[j], 1); else digitalWrite(m[j], 0); } di++; if(di==4){di=0;jnum++;} //One set of pulses sent out if(jnum>=128){return;} //512/2/2 = 128 90° delay(2); } } if(zf == 0) { di = 3; while(1){ for(auto j=0;j<4;++j){ if(di==j) digitalWrite(m[j], 1); else digitalWrite(m[j], 0); } di--; if(di==-1){di=3;jnum++;} if(jnum>=128){return;} delay(2); } } };
21.117647
70
0.410399
JiaxunHong
a2db34a0fc0974ffd62643604af63c4695bddcee
3,890
cpp
C++
modules/tracktion_graph/tracktion_graph/tracktion_graph_PlayHeadState.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
734
2018-11-16T09:39:40.000Z
2022-03-30T16:56:14.000Z
modules/tracktion_graph/tracktion_graph/tracktion_graph_PlayHeadState.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
100
2018-11-16T18:04:08.000Z
2022-03-31T17:47:53.000Z
modules/tracktion_graph/tracktion_graph/tracktion_graph_PlayHeadState.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
123
2018-11-16T15:51:50.000Z
2022-03-29T12:21:27.000Z
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ #pragma once namespace tracktion_graph { #if GRAPH_UNIT_TESTS_PLAYHEADSTATE //============================================================================== //============================================================================== class PlayHeadStateTests : public juce::UnitTest { public: PlayHeadStateTests() : juce::UnitTest ("PlayHeadStateTests", "tracktion_graph") { } void runTest() override { constexpr int64_t blockSize = 44'100; beginTest ("Loop edges"); { PlayHead playHead; PlayHeadState playHeadState (playHead); playHead.play ({ 44'100, 176'400 }, true); // 1-4s auto referenceRange = juce::Range<int64_t>::withStartAndLength (0, blockSize); playHeadState.update (referenceRange); // This is reference samples expect (! playHeadState.isContiguousWithPreviousBlock()); expect (playHeadState.didPlayheadJump()); expect (playHeadState.isFirstBlockOfLoop()); expect (! playHeadState.isLastBlockOfLoop()); referenceRange += blockSize; playHead.setReferenceSampleRange (referenceRange); playHeadState.update (referenceRange); expect (playHeadState.isContiguousWithPreviousBlock()); expect (! playHeadState.didPlayheadJump()); expect (! playHeadState.isFirstBlockOfLoop()); expect (! playHeadState.isLastBlockOfLoop()); referenceRange += blockSize; playHead.setReferenceSampleRange (referenceRange); playHeadState.update (referenceRange); expect (playHeadState.isContiguousWithPreviousBlock()); expect (! playHeadState.didPlayheadJump()); expect (! playHeadState.isFirstBlockOfLoop()); expect (playHeadState.isLastBlockOfLoop()); } beginTest ("Not looping"); { PlayHead playHead; PlayHeadState playHeadState (playHead); playHead.play ({ 44'100, 176'400 }, false); // 1-4s auto referenceRange = juce::Range<int64_t>::withStartAndLength (0, blockSize); playHeadState.update (referenceRange); // This is reference samples expect (! playHeadState.isContiguousWithPreviousBlock()); expect (playHeadState.didPlayheadJump()); expect (! playHeadState.isFirstBlockOfLoop()); expect (! playHeadState.isLastBlockOfLoop()); referenceRange += blockSize; playHead.setReferenceSampleRange (referenceRange); playHeadState.update (referenceRange); expect (playHeadState.isContiguousWithPreviousBlock()); expect (! playHeadState.didPlayheadJump()); expect (! playHeadState.isFirstBlockOfLoop()); expect (! playHeadState.isLastBlockOfLoop()); referenceRange += blockSize; playHead.setReferenceSampleRange (referenceRange); playHeadState.update (referenceRange); expect (playHeadState.isContiguousWithPreviousBlock()); expect (! playHeadState.didPlayheadJump()); expect (! playHeadState.isFirstBlockOfLoop()); expect (! playHeadState.isLastBlockOfLoop()); } } }; static PlayHeadStateTests playHeadStateTests; #endif }
36.698113
90
0.554242
jbloit
a2e2dbd71bc519938ad5621593b4f95b42e4fa6d
877
hpp
C++
paxos++/detail/util/conversion.hpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
54
2015-02-09T11:46:30.000Z
2021-08-13T14:08:52.000Z
paxos++/detail/util/conversion.hpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
null
null
null
paxos++/detail/util/conversion.hpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
17
2015-01-13T03:18:49.000Z
2022-03-23T02:20:57.000Z
/*! Copyright (c) 2012, Leon Mergen, all rights reserved. */ #ifndef LIBPAXOS_CPP_DETAIL_UTIL_CONVERSION_HPP #define LIBPAXOS_CPP_DETAIL_UTIL_CONVERSION_HPP #include <string> #include "debug.hpp" namespace paxos { namespace detail { namespace util { /*! \brief Defines helper functions that convert by arrays to ints and vice versa. */ class conversion { public: /*! \brief Converts POD type to byte array (as string) */ template <typename T> static std::string to_byte_array ( T input); /*! \brief Converts bytearray (as string) to POD type \pre input.size () == sizeof (T) */ template <typename T> static T from_byte_array ( std::string const & input); private: }; }; }; }; #include "conversion.inl" #endif //! LIBPAXOS_CPP_DETAIL_UTIL_CONVERSION_HPP
19.488889
81
0.641961
armos-db
a2e6d8e09b59d4e2ef30957fc20236eb6777f4b0
5,027
cc
C++
stapl_release/test/algorithms/unit/lexicographic_compare.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/algorithms/unit/lexicographic_compare.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/test/algorithms/unit/lexicographic_compare.cc
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #include <iostream> #include <stapl/containers/array/array.hpp> #include <stapl/algorithms/sorting.hpp> #include <stapl/views/array_view.hpp> #include <stapl/containers/generators/functor.hpp> #include <time.h> #include "test_util.hpp" using namespace stapl; const char alfa[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S', 'T','U','V','W','X','Y','Z'}; struct rand_functor { typedef char index_type; typedef char result_type; char operator()(index_type) const { return alfa[rand()%26]; } }; void correct_test() { //Creation of pArrays typedef array<char> p_array_char; typedef array_view<p_array_char> view_array_char; p_array_char p_array1(5); p_array_char p_array2(5); p_array_char p_array3(5); p_array_char p_array4(5); p_array_char p_arraya(4); p_array_char p_arrayb(4); p_array_char p_arrayc(4); p_array_char p_arrayd(4); view_array_char pview1(p_array1); view_array_char pview2(p_array2); view_array_char pview3(p_array3); view_array_char pview4(p_array4); view_array_char pviewa(p_arraya); view_array_char pviewb(p_arrayb); view_array_char pviewc(p_arrayc); view_array_char pviewd(p_arrayd); //Fill them pview1[0]='b'; pview1[1]='b'; pview1[2]='c'; pview1[3]='d'; pview1[4]='e'; pview2[0]='b'; pview2[1]='b'; pview2[2]='c'; pview2[3]='d'; pview2[4]='e'; pview3[0]='b'; pview3[1]='a'; pview3[2]='b'; pview3[3]='d'; pview3[4]='e'; pview4[0]='b'; pview4[1]='c'; pview4[2]='b'; pview4[3]='d'; pview4[4]='e'; pviewa[0]='b'; pviewa[1]='b'; pviewa[2]='c'; pviewa[3]='d'; pviewb[0]='b'; pviewb[1]='a'; pviewb[2]='b'; pviewb[3]='d'; pviewc[0]='b'; pviewc[1]='c'; pviewc[2]='b'; pviewc[3]='d'; pviewd[0]='a'; pviewd[1]='c'; pviewd[2]='b'; pviewd[3]='d'; //Ensure the explicit initialization from all locations is finished. rmi_fence(); //Test of function bool result1 = lexicographical_compare(pview1,pview2); bool result2 = lexicographical_compare(pview1,pview3); bool result3 = lexicographical_compare(pview1,pview4); bool result4 = lexicographical_compare(pview1,pviewa); bool result5 = lexicographical_compare(pview1,pviewb); bool result6 = lexicographical_compare(pview1,pviewc); bool result7 = lexicographical_compare(pview1,pviewd); //Result if (get_location_id()==0){ if (!result1 && !result2 && result3 && !result4 && !result5 && result6 && !result7) { std::cout << "[PASSED]" << std::endl; } else { std::cout << "[FAILED]" << std::endl; } } } void performance_test(long minelem2, long minelembis2) { //Performance test bool result =false; unsigned long minelem = minelem2*get_num_locations(); unsigned long minelembis = minelembis2*get_num_locations(); typedef array<char> p_array_char; typedef array_view<p_array_char> view_array_char; typedef functor_container<rand_functor> rand_container_type; typedef array_view<rand_container_type> rand_gen_view; rand_container_type rgc1(minelem, rand_functor()); rand_container_type rgc2(minelembis, rand_functor()); //Copy from a generator view into the parray p_array_char p_array1(minelem); p_array_char p_array2(minelembis); view_array_char pview1(p_array1); view_array_char pview2(p_array2); rand_gen_view rgen1(rgc1); rand_gen_view rgen2(rgc2); copy(rgen1,pview1); copy(rgen2,pview2); //Timer std::vector <double> vector_time; stapl::counter<stapl::default_timer> t; //Tests for (int i =0; i<= 32 ; i++){ t.reset(); t.start(); result = lexicographical_compare(pview1,pview2); rmi_fence() ; vector_time.push_back(t.stop()); if (get_location_id()==0) if ((pview1[0] > pview2[0] && result) || (pview1[0] < pview2[0] && !result)) std::cout << "[ERROR] lexicographical_compare didn't worked as attended" << std::endl; } std::cout<<std::endl; compute_stats("test_optim_lexical_compare", vector_time); rmi_fence(); } stapl::exit_code stapl_main(int argc, char* argv[]) { unsigned long minelem =10; unsigned long minelembis=10; if (get_location_id()==0){ std::cout << "Testing lexicograhical_compare\t"; } if (argc == 4){ minelem = atol(argv[1]); minelembis = atol(argv[2]); if (atoi(argv[3]) == 1){ correct_test(); } else { performance_test(minelem,minelembis); } } else { if (get_location_id()==0) std::cout << "USAGE: test_lexicographic_compare " << "num_elements_array1 num_elements_array2 " << "1-correctness/2-performance" << std::endl; } return EXIT_SUCCESS; }
31.030864
80
0.667595
parasol-ppl
a2ec6d3136d35858e38c4b358dfd0ba70819f809
8,355
cpp
C++
examples/auth/src/micro_http.cpp
kamaroly/yb-orm
b53987f6b316a4a2e7c23cb82525ad1570d107b7
[ "MIT" ]
null
null
null
examples/auth/src/micro_http.cpp
kamaroly/yb-orm
b53987f6b316a4a2e7c23cb82525ad1570d107b7
[ "MIT" ]
null
null
null
examples/auth/src/micro_http.cpp
kamaroly/yb-orm
b53987f6b316a4a2e7c23cb82525ad1570d107b7
[ "MIT" ]
null
null
null
#include "micro_http.h" #include <sstream> #include <util/thread.h> #include <util/utility.h> #include <util/string_utils.h> using namespace std; using namespace Yb; using namespace Yb::StrUtils; HttpServerBase::HttpServerBase(int port, ILogger *root_logger, const String &content_type, const String &bad_resp) : port_(port) , content_type_(content_type) , bad_resp_(bad_resp) , log_(root_logger->new_logger("http_serv").release()) {} bool HttpServerBase::send_response(TcpSocket &cl_sock, ILogger &logger, int code, const string &desc, const string &body, const String &cont_type) { try { ostringstream out; out << "HTTP/1.0 " << code << " " << desc << "\nContent-Type: " << NARROW(cont_type) << "\nContent-Length: " << body.size() << "\n\n" << body; cl_sock.write(out.str()); cl_sock.close(true); return true; } catch (const std::exception &ex) { logger.error(string("exception: ") + ex.what()); } return false; } void HttpServerBase::process(HttpServerBase *server, SOCKET cl_s) { TcpSocket cl_sock(cl_s); ILogger::Ptr logger = server->log_->new_logger("worker"); string bad_resp = NARROW(server->bad_resp_); String cont_type_resp = server->content_type_; // read and process request try { // read request header string buf = cl_sock.readline(); logger->debug(buf); int cont_len = -1; String cont_type; while (1) { // skip to request's body string s = cl_sock.readline(); if (!s.size()) throw HttpParserError("process", "short read"); if (s == "\r\n" || s == "\n") break; logger->debug(s); String s2 = WIDEN(s); if (starts_with(str_to_upper(s2), _T("CONTENT-LENGTH: "))) { try { Strings parts; split_str_by_chars(s2, _T(" "), parts, 2); from_string(parts[1], cont_len); } catch (const std::exception &ex) { logger->warning( string("couldn't parse CONTENT-LENGTH: ") + ex.what()); } } if (starts_with(str_to_upper(s2), _T("CONTENT-TYPE: "))) { try { Strings parts; split_str_by_chars(s2, _T(": "), parts, 2); cont_type = trim_trailing_space(parts[1]); } catch (const std::exception &ex) { logger->warning( string("couldn't parse CONTENT-TYPE: ") + ex.what()); } } } // parse request StringDict req = parse_http(WIDEN(buf)); req[_T("&content-type")] = cont_type; String method = req.get(_T("&method")); if (method != _T("GET") && method != _T("POST")) { logger->error("unsupported method \"" + NARROW(method) + "\""); send_response(cl_sock, *logger, 400, "Bad request", bad_resp, cont_type_resp); } else { if (method == _T("POST") && cont_len > 0) { String post_data = WIDEN(cl_sock.read(cont_len)); if (cont_type == _T("application/x-www-form-urlencoded")) req.update(parse_params(post_data)); else req[_T("&post-data")] = post_data; } String uri = req.get(_T("&uri")); if (!server->has_uri(uri)) { logger->error("URI " + NARROW(uri) + " not found!"); send_response(cl_sock, *logger, 404, "Not found", bad_resp, cont_type_resp); } else { // handle the request send_response(cl_sock, *logger, 200, "OK", server->call_uri(uri, req), cont_type_resp); } } } catch (const SocketEx &ex) { logger->error(string("socket error: ") + ex.what()); try { send_response(cl_sock, *logger, 400, "Short read", bad_resp, cont_type_resp); } catch (const std::exception &ex2) { logger->error(string("unable to send: ") + ex2.what()); } } catch (const HttpParserError &ex) { logger->error(string("parser error: ") + ex.what()); try { send_response(cl_sock, *logger, 400, "Bad request", bad_resp, cont_type_resp); } catch (const std::exception &ex2) { logger->error(string("unable to send: ") + ex2.what()); } } catch (const std::exception &ex) { logger->error(string("exception: ") + ex.what()); try { send_response(cl_sock, *logger, 500, "Internal server error", bad_resp, cont_type_resp); } catch (const std::exception &ex2) { logger->error(string("unable to send: ") + ex2.what()); } } cl_sock.close(true); } typedef void (*WorkerFunc)(HttpServerBase *, SOCKET); class WorkerThread: public Thread { HttpServerBase *serv_; SOCKET s_; WorkerFunc worker_; void on_run() { worker_(serv_, s_); } public: WorkerThread(HttpServerBase *serv, SOCKET s, WorkerFunc worker) : serv_(serv), s_(s), worker_(worker) {} }; void HttpServerBase::serve() { TcpSocket::init_socket_lib(); log_->info("start server on port " + to_stdstring(port_)); sock_ = TcpSocket(TcpSocket::create()); sock_.bind(port_); sock_.listen(); typedef SharedPtr<WorkerThread>::Type WorkerThreadPtr; typedef std::vector<WorkerThreadPtr> Workers; Workers workers; while (1) { // accept request try { string ip_addr; int ip_port; SOCKET cl_sock = sock_.accept(&ip_addr, &ip_port); log_->info("accepted from " + ip_addr + ":" + to_stdstring(ip_port)); WorkerThreadPtr worker(new WorkerThread( this, cl_sock, HttpServerBase::process)); workers.push_back(worker); worker->start(); Workers workers_dead, workers_alive; for (Workers::iterator i = workers.begin(); i != workers.end(); ++i) if ((*i)->finished()) workers_dead.push_back(*i); else workers_alive.push_back(*i); for (Workers::iterator i = workers_dead.begin(); i != workers_dead.end(); ++i) { (*i)->terminate(); (*i)->wait(); } workers.swap(workers_alive); } catch (const std::exception &ex) { log_->error(string("exception: ") + ex.what()); } } } StringDict parse_params(const String &msg) { StringDict params; Strings param_parts; split_str_by_chars(msg, _T("&"), param_parts); for (size_t i = 0; i < param_parts.size(); ++i) { Strings value_parts; split_str_by_chars(param_parts[i], _T("="), value_parts, 2); if (value_parts.size() < 1) throw HttpParserError("parse_params", "value_parts.size() < 1"); String n = value_parts[0]; String v; if (value_parts.size() == 2) v = WIDEN(url_decode(value_parts[1])); StringDict::iterator it = params.find(n); if (it == params.end()) params[n] = v; else params[n] += v; } return params; } StringDict parse_http(const String &msg) { Strings head_parts; split_str_by_chars(msg, _T(" \t\r\n"), head_parts); if (head_parts.size() != 3) throw HttpParserError("parse_http", "head_parts.size() != 3"); Strings uri_parts; split_str_by_chars(head_parts[1], _T("?"), uri_parts, 2); if (uri_parts.size() < 1) throw HttpParserError("parse_http", "uri_parts.size() < 1"); StringDict params; if (uri_parts.size() == 2) params = parse_params(uri_parts[1]); params[_T("&method")] = head_parts[0]; params[_T("&version")] = head_parts[2]; params[_T("&uri")] = uri_parts[0]; return params; } // vim:ts=4:sts=4:sw=4:et:
34.102041
92
0.529982
kamaroly
a2ee52976e7071314a16371f9be22822de6cace6
3,357
cpp
C++
src/ResourceManagement/MeshLoader.cpp
Ekozmaster/DwarfQuest
02b0406b1796093a6d55ba49fa42873cfba2e6ba
[ "MIT" ]
null
null
null
src/ResourceManagement/MeshLoader.cpp
Ekozmaster/DwarfQuest
02b0406b1796093a6d55ba49fa42873cfba2e6ba
[ "MIT" ]
null
null
null
src/ResourceManagement/MeshLoader.cpp
Ekozmaster/DwarfQuest
02b0406b1796093a6d55ba49fa42873cfba2e6ba
[ "MIT" ]
null
null
null
#include <string> #include <glm/glm.hpp> #include <vector> #include <cstring> #include <src/ResourceManagement/MeshLoader.h> #include <src/Utils/Logger.h> namespace Core { Mesh* LoadMesh(const char* path) { FILE* file = std::fopen(path, "r"); if (file == NULL) { Logger::Error("LoadMesh - Could not read file path: " + std::string(path)); return NULL; } std::vector<glm::vec3> vertices; std::vector<unsigned int> verticesIndices; std::vector<glm::vec3> normals; std::vector<unsigned int> normalsIndices; std::vector<glm::vec2> uvs; std::vector<unsigned int> uvsIndices; unsigned int indicesCount = 0; char lineHeader[128]; int res = fscanf(file, "%s", lineHeader); int scanfRes = 0; while (res != EOF) { if (strcmp(lineHeader, "v") == 0) { // POSITION glm::vec3 vertex; scanfRes = fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); vertices.push_back(vertex); } else if (strcmp(lineHeader, "vt") == 0) { // UVs glm::vec2 uv; scanfRes = fscanf(file, "%f %f\n", &uv.x, &uv.y); uvs.push_back(uv); } else if (strcmp(lineHeader, "vn") == 0) { // NORMALS glm::vec3 normal; scanfRes = fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z); normals.push_back(normal); } else if (strcmp(lineHeader, "f") == 0) { // INDICES unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; scanfRes = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]); verticesIndices.push_back(vertexIndex[0]); verticesIndices.push_back(vertexIndex[1]); verticesIndices.push_back(vertexIndex[2]); normalsIndices.push_back(normalIndex[0]); normalsIndices.push_back(normalIndex[1]); normalsIndices.push_back(normalIndex[2]); uvsIndices.push_back(uvIndex[0]); uvsIndices.push_back(uvIndex[1]); uvsIndices.push_back(uvIndex[2]); indicesCount += 3; } res = fscanf(file, "%s", lineHeader); } std::fclose(file); // TODO: This method makes unnecessary copies of vertices even though they're being shared among multiple triangles. Vertex* finalMesh = new Vertex[verticesIndices.size()]; for (unsigned int i = 0; i < verticesIndices.size(); i++) { unsigned int vertexIndex = verticesIndices[i] - 1; finalMesh[i].position = vertices[verticesIndices[i] - 1]; finalMesh[i].normal = normals[normalsIndices[i] - 1]; finalMesh[i].uv = uvs[uvsIndices[i] - 1]; finalMesh[i].color = glm::vec3(1.0); } for (unsigned int i = 0; i < verticesIndices.size(); i++) verticesIndices[i] = i; Mesh* mesh = new Mesh(); mesh->Create((GLfloat*)finalMesh, verticesIndices.size(), &verticesIndices[0], verticesIndices.size()); delete[] finalMesh; return mesh; } }
41.9625
213
0.554662
Ekozmaster
a2f04173536c35eb07af20d35cdd94248896bc71
19,485
hpp
C++
src/io/filtered_sequence_iterator.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
16
2016-06-07T22:12:02.000Z
2021-12-15T12:40:52.000Z
src/io/filtered_sequence_iterator.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
1
2017-11-13T20:59:33.000Z
2018-12-14T16:40:01.000Z
src/io/filtered_sequence_iterator.hpp
tcpan/bliss
0062fe91fdeef66fce4d1e897c15318241130277
[ "Apache-2.0" ]
7
2016-08-19T21:31:41.000Z
2021-12-19T14:58:45.000Z
/* * Copyright 2015 Georgia Institute of Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file filtered_sequence_iterator.hpp * @ingroup io * @author Tony Pan <tpan7@gatech.edu> * @date Feb 5, 2014 * @brief Contains an iterator for traversing a sequence data, record by record, a FASTQ format specific parser for use by the iterator, * Sequence Id datatype definition, and 2 sequence types (with and without quality score iterators) * * */ #ifndef Filtered_SequencesIterator_HPP_ #define Filtered_SequencesIterator_HPP_ // C includes #include "io/sequence_iterator.hpp" #include "iterators/filter_iterator.hpp" #include "io/fastq_loader.hpp" #include "io/file_loader.hpp" #include <algorithm> namespace bliss { namespace io { /** * @class bliss::io::FilteredSequencesIterator * @brief Iterator for parsing and traversing a block of data to access individual sequence records (of some file format), filtered by a user supplied predicate. * @details This is a convenience class that allows sequence records to be filtered on the fly based on a user supplied predicate function * The predicate can be used to detect presence of "N" character, or to keep only high quality reads. * Sequences that satisfies the predicate (returns true) are passed through. * * Predicate should have operation with input parameter <sequenceType> * * @note this iterator is not a random access or bidirectional iterator, as traversing in reverse is not implemented. * * @tparam Iterator Base iterator type to be parsed into sequences * @tparam SeqParser Functoid type to parse data pointed by Iterator into sequence objects.. * @tparam SequenceType Sequence Type. replaceable as long as it supports Quality if SeqParser requires it. */ template<typename Iterator, template <typename> class SeqParser, typename Predicate> class FilteredSequencesIterator : public ::bliss::iterator::filter_iterator< Predicate, ::bliss::io::SequencesIterator<Iterator, SeqParser> > { // TODO: for long sequence FASTA file, this likely will NOT behave correctly. static_assert(!std::is_same<SeqParser<Iterator>, ::bliss::io::BaseFileParser<Iterator>>::value, "SplitSequencesIterator currently works only with FASTQ and FASTA files where sequences are defined." ); protected: using SeqIterType = ::bliss::io::SequencesIterator<Iterator, SeqParser>; using FilterIterType = ::bliss::iterator::filter_iterator<Predicate, SeqIterType>; public: using iterator_category = typename SeqIterType::iterator_category; using value_type = typename SeqIterType::value_type; using difference_type = typename SeqIterType::difference_type; using pointer = typename SeqIterType::pointer; using reference = typename SeqIterType::reference; /** * @brief constructor, initializes with a start and end. this represents the start of the output iterator * @details at construction, the internal _curr, _next iterators are set to the input start iterator, and _end is set to the input end. * then immediately the first record is parsed, with output populated with the first entry and next pointer advanced. * * @param f parser functoid for parsing the data. * @param start beginning of the data to be parsed * @param end end of the data to be parsed. * @param _range the Range associated with the start and end of the source data. coordinates relative to the file being processed. */ explicit FilteredSequencesIterator(const SeqParser<Iterator> & f, Iterator start, Iterator end, const size_t &_offset, const Predicate & pred = Predicate()) : FilterIterType(pred, SeqIterType(f, start, end, _offset), SeqIterType(end)) {}; /** * @brief constructor, initializes with only the end. this represents the end of the output iterator. * @details at construction, the internal _curr, _next, and _end iterators are set to the input end iterator. * this instance therefore does not traverse and only serves as marker for comparing to the traversing FilteredSequencesIterator. * @param end end of the data to be parsed. */ explicit FilteredSequencesIterator(Iterator end, const Predicate & pred = Predicate()) : FilterIterType(pred, SeqIterType(end)) {} /** * @brief default copy constructor * @param Other The FilteredSequencesIterator to copy from */ FilteredSequencesIterator(const FilteredSequencesIterator& Other) : FilterIterType(Other) {} /** * @brief default copy assignment operator * @param Other The FilteredSequencesIterator to copy from * @return modified copy of self. */ FilteredSequencesIterator& operator=(const FilteredSequencesIterator& Other) { this->FilterIterType::operator=(Other); return *this; } /** * @brief default copy constructor * @param Other The FilteredSequencesIterator to copy from */ FilteredSequencesIterator(FilteredSequencesIterator && Other) : FilterIterType(::std::forward<FilteredSequencesIterator>(Other)) {} /** * @brief default copy assignment operator * @param Other The FilteredSequencesIterator to copy from * @return modified copy of self. */ FilteredSequencesIterator& operator=(FilteredSequencesIterator && Other) { this->FilterIterType::operator=(::std::forward<FilteredSequencesIterator>(Other)); return *this; } /// default constructor deleted. FilteredSequencesIterator() = default; }; /** * @class bliss::io::SequenceNPredicate * @brief given a sequence, determines if it DOES NOT contain N. */ struct NSequenceFilter { template <typename SEQ> bool operator()(SEQ const & x) { // scan through x to look for N. return ::std::find(x.seq_begin, x.seq_end, 'N') == x.seq_end; } }; template <typename Iterator, template <typename> class SeqParser> using NFilterSequencesIterator = bliss::io::FilteredSequencesIterator<Iterator, SeqParser, bliss::io::NSequenceFilter>; /** * @class bliss::io::SplitSequencesIterator * @brief Iterator for parsing and traversing a block of data to access individual sequence records (of some file format), split when predicate fails. * @details for each sequence, scan with predicate. when predicate fails, split the sequence, and continue on. * EFFECTIVELY BREAKS THE SEQUENCE INTO PARTS WHERE PREDICATE FAILS. * * @note this iterator is a forward iterator only (for now). * * @tparam Iterator Base iterator type to be parsed into sequences * @tparam SeqParser Functoid type to parse data pointed by Iterator into sequence objects.. * @tparam SequenceType Sequence Type. replaceable as long as it supports Quality if SeqParser requires it. */ template<typename Iterator, template <typename> class SeqParser, typename Predicate> class SplitSequencesIterator : public ::std::iterator< typename ::std::conditional< ::std::is_same<typename ::std::iterator_traits<Iterator>::iterator_category, ::std::input_iterator_tag>::value, ::std::input_iterator_tag, ::std::forward_iterator_tag>::type, typename SeqParser<Iterator>::SequenceType, typename std::iterator_traits<Iterator>::difference_type > { static_assert(!std::is_same<SeqParser<Iterator>, ::bliss::io::BaseFileParser<Iterator>>::value, "SplitSequencesIterator currently works only with FASTQ and FASTA files where sequences are defined." ); protected: /// predicate function Predicate pred; /// internal sequence iterator type using SeqIterType = ::bliss::io::SequencesIterator<Iterator, SeqParser>; /// current position SeqIterType _curr; /// max (end) position SeqIterType _end; /// cache of the current result to return typename SeqParser<Iterator>::SequenceType seq; /// cache of the next result to check typename SeqParser<Iterator>::SequenceType next; /// get next candidate sequence. void get_next() { // repeatedly get a valid seq. seq should not be "empty", and _curr should not be at end. while ((_curr != _end) && (next.seq_begin == next.seq_end)) { // move to next position. ++_curr; // get the next sequence if curr is not at end. if (_curr != _end) next = *_curr; } } /// splits a sequence based on predicate on chars. void split_seq() { // first copy // leave the quality score as is. traversal is confined by seq_begin/seq_end. seq = next; // std::cout << "RAW SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl; // std::cout << "RAW NEXT " << next << " len " << std::distance(next.seq_begin, next.seq_end) << std::endl; // find the beginning of valid. seq.seq_begin = std::find_if(next.seq_begin, next.seq_end, pred); // std::cout << "first SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl; // find the end of the valid range seq.seq_end = std::find_if_not(seq.seq_begin, next.seq_end, pred); // std::cout << "second SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl; // now update the next seq object. next.seq_begin_offset += std::distance(next.seq_begin, seq.seq_end); next.seq_begin = seq.seq_end; // std::cout << "SEQ " << seq << " len " << std::distance(seq.seq_begin, seq.seq_end) << std::endl; // std::cout << "NEXT " << next << " len " << std::distance(next.seq_begin, next.seq_end) << std::endl; } public: using iterator_category = typename SeqIterType::iterator_category; using value_type = typename SeqIterType::value_type; using difference_type = typename SeqIterType::difference_type; using pointer = typename SeqIterType::pointer; using reference = typename SeqIterType::reference; /** * @brief constructor, initializes with a start and end. this represents the start of the output iterator * @details at construction, the internal _curr, _next iterators are set to the input start iterator, and _end is set to the input end. * then immediately the first record is parsed, with output populated with the first entry and next pointer advanced. * * @param f parser functoid for parsing the data. * @param start beginning of the data to be parsed * @param end end of the data to be parsed. * @param _range the Range associated with the start and end of the source data. coordinates relative to the file being processed. */ explicit SplitSequencesIterator(const SeqParser<Iterator> & f, Iterator start, Iterator end, const size_t &_offset, const Predicate & _pred = Predicate()) : pred(_pred), _curr(f, start, end, _offset), _end(end) { // first initialize one. if (_curr != _end) next = *_curr; // this would not actually increment unless next is empty, but it will split seq. this->operator++(); }; /** * @brief constructor, initializes with only the end. this represents the end of the output iterator. * @details at construction, the internal _curr, _next, and _end iterators are set to the input end iterator. * this instance therefore does not traverse and only serves as marker for comparing to the traversing SplitSequencesIterator. * @param end end of the data to be parsed. */ explicit SplitSequencesIterator(Iterator end, const Predicate & _pred = Predicate()) : pred(_pred), _curr(end), _end(end) {} /** * @brief default copy constructor * @param Other The SplitSequencesIterator to copy from */ SplitSequencesIterator(const SplitSequencesIterator& Other) : pred(Other.pred), _curr(Other._curr), _end(Other._end), seq(Other.seq), next(Other.next) {} /** * @brief default copy assignment operator * @param Other The SplitSequencesIterator to copy from * @return modified copy of self. */ SplitSequencesIterator& operator=(const SplitSequencesIterator& Other) { pred = Other.pred; _curr = Other._curr; _end = Other._end; seq = Other.seq; next = Other.next; return *this; } /** * @brief default copy constructor * @param Other The SplitSequencesIterator to copy from */ SplitSequencesIterator(SplitSequencesIterator && Other) : pred(::std::move(Other.pred)), _curr(::std::move(Other._curr)), _end(::std::move(Other._end)), seq(::std::move(Other.seq)), next(::std::move(Other.next)) {} /** * @brief default copy assignment operator * @param Other The SplitSequencesIterator to copy from * @return modified copy of self. */ SplitSequencesIterator& operator=(SplitSequencesIterator && Other) { pred = std::move(Other.pred ); _curr = std::move(Other._curr); _end = std::move(Other._end ); seq = std::move(Other.seq ); next = std::move(Other.next ); return *this; } /// default constructor deleted. SplitSequencesIterator() = default; /** * @brief iterator's pre increment operation * @details to increment, the class uses the parser functoid to parse and traverse the input iterator * At the end of the traversal, a FASTQ sequence record has been made and is kept in the parser functoid * as state variable, and the input iterator has advanced to where parsing would start for the next record. * The corresponding starting of the current record is saved as _curr iterator. * * conversely, to get the starting position of the next record, we need to parse the current record. * * @note for end iterator, because _curr and _end are both pointing to the input's end, "increment" does not do anything. * @return self, updated with internal position. */ SplitSequencesIterator &operator++() { // TODO get the next, and apply the predicate. this->get_next(); // split if not empty if ((_curr != _end) && (next.seq_begin != next.seq_end)) this->split_seq(); //== states updated. return self. return *this; } /** * @brief iterator's post increment operation * @details to increment, the class uses the parser functoid to parse and traverse the input iterator * At the end of the traversal, a FASTQ sequence record has been made and is kept in the parser functoid * as state variable, and the input iterator has advanced to where parsing would start for the next record. * The corresponding starting of the current record is saved as _curr iterator. * * conversely, to get the starting position of the next record, we need to parse the current record. * * @note for end iterator, because _curr and _end are both pointing to the input's end, "increment" does not do anything. * @param unnamed * @return copy of self incremented. */ SplitSequencesIterator operator++(int) { SplitSequencesIterator output(*this); this->operator++(); return output; } /** * @brief comparison operator. * @details compares the underlying base iterator positions. * @param rhs the SequenceIterator to compare to. * @return true if this and rhs SequenceIterators match. */ bool operator==(const SplitSequencesIterator& rhs) const { return (_curr == rhs._curr) && ((_curr == _end) || (seq.seq_begin == rhs.seq.seq_begin)); } /** * @brief comparison operator. * @details compares the underlying base iterator positions. * @param rhs the SequenceIterator to compare to. * @return true if this and rhs SequenceIterators do not match. */ bool operator!=(const SplitSequencesIterator& rhs) const { return !(this->operator==(rhs)); } /** * @brief dereference operator * @return a const reference to the cached sequence object */ typename SeqParser<Iterator>::SequenceType & operator*() { return seq; } /** * @brief pointer dereference operator * @return a const reference to the cached sequence object */ typename SeqParser<Iterator>::SequenceType *operator->() { return &seq; } }; /** * @class bliss::io::NCharFilter * @brief given a character, return true if it's NOT N. */ struct NCharFilter { template <typename T> bool operator()(T const & x) { // scan through x to look for NOT N return (x != 'N') && (x != 'n'); } }; template <typename Iterator, template <typename> class SeqParser> using NSplitSequencesIterator = bliss::io::SplitSequencesIterator<Iterator, SeqParser, bliss::io::NCharFilter>; // TODO: filter for other characters. // TODO: quality score filter for sequences. } // iterator } // bliss #endif /* Filtered_SequencesIterator_HPP_ */
43.396437
208
0.618938
tcpan
a2f5096b80b4a1a241a0d41f4e16ea60c77b12f4
7,912
cpp
C++
snapshotable_allocator_impl.cpp
jyaif/snapshotable_allocator
711dff8d6414265476bf8eb83eece563c0c183a8
[ "MIT" ]
null
null
null
snapshotable_allocator_impl.cpp
jyaif/snapshotable_allocator
711dff8d6414265476bf8eb83eece563c0c183a8
[ "MIT" ]
null
null
null
snapshotable_allocator_impl.cpp
jyaif/snapshotable_allocator
711dff8d6414265476bf8eb83eece563c0c183a8
[ "MIT" ]
null
null
null
#include "application/memory/snapshotable_allocator_impl.h" #include <algorithm> #include <array> #include <cassert> #include <cstdlib> #include "application/memory/aligned_alloc.h" #include "application/memory/bit_vector.h" #include "application/memory/fls.h" #include "application/memory/memory_snapshot_impl.h" #include "application/memory/scoped_allocator_usage.h" #include "application/memory/snapshotable_allocator_impl.h" namespace { constexpr int extra_bytes_ = 16; } ItemBucket::ItemBucket(size_t item_size, size_t item_count) : free_map_(item_count), item_size_(item_size), item_count_(item_count) { // +16 to also store |free_slots_ptr_|. // +4 would be enough, but then the alignment would be bad (we need 16 byte // alignment). // 16 bytes alignment is necessary because `movaps` can be generated, and // crashes if the alignment is not 16 bytes. //|free_slots_ptr_| is stored in the same contiguous bag of bytes // to allow fast snapshoting/restoring of the free slot counter. allocated_memory_ = static_cast<uint32_t*>( AlignedAlloc(16, item_size * item_count + extra_bytes_)); free_slots_ptr_ = allocated_memory_; memory_ = reinterpret_cast<uint8_t*>(allocated_memory_) + extra_bytes_; *free_slots_ptr_ = static_cast<uint32_t>(item_count); } ItemBucket::~ItemBucket() { AlignedFree(allocated_memory_); } void* ItemBucket::Allocate() { if (!HasSpaceLeft()) { assert(false); return nullptr; } int allocated_index = free_map_.GetFirstBitSetAndClear(); (*free_slots_ptr_)--; return memory_ + (allocated_index * item_size_); } bool ItemBucket::HasSpaceLeft() { return (*free_slots_ptr_) > 0; } bool ItemBucket::IsUnused() { return (*free_slots_ptr_) == item_count_; } void ItemBucket::Free(void* ptr) { size_t offset_from_base = static_cast<uint8_t*>(ptr) - memory_; offset_from_base /= item_size_; assert(offset_from_base >= 0 && offset_from_base < item_count_); free_map_.SetBit(offset_from_base); (*free_slots_ptr_)++; } FixedSizeAllocator2::FixedSizeAllocator2(size_t item_size, size_t item_per_bucket, SnapshotableAllocatorImpl& memory) : memory_(memory), item_size_(item_size), item_per_bucket_(item_per_bucket) { ScopedAllocatorUsage sau; first_bucket_ = new ItemBucket(item_size_, item_per_bucket_); memory_.NewBucketWasCreated(*first_bucket_); } FixedSizeAllocator2::~FixedSizeAllocator2() { ScopedAllocatorUsage sau; delete first_bucket_; } void* FixedSizeAllocator2::Allocate() { ItemBucket* bucket = first_bucket_; while (!bucket->HasSpaceLeft()) { ItemBucket* next = bucket->next_bucket_; if (next == nullptr) { ScopedAllocatorUsage sau; next = new ItemBucket(item_size_, item_per_bucket_); memory_.NewBucketWasCreated(*next); bucket->next_bucket_ = next; } bucket = next; } return bucket->Allocate(); } SnapshotableAllocatorImpl::SnapshotableAllocatorImpl( size_t min_size_for_individual_copy) : min_size_for_individual_copy_(min_size_for_individual_copy) { ScopedAllocatorUsage sau; std::array<std::pair<size_t, size_t>, 20> m = {{ {1, 32}, {2, 32}, {4, 32}, {8, 128}, {16, 256}, {32, 512}, {64, 1024}, {128, 512}, {256, 256}, {512, 128}, {1024, 32}, {2048, 16}, {4096, 4}, {8192, 4}, {16384, 4}, {32768, 4}, {65536, 4}, {131072, 4}, {262144, 2}, {524288, 2}, }}; // |reserve| is necessary to avoid copying the elements of |allocators_| // when the vector is resized: // Copying an allocator is very expensive. allocators_.reserve(m.size()); for (auto const& p : m) { allocators_.emplace_back(p.first, p.second, *this); } } void* SnapshotableAllocatorImpl::Alloc(size_t size) { auto ptr = InternalAlloc(size); InitializeMemory(ptr); return ptr; } void* SnapshotableAllocatorImpl::Realloc(void* ptr, size_t size) { if (ptr == nullptr) { return Alloc(size); } void* old_ptr = ptr; ItemBucket* bucket = BucketForPointer(ptr); size_t old_size = bucket->GetItemSize(); bucket->Free(ptr); void* new_ptr = InternalAlloc(size); if (new_ptr != old_ptr) { if (old_size < size) { memcpy(new_ptr, old_ptr, old_size); } if (old_size >= size) { memcpy(new_ptr, old_ptr, size); } } return new_ptr; } void SnapshotableAllocatorImpl::Free(void* ptr) { if (!ptr) { return; } BucketForPointer(ptr)->Free(ptr); } void SnapshotableAllocatorImpl::LoadMemoryFromSnapshot( MemorySnapshot const& snapshot) { MemorySnapshotImpl const& ms = static_cast<MemorySnapshotImpl const&>(snapshot); ms.RestoreEverything(); } void SnapshotableAllocatorImpl::SaveMemoryIntoSnapshot( MemorySnapshot& snapshot) { MemorySnapshotImpl& ms = static_cast<MemorySnapshotImpl&>(snapshot); ms.Clear(); int skipped_memory_ = 0; for (AllocatorPositionInMemory& allocator_position : sorted_buckets_) { auto bucket = allocator_position.bucket_; ms.AppendData(bucket->free_map_.GetDataLocation(), bucket->free_map_.GetDataLength()); if (bucket->IsUnused()) { ms.AppendData(bucket->allocated_memory_, 4); } else { // Memory optimization where only the slots used in the buckets are // copied, as opposed to the entire bucket. // The lower the threshold, the more memory is saved. // In practice, saves 50% memory with a size of 128. if (bucket->GetItemSize() >= min_size_for_individual_copy_) { const size_t count = bucket->GetItemCount(); ms.AppendData(bucket->allocated_memory_, extra_bytes_); uint8_t* bucket_start_ = reinterpret_cast<uint8_t*>(bucket->allocated_memory_); bucket_start_ += extra_bytes_; for (uint32_t index = 0; index < count; index++) { if (!bucket->free_map_.GetBit(index)) { ms.AppendData(bucket_start_, bucket->GetItemSize()); } else { skipped_memory_ += bucket->GetItemSize(); } bucket_start_ += bucket->GetItemSize(); } } else { ms.AppendData( bucket->allocated_memory_, (bucket->GetItemSize() * bucket->GetItemCount()) + extra_bytes_); } } } } std::unique_ptr<MemorySnapshot> SnapshotableAllocatorImpl::NewEmptySnapshot() { return std::make_unique<MemorySnapshotImpl>(); } void SnapshotableAllocatorImpl::NewBucketWasCreated(ItemBucket& bucket) { AllocatorPositionInMemory apim = { bucket.memory_ + bucket.GetItemSize() * bucket.GetItemCount(), &bucket}; auto it = std::upper_bound(sorted_buckets_.begin(), sorted_buckets_.end(), apim); sorted_buckets_.insert(it, apim); assert(std::is_sorted(sorted_buckets_.begin(), sorted_buckets_.end())); } void SnapshotableAllocatorImpl::SetMemoryInitializationStyle( MemoryInitialization initialization_style) { initialization_style_ = initialization_style; } ItemBucket* SnapshotableAllocatorImpl::BucketForPointer(void* ptr) { AllocatorPositionInMemory apim = {ptr, nullptr}; auto it = std::lower_bound(sorted_buckets_.begin(), sorted_buckets_.end(), apim); if (it == sorted_buckets_.end()) { assert(false); } return it->bucket_; } void* SnapshotableAllocatorImpl::InternalAlloc(size_t size) { int index = FindLastBitSet(static_cast<int32_t>(size)); assert(index < allocators_.size()); return allocators_[index].Allocate(); } void SnapshotableAllocatorImpl::InitializeMemory(void* ptr) { switch (initialization_style_) { case NONE: break; case ZERO: memset(ptr, 0, BucketForPointer(ptr)->GetItemSize()); break; case RANDOM: { uint8_t* p = (uint8_t*)ptr; size_t size = BucketForPointer(ptr)->GetItemSize(); for (size_t i = 0; i < size; i++) { p[i] = rand() % 255; } break; } } }
31.7751
79
0.687184
jyaif
a2f951cda23845319d2644ac4a63932f2e829017
507
hpp
C++
include/IteratorRecognition/Support/Utils/DebugInfo.hpp
robcasloz/IteratorRecognition
fa1a1e67c36cde3639ac40528228ae85e54e3b13
[ "MIT" ]
null
null
null
include/IteratorRecognition/Support/Utils/DebugInfo.hpp
robcasloz/IteratorRecognition
fa1a1e67c36cde3639ac40528228ae85e54e3b13
[ "MIT" ]
6
2019-05-29T21:11:03.000Z
2021-07-01T10:47:02.000Z
include/IteratorRecognition/Support/Utils/DebugInfo.hpp
robcasloz/IteratorRecognition
fa1a1e67c36cde3639ac40528228ae85e54e3b13
[ "MIT" ]
1
2019-05-13T11:55:39.000Z
2019-05-13T11:55:39.000Z
// // // #pragma once #include "IteratorRecognition/Config.hpp" #include <string> // using std::string #include <tuple> // using std::make_tuple namespace llvm { class Loop; class Instruction; } // namespace llvm namespace iteratorrecognition { namespace dbg { std::string extract(const llvm::Instruction &I); using LoopDebugInfoT = std::tuple<unsigned, unsigned, std::string, std::string>; LoopDebugInfoT extract(const llvm::Loop &CurLoop); } // namespace dbg } // namespace iteratorrecognition
15.84375
80
0.733728
robcasloz
a2f9a8c664abf121f5cb44e53e4638b5f11d0e6b
340
cpp
C++
src/NBaseFunction.cpp
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
2
2017-01-04T02:27:10.000Z
2017-01-22T05:36:41.000Z
src/NBaseFunction.cpp
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
null
null
null
src/NBaseFunction.cpp
justinmann/sj
24d0a75723b024f17de6dab9070979a4f1bf1a60
[ "Apache-2.0" ]
1
2020-06-15T12:17:26.000Z
2020-06-15T12:17:26.000Z
#include <sjc.h> FunctionParameter FunctionParameter::create(bool isDefaultValue, AssignOp op, shared_ptr<CVar> var) { FunctionParameter param; param.isDefaultValue = isDefaultValue; param.op = op; param.var = var; return param; } void CBaseFunction::setHasThis() { assert(name != "global"); hasThis = true; }
22.666667
101
0.694118
justinmann
a2f9fc84e6580004190ec17f39301b3897aa6803
209
cpp
C++
Engine/Graphics/ImGui_Window.cpp
Antd23rus/S2DE_DirectX11
4f729278e6c795f7d606afc70a292c6501b0cafd
[ "MIT" ]
null
null
null
Engine/Graphics/ImGui_Window.cpp
Antd23rus/S2DE_DirectX11
4f729278e6c795f7d606afc70a292c6501b0cafd
[ "MIT" ]
null
null
null
Engine/Graphics/ImGui_Window.cpp
Antd23rus/S2DE_DirectX11
4f729278e6c795f7d606afc70a292c6501b0cafd
[ "MIT" ]
1
2021-09-06T08:30:20.000Z
2021-09-06T08:30:20.000Z
#include "ImGui_Window.h" namespace S2DE::Render { ImGui_Window::ImGui_Window() : m_draw(false) { } ImGui_Window::~ImGui_Window() { } void ImGui_Window::ToggleDraw() { m_draw = !m_draw; } }
10.45
32
0.650718
Antd23rus
0c0175c943041bdf71698fd4f117541251b7caf9
7,299
hh
C++
obj/obj/TStnHelix.hh
macndev/Stntuple
b5bb000edf015883eec32d87959cb7bd3ab88577
[ "Apache-2.0" ]
null
null
null
obj/obj/TStnHelix.hh
macndev/Stntuple
b5bb000edf015883eec32d87959cb7bd3ab88577
[ "Apache-2.0" ]
null
null
null
obj/obj/TStnHelix.hh
macndev/Stntuple
b5bb000edf015883eec32d87959cb7bd3ab88577
[ "Apache-2.0" ]
6
2019-11-21T15:27:27.000Z
2022-02-28T20:57:13.000Z
// // Read the track // // $Id: $ // $Author:$ // $Date: $ // // Contact person Pavel Murat // #ifndef Stntuple_obj_TStnHelix_hh #define Stntuple_obj_TStnHelix_hh // storable objects (data products) // // C++ includes. #include <iostream> #include "TString.h" #include "TFolder.h" #include "TFile.h" #include "TBuffer.h" #include "TLorentzVector.h" //namespace murat { namespace mu2e { class HelixSeed; class StrawHit; class CaloCluster; } class TStnHelix : public TObject { enum { kNFreeIntsV2 = 10, // V2 kNFreeFloatsV2 = 10, // V2 kNFreeIntsV3 = 4, // v3: added the indices of the two SimParticles contributing kNFreeFloatsV3 = 10, // the most and their fraction of hits within the helix, // also added the p and pT of the SimParticles. kNFreeIntsV4 = 3, // v4: added helicity kNFreeFloatsV4 = 10, // kNFreeInts = 3, // v5: added number of loops kNFreeFloats = 9 // }; public: //----------------------------------------------------------------------------- // vectors, added in V3 //----------------------------------------------------------------------------- TLorentzVector fMom1; TLorentzVector fOrigin1; TLorentzVector fMom2; TLorentzVector fOrigin2; //----------------------------------------------------------------------------- // integers //----------------------------------------------------------------------------- int fNHits; int fAlgorithmID; // bit-packed : (alg_mask << 16 ) | best int fTimeClusterIndex; int fTrackSeedIndex; int fNComboHits; int fSimpPDG1; // added in v3 int fSimpPDGM1; // added in v3 int fSimpId1Hits; // added in v3 int fSimpPDG2; // added in v3 int fSimpPDGM2; // added in v3 int fSimpId2Hits; // added in v3 int fHelicity; // added in v4 int fInt[kNFreeInts]; // provision for future I/O expansion //----------------------------------------------------------------------------- // floats //----------------------------------------------------------------------------- float fT0; float fT0Err; float fRCent; // radius of circle center float fFCent; // azimuth of circle center float fRadius; // transverse radius of the helix (mm). Always positive float fLambda; // dz/dphi (mm/radian) float fFZ0; // azimuth (phi) at the center z position (radians) float fD0; // impact paramter float fChi2XYNDof; float fChi2PhiZNDof; float fClusterTime; float fClusterEnergy; float fClusterX; float fClusterY; float fClusterZ; float fNLoops; float fFloat[kNFreeFloats]; // provision for future I/O expansion //----------------------------------------------------------------------------- // transients //----------------------------------------------------------------------------- const mu2e::HelixSeed* fHelix; //! int fNumber; //! sequential number in the list, set by TStnHelixBlock::Streamer //----------------------------------------------------------------------------- // methods //----------------------------------------------------------------------------- TStnHelix(int Number = -1); ~TStnHelix(); //----------------------------------------------------------------------------- // accessors //----------------------------------------------------------------------------- int NHits () { return fNHits; } int Number () { return fNumber; } int Helicity () { return fHelicity; } int NComboHits () { return fNComboHits; } int AlgorithmID () { return fAlgorithmID; } int AlgMask () { return (fAlgorithmID >> 16) & 0xffff; } int BestAlg () { return fAlgorithmID & 0xffff; } int TimeClusterIndex() { return fTimeClusterIndex; } int TrackSeedIndex () { return fTrackSeedIndex; } int PDG1 () { return fSimpPDG1; } int PDGMother1 () { return fSimpPDGM1; } int ComboHitsFrom1 () { return fSimpId1Hits; } int PDG2 () { return fSimpPDG2; } int PDGMother2 () { return fSimpPDGM2; } int ComboHitsFrom2 () { return fSimpId2Hits; } float T0 () { return fT0; } float T0Err () { return fT0Err; } float RCent () { return fRCent; } float FCent () { return fFCent; } float Radius () { return fRadius; } float Lambda () { return fLambda; } float FZ0 () { return fFZ0; } float CenterX () { return fRCent*cos(fFCent);} float CenterY () { return fRCent*sin(fFCent);} float D0 () { return fD0; } float Pt () { return fRadius*3./10;}//assumes 1T magnetic field! float P () { return sqrt(fRadius*fRadius + fLambda*fLambda)*3./10;}//assumes 1T magnetic field! float Chi2XY () { return fChi2XYNDof;} float Chi2ZPhi () { return fChi2PhiZNDof;} float ClusterTime () { return fClusterTime; } float ClusterEnergy () { return fClusterEnergy;} float ClusterX () { return fClusterX; } float ClusterY () { return fClusterY; } float ClusterZ () { return fClusterZ; } float NLoops () { return fNLoops; } TLorentzVector Mom1 () { return fMom1; } TLorentzVector Origin1 () { return fOrigin1; } TLorentzVector Mom2 () { return fMom2; } TLorentzVector Origin2 () { return fOrigin2; } //---------------------------------------------------------------------------- // setters //---------------------------------------------------------------------------- void SetTimeClusterIndex(int I) { fTimeClusterIndex = I; } void SetTrackSeedIndex (int I) { fTrackSeedIndex = I; } void SetNumber (int I) { fNumber = I; } //----------------------------------------------------------------------------- // overloaded methods of TObject //----------------------------------------------------------------------------- virtual void Clear(Option_t* Opt = "") ; virtual void Print(Option_t* Opt = "") const ; //----------------------------------------------------------------------------- // schema evolution //----------------------------------------------------------------------------- void ReadV1(TBuffer& R__b); void ReadV2(TBuffer& R__b); void ReadV3(TBuffer& R__b); // 2018-12-05 P.M. void ReadV4(TBuffer& R__b); // 2019-02-27 G.P. ClassDef(TStnHelix,5); }; #endif
40.776536
109
0.42362
macndev
0c05228e85432d9e7621dc1ef61c3dad032e6be6
7,009
cpp
C++
hackathon/hanbo/image_transform_combine_by_amat/image_transform_and_combine_by_affine_mat_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/hanbo/image_transform_combine_by_amat/image_transform_and_combine_by_affine_mat_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2016-12-03T05:33:13.000Z
2016-12-03T05:33:13.000Z
hackathon/hanbo/image_transform_combine_by_amat/image_transform_and_combine_by_affine_mat_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/* image_transform_and_combine_by_affine_mat_plugin.cpp * This plugin will transform and combine image by given affine matrix. Some functions are based on littleQuickWarper. * 2015-3-18 : by Hanbo Chen */ #include "v3d_message.h" #include <vector> #include "image_transform_and_combine_by_affine_mat_plugin.h" #include "image_transform_and_combine_by_affine_mat_func.cpp" using namespace std; Q_EXPORT_PLUGIN2(image_transform_and_combine_by_affine_mat, imageTransfromAndCombine); QStringList imageTransfromAndCombine::menulist() const { return QStringList() <<tr("transform_and_combine_images_by_affine_mat") <<tr("about"); } QStringList imageTransfromAndCombine::funclist() const { return QStringList() <<tr("affineImage") <<tr("help"); } void imageTransfromAndCombine::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent) { if (menu_name == tr("transform_and_combine_images_by_affine_mat")) { v3d_msg("To be implemented."); } else { v3d_msg(tr("This plugin will transform and combine image by given affine matrix. Some functions are based on littleQuickWarper.. " "Developed by Hanbo Chen, 2015-3-18")); } } bool imageTransfromAndCombine::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent) { vector<char*> infiles, inparas, outfiles; if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); if (func_name == tr("affineImage")) { qDebug()<<"==== affine and combine images ===="; if(infiles.size()!=3 || outfiles.size()!=1){ qDebug()<<"ERROR: please set input and output!"; printHelp(); return false; } QString fname_img_tar=((vector<char*> *)(input.at(0).p))->at(0); QString fname_img_sub=((vector<char*> *)(input.at(0).p))->at(1); QString fname_amat=((vector<char*> *)(input.at(0).p))->at(2); QString fname_output=((vector<char*> *)(output.at(0).p))->at(0); //init parameters bool b_channelSeperate = false; bool b_negativeShift = true; int interpMethod = 0; if(input.size() >= 2){ vector<char*> paras = (*(vector<char*> *)(input.at(1).p)); if(paras.size()>0){ int tmp=atoi(paras.at(0)); if(tmp==1) interpMethod = 1; } if(paras.size()>1){ int tmp=atoi(paras.at(1)); if(tmp==0) b_negativeShift = false; } if(paras.size()>2){ int tmp=atoi(paras.at(2)); if(tmp==1) b_channelSeperate = true; } } doAffineImage(callback, fname_img_tar, fname_img_sub, fname_amat, fname_output, interpMethod, b_negativeShift, b_channelSeperate); } else if (func_name == tr("help")) { printHelp(); } else return false; return true; } void imageTransfromAndCombine::doAffineImage(V3DPluginCallback2 & callback, QString fname_tar, QString fname_sub, QString fname_amat, QString fname_output, int interpMethod, bool b_negativeShift, bool b_channelSeperate) { //load amat and check eligibility double amat[16]; if(!readAmat(fname_amat.toStdString().c_str(), amat) ){ qDebug()<<"error: cannot read affine matrix: "<<fname_amat; return; } if(fabs(amat[12])>1e-6 || fabs(amat[13])>1e-6 || fabs(amat[14])>1e-6 || fabs(amat[15]-1)>1e-6 ) { qDebug()<<"invalide last row of amat"; return; } //load images unsigned char * p_img_sub = 0; unsigned char * p_img_tar = 0; unsigned char * p_img_out = 0; V3DLONG sz_sub[4], sz_tar[4], sz_out[4]={0}, globalShift[3]={0}; int type_sub, type_tar, type_out; if(!simple_loadimage_wrapper(callback, fname_tar.toStdString().c_str(), p_img_tar, sz_tar, type_tar)) { qDebug()<<"load image "<<fname_tar<<" error!"; return; } if(!simple_loadimage_wrapper(callback, fname_sub.toStdString().c_str(), p_img_sub, sz_sub, type_sub)) { qDebug()<<"load image "<<fname_sub<<" error!"; return; } if(type_tar != type_sub){ qDebug()<<"error: the data type of target image and subject image is not the same"; return; }else{ type_out = type_tar; } bool success = false; if(type_sub==1){ success=affineCombineImage(p_img_tar, sz_tar, p_img_sub, sz_sub, p_img_out, sz_out, globalShift, amat, interpMethod, b_channelSeperate, true); }else if(type_sub==2){ unsigned short * p_tmp = 0; success=affineCombineImage((unsigned short *)p_img_tar, sz_tar, (unsigned short *)p_img_sub, sz_sub, p_tmp, sz_out, globalShift, amat, interpMethod, b_channelSeperate, b_negativeShift); p_img_out = (unsigned char *) p_tmp; }else if(type_sub==4){ float * p_tmp = 0; success=affineCombineImage((float *)p_img_tar, sz_tar, (float *)p_img_sub, sz_sub, p_tmp, sz_out, globalShift, amat, interpMethod, b_channelSeperate, b_negativeShift); p_img_out = (unsigned char *) p_tmp; }else{ qDebug()<<"error: do not support the input type. Currently only support UINT8, UINT16, FLOAT."; return; } qDebug()<<"Saving output: "<<fname_output; QString fname_gmat=fname_output+"_offset.txt"; double gmat[16]={0}; gmat[0]=gmat[5]=gmat[10]=gmat[15]=1; gmat[3]=globalShift[0]; gmat[7]=globalShift[1]; gmat[11]=globalShift[2]; writeAmat(fname_gmat.toStdString().c_str(),gmat); if(!simple_saveimage_wrapper(callback, fname_output.toStdString().c_str(), p_img_out, sz_out, type_out) ) { qDebug()<<"save image "<<fname_output<<" error!"; return; } } void imageTransfromAndCombine::printHelp() { qDebug()<<"Usage : v3d -x dllname -f affineImage -i <target_img_file> <subject_img_file> <affine_matrix.txt> -p <(0)interpmethod> <(1)negative shifting> <(0)seperate channel> -o <out_img_file>"; qDebug()<<"interpmethod: 0(default): linera interpolate; 1: nearest neighbor interpolate."; qDebug()<<"negative shifting: if set 0, the image component with negative index after affine transform will not be saved. Otherwise(default), the whole image will be shifted to make space for that part."; qDebug()<<"seperate channel: if set 1, target and subject image will be saved in different channels (for visualization), otherwise(default), they will be saved in the same channel."; qDebug()<<" "; }
38.510989
208
0.620631
zzhmark
0c06467c40cdd7d9d54573bba2a2a67e4226830b
3,069
cpp
C++
servicios/Locator.cpp
seblaz/Final-Fight
b79677191a4d4239e8793fa0b6e8a8b69870a14d
[ "MIT" ]
1
2020-02-23T21:15:59.000Z
2020-02-23T21:15:59.000Z
servicios/Locator.cpp
seblaz/Final-Fight
b79677191a4d4239e8793fa0b6e8a8b69870a14d
[ "MIT" ]
1
2020-03-06T21:31:10.000Z
2020-03-06T21:31:10.000Z
servicios/Locator.cpp
seblaz/Final-Fight
b79677191a4d4239e8793fa0b6e8a8b69870a14d
[ "MIT" ]
1
2020-02-23T21:28:28.000Z
2020-02-23T21:28:28.000Z
// // Created by sebas on 8/9/19. // #include "Locator.h" /** * Logger. */ Logger *Locator::logger_; Logger *Locator::logger() { return logger_; } void Locator::provide(Logger *logger) { logger_ = logger; } /** * Configuracion. */ Configuracion *Locator::configuracion_; Configuracion *Locator::configuracion() { return configuracion_; } void Locator::provide(Configuracion *configuracion) { configuracion_ = configuracion; } /** * Renderer. */ SDL_Renderer *Locator::renderer_; SDL_Renderer *Locator::renderer() { return renderer_; } void Locator::provide(SDL_Renderer *renderer) { renderer_ = renderer; } /** * Socket. */ Socket *Locator::socket_; Socket *Locator::socket() { return socket_; } void Locator::provide(Socket *socket) { socket_ = socket; } /** * Posicion. */ Posicion *Locator::posicion; Posicion *Locator::posicionEscenario() { return posicion; } void Locator::provide(Posicion *posicion_) { posicion = posicion_; } /** * Fabrica de sprites. */ FabricaDeSprites *Locator::fabrica; FabricaDeSprites *Locator::fabricaDeSprites() { return fabrica; } void Locator::provide(FabricaDeSprites *fabricaDeSprites) { fabrica = fabricaDeSprites; } /** * Fuente. */ TTF_Font *Locator::fuente_; TTF_Font *Locator::fuente() { return fuente_; } void Locator::provide(TTF_Font *fuente) { fuente_ = fuente; } /** * Eventos a procesar. */ EventosAProcesar *Locator::eventos_; EventosAProcesar *Locator::eventos() { return eventos_; } void Locator::provide(EventosAProcesar *eventos) { eventos_ = eventos; } /** * Manager de usuarios. */ ManagerUsuarios *Locator::usuarios_; ManagerUsuarios *Locator::usuarios() { return usuarios_; } void Locator::provide(ManagerUsuarios *usuarios) { usuarios_ = usuarios; } /** * Mapa. */ Mapa *Locator::mapa_; Mapa *Locator::mapa() { return mapa_; } void Locator::provide(Mapa *mapa) { mapa_ = mapa; } /** * Manager de clientes. */ ManagerClientes *Locator::clientes_; ManagerClientes *Locator::clientes() { return clientes_; } void Locator::provide(ManagerClientes *clientes) { clientes_ = clientes; } /** * Colisionables. */ Colisionables *Locator::colisionables_; void Locator::provide(Colisionables * colisionables) { colisionables_ = colisionables; } Colisionables *Locator::colisionables() { return colisionables_; } void Locator::clean() { logger_->log(DEBUG, "Se limpian configuracion y logger"); delete configuracion_; delete logger_; } /** * Fabrica de Sonidos. */ FabricaDeSonidos *Locator::fabricaSonidos; FabricaDeSonidos *Locator::fabricaDeSonidos() { return fabricaSonidos; } void Locator::provide(FabricaDeSonidos *fabricaDeSonidos) { fabricaSonidos = fabricaDeSonidos; } /** * Fabrica de Musicas. */ FabricaDeMusicas *Locator::fabricaMusicas; FabricaDeMusicas *Locator::fabricaDeMusicas() { return fabricaMusicas; } void Locator::provide(FabricaDeMusicas *_fabricaDeMusicas) { fabricaMusicas = _fabricaDeMusicas; }
15.268657
61
0.693385
seblaz
0c06cb94f1791b3c77a1e2f28308eeb60d302d95
284
cc
C++
test/camera.cc
imkaywu/open3DCV
33ef0507e565bce2ccff7409ff35a8970e6eed2d
[ "BSD-3-Clause" ]
37
2018-07-30T15:34:29.000Z
2022-01-10T22:50:39.000Z
test/camera.cc
imkaywu/open3DCV
33ef0507e565bce2ccff7409ff35a8970e6eed2d
[ "BSD-3-Clause" ]
1
2020-10-09T17:51:42.000Z
2020-11-11T19:41:06.000Z
test/camera.cc
imkaywu/open3DCV
33ef0507e565bce2ccff7409ff35a8970e6eed2d
[ "BSD-3-Clause" ]
14
2017-12-03T15:24:01.000Z
2021-09-16T02:13:31.000Z
// // camera.cpp // open3DCV_test // // Created by KaiWu on Jul/5/17. // Copyright © 2017 KaiWu. All rights reserved. // #include <stdio.h> #include "camera.h" using namespace std; using namespace open3DCV; int main(int argc, const char * argv[]) { return 0; }
12.909091
48
0.630282
imkaywu
0c0cbcc68d367a76f0a1e0a20b7ed339c461c663
839
cpp
C++
cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests_sysconf.cpp
RoryPreddyGithubEnterprise/codeql
af27da1b39f5529faf4c5c6bcf01834f10d89aa9
[ "MIT" ]
643
2018-08-03T11:16:54.000Z
2020-04-27T23:10:55.000Z
cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests_sysconf.cpp
RoryPreddyGithubEnterprise/codeql
af27da1b39f5529faf4c5c6bcf01834f10d89aa9
[ "MIT" ]
1,880
2018-08-03T11:28:32.000Z
2020-04-28T13:18:51.000Z
cpp/ql/test/query-tests/Security/CWE/CWE-497/semmle/tests/tests_sysconf.cpp
RoryPreddyGithubEnterprise/codeql
af27da1b39f5529faf4c5c6bcf01834f10d89aa9
[ "MIT" ]
218
2018-08-03T11:16:58.000Z
2020-04-24T02:24:00.000Z
typedef unsigned long size_t; typedef signed long ssize_t; void *malloc(size_t size); #define NULL (0) int printf(const char *format, ...); size_t strlen(const char *s); int get_fd(); int write(int handle, const void *buffer, size_t length); long sysconf(int name); #define _SC_CHILD_MAX (2) size_t confstr(int name, char *buffer, size_t length); #define _CS_PATH (1) void test_sc_1() { int value = sysconf(_SC_CHILD_MAX); printf("_SC_CHILD_MAX = %i\n", _SC_CHILD_MAX); // GOOD printf("_SC_CHILD_MAX = %i\n", value); // BAD [NOT DETECTED] } void test_sc_2() { char *pathbuf; size_t n; n = confstr(_CS_PATH, NULL, (size_t)0); pathbuf = (char *)malloc(n); if (pathbuf != NULL) { confstr(_CS_PATH, pathbuf, n); printf("path: %s", pathbuf); // BAD [NOT DETECTED] write(get_fd(), pathbuf, strlen(pathbuf)); // BAD } }
19.97619
61
0.680572
RoryPreddyGithubEnterprise
0c0ddeeabdb96e2f498a7e49b45488068edea2da
7,651
cpp
C++
Fuji/Source/Drivers/PS2/MFInput_PS2.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
35
2015-01-19T22:07:48.000Z
2022-02-21T22:17:53.000Z
Fuji/Source/Drivers/PS2/MFInput_PS2.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
1
2022-02-23T09:34:15.000Z
2022-02-23T09:34:15.000Z
Fuji/Source/Drivers/PS2/MFInput_PS2.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
4
2015-05-11T03:31:35.000Z
2018-09-27T04:55:57.000Z
#include "Fuji_Internal.h" #if MF_INPUT == MF_DRIVER_PS2 #include "MFVector.h" #include "MFInput_Internal.h" #include "MFHeap.h" #include "MFIni.h" /*** Structure definitions ***/ /*** Globals ***/ int gGamepadCount = 0; int gKeyboardCount = 0; int gMouseCount = 0; char gKeyState[256]; bool gExclusiveMouse = false; float deadZone = 0.3f; float mouseMultiplier = 1.0f; static const char * const gPS2Buttons[] = { // PS2 controller enums "X", "Circle", "Box", "Triangle", "L1", "R1", "L2", "R2", "Start", "Select", "L3", "R3", // general controller enums "DPad Up", "DPad Down", "DPad Left", "DPad Right", "Left X-Axis", "Left Y-Axis", "Right X-Axis", "Right Y-Axis" }; /**** Platform Specific Functions ****/ #include <stdio.h> #include <kernel.h> #include <sifrpc.h> #include <loadfile.h> #include "libpad.h" static char padBuf[256] __attribute__((aligned(64))); static char actAlign[6]; static int actuators; struct padButtonStatus buttons; u32 new_pad; // Using the X* variety of modules doesnt work for me, so I stick to the vanilla versions #define ROM_PADMAN static int loadModules(void) { int ret; #ifdef ROM_PADMAN ret = SifLoadModule("rom0:SIO2MAN", 0, NULL); #else ret = SifLoadModule("rom0:XSIO2MAN", 0, NULL); #endif if (ret < 0) { MFDebug_Message(MFStr("sifLoadModule sio failed: %d", ret)); return -1; } #ifdef ROM_PADMAN ret = SifLoadModule("rom0:PADMAN", 0, NULL); #else ret = SifLoadModule("rom0:XPADMAN", 0, NULL); #endif if (ret < 0) { printf("sifLoadModule pad failed: %d\n", ret); return -1; } return 0; } int waitPadReady(int port, int slot) { int state; state = padGetState(port, slot); while((state != PAD_STATE_STABLE) && (state != PAD_STATE_FINDCTP1)) { state=padGetState(port, slot); } return 0; } int initializePad(int port, int slot) { MFCALLSTACK; int ret; int modes; int i; waitPadReady(port, slot); // How many different modes can this device operate in? // i.e. get # entrys in the modetable modes = padInfoMode(port, slot, PAD_MODETABLE, -1); // If modes == 0, this is not a Dual shock controller // (it has no actuator engines) if(modes == 0) { // printf("This is a digital controller?\n"); return 1; } // Verify that the controller has a DUAL SHOCK mode i = 0; do { if(padInfoMode(port, slot, PAD_MODETABLE, i) == PAD_TYPE_DUALSHOCK) break; i++; } while (i < modes); if(i >= modes) { // printf("This is no Dual Shock controller\n"); return 1; } // If ExId != 0x0 => This controller has actuator engines // This check should always pass if the Dual Shock test above passed ret = padInfoMode(port, slot, PAD_MODECUREXID, 0); if(ret == 0) { // printf("This is no Dual Shock controller??\n"); return 1; } // When using MMODE_LOCK, user cant change mode with Select button padSetMainMode(port, slot, PAD_MMODE_DUALSHOCK, PAD_MMODE_LOCK); waitPadReady(port, slot); actuators = padInfoAct(port, slot, -1, 0); if(actuators != 0) { actAlign[0] = 0; // Enable small engine actAlign[1] = 1; // Enable big engine actAlign[2] = 0xff; actAlign[3] = 0xff; actAlign[4] = 0xff; actAlign[5] = 0xff; waitPadReady(port, slot); } else { // printf("Did not find any actuators.\n"); } waitPadReady(port, slot); return 1; } void MFInput_InitModulePlatformSpecific() { MFCALLSTACK; int port, slot; int ret; SifInitRpc(0); if(loadModules()) { printf("UNABLE to load modules\n"); return; } if(padInit(0)) { printf("UNABLE to init pad\n"); return; } port = 0; // 0 -> Connector 1, 1 -> Connector 2 slot = 0; // Always zero if not using multitap // printf("PortMax: %d\n", padGetPortMax()); // printf("SlotMax: %d\n", padGetSlotMax(port)); if((ret = padPortOpen(port, slot, padBuf)) == 0) { printf("padOpenPort failed: %d\n", ret); return; } if(!initializePad(port, slot)) { printf("pad initalization failed!\n"); return ; } } void MFInput_DeinitModulePlatformSpecific() { MFCALLSTACK; } void MFInput_UpdatePlatformSpecific() { int ret; int port =0, slot = 0; MFCALLSTACK; ret=padGetState(port, slot); while((ret != PAD_STATE_STABLE) && (ret != PAD_STATE_FINDCTP1)) { if(ret==PAD_STATE_DISCONN) { printf("Pad(%d, %d) is disconnected\n", port, slot); printf("What now?\n"); while(1); } ret=padGetState(port, slot); } ret = padRead(port, slot, &buttons); if (ret != 0) { new_pad = 0xffff ^ buttons.btns; return; } } MFInputDeviceStatus MFInput_GetDeviceStatusInternal(int device, int id) { if(device == IDD_Gamepad && id < 2) return IDS_Disconnected; return IDS_Unavailable; } void MFInput_GetGamepadStateInternal(int id, MFGamepadState *pGamepadState) { MFCALLSTACK; MFZeroMemory(pGamepadState, sizeof(MFGamepadState)); pGamepadState->values[Button_P2_Cross] = (new_pad & PAD_CROSS )?1.0f:0.0f; pGamepadState->values[Button_P2_Circle] = (new_pad & PAD_CIRCLE)?1.0f:0.0f; pGamepadState->values[Button_P2_Box] = (new_pad & PAD_SQUARE)?1.0f:0.0f; pGamepadState->values[Button_P2_Triangle] = (new_pad & PAD_TRIANGLE)?1.0f:0.0f; pGamepadState->values[Button_P2_L1] = (new_pad & PAD_L1)?1.0f:0.0f; pGamepadState->values[Button_P2_R1] = (new_pad & PAD_R1)?1.0f:0.0f; pGamepadState->values[Button_P2_L2] = (new_pad & PAD_L2)?1.0f:0.0f; pGamepadState->values[Button_P2_R2] = (new_pad & PAD_R2)?1.0f:0.0f; pGamepadState->values[Button_P2_Start] = (new_pad & PAD_START)?1.0f:0.0f; pGamepadState->values[Button_P2_Select] = (new_pad & PAD_SELECT)?1.0f:0.0f; pGamepadState->values[Button_P2_L3] = (new_pad & PAD_L3)?1.0f:0.0f; pGamepadState->values[Button_P2_R3] = (new_pad & PAD_R3)?1.0f:0.0f; pGamepadState->values[Button_DUp] = (new_pad & PAD_UP)?1.0f:0.0f; pGamepadState->values[Button_DDown] = (new_pad & PAD_DOWN)?1.0f:0.0f; pGamepadState->values[Button_DLeft] = (new_pad & PAD_LEFT)?1.0f:0.0f; pGamepadState->values[Button_DRight] = (new_pad & PAD_RIGHT)?1.0f:0.0f; pGamepadState->values[Axis_LX] = (float)buttons.ljoy_h /127.5f - 1.0f; pGamepadState->values[Axis_LY] = -((float)buttons.ljoy_v/127.5f - 1.0f); pGamepadState->values[Axis_RX] = (float)buttons.rjoy_h /127.5f - 1.0f; pGamepadState->values[Axis_RY] = -((float)buttons.rjoy_v/127.5f - 1.0f); } void MFInput_GetKeyStateInternal(int id, MFKeyState *pKeyState) { MFCALLSTACK; MFZeroMemory(pKeyState, sizeof(MFKeyState)); } void MFInput_GetMouseStateInternal(int id, MFMouseState *pMouseState) { MFCALLSTACK; MFZeroMemory(pMouseState, sizeof(MFMouseState)); } const char* MFInput_GetDeviceNameInternal(int source, int sourceID) { switch(source) { case IDD_Gamepad: return "DualShock 2"; case IDD_Mouse: return "Mouse"; case IDD_Keyboard: return "Keyboard"; default: break; } return NULL; } const char* MFInput_GetGamepadButtonNameInternal(int button, int sourceID) { MFDebug_Assert(sourceID < 2, "Only two gamepads available on PS2..."); // multitap?? return gPS2Buttons[button]; } MF_API bool MFInput_GetKeyboardStatusState(int keyboardState, int keyboardID) { switch(keyboardState) { case KSS_NumLock: break; case KSS_CapsLock: break; case KSS_ScrollLock: break; case KSS_Insert: break; } return 0; } #endif
21.077135
90
0.649327
TurkeyMan
0c12563f6dc15690aaa6754dda968b5f12ea895d
31,784
cpp
C++
Build/hosEditor/hosEditorDlg.cpp
Game-institute-1st-While-true/hosEngine
2cc0b464740a976a8b37afd7a9e3479fe7484cf0
[ "MIT" ]
null
null
null
Build/hosEditor/hosEditorDlg.cpp
Game-institute-1st-While-true/hosEngine
2cc0b464740a976a8b37afd7a9e3479fe7484cf0
[ "MIT" ]
null
null
null
Build/hosEditor/hosEditorDlg.cpp
Game-institute-1st-While-true/hosEngine
2cc0b464740a976a8b37afd7a9e3479fe7484cf0
[ "MIT" ]
2
2021-07-14T00:14:18.000Z
2021-07-27T04:16:53.000Z
 // hosEditorDlg.cpp: 구현 파일 // #include "pch.h" #include "framework.h" #include "hosEditor.h" #include "SceneView.h" #include "TransformView.h" #include "BoxCollisionview.h" #include "SphereCollisionView.h" #include "CapsuleCollisionView.h" #include "CameraView.h" #include "RigidbodyView.h" #include "AudioListenerView.h" #include "AudioSourceView.h" #include "ScriptView.h" #include "LIghtView.h" #include "MeshFilterView.h" #include "MeshRendererView.h" #include "SkinnedMeshRendererView.h" #include "AnimationView.h" #include "UIImageView.h" #include "UITextView.h" #include "UIButtonView.h" #include "UIInputFieldView.h" #include "SceneInfoView.h" #include "NavInfoView.h" #include "hosEditorDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 응용 프로그램 정보에 사용되는 CAboutDlg 대화 상자입니다. class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 대화 상자 데이터입니다. #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. // 구현입니다. protected: DECLARE_MESSAGE_MAP() public: // afx_msg void OnClose(); }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) // ON_WM_CLOSE() END_MESSAGE_MAP() // ChosEditorDlg 대화 상자 ChosEditorDlg::ChosEditorDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_HOSEditor_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void ChosEditorDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_TREE_GAME_OBJECT_HIERARCHY, GameObjectHierachy); DDX_Control(pDX, IDC_EDIT_GAME_OBJECT_NAME, GameObjectName); DDX_Control(pDX, IDC_LIST_COMPONENT_LIST, ComponentList); DDX_Control(pDX, IDC_COMBO_COMPONENT_LIST, ComponentSelectList); DDX_Control(pDX, IDC_EDIT_SCENE_NAME, EditSceneName); DDX_Control(pDX, IDC_LIST_PREFAB_LIST, ListPrefabList); } BEGIN_MESSAGE_MAP(ChosEditorDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_CREATE_GAME_OBJECT, &ChosEditorDlg::OnBnClickedButtonCreateGameObject) ON_BN_CLICKED(IDC_BUTTON_CHANGE_GAME_OBJECT_NAME, &ChosEditorDlg::OnBnClickedButtonChangeGameObjectName) // ON_WM_CLOSE() ON_NOTIFY(TVN_SELCHANGED, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnTvnSelchangedTreeGameObjectHierarchy) ON_BN_CLICKED(IDC_BUTTON_REMOVE_GAME_OBJECT, &ChosEditorDlg::OnBnClickedButtonRemoveGameObject) ON_NOTIFY(NM_RCLICK, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnNMRClickTreeGameObjectHierarchy) ON_BN_CLICKED(IDC_BUTTON_ADD_COMPONENT, &ChosEditorDlg::OnBnClickedButtonAddComponent) ON_BN_CLICKED(IDC_BUTTON_REMOVE_COMPONENT, &ChosEditorDlg::OnBnClickedButtonRemoveComponent) ON_LBN_SELCHANGE(IDC_LIST_COMPONENT_LIST, &ChosEditorDlg::OnLbnSelchangeListComponentList) ON_EN_CHANGE(IDC_EDIT_SCENE_NAME, &ChosEditorDlg::OnEnChangeEditSceneName) ON_BN_CLICKED(IDC_BUTTON_SCENE_SAVE, &ChosEditorDlg::OnBnClickedButtonSceneSave) ON_BN_CLICKED(IDC_BUTTON_SCENE_LOAD, &ChosEditorDlg::OnBnClickedButtonSceneLoad) ON_BN_CLICKED(IDC_BUTTON_GAME_OBJECT_SAVE, &ChosEditorDlg::OnBnClickedButtonGameObjectSave) ON_BN_CLICKED(IDC_BUTTON_GAME_OBJECT_LOAD, &ChosEditorDlg::OnBnClickedButtonGameObjectLoad) ON_NOTIFY(TVN_BEGINDRAG, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnTvnBegindragTreeGameObjectHierarchy) ON_BN_CLICKED(IDC_BUTTON_ADD_GAME_DATA, &ChosEditorDlg::OnBnClickedButtonAddGameData) ON_BN_CLICKED(IDC_BUTTON_LOAD_GAME_DATA, &ChosEditorDlg::OnBnClickedButtonLoadGameData) ON_WM_CLOSE() ON_NOTIFY(NM_DBLCLK, IDC_TREE_GAME_OBJECT_HIERARCHY, &ChosEditorDlg::OnNMDblclkTreeGameObjectHierarchy) ON_BN_CLICKED(IDC_BUTTON_SCENE_INFO, &ChosEditorDlg::OnBnClickedButtonSceneInfo) ON_BN_CLICKED(IDC_BUTTON_NAV_INFO, &ChosEditorDlg::OnBnClickedButtonNavInfo) END_MESSAGE_MAP() // ChosEditorDlg 메시지 처리기 BOOL ChosEditorDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 시스템 메뉴에 "정보..." 메뉴 항목을 추가합니다. // IDM_ABOUTBOX는 시스템 명령 범위에 있어야 합니다. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는 // 프레임워크가 이 작업을 자동으로 수행합니다. SetIcon(m_hIcon, TRUE); // 큰 아이콘을 설정합니다. SetIcon(m_hIcon, FALSE); // 작은 아이콘을 설정합니다. // TODO: 여기에 추가 초기화 작업을 추가합니다. /// 다이얼로그 만들어야 함 m_SceneView = new SceneView(); m_SceneView->Create(IDD_SceneView, CWnd::GetDesktopWindow()); RECT Size; Size.left = 0; Size.top = 0; Size.right = 1920; Size.bottom = 1080; AdjustWindowRect(&Size, WS_OVERLAPPEDWINDOW, false); m_SceneView->SetWindowPos(NULL, 0, 0, Size.right - Size.left, Size.bottom - Size.top, SWP_NOMOVE | SWP_NOZORDER); m_SceneView->ShowWindow(SW_SHOW); EditorManager::GetIns()->Initialize(m_SceneView->GetSafeHwnd()); ComponentSelectList.AddString(L"Camera"); ComponentSelectList.AddString(L"BoxCollision"); ComponentSelectList.AddString(L"SphereCollision"); ComponentSelectList.AddString(L"CapsuleCollision"); ComponentSelectList.AddString(L"Rigidbody"); ComponentSelectList.AddString(L"AudioListener"); ComponentSelectList.AddString(L"AudioSource"); ComponentSelectList.AddString(L"Script"); ComponentSelectList.AddString(L"Light"); ComponentSelectList.AddString(L"MeshFilter"); ComponentSelectList.AddString(L"MeshRenderer"); ComponentSelectList.AddString(L"SkinnedMeshRenderer"); ComponentSelectList.AddString(L"Animation"); ComponentSelectList.AddString(L"NavAgent"); ComponentSelectList.AddString(L"Networkcomponent"); ComponentSelectList.AddString(L"UIImage"); ComponentSelectList.AddString(L"UIText"); ComponentSelectList.AddString(L"UIButton"); ComponentSelectList.AddString(L"UIInputField"); EditSceneName.SetWindowTextW(EditorManager::GetIns()->GetNowScene()->GetName().c_str()); GameObjectHierachy.InsertItem(L"MainCamera"); GameObjectHierachy.InsertItem(L"DirectionalLight1"); GameObjectHierachy.InsertItem(L"DirectionalLight2"); GameObjectHierachy.InsertItem(L"DirectionalLight3"); CCreateContext context; ZeroMemory(&context, sizeof(context)); CRect _rect; GetDlgItem(IDC_STATIC_INSPECTOR_AREA)->GetWindowRect(&_rect); ScreenToClient(&_rect); m_TransformView = new TransformView(); m_TransformView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_TransformView->OnInitialUpdate(); m_TransformView->ShowWindow(SW_HIDE); m_BoxCollisionView = new BoxCollisionView(); m_BoxCollisionView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_BoxCollisionView->OnInitialUpdate(); m_BoxCollisionView->ShowWindow(SW_HIDE); m_SphereCollisionView = new SphereCollisionView(); m_SphereCollisionView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_SphereCollisionView->OnInitialUpdate(); m_SphereCollisionView->ShowWindow(SW_HIDE); m_CapsuleCollisionView = new CapsuleCollisionView(); m_CapsuleCollisionView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_CapsuleCollisionView->OnInitialUpdate(); m_CapsuleCollisionView->ShowWindow(SW_HIDE); m_CameraView = new CameraView(); m_CameraView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_CameraView->OnInitialUpdate(); m_CameraView->ShowWindow(SW_HIDE); m_RigidbodyView = new RigidbodyView(); m_RigidbodyView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_RigidbodyView->OnInitialUpdate(); m_RigidbodyView->ShowWindow(SW_HIDE); m_AudioListenerView = new AudioListenerView(); m_AudioListenerView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_AudioListenerView->OnInitialUpdate(); m_AudioListenerView->ShowWindow(SW_HIDE); m_AudioSourceView = new AudioSourceView(); m_AudioSourceView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_AudioSourceView->OnInitialUpdate(); m_AudioSourceView->ShowWindow(SW_HIDE); m_ScriptView = new ScriptView(); m_ScriptView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_ScriptView->OnInitialUpdate(); m_ScriptView->ShowWindow(SW_HIDE); m_LightView = new LIghtView(); m_LightView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_LightView->OnInitialUpdate(); m_LightView->ShowWindow(SW_HIDE); m_MeshFilterView = new MeshFilterView(); m_MeshFilterView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_MeshFilterView->OnInitialUpdate(); m_MeshFilterView->ShowWindow(SW_HIDE); m_MeshRendererView = new MeshRendererView(); m_MeshRendererView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_MeshRendererView->OnInitialUpdate(); m_MeshRendererView->ShowWindow(SW_HIDE); m_SkinnedMeshRendererView = new SkinnedMeshRendererView(); m_SkinnedMeshRendererView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_SkinnedMeshRendererView->OnInitialUpdate(); m_SkinnedMeshRendererView->ShowWindow(SW_HIDE); m_AnimationView = new AnimationView(); m_AnimationView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_AnimationView->OnInitialUpdate(); m_AnimationView->ShowWindow(SW_HIDE); m_UIImageView = new UIImageView(); m_UIImageView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_UIImageView->OnInitialUpdate(); m_UIImageView->ShowWindow(SW_HIDE); m_UITextView = new UITextView(); m_UITextView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_UITextView->OnInitialUpdate(); m_UITextView->ShowWindow(SW_HIDE); m_UIButtonView = new UIButtonView(); m_UIButtonView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_UIButtonView->OnInitialUpdate(); m_UIButtonView->ShowWindow(SW_HIDE); m_UIInputFieldView = new UIInputFieldView(); m_UIInputFieldView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_UIInputFieldView->OnInitialUpdate(); m_UIInputFieldView->ShowWindow(SW_HIDE); m_SceneInfoView = new SceneInfoView(); m_SceneInfoView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_SceneInfoView->OnInitialUpdate(); m_SceneInfoView->ShowWindow(SW_HIDE); m_NavInfoView = new NavInfoView(); m_NavInfoView->Create(NULL, NULL, WS_CHILD, _rect, this, IDD_HOSEditor_DIALOG, &context); m_NavInfoView->OnInitialUpdate(); m_NavInfoView->ShowWindow(SW_HIDE); SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); return TRUE; // 포커스를 컨트롤에 설정하지 않으면 TRUE를 반환합니다. } void ChosEditorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 대화 상자에 최소화 단추를 추가할 경우 아이콘을 그리려면 // 아래 코드가 필요합니다. 문서/뷰 모델을 사용하는 MFC 애플리케이션의 경우에는 // 프레임워크에서 이 작업을 자동으로 수행합니다. void ChosEditorDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다. SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 클라이언트 사각형에서 아이콘을 가운데에 맞춥니다. int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 아이콘을 그립니다. dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // 사용자가 최소화된 창을 끄는 동안에 커서가 표시되도록 시스템에서 // 이 함수를 호출합니다. HCURSOR ChosEditorDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void ChosEditorDlg::ResetComponentList(CString* gameObject) { while (ComponentList.GetCount() != 0) { ComponentList.DeleteString(0); } if (gameObject) { hos::com::GameObject* obj = EditorManager::GetIns()->GetNowScene()->FindGameObjectWithName(T2W(gameObject->GetBuffer())); if (obj) { int _ComponentCount = obj->GetComponents().size(); for (int i = 0; i < _ComponentCount; i++) { ComponentList.AddString(obj->GetComponents()[i]->GetName().c_str()); } } } } void ChosEditorDlg::HideAllComponentView() { m_TransformView->ShowWindow(SW_HIDE); m_BoxCollisionView->ShowWindow(SW_HIDE); m_SphereCollisionView->ShowWindow(SW_HIDE); m_CapsuleCollisionView->ShowWindow(SW_HIDE); m_CameraView->ShowWindow(SW_HIDE); m_RigidbodyView->ShowWindow(SW_HIDE); m_AudioListenerView->ShowWindow(SW_HIDE); m_AudioSourceView->ShowWindow(SW_HIDE); m_ScriptView->ShowWindow(SW_HIDE); m_LightView->ShowWindow(SW_HIDE); m_MeshFilterView->ShowWindow(SW_HIDE); m_MeshRendererView->ShowWindow(SW_HIDE); m_SkinnedMeshRendererView->ShowWindow(SW_HIDE); m_AnimationView->ShowWindow(SW_HIDE); m_UIImageView->ShowWindow(SW_HIDE); m_UITextView->ShowWindow(SW_HIDE); m_UIButtonView->ShowWindow(SW_HIDE); m_UIInputFieldView->ShowWindow(SW_HIDE); m_SceneInfoView->ShowWindow(SW_HIDE); m_NavInfoView->ShowWindow(SW_HIDE); } void ChosEditorDlg::ResetAllComponentView() { m_TransformView->ResetTransformView(); m_BoxCollisionView->ResetBoxCollisionView(); m_SphereCollisionView->ResetSphereCollisionView(); m_CapsuleCollisionView->ResetCapsuleCollisionView(); m_CameraView->ResetCameraView(); m_RigidbodyView->ResetRigidbodyView(); m_AudioListenerView->ResetAudioListenerView(); m_AudioSourceView->ResetAudioSourceView(); m_ScriptView->ResetScriptView(); m_LightView->ResetLightView(); m_MeshFilterView->ResetMeshFilterView(); m_MeshRendererView->ResetMeshRendererView(); m_SkinnedMeshRendererView->ResetSkinnedMeshRendererView(); m_AnimationView->ResetAnimationView(); m_UIImageView->ResetUIImageView(); m_UITextView->ResetUITextView(); m_UIButtonView->ResetUIButtonView(); m_UIInputFieldView->ResetUIInputFieldView(); m_SceneInfoView->ResetSceneInfoView(); m_NavInfoView->ResetNavInfoView(); } void ChosEditorDlg::UpdateGameObjectHierarchy() { // 기존 계층구조 삭제 GameObjectHierachy.DeleteAllItems(); // 현재 씬의 오브젝트 계층구조를 가져와서 갱신시키기 for (int i = 0; i < EditorManager::GetIns()->GetNowScene()->GetRoots().size(); i++) { // 루트 오브젝트 가져오기 hos::com::GameObject* _GameObject = EditorManager::GetIns()->GetNowScene()->GetRoots()[i]; // 루트 오브젝트 이름 계층구조에 넣기 HTREEITEM _TreeItem = GameObjectHierachy.InsertItem(_GameObject->GetName().c_str());; // 자식 오브젝트 있는지 확인 후 계층구조에 추가 (반복) MakeGameObjectHierarchy(_GameObject, &_TreeItem); } HideAllComponentView(); ResetComponentList(nullptr); hos::com::GameObject* _ObjectTemp = nullptr; EditorManager::GetIns()->SetNowGameObject(_ObjectTemp); } void ChosEditorDlg::MakeGameObjectHierarchy(hos::com::GameObject* gameObject, HTREEITEM* treeItem) { int _ChildGameObjectCount = gameObject->GetComponent<hos::com::Transform>()->GetChildCount(); if (_ChildGameObjectCount > 0) { for (int i = 0; i < _ChildGameObjectCount; i++) { hos::com::GameObject* _GameObject = gameObject->GetComponent<hos::com::Transform>()->GetChilds()[i]->m_GameObject; HTREEITEM _TreeItem = GameObjectHierachy.InsertItem(_GameObject->GetName().c_str(), *treeItem); MakeGameObjectHierarchy(_GameObject, &_TreeItem); } } } void ChosEditorDlg::OnBnClickedButtonCreateGameObject() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. HideAllComponentView(); //ResetAllComponentView(); HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); CString _temp; if (_TreeItem) { // 하위에 오브젝트 생성 CString _ParentName = GameObjectHierachy.GetItemText(_TreeItem); _temp = EditorManager::GetIns()->CreateGameObject(&_ParentName); GameObjectHierachy.InsertItem(_temp, _TreeItem); } else { // 루트 오브젝트 생성 _temp = EditorManager::GetIns()->CreateGameObject(); //GameObjectHierachy.InsertItem(_temp, nullptr, nullptr); GameObjectHierachy.InsertItem(_temp); } // 선택 해제 GameObjectHierachy.SelectItem(nullptr); Invalidate(TRUE); } void ChosEditorDlg::OnBnClickedButtonChangeGameObjectName() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. int _StringCount = GameObjectName.GetWindowTextLengthW(); if (_StringCount <= 0) { return; } CString _ChangedName; GameObjectName.GetWindowTextW(_ChangedName); if (_ChangedName.GetLength() > 0) { HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); if (_TreeItem != nullptr) { CString _temp = GameObjectHierachy.GetItemText(_TreeItem); _ChangedName = EditorManager::GetIns()->ChangeGameObjectName(&_temp, &_ChangedName); GameObjectHierachy.SetItemText(_TreeItem, _ChangedName); GameObjectHierachy.SelectItem(nullptr); Invalidate(TRUE); } } } void ChosEditorDlg::OnClose() { // TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다. EditorManager::GetIns()->Finalize(); EditorManager::GetIns()->Destory(); delete m_SceneView; m_SceneView = nullptr; delete m_TransformView; delete m_BoxCollisionView; delete m_SphereCollisionView; delete m_CapsuleCollisionView; delete m_CameraView; delete m_RigidbodyView; delete m_AudioListenerView; delete m_AudioSourceView; delete m_ScriptView; delete m_LightView; delete m_MeshFilterView; delete m_MeshRendererView; delete m_SkinnedMeshRendererView; delete m_AnimationView; delete m_UIImageView; delete m_UIButtonView; delete m_UIInputFieldView; delete m_SceneInfoView; delete m_NavInfoView; CDialogEx::OnClose(); } void ChosEditorDlg::OnTvnSelchangedTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. *pResult = 0; // 현재 선택한 GameObject Hierarchy Node 가져오기 CString _temp = GameObjectHierachy.GetItemText(pNMTreeView->itemNew.hItem); GameObjectName.SetWindowTextW(_temp); ResetComponentList(nullptr); HideAllComponentView(); hos::com::GameObject* _ObjectTemp = nullptr; EditorManager::GetIns()->SetNowGameObject(_ObjectTemp); if (_temp.GetLength() > 0) { // 컴포넌트 리스트 초기화 // 선택한 오브젝트의 컴포넌트들을 가져와야 함 ResetComponentList(&_temp); EditorManager::GetIns()->SetNowGameObject(&_temp); } ComponentList.SetCurSel(0); OnLbnSelchangeListComponentList(); /// 테스트 해봄 //SHGetSpecialFolderLocation(NULL, CSIDL_DESKTOP) //CFileFind finder; //bool IsFind = finder.FindFile(L"..\\Resource"); //IsFind = finder.FindNextFileW(); //CString temp = finder.GetFileTitle(); //temp = finder.GetFilePath(); //temp = finder.GetFileName(); Invalidate(TRUE); } void ChosEditorDlg::OnBnClickedButtonRemoveGameObject() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. ResetComponentList(nullptr); HideAllComponentView(); HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); CString _temp = GameObjectHierachy.GetItemText(_TreeItem); if (_TreeItem) { EditorManager::GetIns()->RemoveGameObject(&_temp); GameObjectHierachy.DeleteItem(_TreeItem); GameObjectHierachy.SelectItem(nullptr); Invalidate(TRUE); } } void ChosEditorDlg::OnNMRClickTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. *pResult = 0; ResetComponentList(nullptr); GameObjectHierachy.SelectItem(nullptr); hos::com::GameObject* _temp = nullptr; EditorManager::GetIns()->SetNowGameObject(_temp); HideAllComponentView(); ResetAllComponentView(); Invalidate(TRUE); } void ChosEditorDlg::OnBnClickedButtonAddComponent() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. // 선택한 오브젝트와 추가를 하고싶은 컴포넌트를 보내자 HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); CString _SelectedGameObject = GameObjectHierachy.GetItemText(_TreeItem); CString _ComponentName; ComponentSelectList.GetLBText(ComponentSelectList.GetCurSel(), _ComponentName); if (_SelectedGameObject.GetLength() > 0 && _ComponentName.GetLength() > 0) { EditorManager::GetIns()->AddComponent(&_SelectedGameObject, &_ComponentName, ComponentList.GetCount()); // 컴포넌트 리스트 초기화 후 갱신 ResetComponentList(&_SelectedGameObject); } } void ChosEditorDlg::OnBnClickedButtonRemoveComponent() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. // Transform은 제거 안 됨 HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); CString _SelectedGameObject = GameObjectHierachy.GetItemText(_TreeItem); CString _ComponentName; ComponentList.GetText(ComponentList.GetCurSel(), _ComponentName); if (_SelectedGameObject.GetLength() > 0 && _ComponentName.GetLength() > 0) { EditorManager::GetIns()->RemoveComponent(&_SelectedGameObject, &_ComponentName, ComponentList.GetCurSel()); // 컴포넌트 리스트 초기화 후 갱신 ResetComponentList(&_SelectedGameObject); HideAllComponentView(); } } void ChosEditorDlg::OnLbnSelchangeListComponentList() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. // 선택한 것이 있으면 띄우자 HideAllComponentView(); ////////////////////////////////////////////////////////////////////////// /// 해당하는 컴포넌트마다 띄울게 다르다.. CString _ComponentName; if (ComponentList.GetCurSel() >= 0) { ComponentList.GetText(ComponentList.GetCurSel(), _ComponentName); } if (_ComponentName.Collate(L"Transform") == 0) { m_TransformView->SetTransformView(); m_TransformView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"BoxCollision") == 0) { m_BoxCollisionView->SetBoxCollisionView(); m_BoxCollisionView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"SphereCollision") == 0) { m_SphereCollisionView->SetSphereCollisionView(); m_SphereCollisionView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"CapsuleCollision") == 0) { m_CapsuleCollisionView->SetCapsuleCollisionView(); m_CapsuleCollisionView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"Rigidbody") == 0) { m_RigidbodyView->SetRigidbodyView(); m_RigidbodyView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"Camera") == 0) { m_CameraView->SetCameraView(); m_CameraView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"AudioListener") == 0) { m_AudioListenerView->SetAudioListenerView(); m_AudioListenerView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"AudioSource") == 0) { m_AudioSourceView->SetAudioSourceView(); m_AudioSourceView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"Script") == 0) { m_ScriptView->SetScriptView(ComponentList.GetCurSel()); m_ScriptView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"Light") == 0) { m_LightView->SetLightView(); m_LightView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"MeshFilter") == 0) { m_MeshFilterView->SetMeshFilterView(); m_MeshFilterView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"MeshRenderer") == 0) { m_MeshRendererView->SetMeshRendererView(); m_MeshRendererView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"SkinnedMeshRenderer") == 0) { m_SkinnedMeshRendererView->SetSkinnedMeshRendererView(); m_SkinnedMeshRendererView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"Animation") == 0) { m_AnimationView->SetAnimationView(); m_AnimationView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"UIImage") == 0) { m_UIImageView->SetUIImageView(); m_UIImageView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"UIText") == 0) { m_UITextView->SetUITextView(); m_UITextView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"UIButton") == 0) { m_UIButtonView->SetUIButtonView(); m_UIButtonView->ShowWindow(SW_SHOW); } else if (_ComponentName.Collate(L"UIInputField") == 0) { m_UIInputFieldView->SetUIInputFieldView(); m_UIInputFieldView->ShowWindow(SW_SHOW); } else { HideAllComponentView(); } } void ChosEditorDlg::OnEnChangeEditSceneName() { // TODO: RICHEDIT 컨트롤인 경우, 이 컨트롤은 // CDialogEx::OnInitDialog() 함수를 재지정 //하고 마스크에 OR 연산하여 설정된 ENM_CHANGE 플래그를 지정하여 CRichEditCtrl().SetEventMask()를 호출하지 않으면 // 이 알림 메시지를 보내지 않습니다. // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. int _Length = EditSceneName.GetWindowTextLengthW(); if (_Length > 0) { CString _tempString; EditSceneName.GetWindowTextW(_tempString); EditorManager::GetIns()->GetNowScene()->SetName(T2W(_tempString.GetBuffer())); } } void ChosEditorDlg::OnBnClickedButtonSceneSave() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. //static TCHAR BASED_CODE szFilter[] = _T("*.*||");// 모든파일(*.*) | *.* || "); // 경로 불러오기 CFileDialog _PathDialog(false, L"", L"저장 할 위치나 씬 선택", OFN_HIDEREADONLY); if (IDOK == _PathDialog.DoModal()) { CString _Path = _PathDialog.GetPathName(); CString _File = _PathDialog.GetFileName(); // 씬이 있다면 int _ScenesInPath = _Path.Find(L"Scenes"); int _AssetsInPath = _Path.Find(L"Assets"); if (_AssetsInPath > 0 && _ScenesInPath > 0) { if (_AssetsInPath < _ScenesInPath) { CString _Assets; _Assets = _Path.Left(_AssetsInPath); _Assets.Append(L"Assets"); _Path = _Assets; } } else { // 끝에 씬 이름 빼기 _Path.TrimRight(_File); _Path.TrimRight(L"\\"); } ////////////////////////////////////////////////////////////////////////// // Assets 폴더에 생성하는지 확인하기 // Assets 폴더가 아니라면 해당 경로에 Assets 폴더 생성 hos::string _FindAssets; hos::string _IsAssets; _FindAssets = T2W(_Path.GetBuffer()); _IsAssets = _FindAssets.substr(_FindAssets.find_last_of(L"\\") + 1); if (_IsAssets.compare(L"Assets") == 0) { _Path.Append(L"\\"); } else { _Path.Append(L"\\Assets\\"); CreateDirectory(_Path, nullptr); } ////////////////////////////////////////////////////////////////////////// // 매니저에 경로를 보낸다. EditorManager::GetIns()->SaveScene(&_Path); // 데이터 매니저 내부의 데이터들을 해당 폴더에 저장하기 EditorManager::GetIns()->SaveDataManager(&_Path); MessageBox(L"Save Complete!!!", L"Save", MB_OK); } } void ChosEditorDlg::OnBnClickedButtonSceneLoad() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. static TCHAR BASED_CODE szFilter[] = _T("*.scene, *.scene | *.scene; *.scene |");// 모든파일(*.*) | *.* || "); // 경로 불러오기 CFileDialog _PathDialog(true, L"*.scene", L"", OFN_HIDEREADONLY, szFilter); if (IDOK == _PathDialog.DoModal()) { CString _Path = _PathDialog.GetPathName(); // 매니저에 경로를 보낸다. bool b = EditorManager::GetIns()->LoadScene(&_Path); if (b) { // 씬 이름 변경하기 EditSceneName.SetWindowTextW(EditorManager::GetIns()->GetNowScene()->GetName().c_str()); // Object Hierarchy 갱신해야 함.. 얽 UpdateGameObjectHierarchy(); } } } void ChosEditorDlg::OnBnClickedButtonGameObjectSave() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. // 프리팹을 저장한다. // 오브젝트 계층구조에서 선택된 오브젝트가 있는가 if (GameObjectHierachy.GetSelectedItem()) { // 경로 가져와서 저장하기 static TCHAR BASED_CODE szFilter[] = _T("*.prefab, *.Prefab | *.prefab; *.Prefab |");// 모든파일(*.*) | *.* || "); // 경로 불러오기 CFileDialog _PathDialog(false, L"*.prefab", L"이 이름으로 저장 안 됨", OFN_HIDEREADONLY, szFilter); if (IDOK == _PathDialog.DoModal()) { CString _Path = _PathDialog.GetPathName(); CString _File = _PathDialog.GetFileName(); // 끝에 오브젝트 이름 빼기 _Path.TrimRight(_File); HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); CString _temp; _temp = GameObjectHierachy.GetItemText(_TreeItem); // 경로와 오브젝트의 이름을 보낸다. EditorManager::GetIns()->SavePrefab(&_Path, &_temp); } } } void ChosEditorDlg::OnBnClickedButtonGameObjectLoad() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. static TCHAR BASED_CODE szFilter[] = _T("*.prefab, *.Prefab | *.prefab; *.Prefab |");// 모든파일(*.*) | *.* || "); // 경로 불러오기 CFileDialog _PathDialog(true, L"*.prefab", L"", OFN_HIDEREADONLY, szFilter); if (IDOK == _PathDialog.DoModal()) { CString _Path = _PathDialog.GetPathName(); bool b; // 오브젝트 계층구조에서 선택된 오브젝트가 있는다. if (GameObjectHierachy.GetSelectedItem()) { HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); CString _temp; _temp = GameObjectHierachy.GetItemText(_TreeItem); b = EditorManager::GetIns()->LoadPrefab(&_Path, &_temp); } else { // 없으면 루트 오브젝트로 넣는다. b = EditorManager::GetIns()->LoadPrefab(&_Path, nullptr); } if (b) { // Object Hierarchy 갱신해야 함.. 얽 UpdateGameObjectHierarchy(); } } } void ChosEditorDlg::OnTvnBegindragTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. *pResult = 0; } void ChosEditorDlg::OnBnClickedButtonAddGameData() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. //static TCHAR BASED_CODE szFilter[] = _T("*.prefab, *.Prefab | *.prefab; *.Prefab |");// 모든파일(*.*) | *.* || "); // 경로 불러오기 CFileDialog _PathDialog(true, L"", L"", OFN_HIDEREADONLY); if (IDOK == _PathDialog.DoModal()) { CString _Path = _PathDialog.GetPathName(); EditorManager::GetIns()->LoadGameData(&_Path); UpdateGameObjectHierarchy(); // 프리팹 리스트를 업데이트 한다. while (ListPrefabList.GetCount() != 0) { ListPrefabList.DeleteString(0); } for (auto [name, data] : EditorManager::GetIns()->GetDataManager()->Prefabs) { ListPrefabList.AddString(name.c_str()); } } } void ChosEditorDlg::OnBnClickedButtonLoadGameData() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. // 선택한 프리팹을 오브젝트 하이어라키에 불러오자 CString _PrefabName; ListPrefabList.GetText(ListPrefabList.GetCurSel(), _PrefabName); // 오브젝트 하이어라키에서 선택한 오브젝트가 있는 경우 HideAllComponentView(); ResetComponentList(nullptr); HTREEITEM _TreeItem = GameObjectHierachy.GetSelectedItem(); CString _temp; if (_TreeItem) { // 하위에 오브젝트 생성 CString _ParentName = GameObjectHierachy.GetItemText(_TreeItem); _temp = EditorManager::GetIns()->AddPrefab(&_PrefabName, &_ParentName); GameObjectHierachy.InsertItem(_temp, _TreeItem); } else { // 루트 오브젝트 생성 _temp = EditorManager::GetIns()->AddPrefab(&_PrefabName); GameObjectHierachy.InsertItem(_temp); } // 선택 해제 GameObjectHierachy.SelectItem(nullptr); UpdateGameObjectHierarchy(); Invalidate(TRUE); } BOOL ChosEditorDlg::PreTranslateMessage(MSG* pMsg) { // TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다. if (pMsg->message == WM_KEYDOWN) { if (pMsg->wParam == VK_RETURN) // ENTER키 눌릴 시 return TRUE; else if (pMsg->wParam == VK_ESCAPE) // ESC키 눌릴 시 return TRUE; } return CDialogEx::PreTranslateMessage(pMsg); } void ChosEditorDlg::ExpandAll(HTREEITEM hUserRoot) { if (GameObjectHierachy.ItemHasChildren(hUserRoot)) { // 확장 GameObjectHierachy.Expand(hUserRoot, TVE_EXPAND); // 자식 노드 확인 hUserRoot = GameObjectHierachy.GetChildItem(hUserRoot); if (hUserRoot) { do { // 재귀로 하위 확인 ExpandAll(hUserRoot); } while ((hUserRoot = GameObjectHierachy.GetNextSiblingItem(hUserRoot)) != NULL); } } } void ChosEditorDlg::CollapseAll(HTREEITEM hUserRoot) { if (GameObjectHierachy.ItemHasChildren(hUserRoot)) { // 확장 GameObjectHierachy.Expand(hUserRoot, TVE_COLLAPSE); // 자식 노드 확인 hUserRoot = GameObjectHierachy.GetChildItem(hUserRoot); if (hUserRoot) { do { // 재귀로 하위 확인 ExpandAll(hUserRoot); } while ((hUserRoot = GameObjectHierachy.GetNextSiblingItem(hUserRoot)) != NULL); } } } void ChosEditorDlg::OnNMDblclkTreeGameObjectHierarchy(NMHDR* pNMHDR, LRESULT* pResult) { HTREEITEM hSelectItem = GameObjectHierachy.GetSelectedItem(); static bool bClose = true; if (bClose) { ExpandAll(hSelectItem); } else { CollapseAll(hSelectItem); } bClose = !bClose; *pResult = 1; } void ChosEditorDlg::OnBnClickedButtonSceneInfo() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. HideAllComponentView(); m_SceneInfoView->SetSceneInfoView(); m_SceneInfoView->ShowWindow(SW_SHOW); } void ChosEditorDlg::OnBnClickedButtonNavInfo() { // TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. HideAllComponentView(); m_NavInfoView->SetNavInfoView(); m_NavInfoView->ShowWindow(SW_SHOW); }
26.619765
123
0.745532
Game-institute-1st-While-true
0c12971dc38865e8bb095a745228a17b25f99525
75,153
cpp
C++
src/WndResizer/WndResizer.cpp
AbsCoDes-lib/WndCommons
5af3ce02ad0396617299496cab60673e36a0e653
[ "Apache-2.0" ]
null
null
null
src/WndResizer/WndResizer.cpp
AbsCoDes-lib/WndCommons
5af3ce02ad0396617299496cab60673e36a0e653
[ "Apache-2.0" ]
null
null
null
src/WndResizer/WndResizer.cpp
AbsCoDes-lib/WndCommons
5af3ce02ad0396617299496cab60673e36a0e653
[ "Apache-2.0" ]
null
null
null
/* DISCLAIMER Auther: Mizan Rahman Original publication location: http://www.codeproject.com/KB/dialog/WndResizer.aspx This work is provided under the terms and condition described in The Code Project Open License (CPOL) (http://www.codeproject.com/info/cpol10.aspx) This disclaimer should not be removed and should exist in any reproduction of this work. */ #pragma comment(lib, "uxtheme") #include "stdafx.h" #include "WndResizer/WndResizer.h" namespace abscodes { namespace wndcommons { static CMap<HWND, HWND, CWndResizer*, CWndResizer*> WndResizerData; // ensures that all windows have been unhooked correctly upon process exit struct VerifyUnHooking { ~VerifyUnHooking() { ASSERT(WndResizerData.IsEmpty()); } }; static VerifyUnHooking s_verifyUnHooking; ///////////////////////////// CWndResizer /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CWndResizer(void) { m_pHookedWnd = NULL; m_pfnWndProc = NULL; m_root.Name = _T("_root"); m_pCaptured = NULL; m_hOldCursor = NULL; m_splitterOffset = 0; m_bAutoHandlePaint = TRUE; } CWndResizer::~CWndResizer(void) {} BOOL CWndResizer::GetAutoHandlePaint() { return m_bAutoHandlePaint; } BOOL CWndResizer::SetAutoHandlePaint(BOOL bHandle) { m_bAutoHandlePaint = bHandle; return TRUE; } void CWndResizer::GetTrueClientRect(CWnd* pWnd, CRect* prc) { int nMin = 0; int nMax = 0; int nCur = 0; pWnd->GetClientRect(prc); if((pWnd->GetStyle() & WS_HSCROLL) > 0) { pWnd->GetScrollRange(SB_HORZ, &nMin, &nMax); nCur = pWnd->GetScrollPos(SB_HORZ); prc->right = prc->left + nMax; prc->OffsetRect(-nCur, 0); } if((pWnd->GetStyle() & WS_VSCROLL) > 0) { pWnd->GetScrollRange(SB_VERT, &nMin, &nMax); nCur = pWnd->GetScrollPos(SB_VERT); prc->bottom = prc->top + nMax; prc->OffsetRect(0, -nCur); } } void CWndResizer::EnsureRootMinMax() { if(m_root.Width() < m_root.MinSize.cx) { m_root.right = m_root.left + m_root.MinSize.cx; } if(m_root.Width() > m_root.MaxSize.cx) { m_root.right = m_root.left + m_root.MaxSize.cx; } if(m_root.Height() < m_root.MinSize.cy) { m_root.bottom = m_root.top + m_root.MinSize.cy; } if(m_root.Height() > m_root.MaxSize.cy) { m_root.bottom = m_root.top + m_root.MaxSize.cy; } } void CWndResizer::OnSize(UINT nType, int cx, int cy) { GetTrueClientRect(m_pHookedWnd, &m_root); EnsureRootMinMax(); m_root.OnResized(); ResizeUI(&m_root); } void CWndResizer::OnScroll() { GetTrueClientRect(m_pHookedWnd, &m_root); EnsureRootMinMax(); m_root.OnResized(); ResizeUI(&m_root); } BOOL CWndResizer::Hook(CWnd* pParent) { ASSERT(m_pHookedWnd == NULL); m_pHookedWnd = pParent; GetTrueClientRect(m_pHookedWnd, &m_root); m_root.m_pHookWnd = m_pHookedWnd; // create the resize gripper panel CRect rcResziGrip(&m_root); int cx = ::GetSystemMetrics(SM_CXHSCROLL); int cy = ::GetSystemMetrics(SM_CYVSCROLL); rcResziGrip.DeflateRect(m_root.Width() - cx, m_root.Height() - cy, 0, 0); CGripperPanel* pResizeGripper = new CGripperPanel(&rcResziGrip); pResizeGripper->SetAnchor(ANCHOR_RIGHT | ANCHOR_BOTTOM); pResizeGripper->Name = _T("_resizeGrip"); m_root.AddChild(pResizeGripper); WndResizerData.SetAt(m_pHookedWnd->m_hWnd, this); m_pfnWndProc = (WNDPROC)::SetWindowLongPtr(m_pHookedWnd->m_hWnd, GWLP_WNDPROC, (LONG_PTR)WindowProc); return TRUE; } BOOL CWndResizer::Hook(CWnd* pParent, CSize& size) { ASSERT(m_pHookedWnd == NULL); m_pHookedWnd = pParent; GetTrueClientRect(m_pHookedWnd, &m_root); m_root.right = m_root.left + size.cx; m_root.bottom = m_root.top + size.cy; m_root.m_pHookWnd = m_pHookedWnd; // create the resize gripper panel CRect rcResziGrip(&m_root); int cx = ::GetSystemMetrics(SM_CXHSCROLL); int cy = ::GetSystemMetrics(SM_CYVSCROLL); rcResziGrip.DeflateRect(m_root.Width() - cx, m_root.Height() - cy, 0, 0); CGripperPanel* pResizeGripper = new CGripperPanel(&rcResziGrip); pResizeGripper->SetAnchor(ANCHOR_RIGHT | ANCHOR_BOTTOM); pResizeGripper->Name = _T("_resizeGrip"); m_root.AddChild(pResizeGripper); WndResizerData.SetAt(m_pHookedWnd->m_hWnd, this); m_pfnWndProc = (WNDPROC)::SetWindowLongPtr(m_pHookedWnd->m_hWnd, GWLP_WNDPROC, (LONG_PTR)WindowProc); return TRUE; } BOOL CWndResizer::Draw(CPaintDC* pDC) { CPanelList panelList; GetVisualPanels(&m_root, &panelList); POSITION pos = panelList.GetHeadPosition(); while(pos != NULL) { CVisualPanel* pPanel = (CVisualPanel*)panelList.GetNext(pos); if(pPanel->m_bVisible) { pPanel->Draw(pDC); } } return TRUE; } void CWndResizer::ResizeUI(CWndResizer::CPanel* pRoot) { CPanelList panels; GetUIPanels(pRoot, &panels, FALSE); POSITION pos = NULL; if(panels.GetCount() > 0) { HDWP hDWP = ::BeginDeferWindowPos((int)panels.GetCount()); ASSERT(hDWP != NULL); pos = panels.GetHeadPosition(); while(pos != NULL) { CUIPanel* pPanel = (CUIPanel*)panels.GetNext(pos); ::DeferWindowPos(hDWP, m_pHookedWnd->GetDlgItem(pPanel->m_uID)->m_hWnd, NULL, pPanel->left, pPanel->top, pPanel->Width(), pPanel->Height(), SWP_NOACTIVATE | SWP_NOZORDER); } BOOL bOk = ::EndDeferWindowPos(hDWP); ASSERT(bOk); m_pHookedWnd->InvalidateRect(pRoot, FALSE); } panels.RemoveAll(); GetUIPanels(pRoot, &panels, TRUE); pos = panels.GetHeadPosition(); while(pos != NULL) { CUIPanel* pPanel = (CUIPanel*)panels.GetNext(pos); m_pHookedWnd->GetDlgItem(pPanel->m_uID)->MoveWindow(pPanel); } } void CWndResizer::OnLButtonDown(UINT nFlags, CPoint point) { UpdateSplitterOffset(point); } void CWndResizer::OnMouseMove(UINT nFlags, CPoint point) { if(m_pCaptured != NULL) { if((nFlags & MK_LBUTTON) <= 0) { CPoint ptScreen = point; m_pHookedWnd->ClientToScreen(&ptScreen); HWND hWndFromPoint = ::WindowFromPoint(ptScreen); if(m_pCaptured->PtInRect(point) == FALSE || hWndFromPoint != m_pHookedWnd->m_hWnd) { ::ReleaseCapture(); m_pCaptured = NULL; ASSERT(m_hOldCursor != NULL); HCURSOR hCur = ::SetCursor(m_hOldCursor); ::DestroyCursor(hCur); m_hOldCursor = NULL; } } } if(m_pCaptured == NULL && nFlags == 0) { m_pCaptured = FindSplitterFromPoint(&m_root, point); if(m_pCaptured != NULL) { m_pHookedWnd->SetCapture(); LPCTSTR cursor = NULL; CSplitContainer* pSplitContainer = (CSplitContainer*)m_pCaptured->Parent; if(pSplitContainer->m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { cursor = IDC_SIZEWE; } else { cursor = IDC_SIZENS; } HCURSOR hCur = AfxGetApp()->LoadStandardCursor(cursor); m_hOldCursor = ::SetCursor(hCur); } } if(m_pCaptured != NULL && (nFlags & MK_LBUTTON) > 0) { CSplitContainer* pSplitterContainer = (CSplitContainer*)m_pCaptured->Parent; int nCurSplitterPos = pSplitterContainer->GetSplitterPosition(); if(pSplitterContainer->m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { pSplitterContainer->SetSplitterPosition(point.x - m_splitterOffset); } else { pSplitterContainer->SetSplitterPosition(point.y - m_splitterOffset); } UpdateSplitterOffset(point); if(nCurSplitterPos != pSplitterContainer->GetSplitterPosition()) { ResizeUI(pSplitterContainer); } } } void CWndResizer::OnLButtonUp(UINT nFlags, CPoint point) { OnMouseMove(nFlags, point); } void CWndResizer::UpdateSplitterOffset(CPoint ptCurr) { if(m_pCaptured == NULL) { return; } if(((CSplitContainer*)m_pCaptured->Parent)->m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { if(ptCurr.x < m_pCaptured->left) { m_splitterOffset = 0; } else if(ptCurr.x > m_pCaptured->right) { m_splitterOffset = m_pCaptured->Width(); } else { m_splitterOffset = ptCurr.x - m_pCaptured->left; } } else { if(ptCurr.y < m_pCaptured->top) { m_splitterOffset = 0; } else if(ptCurr.y > m_pCaptured->bottom) { m_splitterOffset = m_pCaptured->Height(); } else { m_splitterOffset = ptCurr.y - m_pCaptured->top; } } } void CWndResizer::OnSizing(UINT fwSide, LPRECT pRect) { CRect* prc = (CRect*)pRect; CRect rcMin(0, 0, m_root.MinSize.cx, m_root.MinSize.cy); CRect rcMax(0, 0, m_root.MaxSize.cx, m_root.MaxSize.cy); LONG_PTR style = GetWindowLongPtr(m_pHookedWnd->m_hWnd, GWL_STYLE); LONG_PTR styleEx = GetWindowLongPtr(m_pHookedWnd->m_hWnd, GWL_EXSTYLE); ::AdjustWindowRectEx(&rcMin, (DWORD)style, (m_pHookedWnd->GetMenu() != NULL), (DWORD)styleEx); ::AdjustWindowRectEx(&rcMax, (DWORD)style, (m_pHookedWnd->GetMenu() != NULL), (DWORD)styleEx); switch(fwSide) { case WMSZ_BOTTOM: if(prc->Height() < rcMin.Height()) { prc->bottom = prc->top + rcMin.Height(); } if(prc->Height() > rcMax.Height()) { prc->bottom = prc->top + rcMax.Height(); } break; case WMSZ_BOTTOMLEFT: if(prc->Height() < rcMin.Height()) { prc->bottom = prc->top + rcMin.Height(); } if(prc->Width() < rcMin.Width()) { prc->left = prc->right - rcMin.Width(); } if(prc->Height() > rcMax.Height()) { prc->bottom = prc->top + rcMax.Height(); } if(prc->Width() > rcMax.Width()) { prc->left = prc->right - rcMax.Width(); } break; case WMSZ_BOTTOMRIGHT: if(prc->Height() < rcMin.Height()) { prc->bottom = prc->top + rcMin.Height(); } if(prc->Width() < rcMin.Width()) { prc->right = prc->left + rcMin.Width(); } if(prc->Height() > rcMax.Height()) { prc->bottom = prc->top + rcMax.Height(); } if(prc->Width() > rcMax.Width()) { prc->right = prc->left + rcMax.Width(); } break; case WMSZ_LEFT: if(prc->Width() < rcMin.Width()) { prc->left = prc->right - rcMin.Width(); } if(prc->Width() > rcMax.Width()) { prc->left = prc->right - rcMax.Width(); } break; case WMSZ_RIGHT: if(prc->Width() < rcMin.Width()) { prc->right = prc->left + rcMin.Width(); } if(prc->Width() > rcMax.Width()) { prc->right = prc->left + rcMax.Width(); } break; case WMSZ_TOP: if(prc->Height() < rcMin.Height()) { prc->top = prc->bottom - rcMin.Height(); } if(prc->Height() > rcMax.Height()) { prc->top = prc->bottom - rcMax.Height(); } break; case WMSZ_TOPLEFT: if(prc->Height() < rcMin.Height()) { prc->top = prc->bottom - rcMin.Height(); } if(prc->Width() < rcMin.Width()) { prc->left = prc->right - rcMin.Width(); } if(prc->Height() > rcMax.Height()) { prc->top = prc->bottom - rcMax.Height(); } if(prc->Width() > rcMax.Width()) { prc->left = prc->right - rcMax.Width(); } break; case WMSZ_TOPRIGHT: if(prc->Height() < rcMin.Height()) { prc->top = prc->bottom - rcMin.Height(); } if(prc->Width() < rcMin.Width()) { prc->right = prc->left + rcMin.Width(); } if(prc->Height() > rcMax.Height()) { prc->top = prc->bottom - rcMax.Height(); } if(prc->Width() > rcMax.Width()) { prc->right = prc->left + rcMax.Width(); } break; } } void CWndResizer::OnPaint() { if(m_pHookedWnd == NULL) { return; } if(!GetAutoHandlePaint()) { return; } CPaintDC dc(m_pHookedWnd); // device context for painting Draw(&dc); } BOOL CWndResizer::SetAnchor(LPCTSTR panelName, UINT uAnchor) { // container must already exist CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } return pPanel->SetAnchor(uAnchor); } BOOL CWndResizer::SetAnchor(UINT uID, UINT uAnchor) { ASSERT(m_pHookedWnd != NULL); CUIPanel* pPanel = GetUIPanel(uID); if(pPanel == NULL) { return FALSE; } pPanel->SetAnchor(uAnchor); return TRUE; } BOOL CWndResizer::GetAnchor(LPCTSTR panelName, UINT& anchor) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) // name of parent must already exist { return FALSE; } anchor = pPanel->Anchor; return TRUE; } BOOL CWndResizer::GetAnchor(UINT uID, UINT& anchor) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) // name of parent must already exist { return FALSE; } anchor = pPanel->Anchor; return TRUE; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CWndResizer::SetDock(LPCTSTR panelName, UINT uDock) { // container must already exist CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } pPanel->Dock = uDock; return TRUE; } BOOL CWndResizer::SetDock(UINT uID, UINT uDock) { ASSERT(m_pHookedWnd != NULL); CUIPanel* pPanel = GetUIPanel(uID); if(pPanel == NULL) { return FALSE; } pPanel->Dock = uDock; return TRUE; } BOOL CWndResizer::GetDock(LPCTSTR panelName, UINT& uDock) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) // name of parent must already exist { return FALSE; } uDock = pPanel->Dock; return TRUE; } BOOL CWndResizer::GetDock(UINT uID, UINT& uDock) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) // name of parent must already exist { return FALSE; } uDock = pPanel->Dock; return TRUE; } ////////////////////// BOOL CWndResizer::SetParent(LPCTSTR panelName, LPCTSTR parentName) { ASSERT(m_pHookedWnd != NULL); // now make sure parentName is OK CPanel* pParent = NULL; if((pParent = FindPanelByName(&m_root, parentName)) == NULL) // name of parent must already exist { return FALSE; } // make sure panelName exist CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } return pParent->AddChild(pPanel); } BOOL CWndResizer::SetParent(UINT uID, LPCTSTR parentName) { ASSERT(m_pHookedWnd != NULL); // now make sure parentName is OK CPanel* pParent = NULL; if((pParent = FindPanelByName(&m_root, parentName)) == NULL) // name of parent must already exist { return FALSE; } // first see if it is already defined CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) { if((pPanel = CreateUIPanel(uID)) == NULL) { return FALSE; } } return pParent->AddChild(pPanel); } BOOL CWndResizer::SetParent(LPCTSTR panelName, UINT uParentID) { ASSERT(m_pHookedWnd != NULL); // now make sure parentName is OK CPanel* pParent = NULL; if((pParent = GetUIPanel(uParentID)) == NULL) // name of parent must already exist { return FALSE; } // make sure panelName exist CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } return pParent->AddChild(pPanel); } BOOL CWndResizer::SetParent(UINT uID, UINT uParentID) { // now make sure parentName is OK CPanel* pParent = NULL; if((pParent = GetUIPanel(uParentID)) == NULL) // name of parent must already exist { return FALSE; } // make sure panelName exist CPanel* pPanel = NULL; if((pPanel = GetUIPanel(uID)) == NULL) { return FALSE; } return pParent->AddChild(pPanel); } BOOL CWndResizer::GetParent(LPCTSTR panelName, CString& parentName) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } parentName = pPanel->Parent->Name; return TRUE; } BOOL CWndResizer::GetParent(UINT uID, CString& parentName) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) // name of parent must already exist { return FALSE; } parentName = pPanel->Parent->Name; return TRUE; } BOOL CWndResizer::SetFixedPanel(LPCTSTR splitContainerName, short panel) { CPanel* pContainer = FindPanelByName(&m_root, splitContainerName); if(pContainer == NULL) { return FALSE; } CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer); if(pSplitContainer == NULL) { return FALSE; } pSplitContainer->SetFixedPanel(panel); return TRUE; } BOOL CWndResizer::GetFixedPanel(LPCTSTR splitContainerName, short& panel) { CPanel* pContainer = FindPanelByName(&m_root, splitContainerName); if(pContainer == NULL) { return FALSE; } CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer); if(pSplitContainer == NULL) { return FALSE; } panel = pSplitContainer->GetFixedPanel(); return TRUE; } BOOL CWndResizer::SetIsSplitterFixed(LPCTSTR splitContainerName, BOOL fixed) { CPanel* pContainer = FindPanelByName(&m_root, splitContainerName); if(pContainer == NULL) { return FALSE; } CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer); if(pSplitContainer == NULL) { return FALSE; } pSplitContainer->SetIsSplitterFixed(fixed); return TRUE; } BOOL CWndResizer::GetIsSplitterFixed(LPCTSTR splitContainerName, BOOL& fixed) { CPanel* pContainer = FindPanelByName(&m_root, splitContainerName); if(pContainer == NULL) { return FALSE; } CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer); if(pSplitContainer == NULL) { return FALSE; } fixed = pSplitContainer->GetIsSplitterFixed(); return TRUE; } BOOL CWndResizer::SetShowSplitterGrip(LPCTSTR splitContainerName, BOOL bShow) { CPanel* pContainer = FindPanelByName(&m_root, splitContainerName); if(pContainer == NULL) { return FALSE; } CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer); if(pSplitContainer == NULL) { return FALSE; } pSplitContainer->SetShowSplitterGrip(bShow); return TRUE; } BOOL CWndResizer::GetShowSplitterGrip(LPCTSTR splitContainerName, BOOL& bShow) { CPanel* pContainer = FindPanelByName(&m_root, splitContainerName); if(pContainer == NULL) { return FALSE; } CSplitContainer* pSplitContainer = dynamic_cast<CSplitContainer*>(pContainer); if(pSplitContainer == NULL) { return FALSE; } bShow = pSplitContainer->GetShowSplitterGrip(); return TRUE; } ///////////////////////// BOOL CWndResizer::SetMinimumSize(LPCTSTR panelName, CSize& size) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } return pPanel->SetMinSize(size); } BOOL CWndResizer::SetMinimumSize(UINT uID, CSize& size) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) { if((pPanel = CreateUIPanel(uID)) == NULL) { return FALSE; } } return pPanel->SetMinSize(size); } BOOL CWndResizer::GetMinimumSize(LPCTSTR panelName, CSize& size) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } size = pPanel->MinSize; return TRUE; } BOOL CWndResizer::GetMinimumSize(UINT uID, CSize& size) { const CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) { return FALSE; } size = pPanel->MinSize; return TRUE; } BOOL CWndResizer::SetMaximumSize(UINT uID, CSize& size) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) { return FALSE; } return pPanel->SetMaxSize(size); } BOOL CWndResizer::SetMaximumSize(LPCTSTR panelName, CSize& size) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } return pPanel->SetMaxSize(size); } BOOL CWndResizer::GetMaximumSize(LPCTSTR panelName, CSize& size) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) == NULL) { return FALSE; } size = pPanel->MaxSize; return TRUE; } BOOL CWndResizer::GetMaximumSize(UINT uID, CSize& size) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, IdToName(uID))) == NULL) { return FALSE; } size = pPanel->MaxSize; return TRUE; } void CWndResizer::SetShowResizeGrip(BOOL show) { CGripperPanel* pPanel = (CGripperPanel*)FindPanelByName(&m_root, _T("_resizeGrip")); ASSERT(pPanel != NULL); if(pPanel->m_bVisible != show) { pPanel->m_bVisible = show; m_pHookedWnd->Invalidate(TRUE); } } BOOL CWndResizer::GetShowResizeGrip() { CGripperPanel* pPanel = (CGripperPanel*)FindPanelByName(&m_root, _T("_resizeGrip")); ASSERT(pPanel != NULL); return pPanel->m_bVisible; } void CWndResizer::OnDestroy() { if(m_pHookedWnd != NULL) { Unhook(); } } BOOL CWndResizer::Unhook() { ASSERT(m_pHookedWnd != NULL); if(m_pHookedWnd == NULL) { return FALSE; // hasent been hooked } WNDPROC pWndProc = (WNDPROC)::SetWindowLongPtr(m_pHookedWnd->m_hWnd, GWLP_WNDPROC, (LONG_PTR)m_pfnWndProc); WndResizerData.RemoveKey(m_pHookedWnd->m_hWnd); m_root.m_pHookWnd = NULL; m_pHookedWnd = NULL; // destroy all chilldren while(m_root.Children.GetCount() > 0) { CPanel* pChild = m_root.Children.RemoveHead(); delete pChild; } return TRUE; } LRESULT CALLBACK CWndResizer::WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CWndResizer* pResizer = NULL; WndResizerData.Lookup(hWnd, pResizer); ASSERT(pResizer != NULL); switch(uMsg) { case WM_SIZE: { int cx = 0; int cy = 0; cx = LOWORD(lParam); cy = HIWORD(lParam); pResizer->OnSize((UINT)wParam, cx, cy); } break; case WM_SIZING: pResizer->OnSizing((UINT)wParam, (LPRECT)lParam); break; case WM_DESTROY: pResizer->OnDestroy(); break; case WM_MOUSEMOVE: pResizer->OnMouseMove((UINT)wParam, CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); break; case WM_LBUTTONDOWN: pResizer->OnLButtonDown((UINT)wParam, CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); break; case WM_LBUTTONUP: pResizer->OnLButtonUp((UINT)wParam, CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); break; case WM_PAINT: pResizer->OnPaint(); break; case WM_HSCROLL: case WM_VSCROLL: pResizer->OnScroll(); break; // case WM_ERASEBKGND: // return FALSE; // break; default: break; } return ::CallWindowProc(pResizer->m_pfnWndProc, hWnd, uMsg, wParam, lParam); } BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, LPCTSTR panelNameA, LPCTSTR panelNameB) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) { return FALSE; } CPanel* pPanelA = NULL; if((pPanelA = FindPanelByName(&m_root, panelNameA)) == NULL) { return FALSE; } CPanel* pPanelB = NULL; if((pPanelB = FindPanelByName(&m_root, panelNameB)) == NULL) { return FALSE; } if(pPanelA == pPanelB) // two panel cannot be same { return FALSE; } CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB); if(pSplitterContainer == NULL) { return FALSE; } pSplitterContainer->Name = panelName; return m_root.AddChild(pSplitterContainer); } BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, LPCTSTR panelNameA, UINT panelIDB) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) { return FALSE; } CPanel* pPanelA = NULL; if((pPanelA = FindPanelByName(&m_root, panelNameA)) == NULL) { return FALSE; } CPanel* pPanelB = GetUIPanel(panelIDB); if(pPanelB == NULL) { return FALSE; } if(pPanelA == pPanelB) // two panel cannot be same { return FALSE; } // first lets make sure the two CRect are properly set CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB); if(pSplitterContainer == NULL) { return FALSE; } pSplitterContainer->Name = panelName; return m_root.AddChild(pSplitterContainer); } BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, UINT panelIDA, LPCTSTR panelNameB) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) { return FALSE; } CPanel* pPanelA = GetUIPanel(panelIDA); if(pPanelA == NULL) { return FALSE; } CPanel* pPanelB = NULL; if((pPanelB = FindPanelByName(&m_root, panelNameB)) == NULL) { return FALSE; } if(pPanelA == pPanelB) // two panel cannot be same { return FALSE; } CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB); if(pSplitterContainer == NULL) { return FALSE; } pSplitterContainer->Name.Append(panelName); return m_root.AddChild(pSplitterContainer); } BOOL CWndResizer::CreateSplitContainer(LPCTSTR panelName, UINT panelIDA, UINT panelIDB) { CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, panelName)) != NULL) { return FALSE; } CPanel* pPanelA = GetUIPanel(panelIDA); if(pPanelA == NULL) { return FALSE; } CPanel* pPanelB = GetUIPanel(panelIDB); if(pPanelB == NULL) { return FALSE; } if(pPanelA == pPanelB) // two panel cannot be same { return FALSE; } CPanel* pSplitterContainer = CSplitContainer::Create(pPanelA, pPanelB); if(pSplitterContainer == NULL) { return FALSE; } pSplitterContainer->Name = panelName; return m_root.AddChild(pSplitterContainer); } BOOL CWndResizer::SetSplitterPosition(LPCTSTR splitContainerName, UINT position) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, splitContainerName)) == NULL) { return FALSE; } CSplitContainer* pContainer = dynamic_cast<CSplitContainer*>(pPanel); if(pContainer == NULL) { return FALSE; } pContainer->SetSplitterPosition((int)position); ResizeUI(pContainer); return TRUE; } BOOL CWndResizer::GetSplitterPosition(LPCTSTR splitContainerName, UINT& position) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, splitContainerName)) == NULL) { return FALSE; } CSplitContainer* pContainer = dynamic_cast<CSplitContainer*>(pPanel); if(pContainer == NULL) { return FALSE; } position = (UINT)pContainer->GetSplitterPosition(); return TRUE; } BOOL CWndResizer::CreatePanel(UINT uID) { ASSERT(m_pHookedWnd != NULL); if(FindPanelByName(&m_root, IdToName(uID)) != NULL) { return FALSE; } CUIPanel* pPanel = GetUIPanel(uID); ASSERT(pPanel != NULL); pPanel->m_bOle = TRUE; return TRUE; } BOOL CWndResizer::SetFlowDirection(LPCTSTR flowPanelName, short direction) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) { return FALSE; } CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel); if(pFlowLayout == NULL) { return FALSE; } pFlowLayout->SetFlowDirection(direction == 1 ? CWndResizer::LEFT_TO_RIGHT : CWndResizer::TOP_TO_BOTTOM); return TRUE; } BOOL CWndResizer::GetFlowDirection(LPCTSTR flowPanelName, short& direction) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) { return FALSE; } CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel); if(pFlowLayout == NULL) { return FALSE; } direction = (pFlowLayout->GetFlowDirection() == CWndResizer::LEFT_TO_RIGHT ? 1 : 2); return TRUE; } BOOL CWndResizer::SetFlowItemSpacingX(LPCTSTR flowPanelName, int nSpacing) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) { return FALSE; } CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel); if(pFlowLayout == NULL) { return FALSE; } pFlowLayout->SetItemSpacingX(nSpacing); return TRUE; } BOOL CWndResizer::GetFlowItemSpacingX(LPCTSTR flowPanelName, int& nSpacing) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) { return FALSE; } CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel); if(pFlowLayout == NULL) { return FALSE; } nSpacing = pFlowLayout->GetItemSpacingX(); return TRUE; } BOOL CWndResizer::SetFlowItemSpacingY(LPCTSTR flowPanelName, int nSpacing) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) { return FALSE; } CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel); if(pFlowLayout == NULL) { return FALSE; } pFlowLayout->SetItemSpacingY(nSpacing); return TRUE; } BOOL CWndResizer::GetFlowItemSpacingY(LPCTSTR flowPanelName, int& nSpacing) { ASSERT(m_pHookedWnd != NULL); CPanel* pPanel = NULL; if((pPanel = FindPanelByName(&m_root, flowPanelName)) == NULL) { return FALSE; } CFlowLayoutPanel* pFlowLayout = dynamic_cast<CFlowLayoutPanel*>(pPanel); if(pFlowLayout == NULL) { return FALSE; } nSpacing = pFlowLayout->GetItemSpacingY(); return TRUE; } BOOL CWndResizer::CreateFlowLayoutPanel(LPCTSTR panelName, const CRect* prcPanel) { if(FindPanelByName(&m_root, panelName) != NULL) { return FALSE; } CPanel* pPanel = new CFlowLayoutPanel(prcPanel); pPanel->Name = panelName; return m_root.AddChild(pPanel); } BOOL CWndResizer::CreateFlowLayoutPanel(LPCTSTR panelName, const CUIntArray* parrID, BOOL setAsChildren) { ASSERT(m_pHookedWnd != NULL); CRect rcFinal(0, 0, 0, 0); for(int i = 0; i < parrID->GetCount(); i++) { CRect rc(0, 0, 0, 0); m_pHookedWnd->GetDlgItem(parrID->GetAt(i))->GetWindowRect(&rc); m_pHookedWnd->ScreenToClient(&rc); rcFinal.UnionRect(&rcFinal, &rc); } BOOL bOk = CreateFlowLayoutPanel(panelName, &rcFinal); if(bOk == FALSE) { return FALSE; } if(setAsChildren) { CPanel* pPanel = FindPanelByName(&m_root, panelName); for(int i = 0; i < parrID->GetCount(); i++) { if(FindPanelByName(&m_root, IdToName(parrID->GetAt(i))) != NULL) { bOk = m_root.RemoveChild(pPanel); ASSERT(bOk); delete pPanel; return FALSE; } CUIPanel* pUIPanel = GetUIPanel(parrID->GetAt(i)); ASSERT(pUIPanel != NULL); bOk = pPanel->AddChild(pUIPanel); ASSERT(bOk); } } return TRUE; } BOOL CWndResizer::CreatePanel(LPCTSTR panelName, const CRect* prcPanel) { if(FindPanelByName(&m_root, panelName) != NULL) { return FALSE; } CPanel* pPanel = new CPanel(prcPanel); pPanel->Name = panelName; return m_root.AddChild(pPanel); } BOOL CWndResizer::CreatePanel(LPCTSTR panelName, const CUIntArray* parrID, BOOL setAsChildren) { ASSERT(m_pHookedWnd != NULL); CRect rcFinal(0, 0, 0, 0); for(int i = 0; i < parrID->GetCount(); i++) { CRect rc(0, 0, 0, 0); m_pHookedWnd->GetDlgItem(parrID->GetAt(i))->GetWindowRect(&rc); m_pHookedWnd->ScreenToClient(&rc); rcFinal.UnionRect(&rcFinal, &rc); } BOOL bOk = CreatePanel(panelName, &rcFinal); if(bOk == FALSE) { return FALSE; } if(setAsChildren) { CPanel* pPanel = FindPanelByName(&m_root, panelName); for(int i = 0; i < parrID->GetCount(); i++) { if(FindPanelByName(&m_root, IdToName(parrID->GetAt(i))) != NULL) { bOk = m_root.RemoveChild(pPanel); ASSERT(bOk); delete pPanel; return FALSE; } CUIPanel* pUIPanel = GetUIPanel(parrID->GetAt(i)); ASSERT(pUIPanel != NULL); bOk = pPanel->AddChild(pUIPanel); ASSERT(bOk); } } return TRUE; } CWndResizer::CPanel* CWndResizer::FindPanelByName(CWndResizer::CPanel* pRoot, LPCTSTR name) { if(CString(name).GetLength() == 0) { return NULL; } if(pRoot == NULL) { return NULL; } if(pRoot->Name.CompareNoCase(name) == 0) { return pRoot; } else { POSITION pos = pRoot->Children.GetHeadPosition(); while(pos != NULL) { CPanel* pChild = pRoot->Children.GetNext(pos); CPanel* pFound = FindPanelByName(pChild, name); if(pFound != NULL) { return pFound; } } } return NULL; } void CWndResizer::GetUIPanels(CWndResizer::CPanel* pRoot, CPanelList* pList, BOOL bOle) { if(pRoot == NULL) { return; } CUIPanel* pUIPanel = dynamic_cast<CUIPanel*>(pRoot); if(pUIPanel != NULL && pUIPanel->m_bOle == bOle) { pList->AddTail(pRoot); } // try the childreen POSITION pos = pRoot->Children.GetHeadPosition(); while(pos != NULL) { CPanel* pChild = pRoot->Children.GetNext(pos); GetUIPanels(pChild, pList, bOle); } } void CWndResizer::GetVisualPanels(CWndResizer::CPanel* pRoot, CPanelList* pList) { if(pRoot == NULL) { return; } CVisualPanel* pUIPanel = dynamic_cast<CVisualPanel*>(pRoot); if(pUIPanel != NULL) { pList->AddTail(pRoot); } // try the childreen POSITION pos = pRoot->Children.GetHeadPosition(); while(pos != NULL) { CPanel* pChild = pRoot->Children.GetNext(pos); GetVisualPanels(pChild, pList); } } CWndResizer::CPanel* CWndResizer::FindSplitterFromPoint(CWndResizer::CPanel* pRoot, CPoint point) { if(pRoot == NULL) { return NULL; } CSpitterPanel* pSpitterPanel = dynamic_cast<CSpitterPanel*>(pRoot); if(pSpitterPanel != NULL && pRoot->PtInRect(point) == TRUE) { CSplitContainer* pContainer = (CSplitContainer*)pRoot->Parent; if(!pContainer->GetIsSplitterFixed()) { CPoint ptScreen = point; m_pHookedWnd->ClientToScreen(&ptScreen); HWND hWndFromPoint = ::WindowFromPoint(ptScreen); if(m_pHookedWnd->m_hWnd == hWndFromPoint) { return pRoot; } } } // try the childreen POSITION pos = pRoot->Children.GetHeadPosition(); while(pos != NULL) { CPanel* pChild = pRoot->Children.GetNext(pos); CPanel* pFound = FindSplitterFromPoint(pChild, point); if(pFound != NULL) { return pFound; } } return NULL; } CString CWndResizer::IdToName(UINT uID) { CString sName; sName.Format(_T("%d"), uID); return sName; } CWndResizer::CUIPanel* CWndResizer::CreateUIPanel(UINT uID) { ASSERT(m_pHookedWnd != NULL); CWnd* pWnd = m_pHookedWnd->GetDlgItem(uID); if(pWnd == NULL) { return NULL; } CRect rc(0, 0, 0, 0); pWnd->GetWindowRect(&rc); m_pHookedWnd->ScreenToClient(&rc); CUIPanel* pPanel = new CUIPanel(&rc, uID); pPanel->Name = IdToName(uID); return pPanel; } CWndResizer::CUIPanel* CWndResizer::GetUIPanel(UINT uID) { CUIPanel* pPanel = NULL; if((pPanel = (CUIPanel*)FindPanelByName(&m_root, IdToName(uID))) == NULL) { pPanel = CreateUIPanel(uID); if(pPanel != NULL) { m_root.AddChild(pPanel); } } return pPanel; } BOOL CWndResizer::InvokeOnResized() { ASSERT(m_pHookedWnd != NULL); OnSize(0, 0, 0); return TRUE; } CString CWndResizer::GetDebugInfo() { ASSERT(m_pHookedWnd != NULL); CString sInfo; CString sIndent; GetDebugInfo(&m_root, sInfo, sIndent); return sInfo; } void CWndResizer::GetDebugInfo(CPanel* pRoot, CString& info, CString indent) { if(pRoot == NULL) { return; } info.Append(_T("\n")); info.Append(indent); info.Append(pRoot->ToString()); indent.Append(_T(" ")); for(int i = 0; i < pRoot->Children.GetCount(); i++) { CPanel* pChild = pRoot->Children.GetAt(pRoot->Children.FindIndex(i)); GetDebugInfo(pChild, info, indent); } } ///////////////////////////// CPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CPanel::CPanel() : CRect(0, 0, 0, 0) { Init(); } CWndResizer::CPanel::CPanel(const CRect* prc) : CRect(prc) { Init(); } void CWndResizer::CPanel::Init() { Parent = NULL; LeftOffset = 0; TopOffset = 0; RightOffset = 0; BottomOffset = 0; MinSize.SetSize(10, 10); MaxSize.SetSize(100000, 100000); Anchor = (ANCHOR_LEFT | ANCHOR_TOP); Dock = DOCK_NONE; } CWndResizer::CPanel::~CPanel() { while(Children.GetCount() > 0) { delete Children.RemoveHead(); } } void CWndResizer::CPanel::OnResized() { BOOL bOk = FALSE; CRect rcEmpty(this); // available area for docking. ininitally it is the entire area POSITION pos = Children.GetHeadPosition(); while(pos != NULL) { CPanel* pChild = Children.GetNext(pos); if(pChild->Dock != DOCK_NONE) { switch(pChild->Dock) { case DOCK_LEFT: pChild->SetRect(rcEmpty.left, rcEmpty.top, rcEmpty.left + pChild->Width(), rcEmpty.bottom); bOk = rcEmpty.SubtractRect(&rcEmpty, pChild); // ASSERT( bOk ); break; case DOCK_TOP: pChild->SetRect(rcEmpty.left, rcEmpty.top, rcEmpty.right, rcEmpty.top + pChild->Height()); bOk = rcEmpty.SubtractRect(&rcEmpty, pChild); // ASSERT( bOk ); break; case DOCK_RIGHT: pChild->SetRect(rcEmpty.right - pChild->Width(), rcEmpty.top, rcEmpty.right, rcEmpty.bottom); bOk = rcEmpty.SubtractRect(&rcEmpty, pChild); // ASSERT( bOk ); break; case DOCK_BOTTOM: pChild->SetRect(rcEmpty.left, rcEmpty.bottom - pChild->Height(), rcEmpty.right, rcEmpty.bottom); bOk = rcEmpty.SubtractRect(&rcEmpty, pChild); // ASSERT( bOk ); break; case DOCK_FILL: pChild->SetRect(rcEmpty.left, rcEmpty.top, rcEmpty.right, rcEmpty.bottom); break; } pChild->OnResized(); // if docking is in action, then we igonre anchor, therefore we continue continue; } CRect rc(0, 0, 0, 0); if((pChild->Anchor & ANCHOR_HORIZONTALLY_CENTERED) == ANCHOR_HORIZONTALLY_CENTERED) { rc.left = this->left + ((int)((this->Width() - pChild->Width()) / 2)); rc.right = rc.left + pChild->Width(); BOOL bReposition = FALSE; if(pChild->MinSize.cx > rc.Width()) { bReposition = TRUE; rc.right = rc.left + pChild->MinSize.cx; } if(pChild->MaxSize.cx < rc.Width()) { bReposition = TRUE; rc.right = rc.left + pChild->MaxSize.cx; } if(bReposition) { int nWidth = rc.Width(); rc.left = (int)((this->Width() - nWidth) / 2); rc.right = rc.left + nWidth; } } else if((pChild->Anchor & ANCHOR_HORIZONTALLY) == ANCHOR_HORIZONTALLY) { rc.left = this->left + pChild->LeftOffset; rc.right = this->right - pChild->RightOffset; // we will be left anchor if minsize or maxsize does not match // (giving ANCHOR_LEFT priority over ANCHOR_RIGHT) if((pChild->Anchor & ANCHOR_PRIORITY_RIGHT) == ANCHOR_PRIORITY_RIGHT) { if(pChild->MinSize.cx > rc.Width()) { rc.left = rc.right - pChild->MinSize.cx; } if(pChild->MaxSize.cx < rc.Width()) { rc.left = rc.right - pChild->MaxSize.cx; } } else { if(pChild->MinSize.cx > rc.Width()) { rc.right = rc.left + pChild->MinSize.cx; } if(pChild->MaxSize.cx < rc.Width()) { rc.right = rc.left + pChild->MaxSize.cx; } } } else if((pChild->Anchor & ANCHOR_RIGHT) == ANCHOR_RIGHT) { rc.right = this->right - pChild->RightOffset; rc.left = rc.right - pChild->Width(); if(pChild->MinSize.cx > rc.Width()) { rc.left = rc.right - pChild->MinSize.cx; } if(pChild->MaxSize.cx < rc.Width()) { rc.left = rc.right - pChild->MaxSize.cx; } } else if((pChild->Anchor & ANCHOR_LEFT) == ANCHOR_LEFT) { rc.left = this->left + pChild->LeftOffset; rc.right = rc.left + pChild->Width(); if(pChild->MinSize.cx > rc.Width()) { rc.right = rc.left + pChild->MinSize.cx; } if(pChild->MaxSize.cx < rc.Width()) { rc.right = rc.left + pChild->MaxSize.cx; } } else { // it should never be here ASSERT(FALSE); } if((pChild->Anchor & ANCHOR_VERTICALLY_CENTERED) == ANCHOR_VERTICALLY_CENTERED) { rc.top = this->top + ((int)((this->Height() - pChild->Height()) / 2)); rc.bottom = rc.top + pChild->Height(); BOOL bReposition = FALSE; if(pChild->MinSize.cy > rc.Height()) { bReposition = TRUE; rc.bottom = rc.top + pChild->MinSize.cy; } if(pChild->MaxSize.cy < rc.Height()) { bReposition = TRUE; rc.bottom = rc.top + pChild->MaxSize.cy; } if(bReposition) { int nHeight = rc.Height(); rc.top = (int)((this->Height() - nHeight) / 2); rc.bottom = rc.top + nHeight; } } else if((pChild->Anchor & ANCHOR_VERTICALLY) == ANCHOR_VERTICALLY) { rc.top = this->top + pChild->TopOffset; rc.bottom = this->bottom - pChild->BottomOffset; if((pChild->Anchor & ANCHOR_PRIORITY_BOTTOM) == ANCHOR_PRIORITY_BOTTOM) { if(pChild->MinSize.cy > rc.Height()) { rc.top = rc.bottom - pChild->MinSize.cy; } if(pChild->MaxSize.cy < rc.Height()) { rc.top = rc.bottom - pChild->MaxSize.cy; } } else { if(pChild->MinSize.cy > rc.Height()) { rc.bottom = rc.top + pChild->MinSize.cy; } if(pChild->MaxSize.cy < rc.Height()) { rc.bottom = rc.top + pChild->MaxSize.cy; } } } else if((pChild->Anchor & ANCHOR_BOTTOM) == ANCHOR_BOTTOM) { rc.bottom = this->bottom - pChild->BottomOffset; rc.top = rc.bottom - pChild->Height(); if(pChild->MinSize.cy > rc.Height()) { rc.top = rc.bottom - pChild->MinSize.cy; } if(pChild->MaxSize.cy < rc.Height()) { rc.top = rc.bottom - pChild->MaxSize.cy; } } else if((pChild->Anchor & ANCHOR_TOP) == ANCHOR_TOP) { rc.top = this->top + pChild->TopOffset; rc.bottom = rc.top + pChild->Height(); if(pChild->MinSize.cy > rc.Height()) { rc.bottom = rc.top + pChild->MinSize.cy; } if(pChild->MaxSize.cy < rc.Height()) { rc.bottom = rc.top + pChild->MaxSize.cy; } } else { // it should never be here ASSERT(FALSE); } pChild->SetRect(rc.TopLeft(), rc.BottomRight()); pChild->OnResized(); } } BOOL CWndResizer::CPanel::AddChild(CPanel* pChild) { if(pChild->Parent != NULL) { BOOL bOk = pChild->Parent->RemoveChild(pChild); if(bOk == FALSE) { return FALSE; } } pChild->LeftOffset = pChild->left - this->left; pChild->TopOffset = pChild->top - this->top; pChild->RightOffset = this->right - pChild->right; pChild->BottomOffset = this->bottom - pChild->bottom; pChild->Parent = this; Children.AddTail(pChild); return TRUE; } BOOL CWndResizer::CPanel::RemoveChild(CPanel* pChild) { POSITION pos = Children.Find(pChild); if(pos == NULL) { return FALSE; } Children.RemoveAt(pos); return TRUE; } BOOL CWndResizer::CPanel::SetMinSize(CSize& size) { if(MaxSize.cx < size.cx) { return FALSE; } if(MaxSize.cy < size.cy) { return FALSE; } MinSize = size; return TRUE; } BOOL CWndResizer::CPanel::SetMaxSize(CSize& size) { if(MinSize.cx > size.cx) { return FALSE; } if(MinSize.cy > size.cy) { return FALSE; } MaxSize = size; return TRUE; } BOOL CWndResizer::CPanel::SetAnchor(UINT anchor) { if((anchor & ANCHOR_VERTICALLY_CENTERED) <= 0) { if((anchor & ANCHOR_TOP) <= 0) { if((anchor & ANCHOR_BOTTOM) <= 0) { anchor |= ANCHOR_TOP; // default } } } if((anchor & ANCHOR_HORIZONTALLY_CENTERED) <= 0) { if((anchor & ANCHOR_LEFT) <= 0) { if((anchor & ANCHOR_RIGHT) <= 0) { anchor |= ANCHOR_LEFT; // default } } } Anchor = anchor; return TRUE; } CString CWndResizer::CPanel::ToString() { CString sFormat(_T("Name(%s), Type(%s), Anchor(%d), Size(w:%d, h:%d), Area(l:%d, t:%d, r:%d, b:%d), MinSize(w:%d, h:%d), MaxSize(w:%d, h:%d), ") _T("Parent(%s), ChildrenCount(%d)")); CString sTo; sTo.Format(sFormat, Name, GetTypeName(), Anchor, Width(), Height(), left, top, right, bottom, MinSize.cx, MinSize.cy, MaxSize.cx, MaxSize.cy, (Parent == NULL ? _T("NULL") : Parent->Name), Children.GetCount()); return sTo; } CString CWndResizer::CPanel::GetTypeName() { return _T("CPanel"); } CWnd* CWndResizer::CPanel::GetHookedWnd() { if(Parent != NULL) { return Parent->GetHookedWnd(); } return NULL; } ///////////////////////////// CSplitContainer /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CSplitContainer::CSplitContainer(CSplitPanel* pPanelA, CSplitPanel* pPanelB, CWndResizer::SplitterOrientation type) : CPanel() { m_IsSplitterFixed = FALSE; m_FixedPanel = 0; m_pPanelA = NULL; m_pPanelB = NULL; m_pSplitter = NULL; m_Orientation = type; m_pPanelA = pPanelA; m_pPanelB = pPanelB; UnionRect(m_pPanelA, m_pPanelB); CRect rc(0, 0, 0, 0); GetSplitArea(&rc); m_pSplitter = new CSpitterPanel(&rc, type); m_pSplitter->m_pGrippePanel->m_bVisible = FALSE; if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { m_pPanelA->Anchor = (ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_BOTTOM); m_pPanelB->Anchor = (ANCHOR_RIGHT | ANCHOR_TOP | ANCHOR_BOTTOM); } else { m_pPanelA->Anchor = (ANCHOR_LEFT | ANCHOR_TOP | ANCHOR_RIGHT); m_pPanelB->Anchor = (ANCHOR_LEFT | ANCHOR_BOTTOM | ANCHOR_RIGHT); } m_nSplitterSize = GetSplitterSize(m_pPanelA, m_pPanelB); BOOL bOk = AddChild(m_pPanelA); ASSERT(bOk); bOk = AddChild(m_pSplitter); ASSERT(bOk); bOk = AddChild(m_pPanelB); ASSERT(bOk); UpdateRatio(); } CWndResizer::CSplitContainer::~CSplitContainer() {} void CWndResizer::CSplitContainer::OnResized() { CPanel::OnResized(); if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { if(Width() < MinSize.cx) { return; } if(m_FixedPanel == 1) // left panel is fixed { m_pPanelB->left = m_pPanelA->right + m_nSplitterSize; if(m_pPanelB->MinSize.cx > m_pPanelB->Width()) { m_pPanelB->left = m_pPanelB->right - m_pPanelB->MinSize.cx; m_pPanelA->right = m_pPanelB->left - m_nSplitterSize; } } else if(m_FixedPanel == 2) // right panel is fixed { m_pPanelA->right = m_pPanelB->left - m_nSplitterSize; if(m_pPanelA->MinSize.cx > m_pPanelA->Width()) { m_pPanelA->right = m_pPanelA->left + m_pPanelA->MinSize.cx; m_pPanelB->left = m_pPanelA->right + m_nSplitterSize; } } else { m_pPanelA->right = (LONG)((double)m_pPanelA->left + ((double)this->Width() * m_nRatio)); if(m_pPanelA->MinSize.cx > m_pPanelA->Width()) { m_pPanelA->right = m_pPanelA->left + m_pPanelA->MinSize.cx; } m_pPanelB->left = m_pPanelA->right + m_nSplitterSize; if(m_pPanelB->MinSize.cx > m_pPanelB->Width()) { m_pPanelB->left = m_pPanelB->right - m_pPanelB->MinSize.cx; m_pPanelA->right = m_pPanelB->left - m_nSplitterSize; } } } else /*if (m_Orientation == CWndResizer::SPLIT_CONTAINER_V)*/ { if(Height() < MinSize.cy) { return; } if(m_FixedPanel == 1) // top panel is fixed { m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize; if(m_pPanelB->MinSize.cy > m_pPanelB->Height()) { m_pPanelB->top = m_pPanelB->bottom - m_pPanelB->MinSize.cy; m_pPanelA->bottom = m_pPanelB->top - m_nSplitterSize; } } else if(m_FixedPanel == 2) // bottom panel is fixed { m_pPanelA->bottom = m_pPanelB->top - m_nSplitterSize; if(m_pPanelA->MinSize.cy > m_pPanelA->Height()) { m_pPanelA->bottom = m_pPanelA->top + m_pPanelA->MinSize.cy; m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize; } } else { m_pPanelA->bottom = (LONG)((double)m_pPanelA->top + ((double)this->Height() * m_nRatio)); if(m_pPanelA->MinSize.cy > m_pPanelA->Height()) { m_pPanelA->bottom = m_pPanelA->top + m_pPanelA->MinSize.cy; } m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize; if(m_pPanelB->MinSize.cy > m_pPanelB->Height()) { m_pPanelB->top = m_pPanelB->bottom - m_pPanelB->MinSize.cy; m_pPanelA->bottom = m_pPanelB->top - m_nSplitterSize; } } } GetSplitArea(m_pSplitter); m_pPanelA->OnResized(); m_pPanelB->OnResized(); m_pSplitter->OnResized(); } void CWndResizer::CSplitContainer::SetSplitterPosition(int leftOfSplitter) { short nFixedPanel = m_FixedPanel; m_FixedPanel = 0; if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { m_pPanelA->right = leftOfSplitter; m_pPanelB->left = m_pPanelA->right + m_nSplitterSize; } else { m_pPanelA->bottom = leftOfSplitter; m_pPanelB->top = m_pPanelA->bottom + m_nSplitterSize; } UpdateRatio(); OnResized(); UpdateRatio(); m_FixedPanel = nFixedPanel; } int CWndResizer::CSplitContainer::GetSplitterPosition() { if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { return m_pPanelA->right; } else { return m_pPanelA->bottom; } } BOOL CWndResizer::CSplitContainer::AddChild(CPanel* prc) { if(Children.GetCount() == 3) { return FALSE; } return CPanel::AddChild(prc); } BOOL CWndResizer::CSplitContainer::RemoveChild(CPanel* prc) { return FALSE; // cannot remove child from split container } void CWndResizer::CSplitContainer::GetSplitArea(CRect* pSplitterPanel) { if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { pSplitterPanel->left = m_pPanelA->right; pSplitterPanel->top = this->top; pSplitterPanel->right = m_pPanelB->left; pSplitterPanel->bottom = this->bottom; } else // vertical { pSplitterPanel->left = this->left; pSplitterPanel->top = m_pPanelA->bottom; pSplitterPanel->right = this->right; pSplitterPanel->bottom = m_pPanelB->top; } } int CWndResizer::CSplitContainer::GetSplitterSize(CPanel* m_pPanelA, CPanel* m_pPanelB) { if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { int nWidth = m_pPanelB->left - m_pPanelA->right; return nWidth; } else // vertical { int nHeight = m_pPanelB->top - m_pPanelA->bottom; return nHeight; } } void CWndResizer::CSplitContainer::UpdateRatio() { if(m_Orientation == CWndResizer::SPLIT_CONTAINER_H) { m_nRatio = (double)m_pPanelA->Width() / (double)this->Width(); } else { m_nRatio = (double)m_pPanelA->Height() / (double)this->Height(); } } CWndResizer::CSplitContainer* CWndResizer::CSplitContainer::Create(CPanel* pPanelA, CPanel* pPanelB) { CSplitPanel* pSplitPanelA = dynamic_cast<CSplitPanel*>(pPanelA); if(pSplitPanelA != NULL) { return NULL; // already a part of a CSplitContainer } CSplitPanel* pSplitPanelB = dynamic_cast<CSplitPanel*>(pPanelB); if(pSplitPanelB != NULL) { return NULL; // already a part of a CSplitContainer } CRect rcDest(0, 0, 0, 0); CWndResizer::SplitterOrientation orien = CWndResizer::SPLIT_CONTAINER_H; if(::IntersectRect(&rcDest, pPanelA, pPanelB) == TRUE) // invalid spliter container, a spliter continer's two panel cannot intersect each other { return NULL; } if(pPanelA->right < pPanelB->left) { orien = CWndResizer::SPLIT_CONTAINER_H; } else if(pPanelA->bottom < pPanelB->top) { orien = CWndResizer::SPLIT_CONTAINER_V; } else { return NULL; } if(pPanelA->Parent != NULL) { if(pPanelA->Parent->RemoveChild(pPanelA) == FALSE) { return NULL; } } if(pPanelB->Parent != NULL) { if(pPanelB->Parent->RemoveChild(pPanelB) == FALSE) { return NULL; } } pSplitPanelA = new CSplitPanel(pPanelA); pSplitPanelB = new CSplitPanel(pPanelB); CSplitContainer* pSpliter = new CSplitContainer(pSplitPanelA, pSplitPanelB, orien); return pSpliter; } CString CWndResizer::CSplitContainer::GetTypeName() { return _T("CSplitContainer"); } void CWndResizer::CSplitContainer::SetFixedPanel(short nFixedPanel /* 1=left/top; 2=right/bototm; other=no fixed panel */) { m_FixedPanel = nFixedPanel; } short CWndResizer::CSplitContainer::GetFixedPanel() { return m_FixedPanel; } void CWndResizer::CSplitContainer::SetIsSplitterFixed(BOOL bFixed) { m_IsSplitterFixed = bFixed; } BOOL CWndResizer::CSplitContainer::GetIsSplitterFixed() { return m_IsSplitterFixed; } void CWndResizer::CSplitContainer::SetShowSplitterGrip(BOOL bShow) { m_pSplitter->m_pGrippePanel->m_bVisible = bShow; } BOOL CWndResizer::CSplitContainer::GetShowSplitterGrip() { return m_pSplitter->m_pGrippePanel->m_bVisible; } ///////////////////////////// CRootPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CRootPanel::CRootPanel() : CPanel() { m_pHookWnd = NULL; } CWndResizer::CRootPanel::~CRootPanel() {} CWnd* CWndResizer::CRootPanel::GetHookedWnd() { return m_pHookWnd; } CString CWndResizer::CRootPanel::GetTypeName() { return _T("CRootPanel"); } ///////////////////////////// CUIPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CUIPanel::CUIPanel(const CRect* prc, UINT uID) : CPanel(prc) { m_uID = uID; m_bOle = FALSE; } CWndResizer::CUIPanel::~CUIPanel() {} CString CWndResizer::CUIPanel::GetTypeName() { return _T("CUIPanel"); } ///////////////////////////// CVisualPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CVisualPanel::CVisualPanel() : CPanel() { m_bVisible = FALSE; m_rcPrev.SetRect(0, 0, 0, 0); } CWndResizer::CVisualPanel::CVisualPanel(const CRect* prc) : CPanel(prc) { m_bVisible = FALSE; m_rcPrev.SetRect(this->left, this->top, this->right, this->bottom); } CWndResizer::CVisualPanel::~CVisualPanel() {} void CWndResizer::CVisualPanel::Draw(CDC* pDC) {} CString CWndResizer::CVisualPanel::GetTypeName() { return _T("CVisualPanel"); } void CWndResizer::CVisualPanel::OnResized() { CWnd* pWnd = NULL; if((pWnd = GetHookedWnd()) != NULL) { pWnd->InvalidateRect(&m_rcPrev, FALSE); pWnd->InvalidateRect(this, FALSE); } m_rcPrev.SetRect(this->left, this->top, this->right, this->bottom); } ///////////////////////////// CGripperPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CGripperPanel::CGripperPanel() : CVisualPanel() { m_hTheme = NULL; m_iPartId = SBP_SIZEBOX; m_iStateId = 5; // SZB_HALFBOTTOMRIGHTALIGN; m_sClassName = _T("SCROLLBAR"); } CWndResizer::CGripperPanel::CGripperPanel(const CRect* prc) : CVisualPanel(prc) { m_hTheme = NULL; m_iPartId = SBP_SIZEBOX; m_iStateId = 5; // SZB_HALFBOTTOMRIGHTALIGN; m_sClassName = _T("SCROLLBAR"); } CWndResizer::CGripperPanel::~CGripperPanel() { if(m_hTheme != NULL) { HRESULT lres = ::CloseThemeData(m_hTheme); ASSERT(SUCCEEDED(lres) == TRUE); m_hTheme = NULL; } } void CWndResizer::CGripperPanel::Draw(CDC* pDC) { if(m_hTheme == NULL) { CWnd* pHookedWnd = GetHookedWnd(); if(pHookedWnd == NULL) { return; } m_hTheme = ::OpenThemeData(pHookedWnd->m_hWnd, m_sClassName.AllocSysString()); } if(m_hTheme == NULL) { BOOL bOk = pDC->DrawFrameControl(this, DFC_SCROLL, DFCS_SCROLLSIZEGRIP); ASSERT(bOk); } else { HRESULT lres = ::DrawThemeBackground(m_hTheme, pDC->m_hDC, m_iPartId, m_iStateId, this, this); ASSERT(SUCCEEDED(lres) == TRUE); } } CString CWndResizer::CGripperPanel::GetTypeName() { return _T("CGripperPanel"); } ///////////////////////////// CSplitterGripperPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CSplitterGripperPanel::CSplitterGripperPanel(CWndResizer::SplitterOrientation type) : CVisualPanel() { m_OrienType = type; } CWndResizer::CSplitterGripperPanel::~CSplitterGripperPanel() {} void CWndResizer::CSplitterGripperPanel::Draw(CDC* pDC) { CPen penDark(PS_SOLID, 1, ::GetSysColor(COLOR_3DSHADOW)); CPen penWhite(PS_SOLID, 1, RGB(255, 255, 255)); if(m_OrienType == CWndResizer::SPLIT_CONTAINER_H) { CPen* pOrigPen = pDC->SelectObject(&penWhite); CRect rc(0, 0, 0, 0); rc.SetRect(left + 1, top + 1, left + 3, top + 3); while(rc.bottom <= bottom) { pDC->Rectangle(&rc); rc.OffsetRect(0, 4); } pDC->SelectObject(&penDark); rc.SetRect(left, top, left + 2, top + 2); while(rc.bottom <= bottom) { pDC->Rectangle(&rc); rc.OffsetRect(0, 4); } pDC->SelectObject(pOrigPen); } else { CPen* pOrigPen = pDC->SelectObject(&penWhite); CRect rc(0, 0, 0, 0); rc.SetRect(left + 1, top + 1, left + 3, top + 3); while(rc.right <= right) { pDC->Rectangle(&rc); rc.OffsetRect(4, 0); } pDC->SelectObject(&penDark); rc.SetRect(left, top, left + 2, top + 2); while(rc.right <= right) { pDC->Rectangle(&rc); rc.OffsetRect(4, 0); } pDC->SelectObject(pOrigPen); } } CString CWndResizer::CSplitterGripperPanel::GetTypeName() { return _T("CSplitterGripperPanel"); } ///////////////////////////// CSpitterPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CSpitterPanel::CSpitterPanel(const CRect* prc, CWndResizer::SplitterOrientation type) : CPanel(prc) { m_OrienType = type; m_pGrippePanel = NULL; if(m_pGrippePanel == NULL) { m_pGrippePanel = new CSplitterGripperPanel(type); if(m_OrienType == CWndResizer::SPLIT_CONTAINER_H) { m_pGrippePanel->SetRect(0, 0, 3, 12); } else { m_pGrippePanel->SetRect(0, 0, 12, 3); } m_pGrippePanel->SetAnchor(ANCHOR_HORIZONTALLY_CENTERED | ANCHOR_VERTICALLY_CENTERED); m_pGrippePanel->SetMinSize(CSize(2, 2)); BOOL bOk = AddChild(m_pGrippePanel); ASSERT(bOk); } } CWndResizer::CSpitterPanel::CSpitterPanel(CWndResizer::SplitterOrientation type) : CPanel() { m_OrienType = type; m_pGrippePanel = NULL; } CWndResizer::CSpitterPanel::~CSpitterPanel() {} CString CWndResizer::CSpitterPanel::GetTypeName() { return _T("CSpitterPanel"); } ///////////////////////////// CSpitPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CSplitPanel::CSplitPanel(CPanel* pPanel) : CPanel(pPanel) { pPanel->LeftOffset = 0; pPanel->TopOffset = 0; pPanel->RightOffset = 0; pPanel->BottomOffset = 0; pPanel->Anchor = ANCHOR_ALL; Name = pPanel->Name; pPanel->Name = _T(""); m_pOriginalPanel = pPanel; MaxSize = pPanel->MaxSize; MinSize = pPanel->MinSize; Children.AddTail(pPanel); } CWndResizer::CSplitPanel::~CSplitPanel() {} BOOL CWndResizer::CSplitPanel::SetAnchor(UINT anchor) { return FALSE; } BOOL CWndResizer::CSplitPanel::AddChild(CPanel* prc) { return m_pOriginalPanel->AddChild(prc); } BOOL CWndResizer::CSplitPanel::RemoveChild(CPanel* prc) { return m_pOriginalPanel->RemoveChild(prc); } CString CWndResizer::CSplitPanel::GetTypeName() { return _T("CSplitPanel"); } ///////////////////////////// CFlowLayoutPanel /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// CWndResizer::CFlowLayoutPanel::CFlowLayoutPanel() : CPanel() { m_nItemSpacingX = 0; m_nItemSpacingY = 0; m_nFlowDirection = CWndResizer::LEFT_TO_RIGHT; } CWndResizer::CFlowLayoutPanel::CFlowLayoutPanel(const CRect* prc) : CPanel(prc) { m_nItemSpacingX = 0; m_nItemSpacingY = 0; m_nFlowDirection = CWndResizer::LEFT_TO_RIGHT; } CWndResizer::CFlowLayoutPanel::~CFlowLayoutPanel() {} void CWndResizer::CFlowLayoutPanel::OnResized() { int max = 0; // maximimum height of a item in the row in case of left-to-right, otherwise maximum width of a item int x = left; int y = top; POSITION pos = Children.GetHeadPosition(); // first one will be at the top-left corner, no matter what if(pos != NULL) { CPanel* pPanel = Children.GetNext(pos); pPanel->MoveToXY(x, y); pPanel->OnResized(); if(m_nFlowDirection == CWndResizer::LEFT_TO_RIGHT) { x += pPanel->Width() + m_nItemSpacingX; max = (pPanel->Height() > max ? pPanel->Height() : max); } else { y += pPanel->Height() + m_nItemSpacingY; max = (pPanel->Width() > max ? pPanel->Width() : max); } } if(m_nFlowDirection == CWndResizer::LEFT_TO_RIGHT) { while(pos != NULL) { CPanel* pPanel = Children.GetNext(pos); // check to see if it is to wrap if(x + pPanel->Width() > right) { x = left; y += (max + m_nItemSpacingY); max = 0; } pPanel->MoveToXY(x, y); pPanel->OnResized(); x += pPanel->Width() + m_nItemSpacingX; max = (pPanel->Height() > max ? pPanel->Height() : max); } } else { while(pos != NULL) { CPanel* pPanel = Children.GetNext(pos); // check to see if it is to wrap if(y + pPanel->Height() > bottom) { x += (max + m_nItemSpacingX); y = top; max = 0; } pPanel->MoveToXY(x, y); pPanel->OnResized(); y += pPanel->Height() + m_nItemSpacingY; max = (pPanel->Width() > max ? pPanel->Width() : max); } } } CString CWndResizer::CFlowLayoutPanel::GetTypeName() { return _T("CFlowLayoutPanel"); } void CWndResizer::CFlowLayoutPanel::SetFlowDirection(CWndResizer::FlowDirection direction) { m_nFlowDirection = direction; } CWndResizer::FlowDirection CWndResizer::CFlowLayoutPanel::GetFlowDirection() { return m_nFlowDirection; } void CWndResizer::CFlowLayoutPanel::SetItemSpacingX(int nSpace) { m_nItemSpacingX = nSpace; } int CWndResizer::CFlowLayoutPanel::GetItemSpacingX() { return m_nItemSpacingX; } void CWndResizer::CFlowLayoutPanel::SetItemSpacingY(int nSpace) { m_nItemSpacingY = nSpace; } int CWndResizer::CFlowLayoutPanel::GetItemSpacingY() { return m_nItemSpacingY; } } // namespace wndcommons } // namespace abscodes
34.207101
155
0.527723
AbsCoDes-lib
0c1714ca9d511e0ec4fdc808b2261c7c4d31608c
1,896
cpp
C++
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/BreathingCircuit/ControlLoop.cpp
pez-globo/pufferfish-software
b42fecd652731dd80fbe366e95983503fced37a4
[ "Apache-2.0" ]
1
2020-10-20T23:47:23.000Z
2020-10-20T23:47:23.000Z
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/BreathingCircuit/ControlLoop.cpp
pez-globo/pufferfish-software
b42fecd652731dd80fbe366e95983503fced37a4
[ "Apache-2.0" ]
242
2020-10-23T06:44:01.000Z
2022-01-28T05:50:45.000Z
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/BreathingCircuit/ControlLoop.cpp
pez-globo/pufferfish-vent-software
f1e5e47acf1941e7c729adb750b85bf26c38b274
[ "Apache-2.0" ]
1
2021-04-12T02:10:18.000Z
2021-04-12T02:10:18.000Z
/* * BreathingCircuit.tpp * * Created on: June 6, 2020 * Author: Ethan Li */ #include "Pufferfish/Driver/BreathingCircuit/ControlLoop.h" namespace Pufferfish::Driver::BreathingCircuit { // ControlLoop // HFNC ControlLoop SensorVars &HFNCControlLoop::sensor_vars() { return sensor_vars_; } const SensorVars &HFNCControlLoop::sensor_vars() const { return sensor_vars_; } const ActuatorVars &HFNCControlLoop::actuator_vars() const { return actuator_vars_; } const SensorConnections &HFNCControlLoop::sensor_connections() const { return sensor_connections_; } void HFNCControlLoop::update(uint32_t current_time) { if (step_timer().within_timeout(current_time)) { return; } if (parameters_.mode != Application::VentilationMode_hfnc) { return; } // Update sensors InitializableState air_status = sfm3019_air_.output(sensor_vars_.flow_air); InitializableState o2_status = sfm3019_o2_.output(sensor_vars_.flow_o2); if (air_status == InitializableState::ok && o2_status == InitializableState::ok) { sensor_measurements_.flow = sensor_vars_.flow_air + sensor_vars_.flow_o2; } // TODO(lietk12): we should probably set flow to NaN otherwise, but for now we do nothing // so that we don't overwrite the simulated values if the sensors aren't available sensor_connections_.sfm3019_air_connected = air_status == InitializableState::ok; sensor_connections_.sfm3019_o2_connected = o2_status == InitializableState::ok; // Update controller controller_.transform( current_time, parameters_, sensor_vars_, sensor_measurements_, actuator_setpoints_, actuator_vars_); // Update actuators valve_air_.set_duty_cycle(actuator_vars_.valve_air_opening); valve_o2_.set_duty_cycle(actuator_vars_.valve_o2_opening); step_timer().reset(current_time); } } // namespace Pufferfish::Driver::BreathingCircuit
27.085714
91
0.757384
pez-globo
0c176e32658501cbd22417750727509d9286caa6
145
cpp
C++
src/TacticsVictory/common_files/Scene/Objects/Units/Ground/GroundUnit_.cpp
Sasha7b9/U-Cube
442927ff1391bfe78cdf520ad303c7dc29086b46
[ "MIT" ]
null
null
null
src/TacticsVictory/common_files/Scene/Objects/Units/Ground/GroundUnit_.cpp
Sasha7b9/U-Cube
442927ff1391bfe78cdf520ad303c7dc29086b46
[ "MIT" ]
null
null
null
src/TacticsVictory/common_files/Scene/Objects/Units/Ground/GroundUnit_.cpp
Sasha7b9/U-Cube
442927ff1391bfe78cdf520ad303c7dc29086b46
[ "MIT" ]
null
null
null
// 2021/03/10 17:40:18 (c) Aleksandr Shevchenko e-mail : Sasha7b9@tut.by #include "stdafx.h" #include "Scene/Objects/Units/Ground/GroundUnit_.h"
36.25
72
0.744828
Sasha7b9
0c19a5e41dfde254edb0756b883eb0365a0070d1
1,800
cpp
C++
src/NativeScript/Marshalling/FunctionReference/FunctionReferenceConstructor.cpp
linwaiwai/ios-runtime
1e01a18c0cf936266a0c8d86bcc5ffc4ff3653ef
[ "Apache-2.0" ]
1
2020-09-03T01:33:53.000Z
2020-09-03T01:33:53.000Z
src/NativeScript/Marshalling/FunctionReference/FunctionReferenceConstructor.cpp
linwaiwai/ios-runtime
1e01a18c0cf936266a0c8d86bcc5ffc4ff3653ef
[ "Apache-2.0" ]
null
null
null
src/NativeScript/Marshalling/FunctionReference/FunctionReferenceConstructor.cpp
linwaiwai/ios-runtime
1e01a18c0cf936266a0c8d86bcc5ffc4ff3653ef
[ "Apache-2.0" ]
null
null
null
// // FunctionReferenceConstructor.cpp // NativeScript // // Created by Jason Zhekov on 10/20/14. // Copyright (c) 2014 Telerik. All rights reserved. // #include "FunctionReferenceConstructor.h" #include "FunctionReferenceInstance.h" #include "Interop.h" namespace NativeScript { using namespace JSC; const ClassInfo FunctionReferenceConstructor::s_info = { "FunctionReference", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(FunctionReferenceConstructor) }; void FunctionReferenceConstructor::finishCreation(VM& vm, JSValue prototype) { Base::finishCreation(vm, this->classInfo()->className); this->putDirect(vm, vm.propertyNames->prototype, prototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); this->putDirect(vm, vm.propertyNames->length, jsNumber(1), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum | PropertyAttribute::DontDelete); } EncodedJSValue JSC_HOST_CALL FunctionReferenceConstructor::constructFunctionReferenceInstance(ExecState* execState) { CallData callData; JSC::VM& vm = execState->vm(); if (!(execState->argumentCount() == 1 && JSC::getCallData(vm, execState->uncheckedArgument(0), callData) != CallType::None)) { auto scope = DECLARE_THROW_SCOPE(vm); return JSValue::encode(scope.throwException(execState, createError(execState, "Function required."_s))); } GlobalObject* globalObject = jsCast<GlobalObject*>(execState->lexicalGlobalObject()); JSCell* func = execState->uncheckedArgument(0).asCell(); auto functionReference = FunctionReferenceInstance::create(execState->vm(), globalObject, globalObject->interop()->functionReferenceInstanceStructure(), func); return JSValue::encode(functionReference.get()); } } // namespace NativeScript
43.902439
163
0.761667
linwaiwai
0c19c64ff9b0bfc0523431936929e35da155ecee
8,027
cpp
C++
lib/libcpp/Solvers/applicationinterface.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/Solvers/applicationinterface.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/Solvers/applicationinterface.cpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#include "Alat/stringvector.hpp" #include "Solvers/applicationinterface.hpp" #include "Mesh/meshunitinterface.hpp" #include <cassert> using namespace solvers; /*--------------------------------------------------------------------------*/ ApplicationInterface::~ApplicationInterface() {} ApplicationInterface::ApplicationInterface(): alat::InterfaceBase(), _mesh(NULL){} ApplicationInterface::ApplicationInterface( const ApplicationInterface& applicationinterface): alat::InterfaceBase(applicationinterface) { assert(0); } ApplicationInterface& ApplicationInterface::operator=( const ApplicationInterface& applicationinterface) { assert(0); alat::InterfaceBase::operator=(applicationinterface); return *this; } std::string ApplicationInterface::getClassName() const { return "ApplicationInterface"; } void ApplicationInterface::setModel(const solvers::ModelInterface* model){_model=model;} /*--------------------------------------------------------------------------*/ std::unique_ptr<solvers::InitialConditionInterface> ApplicationInterface::newInitialCondition(std::string varname) const { return std::unique_ptr<solvers::InitialConditionInterface>(nullptr); } std::unique_ptr<solvers::RightHandSideInterface> ApplicationInterface::newRightHandSide(std::string varname) const { return std::unique_ptr<solvers::RightHandSideInterface>(nullptr); } std::unique_ptr<solvers::DirichletInterface> ApplicationInterface::newDirichlet(std::string varname) const { return std::unique_ptr<solvers::DirichletInterface>(nullptr); } std::unique_ptr<solvers::NeumannInterface> ApplicationInterface::newNeumann(std::string varname) const { return std::unique_ptr<solvers::NeumannInterface>(nullptr); } std::shared_ptr<solvers::FunctionInterface> ApplicationInterface::newDataFunction(std::string varname) const { return std::shared_ptr<solvers::FunctionInterface>(nullptr); } std::shared_ptr<solvers::FunctionInterface> ApplicationInterface::newExactSolution(std::string varname) const { return std::shared_ptr<solvers::FunctionInterface>(nullptr); } const InitialConditionInterface& ApplicationInterface::getInitialCondition(int ivar)const{return *_initialconditions[ivar].get();} const RightHandSideInterface& ApplicationInterface::getRightHandSide(int ivar)const{assert(ivar<_righthandsides.size());return *_righthandsides[ivar].get();} const DirichletInterface& ApplicationInterface::getDirichlet(int ivar)const{assert(ivar<_dirichlets.size()); return *_dirichlets[ivar].get();} const NeumannInterface& ApplicationInterface::getNeumann(int ivar)const{assert(ivar<_neumanns.size()); return *_neumanns[ivar].get();} const FunctionInterface& ApplicationInterface::getDataFunction(int ivar)const{assert(ivar<_datafunctions.size()); return *_datafunctions[ivar].get();} const solvers::FunctionInterface& ApplicationInterface::getExactSolution(int ivar)const { assert(_exactsolutions[ivar]); return *_exactsolutions[ivar].get(); } solvers::FunctionInterface& ApplicationInterface::getExactSolution(int ivar) { assert(_exactsolutions[ivar]); return *_exactsolutions[ivar].get(); } const InitialConditionInterface& ApplicationInterface::getInitialCondition(std::string varname)const { return *_initialconditions[_indexofvar[varname]].get(); } const RightHandSideInterface& ApplicationInterface::getRightHandSide(std::string varname)const { return *_righthandsides[_indexofvar[varname]].get(); } const DirichletInterface& ApplicationInterface::getDirichlet(std::string varname)const { return *_dirichlets[_indexofvar[varname]].get(); } const NeumannInterface& ApplicationInterface::getNeumann(std::string varname)const { return *_neumanns[_indexofvar[varname]].get(); } const FunctionInterface& ApplicationInterface::getDataFunction(std::string varname)const { assert(_datafunctions[_indexofdatavar[varname]]); return *_datafunctions[_indexofdatavar[varname]]; } const solvers::FunctionInterface& ApplicationInterface::getExactSolution(std::string varname)const { return *_exactsolutions[_indexofvar[varname]].get(); } solvers::FunctionInterface& ApplicationInterface::getExactSolution(std::string varname) { return *_exactsolutions[_indexofvar[varname]].get(); } bool ApplicationInterface::hasInitialCondition(int ivar)const { assert(ivar<_initialconditions.size()); return _initialconditions[ivar] != nullptr; } bool ApplicationInterface::hasDataFunction(int ivar)const { assert(ivar<_datafunctions.size()); return _datafunctions[ivar] != nullptr; } bool ApplicationInterface::hasExactSolution(int ivar)const { assert(ivar<_exactsolutions.size()); return _exactsolutions[ivar] != nullptr; } bool ApplicationInterface::hasExactSolution(std::string varname)const { return hasExactSolution(_indexofvar[varname]); } bool ApplicationInterface::hasRightHandSide(int ivar)const{return _righthandsides[ivar] != nullptr;} bool ApplicationInterface::hasDirichlet(int ivar)const{return _dirichlets[ivar] != nullptr;} const alat::IntSet& ApplicationInterface::getStrongDirichletColor() const {return _dircolors;} /*--------------------------------------------------------------------------*/ void ApplicationInterface::initApplication(const mesh::MeshUnitInterface* mesh, const alat::StringVector& varnames, const alat::StringVector& varnamesdata, const alat::armaivec& ncomps, const alat::armaivec& ncompsdata) { _mesh=mesh; int nvars = varnames.size(); _initialconditions.set_size(nvars); _righthandsides.set_size(nvars); _dirichlets.set_size(nvars); _neumanns.set_size(nvars); _exactsolutions.set_size(nvars); int dim = _mesh->getDimension(); for(int ivar=0;ivar<nvars;ivar++) { std::string varname = varnames[ivar]; _indexofvar[varname] = ivar; _exactsolutions[ivar] = newExactSolution(varname); _initialconditions[ivar] = newInitialCondition(varname); _righthandsides[ivar] = newRightHandSide(varname); _dirichlets[ivar] = newDirichlet(varname); _neumanns[ivar] = newNeumann(varname); if(_initialconditions[ivar]) {_initialconditions[ivar]->setNcompAndDim(ncomps[ivar], dim);} if(_righthandsides[ivar]) {_righthandsides[ivar]->setNcompAndDim(ncomps[ivar], dim);} if(_dirichlets[ivar]) {_dirichlets[ivar]->setNcompAndDim(ncomps[ivar], dim);} if(_neumanns[ivar]) {_neumanns[ivar]->setNcompAndDim(ncomps[ivar], dim);} } int nvarsdata = varnamesdata.size(); _datafunctions.set_size(nvarsdata); for(int ivar=0;ivar<nvarsdata;ivar++) { std::string varname = varnamesdata[ivar]; _indexofdatavar[varname] = ivar; _datafunctions[ivar] = newDataFunction(varname); if(_datafunctions[ivar]) {_datafunctions[ivar]->setNcompAndDim(ncompsdata[ivar], dim);} } _dircolors.clear(); for(mesh::MeshUnitInterface::BoundaryInformationMap::const_iterator p=_mesh->getBoundaryInformationMap().begin();p!=_mesh->getBoundaryInformationMap().end();p++) { int color = p->first; if(isStrongDirichlet(color)) _dircolors.insert(color); } } /*--------------------------------------------------------------------------*/ std::string ApplicationInterface::getInfo() const { std::stringstream ss; ss << "\t RightHandSides: "; int nvars = _righthandsides.size(); for(int ivar=0;ivar<nvars;ivar++) { if(_righthandsides[ivar]) { ss << _righthandsides[ivar]->getClassName() << " "; } else { ss << " NULL "; } } ss << "\n\t Dirichlets: "; for(int ivar=0;ivar<nvars;ivar++) { if(_dirichlets[ivar]) { ss << _dirichlets[ivar]->getClassName() << " "; } else { ss << " NULL "; } } ss << "\n\t Neumanns: "; for(int ivar=0;ivar<nvars;ivar++) { if(_neumanns[ivar]) { ss << _neumanns[ivar]->getClassName() << " "; } else { ss << " NULL "; } } ss << "\n\t Exactsolutoins: "; for(int ivar=0;ivar<nvars;ivar++) { if(_exactsolutions[ivar]) { ss << _exactsolutions[ivar]->getClassName() << " "; } else { ss << " NULL "; } } return ss.str(); }
36.486364
219
0.722935
beckerrh
0c1a63aa55eb99305c8b4e17f2e422ba46d74a22
3,923
hxx
C++
inetcore/mshtml/src/site/text/fontcache.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/mshtml/src/site/text/fontcache.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/mshtml/src/site/text/fontcache.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#ifndef I_FONTCACHE_HXX_ #define I_FONTCACHE_HXX_ #pragma INCMSG("--- Beg 'fontcache.hxx'") class CCcs; class CBaseCcs; // These definitions are for the face cache held within the font cache. // This is used to speed up the ApplyFontFace() function used during // format calculation. typedef struct _FACECACHE { LONG _latmFaceName; // Pack it tight. union { BYTE _bFlagsVar; struct { BYTE _fExplicitFace : 1; BYTE _fNarrow : 1; }; }; BYTE _bCharSet; BYTE _bPitchAndFamily; } FACECACHE; enum { FC_SIDS_DOWNLOADEDFONT = 0x0001, FC_SIDS_USEMLANG = 0x0002 }; MtExtern(CFontCache); //---------------------------------------------------------------------------- // class CFontCache //---------------------------------------------------------------------------- class CFontCache { friend class CCcs; friend class CBaseCcs; public: CFontCache(); ~CFontCache(); HRESULT Init(); void DeInit(); void FreeScriptCaches(); void ClearFontCache(); void ClearFaceCache(); public: BOOL GetCcs (CCcs* pccs, XHDC hdc, CDocInfo * pdci, const CCharFormat * const pcf); BOOL GetFontLinkCcs(CCcs* pccs, XHDC hdc, CDocInfo * pdci, CCcs * pccsBase, const CCharFormat * const pcf); CBaseCcs* GetBaseCcs(XHDC hdc, CDocInfo * pdci, const CCharFormat * const pcf, const CBaseCcs * const pBaseBaseCcs, BOOL fForceTTFont); LONG GetAtomFromFaceName(const TCHAR* szFaceName); LONG FindAtomFromFaceName(const TCHAR* szFaceName); const TCHAR * GetFaceNameFromAtom(LONG latmFontInfo); SCRIPT_IDS EnsureScriptIDsForFont(XHDC hdc, const CBaseCcs * pccs, DWORD dwFlags, BOOL * pfHKSCSHack = NULL); LONG GetAtomWingdings(); WHEN_DBG(void DumpFontInfo() { _atFontInfo.Dump(); }); //private: CBaseCcs* GrabInitNewBaseCcs(XHDC hdc, const CCharFormat * const pcf, CDocInfo * pdci, LONG latmBaseFace, BOOL fForceTTFont); //private: enum { cFontCacheSize = 16, cFontFaceCacheSize = 3, cQuickCrcSearchSize = 31 // Must be 2^n - 1 for quick MOD operation, it is a simple hash. }; struct { BYTE bCrc; CBaseCcs *pBaseCcs; } quickCrcSearch[cQuickCrcSearchSize+1]; CRITICAL_SECTION _cs; CRITICAL_SECTION _csOther; // critical section used by cccs stored in rpccs CRITICAL_SECTION _csFaceCache; // face name cache guard // critical section used for quick face name resolution CRITICAL_SECTION _csFaceNames; unsigned long _lCSInited; // Track how many of the Critical Sections need to be cleaned up CBaseCcs * _rpBaseCcs[cFontCacheSize]; DWORD _dwAgeNext; FACECACHE _fcFaceCache[cFontFaceCacheSize]; int _iCacheLen; // increments until equal to CACHEMAX int _iCacheNext; // The next available spot. #if DBG == 1 int _iCacheHitCount; LONG _cCccsReplaced; #endif // // Cached atom values for global font atoms. // These are put in the table lazilly // LONG _latmWingdings; CFontInfoCache _atFontInfo; }; //---------------------------------------------------------------------------- extern CFontCache g_FontCache; inline CFontCache & fc() { return g_FontCache; } #pragma INCMSG("--- End 'fontcache.hxx'") #else #pragma INCMSG("*** Dup 'fontcache.hxx'") #endif
28.845588
117
0.544481
npocmaka
0c1a81f55bd4c87c63a37af2ba676373bd8308f2
1,391
cpp
C++
cpp/prime_factors.cpp
scoraig52/code
c9335071266267227b56e48861a4f188d16ca4a4
[ "MIT" ]
2
2021-02-18T04:42:40.000Z
2021-12-12T00:27:42.000Z
cpp/prime_factors.cpp
akar-0/code
be15d79e7c9de107cc66cbdfcb3ae91a799607dd
[ "MIT" ]
null
null
null
cpp/prime_factors.cpp
akar-0/code
be15d79e7c9de107cc66cbdfcb3ae91a799607dd
[ "MIT" ]
1
2021-11-20T10:24:09.000Z
2021-11-20T10:24:09.000Z
using namespace std; #include <unordered_map> #include <vector> #include <cmath> using namespace std; unordered_map<int,unsigned> factors(int n) { vector<int> arr; unordered_map<int, unsigned> count; // if (n<2) {return unordered_map<int, unsigned>();} int m=n, p=7, i=0; while (m%2 == 0){ arr.push_back(2); m /= 2; } while (m%3 == 0){ arr.push_back(3); m /= 3; } while (m%5 == 0){ arr.push_back(5); m /= 5; } int c[8]={4, 2, 4, 2, 4, 6, 2, 6}; while (m!=1 || p*p<=n) { while (!(m%p)){ m/=p; arr.push_back(p); } p+=c[i]; i=(i+1)%8; } if (m>1) {arr.push_back(n);} for (int k: arr) {count[k]++;} return count; } std::vector<int> prime_factors(long n){ if (isPrime(n)) //A FINIR vector< int > arr; int p=3; if (n<2){ return arr; } while (n%2 == 0){ arr.push_back(2); n /= 2; } while (n%3 == 0){ arr.push_back(3); n /= 3; } while (p*p<=n){ while (n % p == 0){ arr.push_back(p); n /= p; } p += 2; } if (n != 1){arr.push_back(n);} return arr; } bool isPrime(int n){ if (n<2){return false;} if (n==2||n==3||n==5||n==7){return true;} if (!(n%2)||!(n%3)||!(n%5)||!(n%7)){return false;} int c[8]={4, 2, 4, 2, 4, 6, 2, 6}, p=7, i=0; while (p*p<=n) { if (!(n%p)){return false;} p+=c[i]; i=(i+1)%8; } return true; }
17.17284
53
0.483106
scoraig52
0c1cde67c4607587c8bff564ac0f6c1e2868ddd2
4,493
cpp
C++
source/gameos/src/winmain.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
38
2015-04-10T13:31:03.000Z
2021-09-03T22:34:05.000Z
source/gameos/src/winmain.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
1
2020-07-09T09:48:44.000Z
2020-07-12T12:41:43.000Z
source/gameos/src/winmain.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
12
2015-06-29T08:06:57.000Z
2021-10-13T13:11:41.000Z
/******************************************************************************* This file consist of reversed and interpreted code from object source in the x86 debug build gameos.lib. The code in this file can not be used in any way other than serve as an information reference to the original released source of Mechcommander2. The code is a work of progress and there is no guarantee it is complete, accurate or useful in any way. The purpose is instead to make it possible to safely remove any dependencies of gameos.lib from Mechcommander2. All code is logically copyrighted to Microsoft *******************************************************************************/ /******************************************************************************* winmain.cpp - GameOS reference pseudo code MechCommander;source code ;-07-24 Jerker Back, created *******************************************************************************/ #include "stdinc.h" #include "texture_manager.hpp" #include "platform.hpp" #include "windows.hpp" // ----------------------------------------------------------------------------- // Global data exported from this module MECH_IMPEXP PlatformType Platform; MECH_IMPEXP char ApplicationName[256]; MECH_IMPEXP char AssetsDirectory1[MAX_PATH]; MECH_IMPEXP char AssetsDirectory2[MAX_PATH]; MECH_IMPEXP char ImageHelpPath[MAX_PATH]; MECH_IMPEXP bool gNoBlade; // global referenced data not listed in headers MECH_IMPEXP uint32_t gDirectX7; MECH_IMPEXP uint32_t gDisableForceFeedback; // local data int64_t TUploadTexture; char MachineInfoFile[MAX_PATH]; int64_t TRenderTextures; int64_t TMipmapTexture; char InitialLogFile[256]; char PauseSpewOn[256]; int64_t TConvertTexture; int64_t volatile TimeMM; char SpewOptions[256]; int64_t volatile TimeControls; void (*DoScriptUpdate)(int32_t); uint32_t gNoFree; uint32_t StartupMemory; uint32_t gLoadAllSymbols; uint32_t gDisableJoystick; uint32_t gNumberCompatFlags; uint32_t gCompatFlags; uint32_t gCompatFlags1; uint32_t RenderersSkipped; uint32_t gNoFPU; uint32_t gEnableGosView; uint32_t gUseBlade; uint32_t gStartWithLog; uint32_t gEnableSpew; uint32_t gDisableSound; uint32_t LastModalLoop; uint32_t ModalLoop; uint32_t gDisableRDTSC; uint32_t gLocalize; bool PerfCounters; bool RealTerminate; bool gShowAllocations; bool gUse3D; uint32_t InGameLogicCounter; bool gPauseSpew; bool gNoDialogs; bool gDumpMachineInfo; int64_t volatile TimeScripts; int64_t volatile TimeScriptsUpdate; int64_t volatile TimeGameLogic; int64_t volatile TimeNetwork; int64_t volatile TimeGameOS; int64_t volatile TimeSoundStream; int64_t volatile TimeGameOS1; int64_t volatile TimeDebugger; int64_t volatile TimeRenderers; int64_t volatile TimeOutSideLoop; int64_t volatile StartTimeOutSideLoop; int64_t volatile TimeDisplay; int64_t volatile TimeWindows; int64_t volatile TimeEndScene; int64_t volatile TimeFont3D; int64_t volatile TimeD3D; int64_t volatile TimeDXShow; int64_t volatile TimeElementRenderers; uint32_t ModalScripts; uint32_t SavedSP; uint32_t SavedBP; bool RunFullScreen; // ----------------------------------------------------------------------------- // global implemented functions in this module listed in headers MECH_IMPEXP void _stdcall RunFromOtherApp(HINSTANCE hinstance, HWND hwnd, PSTR commandline); MECH_IMPEXP int32_t _stdcall RunFromWinMain( HINSTANCE hinstance, HINSTANCE hPrevInstance, PSTR commandline, int32_t nCmdShow); MECH_IMPEXP void __stdcall RestartGameOS(void); MECH_IMPEXP void __stdcall gos_UpdateDisplay(bool Everything); MECH_IMPEXP uint32_t __stdcall RunGameOSLogic(void); MECH_IMPEXP void __stdcall gos_TerminateApplication(void); MECH_IMPEXP void __stdcall gos_AbortTermination(void); MECH_IMPEXP uint8_t __stdcall gos_UserExit(void); MECH_IMPEXP uint8_t __stdcall gos_RunMainLoop(void(__stdcall* DoGameLogic)(void) = nullptr); // inline void __stdcall InitTextureManager(void) // inline void __stdcall DestroyTextureManager(void); // global implemented functions not listed in headers // local functions static int32_t __stdcall CheckOption(PSTR substr); static void __stdcall InitializeGOS(HINSTANCE hinstance, PSTR commandline); static void __stdcall ProfileRenderStart(void); static int64_t __stdcall ProfileRenderEnd(int64_t); static uint32_t __stdcall InternalRunGameOSLogic(void(__stdcall* DoGameLogic)(void)); // ----------------------------------------------------------------------------- // externals referenced in this file not specified in headers
34.829457
92
0.732918
mechasource
0c1cf45447ae41123638fe8c231d053cd93601c7
19,947
cpp
C++
reference/1bitstudio-20190604/src/1bs_pulsesynth/pulsesynth.cpp
linuxmao-org/shiru-plugins
08853f99140012234649e67e5647906fda74f6cc
[ "WTFPL" ]
11
2019-06-15T06:36:36.000Z
2022-02-22T04:49:22.000Z
reference/1bitstudio-20190604/src/1bs_pulsesynth/pulsesynth.cpp
nyxkn/shiru-plugins
8088c04b94afb498cec6a14bd03c448936bf31e9
[ "WTFPL" ]
6
2019-06-15T14:04:49.000Z
2019-11-27T15:35:13.000Z
reference/1bitstudio-20190604/src/1bs_pulsesynth/pulsesynth.cpp
nyxkn/shiru-plugins
8088c04b94afb498cec6a14bd03c448936bf31e9
[ "WTFPL" ]
2
2020-12-30T00:21:35.000Z
2021-07-04T18:32:46.000Z
#include "PulseSynth.h" AudioEffect* createEffectInstance(audioMasterCallback audioMaster) { return new PulseSynth(audioMaster); } PulseSynth::PulseSynth(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, NUM_PROGRAMS, NUM_PARAMS) { VstInt32 pgm,chn; setNumInputs(NUM_INPUTS); setNumOutputs(NUM_OUTPUTS); setUniqueID(PLUGIN_UID); isSynth(); canProcessReplacing(); programsAreChunks(true); Program=0; LoadPresetChunk((float*)ChunkPresetData); for(pgm=0;pgm<NUM_PROGRAMS;++pgm) { strcpy(ProgramName[pgm],programDefaultNames[pgm]); /*pAttack [pgm]=0; pDecay [pgm]=0; pSustain [pgm]=1.0f; pRelease [pgm]=0; pPulseWidth[pgm]=.25f; pDetune [pgm]=.5f; pLowBoost [pgm]=0; pPolyphony [pgm]=1.0f; pSlideSpeed[pgm]=1.0f; pOutputGain[pgm]=1.0f;*/ } for(chn=0;chn<SYNTH_CHANNELS;++chn) { SynthChannel[chn].note=-1; SynthChannel[chn].freq=0; SynthChannel[chn].freq_new=0; SynthChannel[chn].acc=0; SynthChannel[chn].e_stage=eStageReset; SynthChannel[chn].e_delta=0; SynthChannel[chn].e_level=0; SynthChannel[chn].pulse=0; SynthChannel[chn].volume=1.0f; } sEnvelopeDiv=0; MidiQueue.clear(); MidiRPNLSB=0; MidiRPNMSB=0; MidiDataLSB=0; MidiDataMSB=0; MidiPitchBend=0; MidiPitchBendRange=2.0f; MidiModulationDepth=0; MidiModulationCount=0; sSlideStep=0; memset(MidiKeyState,0,sizeof(MidiKeyState)); suspend(); } PulseSynth::~PulseSynth() { } void PulseSynth::setParameter(VstInt32 index,float value) { switch(index) { case pIdAttack: pAttack [Program]=value; break; case pIdDecay: pDecay [Program]=value; break; case pIdSustain: pSustain [Program]=value; break; case pIdRelease: pRelease [Program]=value; break; case pIdPulseWidth: pPulseWidth[Program]=value; break; case pIdDetune: pDetune [Program]=value; break; case pIdLowBoost: pLowBoost [Program]=value; break; case pIdPolyphony: pPolyphony [Program]=value; break; case pIdPortaSpeed: pPortaSpeed[Program]=value; break; case pIdOutputGain: pOutputGain[Program]=value; break; } } float PulseSynth::getParameter(VstInt32 index) { switch(index) { case pIdAttack: return pAttack [Program]; case pIdDecay: return pDecay [Program]; case pIdSustain: return pSustain [Program]; case pIdRelease: return pRelease [Program]; case pIdPulseWidth: return pPulseWidth[Program]; case pIdDetune: return pDetune [Program]; case pIdLowBoost: return pLowBoost [Program]; case pIdPolyphony: return pPolyphony [Program]; case pIdPortaSpeed: return pPortaSpeed[Program]; case pIdOutputGain: return pOutputGain[Program]; } return 0; } void PulseSynth::getParameterName(VstInt32 index,char *label) { switch(index) { case pIdAttack: strcpy(label,"Attack time"); break; case pIdDecay: strcpy(label,"Decay time"); break; case pIdSustain: strcpy(label,"Sustain level"); break; case pIdRelease: strcpy(label,"Release time"); break; case pIdPulseWidth: strcpy(label,"Pulse width"); break; case pIdDetune: strcpy(label,"Detune"); break; case pIdLowBoost: strcpy(label,"Boost low end"); break; case pIdPolyphony: strcpy(label,"Polyphony"); break; case pIdPortaSpeed: strcpy(label,"Porta speed"); break; case pIdOutputGain: strcpy(label,"Output gain"); break; default: strcpy(label,""); } } void PulseSynth::getParameterDisplay(VstInt32 index,char *text) { switch(index) { case pIdAttack: float2string(ENVELOPE_ATTACK_MAX_MS*pAttack[Program],text,6); break; case pIdDecay: float2string(ENVELOPE_DECAY_MAX_MS*pDecay[Program],text,6); break; case pIdSustain: float2string(pSustain[Program],text,5); break; case pIdRelease: float2string(ENVELOPE_RELEASE_MAX_MS*pRelease[Program],text,5); break; case pIdPulseWidth: float2string(PULSE_WIDTH_MAX_US*pPulseWidth[Program],text,5); break; case pIdDetune: float2string(-1.0f+pDetune[Program]*2.0f,text,5); break; case pIdLowBoost: strcpy(text,pLowBoost[Program]<.5f?"Disabled":"Enabled"); break; case pIdPolyphony: strcpy(text,pPolyphonyModeNames[(int)(pPolyphony[Program]*2.99f)]); break; case pIdPortaSpeed: float2string(pPortaSpeed[Program],text,5); break; case pIdOutputGain: dB2string(pOutputGain[Program],text,3); break; default: strcpy(text,""); } } void PulseSynth::getParameterLabel(VstInt32 index,char *label) { switch(index) { case pIdAttack: case pIdDecay: case pIdRelease: strcpy(label,"ms"); break; case pIdPulseWidth: strcpy(label,"us"); break; case pIdOutputGain: strcpy(label,"dB"); break; default: strcpy(label,""); } } VstInt32 PulseSynth::getProgram(void) { return Program; } void PulseSynth::setProgram(VstInt32 program) { Program=program; } void PulseSynth::getProgramName(char* name) { strcpy(name,ProgramName[Program]); } void PulseSynth::setProgramName(char* name) { strncpy(ProgramName[Program],name,MAX_NAME_LEN); ProgramName[Program][MAX_NAME_LEN-1]='\0'; } VstInt32 PulseSynth::canDo(char* text) { if(!strcmp(text,"receiveVstEvents" )) return 1; if(!strcmp(text,"receiveVstMidiEvent")) return 1; return -1; } VstInt32 PulseSynth::getNumMidiInputChannels(void) { return 1;//monophonic } VstInt32 PulseSynth::getNumMidiOutputChannels(void) { return 0;//no MIDI output } VstInt32 PulseSynth::SaveStringChunk(char *str,float *dst) { VstInt32 i; for(i=0;i<(VstInt32)strlen(str);++i) *dst++=str[i]; *dst++=0; return (VstInt32)strlen(str)+1; } VstInt32 PulseSynth::LoadStringChunk(char *str,int max_length,float *src) { unsigned int c,ptr; ptr=0; while(1) { c=(unsigned int)*src++; str[ptr++]=c; if(!c) break; if(ptr==max_length-1) { str[ptr]=0; break; } } return ptr; } VstInt32 PulseSynth::SavePresetChunk(float *chunk) { int ptr,pgm; ptr=0; chunk[ptr++]=DATA; for(pgm=0;pgm<NUM_PROGRAMS;++pgm) { chunk[ptr++]=PROG; chunk[ptr++]=(float)pgm; chunk[ptr++]=NAME; ptr+=SaveStringChunk(ProgramName[pgm],&chunk[ptr]); chunk[ptr++]=EATT; chunk[ptr++]=pAttack [pgm]; chunk[ptr++]=EDEC; chunk[ptr++]=pDecay [pgm]; chunk[ptr++]=ESUS; chunk[ptr++]=pSustain [pgm]; chunk[ptr++]=EREL; chunk[ptr++]=pRelease [pgm]; chunk[ptr++]=PWDT; chunk[ptr++]=pPulseWidth[pgm]; chunk[ptr++]=DETU; chunk[ptr++]=pDetune [pgm]; chunk[ptr++]=LOWB; chunk[ptr++]=pLowBoost [pgm]; chunk[ptr++]=POLY; chunk[ptr++]=pPolyphony [pgm]; chunk[ptr++]=POSP; chunk[ptr++]=pPortaSpeed[pgm]; chunk[ptr++]=GAIN; chunk[ptr++]=pOutputGain[pgm]; } chunk[ptr++]=DONE; /* FILE *file=fopen("g:/params.txt","wt"); fprintf(file,"DATA,\n\n"); for(pgm=0;pgm<NUM_PROGRAMS;++pgm) { fprintf(file,"PROG,%i,\n",pgm); fprintf(file,"EATT,%1.3ff,",pAttack [pgm]); fprintf(file,"EDEC,%1.3ff,",pDecay [pgm]); fprintf(file,"ESUS,%1.3ff,",pSustain [pgm]); fprintf(file,"EREL,%1.3ff,",pRelease [pgm]); fprintf(file,"PWDT,%1.3ff,",pPulseWidth[pgm]); fprintf(file,"DETU,%1.3ff,",pDetune [pgm]); fprintf(file,"LOWB,%1.3ff,",pLowBoost [pgm]); fprintf(file,"POLY,%1.3ff,",pPolyphony [pgm]); fprintf(file,"POSP,%1.3ff,",pPortaSpeed[pgm]); fprintf(file,"GAIN,%1.3ff,",pOutputGain[pgm]); fprintf(file,"\n"); } fprintf(file,"\nDONE"); fclose(file); */ return ptr*sizeof(float);//size in bytes } void PulseSynth::LoadPresetChunk(float *chunk) { int pgm; float tag; //default parameters for legacy data support for(pgm=0;pgm<NUM_PROGRAMS;++pgm) { pLowBoost[pgm]=0; } if(chunk[0]!=DATA) //load legacy data { for(pgm=0;pgm<NUM_PROGRAMS;++pgm) { pAttack [pgm]=*chunk++; pDecay [pgm]=*chunk++; pSustain [pgm]=*chunk++; pRelease [pgm]=*chunk++; pPulseWidth[pgm]=*chunk++; pDetune [pgm]=*chunk++; pPolyphony [pgm]=*chunk++; pPortaSpeed[pgm]=*chunk++; pOutputGain[pgm]=*chunk++; } } else //load normal data { while(1) { tag=*chunk++; if(tag==DONE) break; if(tag==PROG) pgm =(int)*chunk++; if(tag==NAME) chunk+=LoadStringChunk(ProgramName[pgm],MAX_NAME_LEN,chunk); if(tag==EATT) pAttack [pgm]=*chunk++; if(tag==EDEC) pDecay [pgm]=*chunk++; if(tag==ESUS) pSustain [pgm]=*chunk++; if(tag==EREL) pRelease [pgm]=*chunk++; if(tag==PWDT) pPulseWidth[pgm]=*chunk++; if(tag==DETU) pDetune [pgm]=*chunk++; if(tag==LOWB) pLowBoost [pgm]=*chunk++; if(tag==POLY) pPolyphony [pgm]=*chunk++; if(tag==POSP) pPortaSpeed[pgm]=*chunk++; if(tag==GAIN) pOutputGain[pgm]=*chunk++; } } } VstInt32 PulseSynth::getChunk(void** data,bool isPreset) { int size; size=SavePresetChunk(Chunk); *data=Chunk; return size; } VstInt32 PulseSynth::setChunk(void* data,VstInt32 byteSize,bool isPreset) { if(byteSize>sizeof(Chunk)) return 0; memcpy(Chunk,data,byteSize); LoadPresetChunk(Chunk); return 0; } void PulseSynth::MidiAddNote(VstInt32 delta,VstInt32 note,VstInt32 velocity) { MidiQueueStruct entry; entry.type =mEventTypeNote; entry.delta =delta; entry.note =note; entry.velocity=velocity;//0 for key off MidiQueue.push_back(entry); } void PulseSynth::MidiAddProgramChange(VstInt32 delta,VstInt32 program) { MidiQueueStruct entry; entry.type =mEventTypeProgram; entry.delta =delta; entry.program=program; MidiQueue.push_back(entry); } void PulseSynth::MidiAddPitchBend(VstInt32 delta,float depth) { MidiQueueStruct entry; entry.type =mEventTypePitchBend; entry.delta=delta; entry.depth=depth; MidiQueue.push_back(entry); } void PulseSynth::MidiAddModulation(VstInt32 delta,float depth) { MidiQueueStruct entry; entry.type =mEventTypeModulation; entry.delta=delta; entry.depth=depth; MidiQueue.push_back(entry); } bool PulseSynth::MidiIsAnyKeyDown(void) { int i; for(i=0;i<128;++i) if(MidiKeyState[i]) return true; return false; } VstInt32 PulseSynth::processEvents(VstEvents* ev) { VstMidiEvent* event; VstInt32 i,status,note,velocity,wheel; char* midiData; for(i=0;i<ev->numEvents;++i) { event=(VstMidiEvent*)ev->events[i]; if(event->type!=kVstMidiType) continue; midiData=event->midiData; status=midiData[0]&0xf0; switch(status) { case 0x80://note off case 0x90://note on { note=midiData[1]&0x7f; velocity=midiData[2]&0x7f; if(status==0x80) velocity=0; MidiAddNote(event->deltaFrames,note,velocity); } break; case 0xb0://control change { if(midiData[1]==0x64) MidiRPNLSB =midiData[2]&0x7f; if(midiData[1]==0x65) MidiRPNMSB =midiData[2]&0x7f; if(midiData[1]==0x26) MidiDataLSB=midiData[2]&0x7f; if(midiData[1]==0x01) { MidiModulationMSB=midiData[2]&0x7f; MidiAddModulation(event->deltaFrames,(float)MidiModulationMSB/128.0f); } if(midiData[1]==0x06) { MidiDataMSB=midiData[2]&0x7f; if(MidiRPNLSB==0&&MidiRPNMSB==0) MidiPitchBendRange=(float)MidiDataMSB*.5f; } if(midiData[1]>=0x7b)//all notes off and mono/poly mode changes that also requires to do all notes off { MidiAddNote(event->deltaFrames,-1,0); } } break; case 0xc0: //program change { MidiAddProgramChange(event->deltaFrames,midiData[1]&0x7f); } break; case 0xe0://pitch bend change { wheel=(midiData[1]&0x7f)|((midiData[2]&0x7f)<<7); MidiAddPitchBend(event->deltaFrames,(float)(wheel-0x2000)*MidiPitchBendRange/8192.0f); } break; } } return 1; } VstInt32 PulseSynth::SynthAllocateVoice(VstInt32 note) { VstInt32 chn; for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].note==note) return chn; for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].note<0) return chn; for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].e_stage==eStageRelease) return chn; return -1; } void PulseSynth::SynthChannelChangeNote(VstInt32 chn,VstInt32 note) { SynthChannel[chn].note=note; if(note>=0) { SynthChannel[chn].freq_new=(float)SynthChannel[chn].note-69; sSlideStep=(SynthChannel[chn].freq-SynthChannel[chn].freq_new)*20.0f*log(1.0f-pPortaSpeed[Program]); } } float PulseSynth::SynthEnvelopeTimeToDelta(float value,float max_ms) { return (1.0f/ENVELOPE_UPDATE_RATE_HZ)/(value*max_ms/1000.0f); } void PulseSynth::SynthRestartEnvelope(VstInt32 chn) { if(pAttack[Program]>0||pDecay[Program]>0) { SynthChannel[chn].e_stage=eStageAttack; SynthChannel[chn].e_level=0; SynthChannel[chn].e_delta=SynthEnvelopeTimeToDelta(pAttack[Program],ENVELOPE_ATTACK_MAX_MS); } else { SynthChannel[chn].e_stage=eStageSustain; SynthChannel[chn].e_level=pSustain[Program]; } } void PulseSynth::SynthStopEnvelope(VstInt32 chn) { SynthChannel[chn].e_stage=eStageRelease; SynthChannel[chn].e_delta=SynthEnvelopeTimeToDelta(pRelease[Program],ENVELOPE_RELEASE_MAX_MS); } void PulseSynth::SynthAdvanceEnvelopes(void) { VstInt32 chn; for(chn=0;chn<SYNTH_CHANNELS;++chn) { if(SynthChannel[chn].e_stage==eStageReset) { SynthChannel[chn].note=-1; SynthChannel[chn].e_level=0; } else { switch(SynthChannel[chn].e_stage) { case eStageAttack: { SynthChannel[chn].e_level+=SynthChannel[chn].e_delta; if(SynthChannel[chn].e_level>=1.0f) { SynthChannel[chn].e_level=1.0f; SynthChannel[chn].e_delta=SynthEnvelopeTimeToDelta(pDecay[Program],ENVELOPE_DECAY_MAX_MS); SynthChannel[chn].e_stage=eStageDecay; } } break; case eStageDecay: { SynthChannel[chn].e_level-=SynthChannel[chn].e_delta; if(SynthChannel[chn].e_level<=pSustain[Program]) { SynthChannel[chn].e_level=pSustain[Program]; SynthChannel[chn].e_stage=eStageSustain; } } break; case eStageRelease: { SynthChannel[chn].e_level-=SynthChannel[chn].e_delta; if(SynthChannel[chn].e_level<=0) SynthChannel[chn].e_stage=eStageReset; } break; } } } } void PulseSynth::processReplacing(float **inputs,float **outputs,VstInt32 sampleFrames) { float *outL=outputs[0]; float *outR=outputs[1]; float level,pulsefix,modulation,mod_step,sampleRate; unsigned int i,s,poly,out; int chn,note,prev_note; bool key_off; sampleRate=(float)updateSampleRate(); mod_step=12.0f/sampleRate*(float)M_PI; poly=(int)(pPolyphony[Program]*2.99f); pulsefix=sampleRate*PULSE_WIDTH_MAX_US*OVERSAMPLING*pPulseWidth[Program]; while(--sampleFrames>=0) { if(MidiModulationDepth>=.01f) modulation=sinf(MidiModulationCount)*MidiModulationDepth; else modulation=0; MidiModulationCount+=mod_step; key_off=false; for(i=0;i<MidiQueue.size();++i) { if(MidiQueue[i].delta>=0) { --MidiQueue[i].delta; if(MidiQueue[i].delta<0)//new message { switch(MidiQueue[i].type) { case mEventTypeNote: { if(MidiQueue[i].velocity)//key on { MidiKeyState[MidiQueue[i].note]=1; if(!poly) chn=0; else chn=SynthAllocateVoice(MidiQueue[i].note); if(chn>=0) { prev_note=SynthChannel[chn].note; SynthChannelChangeNote(chn,MidiQueue[i].note); if(prev_note<0||poly) SynthChannel[chn].freq=SynthChannel[chn].freq_new; if(poly||prev_note<0) { SynthChannel[chn].acc=0; //phase reset SynthChannel[chn].volume=((float)MidiQueue[i].velocity/100.0f); if(pLowBoost[Program]>=.5f) //even out energy spread to make lower end louder { SynthChannel[chn].volume*=.021f*pow(2.0f,(127.0f-MidiQueue[i].note)/12.0f); } SynthRestartEnvelope(chn); } } } else//key off { key_off=true; if(MidiQueue[i].note>=0) { MidiKeyState[MidiQueue[i].note]=0; if(poly) { for(chn=0;chn<SYNTH_CHANNELS;++chn) if(SynthChannel[chn].note==MidiQueue[i].note) SynthStopEnvelope(chn); } else { for(note=127;note>=0;--note) { if(MidiKeyState[note]) { SynthChannelChangeNote(0,note); break; } } } } else { memset(MidiKeyState,0,sizeof(MidiKeyState)); for(chn=0;chn<SYNTH_CHANNELS;++chn) SynthStopEnvelope(chn); } } } break; case mEventTypeProgram: { Program=MidiQueue[i].program; updateDisplay(); } break; case mEventTypePitchBend: { MidiPitchBend=MidiQueue[i].depth; } break; case mEventTypeModulation: { MidiModulationDepth=MidiQueue[i].depth/4.0f; } break; } } } } if(!poly&&key_off) { if(!MidiIsAnyKeyDown()) { for(chn=0;chn<SYNTH_CHANNELS;++chn) SynthStopEnvelope(chn); } } sEnvelopeDiv+=ENVELOPE_UPDATE_RATE_HZ/sampleRate; if(sEnvelopeDiv>=1.0f) { sEnvelopeDiv-=1.0f; SynthAdvanceEnvelopes(); } for(chn=0;chn<SYNTH_CHANNELS;++chn) { if(SynthChannel[chn].note<0) continue; if(pPortaSpeed[Program]>=1.0f) { SynthChannel[chn].freq=SynthChannel[chn].freq_new; } else { if(SynthChannel[chn].freq<SynthChannel[chn].freq_new) { SynthChannel[chn].freq+=sSlideStep/sampleRate; if(SynthChannel[chn].freq>SynthChannel[chn].freq_new) SynthChannel[chn].freq=SynthChannel[chn].freq_new; } if(SynthChannel[chn].freq>SynthChannel[chn].freq_new) { SynthChannel[chn].freq+=sSlideStep/sampleRate; if(SynthChannel[chn].freq<SynthChannel[chn].freq_new) SynthChannel[chn].freq=SynthChannel[chn].freq_new; } } SynthChannel[chn].add=440.0f*pow(2.0f,(SynthChannel[chn].freq+modulation+MidiPitchBend+pDetune[Program]*2.0f-1.0f)/12.0f)/sampleRate/OVERSAMPLING; } level=0; if(poly<2) //poly PWM { for(s=0;s<OVERSAMPLING;++s) { out=0; for(chn=0;chn<SYNTH_CHANNELS;++chn) { if(SynthChannel[chn].note<0) continue; SynthChannel[chn].acc+=SynthChannel[chn].add; while(SynthChannel[chn].acc>=1.0f) { SynthChannel[chn].acc-=1.0f; SynthChannel[0].pulse+=pulsefix*SynthChannel[chn].e_level*SynthChannel[chn].volume/1000000.0f; } } if(SynthChannel[0].pulse>0) { SynthChannel[0].pulse-=1.0f; out=1; } else { SynthChannel[0].pulse=0; } if(out) level+=1.0f/OVERSAMPLING; } } else //poly ADD { for(s=0;s<OVERSAMPLING;++s) { for(chn=0;chn<SYNTH_CHANNELS;++chn) { if(SynthChannel[chn].note<0) continue; SynthChannel[chn].acc+=SynthChannel[chn].add; while(SynthChannel[chn].acc>=1.0f) { SynthChannel[chn].acc-=1.0f; SynthChannel[chn].pulse+=pulsefix*SynthChannel[chn].e_level*SynthChannel[chn].volume/1000000.0f; } if(SynthChannel[chn].pulse>0) { SynthChannel[chn].pulse-=1.0f; level+=1.0f/OVERSAMPLING/(SYNTH_CHANNELS/4); } else { SynthChannel[chn].pulse=0; } } } } level=level*pOutputGain[Program]; (*outL++)=level; (*outR++)=level; } MidiQueue.clear(); }
21.895719
150
0.636437
linuxmao-org
0c2299151f3cc19d2e5fe05fe0551cbe7d80f95d
5,944
cc
C++
math/test/discrete_lyapunov_equation_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
math/test/discrete_lyapunov_equation_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
math/test/discrete_lyapunov_equation_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/math/discrete_lyapunov_equation.h" #include <limits> #include <stdexcept> #include <vector> #include <Eigen/Core> #include <gtest/gtest.h> #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/expect_no_throw.h" namespace drake { namespace math { namespace { using Eigen::MatrixXd; const double kTolerance = 5 * std::numeric_limits<double>::epsilon(); void SolveRealLyapunovEquationAndVerify(const Eigen::Ref<const MatrixXd>& A, const Eigen::Ref<const MatrixXd>& Q) { MatrixXd X{RealDiscreteLyapunovEquation(A, Q)}; // Check that X is symmetric. EXPECT_TRUE( CompareMatrices(X, X.transpose(), 0, MatrixCompareType::absolute)); // Check that X is the solution to the discrete time ARE. EXPECT_TRUE(CompareMatrices(A.transpose() * X * A - X, -Q, 5 * kTolerance * Q.norm(), MatrixCompareType::absolute)); } GTEST_TEST(RealDiscreteLyapunovEquation, ThrowInvalidSizedMatricesTest) { // This tests if the exceptions are thrown for invalidly sized matrices. A and // Q need to be square and of same size. const int n{1}, m{2}; // non-square A MatrixXd A1(n, m); A1 << 1, 1; MatrixXd Q1(m, m); Q1 << 1, 1, 1, 1; // non-square Q MatrixXd A2(m, m); A2 << 1, 1, 1, 1; MatrixXd Q2(n, m); Q2 << 1, 1; // not-same sized MatrixXd A3(m, m); A3 << 1, 1, 1, 1; MatrixXd Q3(n, n); Q3 << 1; std::vector<MatrixXd> As{A1, A2, A3}; std::vector<MatrixXd> Qs{Q1, Q2, Q3}; for (int i = 0; i < static_cast<int>(As.size()); ++i) { EXPECT_ANY_THROW(RealDiscreteLyapunovEquation(As[i], Qs[i])); } } GTEST_TEST(RealDiscreteLyapunovEquation, ThrowEigenValuesATest) { // Given the Eigenvalues of @param A as lambda_1, ..., lambda_n, then the // solution is unique if and only if lambda_i * lambda_j != 1 for all i, j. // (see Barraud, A.Y., "A numerical algorithm to solve AᵀXA - X = Q," IEEE® // Trans. Auto. Contr., AC-22, pp. 883-885, 1977.) // This tests if an exception is thrown if the eigenvalues violate this // requirement. const int n{3}; // pair of eigenvalues that multiplies to 1 MatrixXd A1(n, n); A1 << 1, 0, 0, 0, 1, 0, 0, 0, 1; // pairs of eigenvalues that multiply to ±i, i.e should not throw MatrixXd A2(n, n); A2 << 0.5, 0, 0, 0, 0, 2.0, 0, -2.0, 0; // pair of eigenvalues whose product is within tol of 1 MatrixXd A3(n, n); A3 << 1 + 1e-6, 0, 0, 0, 0.5, 0, 0, 0, 1 - 1e-6; // no pair of eigenvalues whose product is within tol of 1 MatrixXd A4(n, n); A4 << 1 + 1e-6, 0, 0, 0, 1 + 1e-6, 0, 0, 0, 1 + 1e-6; MatrixXd Q(n, n); Q << 1, 0, 0, 0, 1, 0, 0, 0, 1; EXPECT_ANY_THROW(RealDiscreteLyapunovEquation(A1, Q)); DRAKE_EXPECT_NO_THROW(RealDiscreteLyapunovEquation(A2, Q)); EXPECT_ANY_THROW(RealDiscreteLyapunovEquation(A3, Q)); DRAKE_EXPECT_NO_THROW(RealDiscreteLyapunovEquation(A4, Q)); } GTEST_TEST(RealDiscreteLyapunovEquation, Solve1by1Test) { // This is a simple 1-by-1 test case, it tests the internal 1-by-1 solver. const int n{1}; MatrixXd A(n, n); A << 0.5; MatrixXd Q(n, n); Q << 1; MatrixXd X(n, n); X << 4.0 / 3.0; EXPECT_TRUE( CompareMatrices(internal::Solve1By1RealDiscreteLyapunovEquation(A, Q), X, kTolerance, MatrixCompareType::absolute)); SolveRealLyapunovEquationAndVerify(A, Q); } GTEST_TEST(RealDiscreteLyapunovEquation, Solve2by2Test) { // This is a simple 2-by-2 test case, which tests the internal 2-by-2 solver. // The result is compared to the one generated by Matlab's dlyap function. const int n{2}; MatrixXd A(n, n); A << 0.5, -0.5, 0, 0.25; MatrixXd X(n, n); X << 4.0, 0, 0, 2.0 + 1.0 / 7.5; MatrixXd Q_internal(n, n); Q_internal << 3, 1, NAN, 1; EXPECT_TRUE(CompareMatrices( internal::Solve2By2RealDiscreteLyapunovEquation(A, Q_internal), X, kTolerance, MatrixCompareType::absolute)); MatrixXd Q(n, n); Q << 3, 1, 1, 1; EXPECT_TRUE(CompareMatrices(RealDiscreteLyapunovEquation(A, Q), X, kTolerance, MatrixCompareType::absolute)); SolveRealLyapunovEquationAndVerify(A.transpose(), Q); } GTEST_TEST(RealDiscreteLyapunovEquation, Solve3by3Test1) { // Tests if a 3-by-3 problem is reduced. const int n{3}; MatrixXd A(n, n); A << -0.5 * MatrixXd::Identity(n, n); MatrixXd Q(n, n); Q << MatrixXd::Identity(n, n); SolveRealLyapunovEquationAndVerify(A, Q); } GTEST_TEST(RealDiscreteLyapunovEquation, Solve3by3Test2) { // The system has eigenvalues: lambda_1/2 = -0 +/- 0.5i // and lambda_3 = -0.5. Therefore, there exists a 2-by-2 block on the // diagonal. // The compared solution is generated by matlab's dlyap function. int n{3}; MatrixXd A(n, n); A << 0.5, 0, 0, 0, 0, 0.5, 0, -0.5, 0; MatrixXd Q(n, n); Q << MatrixXd::Identity(n, n); MatrixXd X(n, n); X << (4.0 / 3.0) * MatrixXd::Identity(n, n); EXPECT_TRUE(CompareMatrices(RealDiscreteLyapunovEquation(A, Q), X, kTolerance, MatrixCompareType::absolute)); SolveRealLyapunovEquationAndVerify(A, Q); } GTEST_TEST(RealDiscreteLyapunovEquation, Solve4by4Test1) { // The system has eigenvalues: lambda_1/2 = -0.4500 +/- 0.7794i // and lambda_3/4 = -0.9. const int n{4}; MatrixXd A(n, n); A << -0.9, 0, 0, 0, 0, 0, 0.9, 0, 0, -0.9, -0.9, 0, 0, 0, 0, -0.9; MatrixXd Q(n, n); Q << MatrixXd::Identity(n, n); SolveRealLyapunovEquationAndVerify(A, Q); } GTEST_TEST(RealDiscreteLyapunovEquation, Solve4by4Test2) { // The system has eigenvalues: lambda_1/2 = 0.3 +/- 0.4i // and lambda_3/4 = 0.4 +/- 0.5i const int n{4}; MatrixXd A(n, n); A << 0.3, 0, 0, 0.4, 0, 0.4, 0.5, 0, 0, -0.5, 0.4, 0, -0.4, 0, 0, 0.3; MatrixXd Q(n, n); Q << MatrixXd::Identity(n, n); SolveRealLyapunovEquationAndVerify(A, Q); } } // namespace } // namespace math } // namespace drake
31.449735
80
0.642665
RobotLocomotion
0c2b42e4ea8cc821ef8692d0338feb6737dbf398
196
cpp
C++
examples/tetris/lib/Moon/src/cmp/cmp_base.cpp
KEGEStudios/Moon
0e6aa078c8bf876c60aafe875ef53217ebdc74f1
[ "MIT" ]
2
2021-05-20T06:55:38.000Z
2021-05-23T05:09:06.000Z
examples/tetris/lib/Moon/src/cmp/cmp_base.cpp
KEGEStudios/Moon
0e6aa078c8bf876c60aafe875ef53217ebdc74f1
[ "MIT" ]
15
2021-04-21T05:26:39.000Z
2021-07-06T07:07:28.000Z
examples/tetris/lib/Moon/src/cmp/cmp_base.cpp
reitmas32/Moon
02790eb476f039b44664e7d8f24fa2839187e4fc
[ "MIT" ]
1
2021-02-21T08:26:40.000Z
2021-02-21T08:26:40.000Z
#include "../../include/cmp/cmp_base.hpp" namespace Moon::Core { ComponentBase_t::ComponentBase_t() { } ComponentBase_t::~ComponentBase_t() { } } // namespace Moon::Core
15.076923
41
0.622449
KEGEStudios
0c2e5ccbb3f844de01e73aef5083d8e28da739d5
1,284
cpp
C++
Luogu/P3052.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
Luogu/P3052.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
1
2021-11-18T15:10:29.000Z
2021-11-20T07:13:31.000Z
Luogu/P3052.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2022 */ #include <algorithm> #include <cstdio> #include <cstring> int n, w, a[20], f[1 << 19], g[1 << 19]; long long sum[1 << 19]; int main() { scanf("%d%d", &n, &w); for (int i = 0; i < n; ++i) scanf("%d", a + i); memset(f, 0x3f, sizeof(f)); f[0] = 1; for (int S = 0; S < (1 << n); ++S) { for (int i = 0; i < n; ++i) { if ((S >> i) & 1) continue; if (g[S] + a[i] <= w) { if (f[S | (1 << i)] > f[S]) { f[S | (1 << i)] = f[S]; g[S | (1 << i)] = g[S] + a[i]; } else if (f[S | (1 << i)] == f[S] && g[S | (1 << i)] > g[S] + a[i]) g[S | (1 << i)] = g[S] + a[i]; } else { if (f[S | (1 << i)] > f[S] + 1) { f[S | (1 << i)] = f[S] + 1; g[S | (1 << i)] = a[i]; } else if (f[S | (1 << i)] == f[S] + 1 && g[S | (1 << i)] > a[i]) g[S | (1 << i)] = a[i]; } } } printf("%d\n", f[(1 << n) - 1]); return 0; }
25.68
82
0.271028
Nickel-Angel
0c2f9485fc072c724cf0d8ec52627f4704423fa7
3,246
cpp
C++
src/mod/debug/quantum_duck.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
33
2016-02-18T04:27:53.000Z
2022-01-15T18:59:53.000Z
src/mod/debug/quantum_duck.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2018-01-10T18:41:38.000Z
2020-10-01T13:34:53.000Z
src/mod/debug/quantum_duck.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
14
2017-08-06T23:02:49.000Z
2021-08-24T00:24:16.000Z
#include "mod.h" namespace Mod::Debug::Quantum_Duck { // +CBasePlayer::m_bDucked // +CBasePlayer::m_bDucking // +CBasePlayer::m_bInDuckJump // +CBasePlayer::m_flDuckTime // +CBasePlayer::m_flDuckJumpTime // +CBasePlayer::m_bDuckToggled // +CBasePlayer::m_fFlags <-- particularly FL_DUCKING, FL_ANIMDUCKING // +CBasePlayer::m_afPhysicsFlags <-- particularly PFLAG_DUCKING // CBasePlayer::m_vphysicsCollisionState << need prop accessors for these // CBasePlayer::m_pShadowStand << need prop accessors for these // CBasePlayer::m_pShadowCrouch << need prop accessors for these // see game/server/playerlocaldata.h for descriptions of the meanings of these variables // CLIENT ONLY // - C_BasePlayer::PostThink: based on GetFlags() & FL_DUCKING, call SetCollisionBounds(...) // SERVER ONLY // - virtual CBasePlayer::Duck (TODO: is there a client equivalent for prediction?) // - CBasePlayer::RunCommand // - CBasePlayer::PreThink // - FixPlayerCrouchStuck (only from CBasePlayer::Restore) // - CBasePlayer::PostThink: based on GetFlags() & FL_DUCKING, calls SetCollisionBounds(...) // - CBasePlayer::PostThinkVPhysics: based on GetFlags() & FL_DUCKING, may call SetVCollisionState(..., ..., VPHYS_CROUCH) // - CBasePlayer::SetupVPhysicsShadow: based on GetFlags & FL_DUCKING, calls SetVCollisionState(..., ..., VPHYS_CROUCH or VPHYS_WALK) // SHARED // - CBasePlayer::GetPlayerMins: based on GetFlags() & FL_DUCKING, returns VEC(_DUCK)?_HULL_MIN_SCALED // - CBasePlayer::GetPlayerMaxs: based on GetFlags() & FL_DUCKING, returns VEC(_DUCK)?_HULL_MAX_SCALED // - CGameMovement::GetPlayerMins: based on parameter or m_Local.m_bDucked, returns VEC(_DUCK)?_HULL_MIN_SCALED // - CGameMovement::GetPlayerMaxs: based on parameter or m_Local.m_bDucked, returns VEC(_DUCK)?_HULL_MAX_SCALED // - CGameMovement::GetPlayerViewOffset: based on parameter, returns VEC(_DUCK)?_VIEW_SCALED // - CGameMovement::FixPlayerCrouchStuck // - CGameMovement::CanUnduck // - CGameMovement::FinishUnDuck // - CGameMovement::UpdateDuckJumpEyeOffset // - CGameMovement::FinishUnDuckJump // - CGameMovement::FinishDuck // - CGameMovement::StartUnDuckJump // - CGameMovement::SetDuckedEyeOffset // - CGameMovement::Duck (ESPECIALLY THE HACK AT THE END OF THE FUNCTION!!) // tweaks: // - debug_latch_reset_onduck (STAGING_ONLY) // overlays: // player->CollisionProperty->OBBMins() // player->CollisionProperty->OBBMaxs() // player->EyePosition() // player->GetViewOffset() // player origin // player wsc // draw vphysics shadow // draw all boxes that ICollideable will tell us about // TODO: find in files for "crouch" // TODO: find TF specific stuff // - any users of CGameMovement::SplineFraction? class CMod : public IMod { public: CMod() : IMod("Debug:Quantum_Duck") { } }; CMod s_Mod; ConVar cvar_enable("sig_debug_quantum_duck", "0", FCVAR_NOTIFY, "Debug: determine why quantum ducking is possible and how to fix it", [](IConVar *pConVar, const char *pOldValue, float flOldValue){ s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool()); }); }
35.67033
135
0.705176
fugueinheels
0c3799b6c2560fd09d84cafa4ad16e1e896efc78
1,238
cpp
C++
03/roh/2644.cpp
Dcom-KHU/2021-Winter-Algorithm-Study
ea32826abe7d8245ee9d3dc8d0161f7ba018a02f
[ "MIT" ]
2
2021-01-09T10:05:21.000Z
2021-01-10T06:14:03.000Z
03/roh/2644.cpp
Dcom-KHU/2021-Winter-Algorithm-Study
ea32826abe7d8245ee9d3dc8d0161f7ba018a02f
[ "MIT" ]
null
null
null
03/roh/2644.cpp
Dcom-KHU/2021-Winter-Algorithm-Study
ea32826abe7d8245ee9d3dc8d0161f7ba018a02f
[ "MIT" ]
1
2021-02-03T13:09:09.000Z
2021-02-03T13:09:09.000Z
#include<iostream> #include<vector> //lca(least common ancestor) 문제는 사실... log(n) 해결방법이 있습니다...... using namespace std; //각노드의 부모의 인덱스를 저장하는 배열 int parent[1000]; //child가 final ancestor 에 도달할때까지의 방문하는 노드의 idx를 돌려준다. vector<int> get_p(int child){ vector<int> result; while(child != -1){ result.push_back(child); child = parent[child]; } return result; } int main(){ ios::sync_with_stdio(false); for(int i =0 ;i<1000; i++){ parent[i] = -1; } int n_people; cin>>n_people; int target_a, target_b; cin>>target_a>>target_b; int n_rule; cin>>n_rule; while(n_rule--){ int c,p; cin>>p>>c; //트리를 만들어 줍니다! //c번 노드의 부모는 p parent[c] = p; } //a,b 가 final ancestor 까지 가려면 누구를 거쳐가야하는지 저장하는 리스트(벡터) vector<int> a_parents = get_p(target_a); vector<int> b_parents = get_p(target_b); //만약 두 노드의 final ancestor 가 다르면 둘은 서로다른 트리에 존재하는것임. if(a_parents.back() != b_parents.back()){ cout<<-1; } else{ //둘의 모든 공통된 조상들을 제외하고나면 그들이 최초로 공통되는 조상까지의 거리가 나온다. while(!a_parents.empty() && !b_parents.empty() && a_parents.back() == b_parents.back()){ a_parents.pop_back(); b_parents.pop_back(); } cout<<a_parents.size() + b_parents.size(); } return 0; }
20.295082
92
0.62601
Dcom-KHU
0c39ef78e2d076f6d2e13654b6b913a2f6f8254c
2,483
cpp
C++
source/d3d9/d3d9_impl_state_block.cpp
neonkingfr/ReshadeC
bdce0e6b6b4456f9eb04c2cb847b392e31460c90
[ "BSD-3-Clause" ]
null
null
null
source/d3d9/d3d9_impl_state_block.cpp
neonkingfr/ReshadeC
bdce0e6b6b4456f9eb04c2cb847b392e31460c90
[ "BSD-3-Clause" ]
null
null
null
source/d3d9/d3d9_impl_state_block.cpp
neonkingfr/ReshadeC
bdce0e6b6b4456f9eb04c2cb847b392e31460c90
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2014 Patrick Mours * SPDX-License-Identifier: BSD-3-Clause */ #include "d3d9_impl_state_block.hpp" reshade::d3d9::state_block::state_block(IDirect3DDevice9 *device) : _device(device) { #ifdef RESHADE_TEST_APPLICATION // Avoid errors from the D3D9 debug runtime because the other slots return D3DERR_NOTFOUND with the test application _num_simultaneous_rts = 1; #else D3DCAPS9 caps; _device->GetDeviceCaps(&caps); _num_simultaneous_rts = caps.NumSimultaneousRTs; if (_num_simultaneous_rts > ARRAYSIZE(_render_targets)) _num_simultaneous_rts = ARRAYSIZE(_render_targets); #endif } reshade::d3d9::state_block::~state_block() { release_all_device_objects(); } void reshade::d3d9::state_block::capture() { assert(!has_captured()); if (SUCCEEDED(_device->CreateStateBlock(D3DSBT_ALL, &_state_block))) _state_block->Capture(); else assert(false); _device->GetViewport(&_viewport); for (DWORD target = 0; target < _num_simultaneous_rts; target++) _device->GetRenderTarget(target, &_render_targets[target]); _device->GetDepthStencilSurface(&_depth_stencil); _device->GetRenderState(D3DRS_SRGBWRITEENABLE, &_srgb_write); _device->GetSamplerState(0, D3DSAMP_SRGBTEXTURE, &_srgb_texture); } void reshade::d3d9::state_block::apply_and_release() { if (_state_block != nullptr) _state_block->Apply(); // Release state block every time, so that all references to captured vertex and index buffers, textures, etc. are released again _state_block.reset(); // This should technically be captured and applied by the state block already ... // But Steam overlay messes it up somehow and this is neceesary to fix the screen darkening in Portal when the Steam overlay is showing a notification popup and the ReShade overlay is open at the same time _device->SetRenderState(D3DRS_SRGBWRITEENABLE, _srgb_write); _device->SetSamplerState(0, D3DSAMP_SRGBTEXTURE, _srgb_texture); for (DWORD target = 0; target < _num_simultaneous_rts; target++) _device->SetRenderTarget(target, _render_targets[target].get()); _device->SetDepthStencilSurface(_depth_stencil.get()); // Set viewport after render targets have been set, since 'SetRenderTarget' causes the viewport to be set to the full size of the render target _device->SetViewport(&_viewport); release_all_device_objects(); } void reshade::d3d9::state_block::release_all_device_objects() { _depth_stencil.reset(); for (auto &render_target : _render_targets) render_target.reset(); }
33.554054
206
0.778896
neonkingfr
0c3a6e0c49281a3641ac269e4b58fc34cf12dedf
339
hpp
C++
snowman.hpp
Roniharel100/CPP_EX1-Snowman_b
0b41fc0f7946a373350819386b3bd0947eb597ee
[ "MIT" ]
null
null
null
snowman.hpp
Roniharel100/CPP_EX1-Snowman_b
0b41fc0f7946a373350819386b3bd0947eb597ee
[ "MIT" ]
null
null
null
snowman.hpp
Roniharel100/CPP_EX1-Snowman_b
0b41fc0f7946a373350819386b3bd0947eb597ee
[ "MIT" ]
null
null
null
#include <string> #include <array> using namespace std; namespace ariel { string snowman(int code); const int min_snowman_code = 11111111; const int max_snowman_code = 44444444; const int base_num = 10; const int min_index = 0; const int max_index = 3; const int top_arm = 0; const int bottom_arm = 1; }
19.941176
42
0.675516
Roniharel100
0c3cdf0a548cb47115845f53749009a730f9ea86
3,102
cpp
C++
Source/XsollaUtils/Private/XsollaUtilsUrlBuilder.cpp
xsolla/store-ue4-sdk
e25440e9d0b82663929ee7f49807e9b6bb09606b
[ "Apache-2.0" ]
14
2019-08-28T19:49:07.000Z
2021-12-04T14:34:18.000Z
Plugins/XSolla/Source/XsollaUtils/Private/XsollaUtilsUrlBuilder.cpp
anchorholdgames/anchorhold
00b4fb6b1229c9fd2dd1aff01f09ad0e9a224bbb
[ "MIT" ]
34
2019-08-17T08:23:18.000Z
2021-12-08T08:25:14.000Z
Plugins/XSolla/Source/XsollaUtils/Private/XsollaUtilsUrlBuilder.cpp
anchorholdgames/anchorhold
00b4fb6b1229c9fd2dd1aff01f09ad0e9a224bbb
[ "MIT" ]
12
2019-09-25T15:14:58.000Z
2022-03-21T09:27:58.000Z
// Copyright 2021 Xsolla Inc. All Rights Reserved. #include "XsollaUtilsUrlBuilder.h" XsollaUtilsUrlBuilder::XsollaUtilsUrlBuilder(const FString& UrlTemplate) : Url(UrlTemplate) { } FString XsollaUtilsUrlBuilder::Build() { FString ResultUrl = Url; // set path params for (const auto& Param : PathParams) { const FString ParamPlaceholder = FString::Printf(TEXT("{%s}"), *Param.Key); if (ResultUrl.Contains(ParamPlaceholder)) { ResultUrl = ResultUrl.Replace(*ParamPlaceholder, *Param.Value); } } // add query params for (const auto& Param : StringQueryParams) { const FString NewParam = FString::Printf(TEXT("%s%s=%s"), ResultUrl.Contains(TEXT("?")) ? TEXT("&") : TEXT("?"), *Param.Key, *Param.Value); ResultUrl.Append(NewParam); } for (const auto& Param : NumberQueryParams) { const FString NewParam = FString::Printf(TEXT("%s%s=%d"), ResultUrl.Contains(TEXT("?")) ? TEXT("&") : TEXT("?"), *Param.Key, Param.Value); ResultUrl.Append(NewParam); } return ResultUrl; } XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::SetPathParam(const FString& ParamName, const FString& ParamValue) { PathParams.Add(TPair<FString, FString>(ParamName, ParamValue)); return *this; } XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::SetPathParam(const FString& ParamName, const int32 ParamValue) { PathParams.Add(TPair<FString, FString>(ParamName, FString::FromInt(ParamValue))); return *this; } XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::SetPathParam(const FString& ParamName, const int64 ParamValue) { PathParams.Add(TPair<FString, FString>(ParamName, FString::Printf(TEXT("%llu"), ParamValue))); return *this; } XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddStringQueryParam(const FString& ParamName, const FString& ParamValue, const bool IgnoreEmpty) { if (IgnoreEmpty && ParamValue.IsEmpty()) { return *this; } StringQueryParams.Add(TPair<FString, FString>(ParamName, ParamValue)); return *this; } XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddArrayQueryParam(const FString& ParamName, const TArray<FString>& ParamValueArray, const bool IgnoreEmpty, const bool AsOneParam) { if (IgnoreEmpty && ParamValueArray.Num() == 0) { return *this; } if (AsOneParam) { FString AdditionalFieldsString = FString::Join(ParamValueArray, TEXT(",")); AdditionalFieldsString.RemoveFromEnd(","); AddStringQueryParam(ParamName, AdditionalFieldsString, IgnoreEmpty); } else { for (const auto& Param : ParamValueArray) { AddStringQueryParam(ParamName, Param, IgnoreEmpty); } } return *this; } XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddNumberQueryParam(const FString& ParamName, const int32 ParamValue) { NumberQueryParams.Add(TPair<FString, int32>(ParamName, ParamValue)); return *this; } XsollaUtilsUrlBuilder& XsollaUtilsUrlBuilder::AddBoolQueryParam(const FString& ParamName, const bool ParamValue, const bool AsNumber) { if (AsNumber) { AddStringQueryParam(ParamName, ParamValue ? TEXT("1") : TEXT("0"), true); } else { AddStringQueryParam(ParamName, ParamValue ? TEXT("true") : TEXT("false"), true); } return *this; }
26.741379
177
0.742424
xsolla
0c3f7b33a7a6b6f3dbe2e0b6c39973c0265e6e78
2,342
hpp
C++
include/ccbase/filesystem/directory_entry.hpp
adityaramesh/ccbase
595e1416aab3cc8bc976aad9bb3e262c7d11e3b2
[ "BSD-3-Clause-Clear" ]
8
2015-01-08T05:44:43.000Z
2021-05-11T15:54:17.000Z
include/ccbase/filesystem/directory_entry.hpp
adityaramesh/ccbase
595e1416aab3cc8bc976aad9bb3e262c7d11e3b2
[ "BSD-3-Clause-Clear" ]
1
2016-01-31T08:48:53.000Z
2016-01-31T08:54:28.000Z
include/ccbase/filesystem/directory_entry.hpp
adityaramesh/ccbase
595e1416aab3cc8bc976aad9bb3e262c7d11e3b2
[ "BSD-3-Clause-Clear" ]
2
2015-03-26T11:08:18.000Z
2016-01-30T03:28:06.000Z
/* ** File Name: directory_entry.hpp ** Author: Aditya Ramesh ** Date: 08/23/2013 ** Contact: _@adityaramesh.com */ #ifndef ZDDEA7CE4_14FD_40C7_AA27_9BBF59D67383 #define ZDDEA7CE4_14FD_40C7_AA27_9BBF59D67383 #include <cstdint> #include <ostream> #include <ccbase/format.hpp> #include <ccbase/platform.hpp> #if PLATFORM_KERNEL == PLATFORM_KERNEL_LINUX #include <dirent.h> #elif PLATFORM_KERNEL == PLATFORM_KERNEL_XNU #include <sys/dirent.h> #else #error "Unsupported kernel." #endif namespace cc { enum class file_type : unsigned char { block_device = DT_BLK, character_device = DT_CHR, directory = DT_DIR, fifo = DT_FIFO, symbolic_link = DT_LNK, regular = DT_REG, socket = DT_SOCK, unknown = DT_UNKNOWN }; std::ostream& operator<<(std::ostream& os, const file_type& t) { switch (t) { case file_type::block_device: cc::write (os, "block device"); return os; case file_type::character_device: cc::write (os, "character device"); return os; case file_type::directory: cc::write (os, "directory"); return os; case file_type::fifo: cc::write (os, "fifo"); return os; case file_type::symbolic_link: cc::write (os, "symbolic link"); return os; case file_type::regular: cc::write (os, "regular file"); return os; case file_type::socket: cc::write (os, "socket"); return os; case file_type::unknown: cc::write (os, "unknown"); return os; } return os; } class directory_iterator; class directory_entry { friend class directory_iterator; using length_type = uint16_t; const directory_iterator& m_dir_it; const boost::string_ref m_name; const file_type m_type; directory_entry( const directory_iterator& dir_it, const char* name, const length_type len, const file_type type ) noexcept : m_dir_it(dir_it), m_name{name, len}, m_type{type} {} public: // Defined in `directory_iterator.hpp` due to cyclic dependencies. const boost::string_ref path() const noexcept; const boost::string_ref name() const noexcept { return m_name; } file_type type() const noexcept { return m_type; } }; std::ostream& operator<<(std::ostream& os, const directory_entry& e) { cc::write(os, "{{name: \"$\", type: \"$\"}}", e.name(), e.type()); return os; } } #endif
27.232558
81
0.675064
adityaramesh
0c41e9aa1e73a450c579104682ff33720d2c91c8
58,178
cpp
C++
src/JointMechanicsTool.cpp
j-d-roth/opensim-jam
a49f9ccdb202ded3e90da02bc7386e4f40bad0a1
[ "Apache-2.0" ]
16
2019-11-07T17:35:44.000Z
2022-02-16T15:31:10.000Z
src/JointMechanicsTool.cpp
j-d-roth/opensim-jam
a49f9ccdb202ded3e90da02bc7386e4f40bad0a1
[ "Apache-2.0" ]
2
2020-07-13T05:00:45.000Z
2020-08-11T15:38:15.000Z
src/JointMechanicsTool.cpp
j-d-roth/opensim-jam
a49f9ccdb202ded3e90da02bc7386e4f40bad0a1
[ "Apache-2.0" ]
2
2019-11-13T22:36:34.000Z
2020-10-22T14:05:44.000Z
/* -------------------------------------------------------------------------- * * JointMechanicsTool.cpp * * -------------------------------------------------------------------------- * * Author(s): Colin Smith * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include <OpenSim/Simulation/Model/Model.h> #include "JointMechanicsTool.h" #include "VTPFileAdapter.h" #include "H5Cpp.h" #include "hdf5_hl.h" #include "Smith2018ArticularContactForce.h" #include "HelperFunctions.h" #include "Blankevoort1991Ligament.h" #include <OpenSim/Analyses/StatesReporter.h> #include <OpenSim/Common/STOFileAdapter.h> #include <OpenSim/Common/GCVSpline.h> #include <OpenSim/Common/CSVFileAdapter.h> using namespace OpenSim; JointMechanicsTool::JointMechanicsTool() : Object() { setNull(); constructProperties(); _directoryOfSetupFile = ""; } JointMechanicsTool::JointMechanicsTool(std::string settings_file) : Object(settings_file) { constructProperties(); updateFromXMLDocument(); loadModel(settings_file); _directoryOfSetupFile = IO::getParentDirectory(settings_file); IO::chDir(_directoryOfSetupFile); } JointMechanicsTool::JointMechanicsTool(Model *aModel, std::string states_file, std::string results_dir) : JointMechanicsTool() { if(aModel==NULL) return; setModel(*aModel); set_states_file(states_file); set_results_directory(results_dir); } void JointMechanicsTool::setNull() { setAuthors("Colin Smith"); } void JointMechanicsTool::constructProperties() { Array<std::string> defaultListAll; defaultListAll.append("all"); Array<std::string> defaultListNone; defaultListNone.append("none"); constructProperty_model_file(""); constructProperty_states_file(""); constructProperty_results_directory("."); constructProperty_results_file_basename(""); constructProperty_start_time(-1); constructProperty_stop_time(-1); constructProperty_resample_step_size(-1); constructProperty_normalize_to_cycle(false); constructProperty_lowpass_filter_frequency(-1); constructProperty_print_processed_kinematics(false); constructProperty_contacts(defaultListAll); constructProperty_contact_outputs(defaultListAll); constructProperty_contact_mesh_properties(defaultListNone); constructProperty_ligaments(defaultListAll); constructProperty_ligament_outputs(defaultListAll); constructProperty_muscles(defaultListNone); constructProperty_muscle_outputs(defaultListNone); constructProperty_attached_geometry_bodies(defaultListNone); constructProperty_output_origin("ground"); constructProperty_output_frame("ground"); constructProperty_write_vtp_files(true); constructProperty_vtp_file_format("binary"); constructProperty_write_h5_file(true); constructProperty_h5_states_data(true); constructProperty_h5_kinematics_data(true); constructProperty_AnalysisSet(AnalysisSet()); } void JointMechanicsTool::setModel(Model& aModel) { _model = &aModel; set_model_file(_model->getDocumentFileName()); } void JointMechanicsTool::run() { //Set the max number of points a ligament or muscle path can contain _max_path_points = 100; //Make results directory int makeDir_out = IO::makeDir(get_results_directory()); if (errno == ENOENT && makeDir_out == -1) { OPENSIM_THROW(Exception, "Could not create " + get_results_directory() + "Possible reason: This tool cannot make new folder with subfolder."); } if (_model == NULL) { OPENSIM_THROW(Exception, "No model was set in JointMechanicsTool"); } SimTK::State state = _model->initSystem(); readStatesFromFile(); initialize(state); //loop over each frame for (int i = 0; i < _n_frames; ++i) { //Set Time state.setTime(_time[i]); std::cout << "Time: " << _time[i] << std::endl; //Set Qs and Us int nCoord = 0; for (const Coordinate& coord : _model->getComponentList<Coordinate>()) { coord.setValue(state, _q_matrix(i, nCoord)); coord.setSpeedValue(state, _u_matrix(i, nCoord)); nCoord++; } //Set Muscle States if(!_muscle_paths.empty()){ int nMsl = 0; for (const Muscle& msl : _model->updComponentList<Muscle>()) { for (int j = 0; j < _muscle_state_names[nMsl].size(); ++j) { msl.setStateVariableValue(state, _muscle_state_names[nMsl][j], _muscle_state_data[nMsl][j][i]); } nMsl++; } } //Record Values record(state,i); //Perform analyses if (i == 0) { _model->updAnalysisSet().begin(state); } else { _model->updAnalysisSet().step(state, i); } } printResults(get_results_file_basename(), get_results_directory()); } void JointMechanicsTool::readStatesFromFile() { std::string saveWorkingDirectory = IO::getCwd(); IO::chDir(_directoryOfSetupFile); Storage store = Storage(get_states_file()); IO::chDir(saveWorkingDirectory); //Set Start and Stop Times store.getTimeColumn(_time); if (get_start_time() == -1) { set_start_time(_time.get(0)); } if (get_stop_time() == -1) { set_stop_time(_time.getLast()); } const CoordinateSet& coordinateSet = _model->getCoordinateSet(); if (store.isInDegrees()) { _model->getSimbodyEngine().convertDegreesToRadians(store); } else if (get_lowpass_filter_frequency() != -1) { store.pad(store.getSize() / 2); store.lowpassIIR(get_lowpass_filter_frequency()); } //Cut to start and stop times store.crop(get_start_time(), get_stop_time()); if (get_normalize_to_cycle() == true) { double norm_dt = (get_stop_time() - get_start_time()) / 100; store.resampleLinear(norm_dt); } else if (get_resample_step_size() != -1 && get_normalize_to_cycle() == false) { store.resampleLinear(get_resample_step_size()); } if (get_print_processed_kinematics()) { store.print(get_results_directory() + "/" + get_results_file_basename() + "_processed_kinematics.sto"); } //Update the time store.getTimeColumn(_time); //Set number of Frames _n_frames = _time.size(); //Gather Q and U values Array<std::string> col_labels = store.getColumnLabels(); Array<int> q_col_map(-1, _model->getNumCoordinates()); for (int i = 0; i < col_labels.size(); ++i) { std::vector<std::string> split_label = split_string(col_labels[i], "/"); int j = 0; for (const Coordinate& coord : _model->getComponentList<Coordinate>()) { if (contains_string(split_label, coord.getName())) { if (split_label.back() == "value" || split_label.back() == coord.getName()) { q_col_map[j] = i; } } j++; } } _q_matrix.resize(_n_frames, _model->getNumCoordinates()); _u_matrix.resize(_n_frames, _model->getNumCoordinates()); _q_matrix = 0; _u_matrix = 0; int j = 0; for (const Coordinate& coord : _model->getComponentList<Coordinate>()) { if (q_col_map[j] != -1) { double* data = NULL; store.getDataColumn(col_labels[q_col_map[j]], data); for (int i = 0; i < _n_frames; ++i) { _q_matrix(i, j) = data[i]; } } else { std::cout << "Coordinate Value: " << coord.getName() << " not found in coordinates_file, assuming 0." << std::endl; } GCVSpline q_spline; q_spline.setDegree(5); for (int i = 0; i < _n_frames; ++i) { q_spline.addPoint(_time[i], _q_matrix(i,j)); } for (int i = 0; i < _n_frames; ++i) { SimTK::Vector x(1); x(0) = _time[i]; std::vector<int> u_order = { 0 }; _u_matrix(i, j) = q_spline.calcDerivative(u_order, x); } j++; } //Gather Muscle States //if(!_muscle_paths.empty()){ for (const Muscle& msl : _model->updComponentList<Muscle>()) { std::vector<std::string> state_names; std::vector<SimTK::Vector> state_values; Array<std::string> stateVariableNames = msl.getStateVariableNames(); for (int i = 0; i < stateVariableNames.getSize(); ++i) { state_names.push_back(stateVariableNames[i]); } _muscle_state_names.push_back(state_names); for (std::string msl_state : state_names) { int col_ind = -1; for (int j = 0; j < col_labels.size(); ++j) { if (col_labels[j] == msl_state) { col_ind = j; break; } } SimTK::Vector state_data(_n_frames, 0.0); if (col_ind == -1) { // std::cout << "WARNING:: Muscle state (" + msl_state + ") NOT found in coordinates file. Assumed 0.0" << std::endl; } else { Array<double> data; store.getDataColumn(col_labels[col_ind], data); for (int j = 0; j < data.getSize(); ++j) { state_data.set(j, data[j]); } } state_values.push_back(state_data); } _muscle_state_data.push_back(state_values); } //} } void JointMechanicsTool::initialize(SimTK::State& state) { //States if (get_h5_states_data()) { StatesReporter* states_rep = new StatesReporter(); states_rep->setName("states_analysis"); states_rep->setStepInterval(1); states_rep->setPrintResultFiles(false); _model->addAnalysis(states_rep); } //Add Analysis set AnalysisSet aSet = get_AnalysisSet(); int size = aSet.getSize(); for(int i=0;i<size;i++) { Analysis *analysis = aSet.get(i).clone(); _model->addAnalysis(analysis); } AnalysisSet& analysisSet = _model->updAnalysisSet(); state = _model->initSystem(); setupContactStorage(state); setupLigamentStorage(); setupMuscleStorage(); setupAttachedGeometriesStorage(); if (get_h5_kinematics_data()) { setupCoordinateStorage(); } } void JointMechanicsTool::setupContactStorage(SimTK::State& state) { if (_model->countNumComponents<Smith2018ArticularContactForce>() == 0) return; //Contact Names if (getProperty_contacts().size() == 0 || get_contacts(0) == "none") { return; } else if (get_contacts(0) == "all") { for (const Smith2018ArticularContactForce& contactForce : _model->getComponentList<Smith2018ArticularContactForce>()) { _contact_force_names.push_back(contactForce.getName()); _contact_force_paths.push_back(contactForce.getAbsolutePathString()); std::string casting_mesh_name = contactForce.getConnectee<Smith2018ContactMesh>("casting_mesh").getName(); std::string target_mesh_name = contactForce.getConnectee<Smith2018ContactMesh>("target_mesh").getName(); std::string casting_mesh_path = contactForce.getConnectee<Smith2018ContactMesh>("casting_mesh").getAbsolutePathString(); std::string target_mesh_path = contactForce.getConnectee<Smith2018ContactMesh>("target_mesh").getAbsolutePathString(); if (!contains_string(_contact_mesh_names, casting_mesh_name)) { _contact_mesh_names.push_back(casting_mesh_name); _contact_mesh_paths.push_back(casting_mesh_path); } if (!contains_string(_contact_mesh_names, target_mesh_name)) { _contact_mesh_names.push_back(target_mesh_name); _contact_mesh_paths.push_back(target_mesh_path); } } } else { for (int i = 0; i < getProperty_contacts().size(); ++i) { try { const Smith2018ArticularContactForce& contactForce = _model->getComponent<Smith2018ArticularContactForce>(get_contacts(i)); _contact_force_names.push_back(contactForce.getName()); _contact_force_paths.push_back(contactForce.getAbsolutePathString()); std::string casting_mesh_name = contactForce.getConnectee<Smith2018ContactMesh>("casting_mesh").getName(); std::string target_mesh_name = contactForce.getConnectee<Smith2018ContactMesh>("target_mesh").getName(); std::string casting_mesh_path = contactForce.getConnectee<Smith2018ContactMesh>("casting_mesh").getAbsolutePathString(); std::string target_mesh_path = contactForce.getConnectee<Smith2018ContactMesh>("target_mesh").getAbsolutePathString(); if (!contains_string(_contact_mesh_names, casting_mesh_name)) { _contact_mesh_names.push_back(casting_mesh_name); _contact_mesh_paths.push_back(casting_mesh_path); } if (!contains_string(_contact_mesh_names, target_mesh_name)) { _contact_mesh_names.push_back(target_mesh_name); _contact_mesh_paths.push_back(target_mesh_path); } } catch (ComponentNotFoundOnSpecifiedPath){ OPENSIM_THROW(Exception, "contact_name: " + get_contacts(i) + " was not found as a Smith2018ArticularContactForce path" " in the model. Did you use absolute path?"); } } } //Turn on mesh flipping so metrics are computed for casting and target for (int i = 0; i < _contact_force_paths.size(); ++i) { Smith2018ArticularContactForce& contactForce = _model->updComponent <Smith2018ArticularContactForce>(_contact_force_paths[i]); contactForce.setModelingOption(state, "flip_meshes", 1); } //Realize Report so the sizes of output vectors are known _model->realizeReport(state); //Contact Outputs const Smith2018ArticularContactForce& frc0 = _model->getComponent <Smith2018ArticularContactForce>(_contact_force_paths[0]); if (get_contact_outputs(0) == "all") { for (const auto& entry : frc0.getOutputs()) { const std::string& output_name = entry.first; const AbstractOutput* output = entry.second.get(); if(output->isListOutput()){continue;} if (output->getTypeName() == "double") { _contact_output_double_names.push_back(output->getName()); } if (output->getTypeName() == "Vec3") { _contact_output_vec3_names.push_back(output->getName()); } if (output->getTypeName() == "Vector") { _contact_output_vector_double_names.push_back( output->getName()); } } } else if (getProperty_contact_outputs().size() != 0 && get_contact_outputs(0) != "none") { for (int i = 0; i < getProperty_contact_outputs().size(); ++i) { try { std::string output_name = get_contact_outputs(i); const AbstractOutput& output = frc0.getOutput(output_name); if (output.getTypeName() == "double") { _contact_output_double_names.push_back(output_name); } if (output.getTypeName() == "Vec3") { _contact_output_vec3_names.push_back(output_name); } if (output.getTypeName() == "Vector") { _contact_output_vector_double_names.push_back(output_name); } } catch (Exception){ OPENSIM_THROW(Exception, "contact_output: " + get_contact_outputs(i) + " is not a valid " "Smith2018ArticularContactForce output name") } } } // Output Storage int nOutputDouble = _contact_output_double_names.size(); int nOutputVec3 = _contact_output_vec3_names.size(); int nOutputVector = _contact_output_vector_double_names.size(); SimTK::Matrix double_data(_n_frames, nOutputDouble,-1); SimTK::Matrix_<SimTK::Vec3> vec3_data(_n_frames, nOutputVec3,SimTK::Vec3(-1)); for (std::string frc_path : _contact_force_paths) { const Smith2018ArticularContactForce& frc = _model->updComponent<Smith2018ArticularContactForce>(frc_path); _contact_output_double_values.push_back(double_data); _contact_output_vec3_values.push_back(vec3_data); std::vector<SimTK::Matrix> def_output_vector; for (int i = 0; i < nOutputVector; ++i) { const AbstractOutput& abs_output = frc.getOutput(_contact_output_vector_double_names[i]); const Output<SimTK::Vector>& vector_output = dynamic_cast<const Output<SimTK::Vector>&>(abs_output); int output_vector_size = vector_output.getValue(state).size(); def_output_vector.push_back(SimTK::Matrix(_n_frames, output_vector_size,-1)); } _contact_output_vector_double_values.push_back(def_output_vector); } //Vertex location storage _mesh_vertex_locations.resize(_contact_mesh_paths.size()); for (int i = 0; i < _contact_mesh_paths.size(); ++i) { int mesh_nVer = _model->getComponent<Smith2018ContactMesh> (_contact_mesh_paths[i]).getPolygonalMesh().getNumVertices(); _mesh_vertex_locations[i].resize(_n_frames, mesh_nVer); } } void JointMechanicsTool::setupAttachedGeometriesStorage() { std::vector<std::string> body_path_list; if (get_attached_geometry_bodies(0) == "none" || getProperty_attached_geometry_bodies().empty()) { return; } else if (get_attached_geometry_bodies(0) == "all") { for (const Frame& frame : _model->updComponentList<Frame>()) { body_path_list.push_back(frame.getAbsolutePathString()); } } else { int nAttachedGeoBodies = getProperty_attached_geometry_bodies().size(); for (int i = 0; i < nAttachedGeoBodies; ++i) { try { const Frame& frame = _model->updComponent<Frame> (get_attached_geometry_bodies(i)); body_path_list.push_back(frame.getAbsolutePathString()); } catch (Exception) { OPENSIM_THROW(Exception, "attached_geometry_bodies: " + get_attached_geometry_bodies(i) + "does not exist as a " "Frame component in model. Did you use Absolute Path?"); } } } for (std::string body_path : body_path_list){ const Frame& frame = _model->updComponent<Frame>(body_path); int nAttachedGeos = frame.getProperty_attached_geometry().size(); for (int i = 0; i < nAttachedGeos; ++i) { const Geometry& geo = frame.get_attached_geometry(i); if (geo.getConcreteClassName() != "Mesh") { continue; } if (contains_string(_attach_geo_names, geo.getName())) { continue; } Mesh* mesh = (Mesh*)&geo; std::string filename = findMeshFile(mesh->get_mesh_file()); SimTK::PolygonalMesh ply_mesh; ply_mesh.loadFile(filename); //Apply Scale Factors SimTK::Vec3 scale = mesh->get_scale_factors(); if (scale != SimTK::Vec3(1)) { SimTK::PolygonalMesh scaled_mesh; for (int v = 0; v < ply_mesh.getNumVertices(); ++v) { scaled_mesh.addVertex(ply_mesh. getVertexPosition(v).elementwiseMultiply(scale)); } for (int f = 0; f < ply_mesh.getNumFaces(); ++f) { SimTK::Array_<int> facevertex; int numVertex = ply_mesh.getNumVerticesForFace(f); for (int k = 0; k < numVertex; ++k) { facevertex.push_back(ply_mesh.getFaceVertex(f, k)); } scaled_mesh.addFace(facevertex); } ply_mesh.copyAssign(scaled_mesh); } _attach_geo_names.push_back(geo.getName()); _attach_geo_frames.push_back(frame.getAbsolutePathString()); _attach_geo_meshes.push_back(ply_mesh); _attach_geo_vertex_locations.push_back(SimTK::Matrix_<SimTK::Vec3>(_n_frames, ply_mesh.getNumVertices())); } } } std::string JointMechanicsTool::findMeshFile(const std::string& mesh_file) { std::string model_file = SimTK::Pathname::getAbsolutePathname(_model->getDocumentFileName()); std::string model_dir, dummy1, dummy2; bool dummyBool; SimTK::Pathname::deconstructPathname(model_file, dummyBool, model_dir, dummy1, dummy2); std::string mesh_full_path; std::ifstream file(mesh_file); if (!file) { mesh_full_path = model_dir + mesh_file; file.open(mesh_full_path); } if (!file) { mesh_full_path = model_dir + "Geometry/" + mesh_file; file.open(mesh_full_path); } if (!file) { OPENSIM_THROW(Exception, "Attached Geometry file doesn't exist:\n" + model_dir + "[Geometry/]" + mesh_file); } return mesh_full_path; } void JointMechanicsTool::setupLigamentStorage() { if (_model->countNumComponents<Blankevoort1991Ligament>() == 0) return; //Ligament Names if (getProperty_ligaments().size() == 0 || get_ligaments(0) == "none") { return; } else if (get_ligaments(0) == "all") { for (const Blankevoort1991Ligament& lig : _model->updComponentList<Blankevoort1991Ligament>()) { _ligament_names.push_back(lig.getName()); _ligament_paths.push_back(lig.getAbsolutePathString()); } } else { for (int i = 0; i < getProperty_ligaments().size(); ++i) { try { const Blankevoort1991Ligament& lig = _model->updComponent <Blankevoort1991Ligament>(get_ligaments(i)); _ligament_names.push_back(lig.getName()); _ligament_paths.push_back(lig.getAbsolutePathString()); } catch (ComponentNotFoundOnSpecifiedPath) { OPENSIM_THROW(Exception, "ligament: " + get_ligaments(i) + " was not found in the model. " "Are you using the absolute path?"); } } } //Ligament Outputs const Blankevoort1991Ligament& lig0 = _model-> updComponentList<Blankevoort1991Ligament>().begin().deref(); if (get_ligament_outputs(0) == "all") { for (const auto& entry : lig0.getOutputs()) { const AbstractOutput* output = entry.second.get(); if(output->isListOutput()){continue;} if (output->getTypeName() == "double") { _ligament_output_double_names.push_back(output->getName()); } } } else if (getProperty_ligament_outputs().size() != 0 && get_ligament_outputs(0) != "none") { for (int i = 0; i < getProperty_ligament_outputs().size(); ++i) { try { std::string output_name = get_ligament_outputs(i); lig0.getOutput(output_name); _ligament_output_double_names.push_back(output_name); } catch (Exception){ OPENSIM_THROW(Exception, "ligament_output: " + get_ligament_outputs(i) + " is not a valid " "Blankevoort1991Ligament output name") } } } int nLigamentOutputs = _ligament_output_double_names.size(); SimTK::Matrix lig_output_data(_n_frames, nLigamentOutputs,-1); //Ligament Storage for (std::string lig_path : _ligament_paths) { Blankevoort1991Ligament lig = _model->updComponent<Blankevoort1991Ligament>(lig_path); //Path Point Storage SimTK::Matrix_<SimTK::Vec3> lig_matrix(_n_frames, _max_path_points, SimTK::Vec3(-1)); SimTK::Vector lig_vector(_n_frames, -1); _ligament_path_points.push_back(lig_matrix); _ligament_path_nPoints.push_back(lig_vector); //Output Data Storage _ligament_output_double_values.push_back(lig_output_data); } } void JointMechanicsTool::setupMuscleStorage() { if (_model->countNumComponents<Muscle>() == 0) return; //Muscle Names if (getProperty_muscles().size() == 0 || get_muscles(0) == "none") { return; } else if (get_muscles(0) == "all") { for (const Muscle& msl : _model->updComponentList<Muscle>()) { _muscle_names.push_back(msl.getName()); _muscle_paths.push_back(msl.getAbsolutePathString()); } } else { for (int i = 0; i < getProperty_muscles().size(); ++i) { try { const Muscle& msl = _model->updComponent <Muscle>(get_muscles(i)); _muscle_names.push_back(msl.getName()); _muscle_paths.push_back(msl.getAbsolutePathString()); } catch (ComponentNotFoundOnSpecifiedPath) { OPENSIM_THROW(Exception, "Muscle: " + get_muscles(i) + " was not found in the model. " "Are you using the absolute path?"); } } } //Muscle Outputs const Muscle& msl0 = _model->getMuscles().get(0); if (get_muscle_outputs(0) == "all") { for (const auto& entry : msl0.getOutputs()) { const AbstractOutput* output = entry.second.get(); if(output->isListOutput()){continue;} if (output->getTypeName() == "double") { _muscle_output_double_names.push_back(output->getName()); } } } else if (getProperty_muscle_outputs().size() != 0 && get_muscle_outputs(0) != "none") { for (int i = 0; i < getProperty_muscle_outputs().size(); ++i) { try { std::string output_name = get_muscle_outputs(i); msl0.getOutput(output_name); _muscle_output_double_names.push_back(output_name); } catch (Exception){ OPENSIM_THROW(Exception, "muscle_output: " + get_muscle_outputs(i) + " is not a valid " "Muscle output name") } } } int nMuscleOutputs = _muscle_output_double_names.size(); SimTK::Matrix msl_output_data(_n_frames, nMuscleOutputs,-1); //Muscle Storage for (std::string msl_path : _muscle_paths) { const Muscle& msl = _model->updComponent<Muscle>(msl_path); //Path Point Storage SimTK::Matrix_<SimTK::Vec3> msl_matrix(_n_frames, _max_path_points, SimTK::Vec3(-1)); SimTK::Vector msl_vector(_n_frames, -1); _muscle_path_points.push_back(msl_matrix); _muscle_path_nPoints.push_back(msl_vector); //Output Data Storage _muscle_output_double_values.push_back(msl_output_data); } } void JointMechanicsTool::setupCoordinateStorage() { _coordinate_output_double_names.push_back("value"); _coordinate_output_double_names.push_back("speed"); for (const Coordinate& coord : _model->updComponentList<Coordinate>()) { _coordinate_names.push_back(coord.getName()); SimTK::Matrix coord_data(_n_frames, 2, -1.0); _coordinate_output_double_values.push_back(coord_data); } } int JointMechanicsTool::record(const SimTK::State& s, const int frame_num) { _model->realizeReport(s); //Store mesh vertex locations std::string frame_name = get_output_frame(); const Frame& frame = _model->updComponent<Frame>(frame_name); std::string origin_name = get_output_origin(); const Frame& origin = _model->updComponent<Frame>(origin_name); SimTK::Vec3 origin_pos = origin.findStationLocationInAnotherFrame(s, SimTK::Vec3(0), frame); for (int i = 0; i < _contact_mesh_paths.size(); ++i) { int nVertex = _mesh_vertex_locations[i].ncol(); SimTK::Vector_<SimTK::Vec3> ver = _model->getComponent<Smith2018ContactMesh> (_contact_mesh_paths[i]).getVertexLocations(); const SimTK::Transform& T = _model->getComponent<Smith2018ContactMesh> (_contact_mesh_paths[i]).getMeshFrame().findTransformBetween(s,frame); for (int j = 0; j < nVertex; ++j) { _mesh_vertex_locations[i](frame_num, j) = T.shiftFrameStationToBase(ver(j)) - origin_pos; } } // Store Attached Geometries if (!_attach_geo_names.empty()) { for (int i = 0; i < _attach_geo_names.size(); ++i) { const SimTK::PolygonalMesh& mesh = _attach_geo_meshes[i]; SimTK::Transform trans = _model->updComponent<PhysicalFrame>(_attach_geo_frames[i]).findTransformBetween(s, frame); for (int j = 0; j < mesh.getNumVertices(); ++j) { _attach_geo_vertex_locations[i](frame_num, j) = trans.shiftFrameStationToBase(mesh.getVertexPosition(j)) - origin_pos; } } } //Store Contact data if (!_contact_force_paths.empty()) { int nFrc = 0; for (std::string frc_path : _contact_force_paths) { const Smith2018ArticularContactForce& frc = _model->updComponent<Smith2018ArticularContactForce>(frc_path); int nDouble = 0; for (std::string output_name : _contact_output_double_names) { _contact_output_double_values[nFrc].set(frame_num, nDouble, frc.getOutputValue<double>(s, output_name)); nDouble++; } int nVec3 = 0; for (std::string output_name : _contact_output_vec3_names) { _contact_output_vec3_values[nFrc].set(frame_num, nVec3, frc.getOutputValue<SimTK::Vec3>(s, output_name)); nVec3++; } int nVector = 0; for (std::string output_name : _contact_output_vector_double_names) { _contact_output_vector_double_values[nFrc][nVector].updRow(frame_num) = ~frc.getOutputValue<SimTK::Vector>(s, output_name); nVector++; } nFrc++; } } //Store ligament data if (!_ligament_paths.empty()) { int nLig = 0; for (const std::string& lig_path : _ligament_paths) { Blankevoort1991Ligament& lig = _model->updComponent<Blankevoort1991Ligament>(lig_path); //Path Points const GeometryPath& geoPath = lig.upd_GeometryPath(); int nPoints = 0; SimTK::Vector_<SimTK::Vec3> path_points(_max_path_points, SimTK::Vec3(-1)); getGeometryPathPoints(s, geoPath, path_points, nPoints); for (int i = 0; i < nPoints; ++i) { _ligament_path_points[nLig].set(frame_num,i,path_points(i)); } _ligament_path_nPoints[nLig][frame_num] = nPoints; //Output Data int j = 0; for (std::string output_name : _ligament_output_double_names) { _ligament_output_double_values[nLig].set(frame_num,j, lig.getOutputValue<double>(s, output_name)); j++; } nLig++; } } //Store muscle data if (!_muscle_paths.empty()) { int nMsl = 0; for (const std::string& msl_path : _muscle_paths) { Muscle& msl = _model->updComponent<Muscle>(msl_path); //Path Points const GeometryPath& geoPath = msl.upd_GeometryPath(); int nPoints = 0; SimTK::Vector_<SimTK::Vec3> path_points(_max_path_points,SimTK::Vec3(-1)); getGeometryPathPoints(s, geoPath, path_points, nPoints); for (int i = 0; i < nPoints; ++i) { _muscle_path_points[nMsl].set(frame_num,i,path_points(i)); } _muscle_path_nPoints[nMsl][frame_num] = nPoints; //Output Data int j = 0; for (std::string output_name : _muscle_output_double_names) { _muscle_output_double_values[nMsl].set(frame_num,j, msl.getOutputValue<double>(s, output_name)); j++; } nMsl++; } } //Store Coordinate Data if (get_h5_kinematics_data()) { int nCoord = 0; for (const Coordinate& coord : _model->updComponentList<Coordinate>()) { _coordinate_output_double_values[nCoord](frame_num,0) = coord.getValue(s); _coordinate_output_double_values[nCoord](frame_num,1) = coord.getSpeedValue(s); nCoord++; } } return(0); } void JointMechanicsTool::getGeometryPathPoints(const SimTK::State& s, const GeometryPath& geoPath, SimTK::Vector_<SimTK::Vec3>& path_points, int& nPoints) { const Frame& out_frame = _model->getComponent<Frame>(get_output_frame()); const Frame& origin = _model->getComponent<Frame>(get_output_origin()); SimTK::Vec3 origin_pos = origin.findStationLocationInAnotherFrame(s, SimTK::Vec3(0), out_frame); const Array<AbstractPathPoint*>& pathPoints = geoPath.getCurrentPath(s); nPoints = 0; for (int i = 0; i < pathPoints.getSize(); ++i) { AbstractPathPoint* point = pathPoints[i]; PathWrapPoint* pwp = dynamic_cast<PathWrapPoint*>(point); SimTK::Vec3 pos; //If wrapping point, need to collect all points on wrap object surface if (pwp) { Array<SimTK::Vec3>& surfacePoints = pwp->getWrapPath(); const SimTK::Transform& X_BG = pwp->getParentFrame().findTransformBetween(s, out_frame); // Cycle through each surface point and tranform to output frame for (int j = 0; j < surfacePoints.getSize(); ++j) { pos = X_BG * surfacePoints[j]-origin_pos; path_points.set(nPoints, pos); nPoints++; } } else { // otherwise a regular PathPoint so just draw its location const SimTK::Transform& X_BG = point->getParentFrame().findTransformBetween(s, out_frame); pos = X_BG * point->getLocation(s)-origin_pos; path_points.set(nPoints, pos); nPoints++; } } } //============================================================================= // IO //============================================================================= //_____________________________________________________________________________ /** * Print results. * * The file names are constructed as * aDir + "/" + aBaseName + "_" + ComponentName + aExtension * * @param aDir Directory in which the results reside. * @param aBaseName Base file name. * @param aDT Desired time interval between adjacent storage vectors. Linear * interpolation is used to print the data out at the desired interval. * @param aExtension File extension. * * @return 0 on success, -1 on error. */ int JointMechanicsTool::printResults(const std::string &aBaseName,const std::string &aDir) { std::string file_path = get_results_directory(); std::string base_name = get_results_file_basename(); //Analysis Results _model->updAnalysisSet().printResults(get_results_file_basename(), get_results_directory()); //Write VTP files if (get_write_vtp_files()) { //Contact Meshes for (int i = 0; i < _contact_mesh_names.size(); ++i) { std::string mesh_name = _contact_mesh_names[i]; std::string mesh_path = _contact_mesh_paths[i]; std::cout << "Writing .vtp files: " << file_path << "/" << base_name << "_"<< mesh_name << std::endl; writeVTPFile(mesh_path, _contact_force_names, true); } //Attached Geometries if (!_attach_geo_names.empty()) { writeAttachedGeometryVTPFiles(true); } //Ligaments if (!_ligament_names.empty()) { int i = 0; for (std::string lig : _ligament_names) { std::cout << "Writing .vtp files: " << file_path << "/" << base_name << "_"<< lig << std::endl; writeLineVTPFiles("ligament_" + lig, _ligament_path_nPoints[i], _ligament_path_points[i], _ligament_output_double_names, _ligament_output_double_values[i]); i++; } } //Muscles if (!_muscle_names.empty()) { int i = 0; for (std::string msl : _muscle_names) { std::cout << "Writing .vtp files: " << file_path << "/" << base_name << "_"<< msl << std::endl; writeLineVTPFiles("muscle_" + msl, _muscle_path_nPoints[i], _muscle_path_points[i], _muscle_output_double_names, _muscle_output_double_values[i]); i++; } } } //Write h5 file if (get_write_h5_file()) { writeH5File(aBaseName, aDir); } return(0); } void JointMechanicsTool::collectMeshContactOutputData( const std::string& mesh_name, std::vector<SimTK::Matrix>& triData, std::vector<std::string>& triDataNames, std::vector<SimTK::Matrix>& vertexData, std::vector<std::string>& vertexDataNames) { Smith2018ContactMesh mesh; int nFrc = -1; for (std::string frc_path : _contact_force_paths) { nFrc++; std::string mesh_type = ""; const Smith2018ArticularContactForce& frc = _model->updComponent<Smith2018ArticularContactForce>(frc_path); std::string casting_mesh_name = frc.getConnectee<Smith2018ContactMesh>("casting_mesh").getName(); std::string target_mesh_name = frc.getConnectee<Smith2018ContactMesh>("target_mesh").getName(); if (mesh_name == casting_mesh_name) { mesh_type = "casting"; mesh = frc.getConnectee<Smith2018ContactMesh>("casting_mesh"); } else if (mesh_name == target_mesh_name) { mesh_type = "target"; mesh = frc.getConnectee<Smith2018ContactMesh>("target_mesh"); } else { continue; } int nVectorDouble = -1; for (std::string output_name : _contact_output_vector_double_names) { nVectorDouble++; std::vector<std::string> output_name_split = split_string(output_name, "_"); std::string output_mesh_type = output_name_split[0]; std::string output_data_type = output_name_split[1]; std::string output_data_name = ""; for (int i = 2; i < output_name_split.size(); ++i) { if (i == 2) { output_data_name = output_name_split[i]; } else { output_data_name = output_data_name + "_" + output_name_split[i]; } } if (output_mesh_type != mesh_type) { continue; } if (output_data_type == "triangle") { //Seperate data for each contact force triDataNames.push_back(output_name + "_" + frc.getName()); triData.push_back( _contact_output_vector_double_values[nFrc][nVectorDouble]); //Combined data for all contacts visualized on one mesh int data_index; if (contains_string(triDataNames, output_name, data_index)) { triData[data_index] += _contact_output_vector_double_values[nFrc][nVectorDouble]; } else { triDataNames.push_back(output_name); triData.push_back(_contact_output_vector_double_values[nFrc][nVectorDouble]); } } } //Variable Cartilage Properties if ((getProperty_contact_mesh_properties().findIndex("thickness") != -1 || getProperty_contact_mesh_properties().findIndex("all") != -1) && !contains_string(triDataNames, "triangle.thickness")) { SimTK::Matrix thickness_matrix(_n_frames, mesh.getNumFaces()); for (int i = 0; i < _n_frames; ++i) { for (int j = 0; j < mesh.getNumFaces(); ++j) { thickness_matrix(i, j) = mesh.getTriangleThickness(j); } } triDataNames.push_back("triangle.thickness"); triData.push_back(thickness_matrix); } if ((getProperty_contact_mesh_properties().findIndex("elastic_modulus") != -1 || getProperty_contact_mesh_properties().findIndex("all") != -1) && !contains_string(triDataNames, "triangle.elastic_modulus")) { SimTK::Matrix E_matrix(_n_frames, mesh.getNumFaces()); for (int i = 0; i < _n_frames; ++i) { for (int j = 0; j < mesh.getNumFaces(); ++j) { E_matrix(i, j) = mesh.getTriangleElasticModulus(j); } } triDataNames.push_back("triangle.elastic_modulus"); triData.push_back(E_matrix); } if ((getProperty_contact_mesh_properties().findIndex("poissons_ratio") != -1 || getProperty_contact_mesh_properties().findIndex("all") != -1) && !contains_string(triDataNames, "triangle.poissons_ratio")) { SimTK::Matrix v_matrix(_n_frames, mesh.getNumFaces()); for (int i = 0; i < _n_frames; ++i) { for (int j = 0; j < mesh.getNumFaces(); ++j) { v_matrix(i, j) = mesh.getTrianglePoissonsRatio(j); } } triDataNames.push_back("triangle.poissons_ratio"); triData.push_back(v_matrix); } if ((getProperty_contact_mesh_properties().findIndex("area") != -1 || getProperty_contact_mesh_properties().findIndex("all") != -1) && !contains_string(triDataNames, "triangle.area")) { SimTK::Matrix area_matrix(_n_frames, mesh.getNumFaces()); for (int i = 0; i < _n_frames; ++i) { area_matrix[i] = ~mesh.getTriangleAreas(); } triDataNames.push_back("triangle.area"); triData.push_back(area_matrix); } } } void JointMechanicsTool::writeVTPFile(const std::string& mesh_path, const std::vector<std::string>& contact_names, bool isDynamic) { const Smith2018ContactMesh& cnt_mesh = _model->getComponent<Smith2018ContactMesh>(mesh_path); std::string mesh_name = cnt_mesh.getName(); std::string file_path = get_results_directory(); std::string base_name = get_results_file_basename(); std::string frame = split_string(get_output_frame(), "/").back(); std::string origin = split_string(get_output_origin(), "/").back(); //Collect data std::vector<SimTK::Matrix> triData, vertexData; std::vector<std::string> triDataNames, vertexDataNames; collectMeshContactOutputData(mesh_name, triData, triDataNames, vertexData, vertexDataNames); //Mesh face connectivity const SimTK::PolygonalMesh& mesh = cnt_mesh.getPolygonalMesh(); SimTK::Matrix mesh_faces(mesh.getNumFaces(), mesh.getNumVerticesForFace(0)); for (int j = 0; j < mesh.getNumFaces(); ++j) { for (int k = 0; k < mesh.getNumVerticesForFace(0); ++k) { mesh_faces(j, k) = mesh.getFaceVertex(j, k); } } for (int frame_num = 0; frame_num < _n_frames; ++frame_num) { //Write file VTPFileAdapter* mesh_vtp = new VTPFileAdapter(); mesh_vtp->setDataFormat("binary"); //mesh_vtp->setDataFormat("ascii"); for (int i = 0; i < triDataNames.size(); ++i) { mesh_vtp->appendFaceData(triDataNames[i], ~triData[i][frame_num]); } if (isDynamic) { int mesh_index; contains_string(_contact_mesh_names, mesh_name, mesh_index); mesh_vtp->setPointLocations(_mesh_vertex_locations[mesh_index][frame_num]); mesh_vtp->setPolygonConnectivity(mesh_faces); mesh_vtp->write(base_name + "_contact_" + mesh_name + "_dynamic_" + frame + "_" + origin, file_path + "/", frame_num); } else { //static SimTK::PolygonalMesh poly_mesh = _model->getComponent<Smith2018ContactMesh>(mesh_name).getPolygonalMesh(); mesh_vtp->setPolygonsFromMesh(poly_mesh); mesh_vtp->write(base_name + "_contact_" + mesh_name + "_static_" + frame, file_path + "/", frame_num); } delete mesh_vtp; } } void JointMechanicsTool::writeAttachedGeometryVTPFiles(bool isDynamic) { std::string file_path = get_results_directory(); std::string base_name = get_results_file_basename(); std::string frame = split_string(get_output_frame(), "/").back(); std::string origin = split_string(get_output_origin(), "/").back(); for (int i = 0; i < _attach_geo_names.size(); ++i) { std::cout << "Writing .vtp files: " << file_path << "/" << base_name << "_"<< _attach_geo_names[i] << std::endl; //Face Connectivity const SimTK::PolygonalMesh& mesh = _attach_geo_meshes[i]; SimTK::Matrix mesh_faces(mesh.getNumFaces(), mesh.getNumVerticesForFace(0)); for (int j = 0; j < mesh.getNumFaces(); ++j) { for (int k = 0; k < mesh.getNumVerticesForFace(0); ++k) { mesh_faces(j, k) = mesh.getFaceVertex(j, k); } } for (int frame_num = 0; frame_num < _n_frames; ++frame_num) { //Write file VTPFileAdapter* mesh_vtp = new VTPFileAdapter(); mesh_vtp->setDataFormat("binary"); if (isDynamic) { mesh_vtp->setPointLocations(_attach_geo_vertex_locations[i][frame_num]); mesh_vtp->setPolygonConnectivity(mesh_faces); mesh_vtp->write(base_name + "_mesh_" + _attach_geo_names[i] + "_dynamic_" + frame + "_" + origin, file_path + "/", frame_num); } else { //static mesh_vtp->setPolygonsFromMesh(mesh); mesh_vtp->write(base_name + "_mesh_" + _attach_geo_names[i] + "_static_" + frame + "_" + origin, file_path + "/", frame_num); } delete mesh_vtp; } } } void JointMechanicsTool::writeLineVTPFiles(std::string line_name, const SimTK::Vector& nPoints, const SimTK::Matrix_<SimTK::Vec3>& path_points, const std::vector<std::string>& output_double_names, const SimTK::Matrix& output_double_values) { for (int i = 0; i < _n_frames; ++i) { int nPathPoints = nPoints.get(i); VTPFileAdapter* mesh_vtp = new VTPFileAdapter(); mesh_vtp->setDataFormat("binary"); //Collect points SimTK::RowVector_<SimTK::Vec3> points(nPathPoints); SimTK::Vector lines(nPathPoints); for (int k = 0; k < nPathPoints; k++) { points(k) = path_points.get(i, k); lines(k) = k; } mesh_vtp->setPointLocations(points); mesh_vtp->setLineConnectivity(lines); //Collect Data for (int k = 0; k < output_double_names.size(); ++k) { SimTK::Vector point_data(nPathPoints, output_double_values[i][k]); mesh_vtp->appendPointData(output_double_names[k], point_data); } //Write File std::string frame = split_string(get_output_frame(), "/").back(); std::string origin = split_string(get_output_origin(), "/").back(); mesh_vtp->write(get_results_file_basename() + "_" + line_name + "_" + frame + "_" + origin, get_results_directory() + "/", i); delete mesh_vtp; } } void JointMechanicsTool::writeH5File( const std::string &aBaseName, const std::string &aDir) { H5FileAdapter h5_adapter; const std::string h5_file{ aDir + "/" + aBaseName + ".h5" }; h5_adapter.open(h5_file); h5_adapter.writeTimeDataSet(_time); //Write States Data if (get_h5_states_data()) { StatesReporter& states_analysis = dynamic_cast<StatesReporter&>(_model->updAnalysisSet().get("states_analysis")); const TimeSeriesTable& states_table = states_analysis.getStatesStorage().exportToTable(); h5_adapter.writeStatesDataSet(states_table); } //Write coordinate data if (get_h5_kinematics_data()) { h5_adapter.writeComponentGroupDataSet("Coordinates", _coordinate_names, _coordinate_output_double_names, _coordinate_output_double_values); } //Write Muscle Data if (!_muscle_names.empty()) { h5_adapter.writeComponentGroupDataSet("Muscles",_muscle_names, _muscle_output_double_names, _muscle_output_double_values); } //Write Ligament Data if (!_ligament_names.empty()) { h5_adapter.writeComponentGroupDataSet("Ligaments",_ligament_names, _ligament_output_double_names, _ligament_output_double_values); } //Write Contact Data if (!_contact_mesh_names.empty()) { h5_adapter.writeComponentGroupDataSet("Smith2018ArticularContactForce", _contact_force_names, _contact_output_double_names, _contact_output_double_values); h5_adapter.writeComponentGroupDataSetVec3("Smith2018ArticularContactForce", _contact_force_names, _contact_output_vec3_names, _contact_output_vec3_values); h5_adapter.writeComponentGroupDataSetVector("Smith2018ArticularContactForce", _contact_force_names, _contact_output_vector_double_names, _contact_output_vector_double_values); //h5_adapter.writeComponentGroupDataSet("Smith2018ArticularContactForce",_contact_force_names, _contact_output_double_names, _contact_output_double_values); /*std::string contact_path = "/Smith2018ArticularContactForce"; h5_adapter.createGroup(contact_path); for (std::string force_name : _contact_force_names) { h5_adapter.createGroup(contact_path + "/" + force_name); int i = 0; for (std::string comp_name : _contact_output_double_names) { std::string comp_group = group_name + "/" + comp_name; _file.createGroup(comp_group); int j = 0; for (std::string data_label : output_double_names) { SimTK::Vector data = output_double_values[i](j); writeDataSetSimTKVector(data, lig_group + "/" + data_label); j++; } i++; } } std::vector<std::string> _contact_force_names; std::vector<std::string> _contact_force_paths; std::vector<std::string> _contact_mesh_names; std::vector<std::string> _contact_mesh_paths; std::vector<SimTK::Matrix_<SimTK::Vec3>> _mesh_vertex_locations; std::vector<std::string> _contact_output_double_names; std::vector<std::string> _contact_output_vec3_names; std::vector<std::string> _contact_output_vector_double_names; std::vector<SimTK::Matrix> _contact_output_double_values; std::vector<SimTK::Matrix_<SimTK::Vec3>> _contact_output_vec3_values; std::vector<std::vector<SimTK::Matrix>> _contact_output_vector_double_values;*/ /* std::string cnt_group_name{ "/Contacts" }; h5_adapter.createGroup(cnt_group_name); //Contact Force for (int i = 0; i < _contact_force_paths.size(); ++i) { std::string contact_path = _contact_force_paths[i]; Smith2018ArticularContactForce& frc = _model-> updComponent<Smith2018ArticularContactForce>(contact_path); std::string contact_name = frc.getName(); h5_adapter.createGroup(cnt_group_name + "/" + contact_name); //Contact Meshes std::vector<std::string> mesh_names; mesh_names.push_back(frc.getConnectee<Smith2018ContactMesh>("target_mesh").getName()); mesh_names.push_back(frc.getConnectee<Smith2018ContactMesh>("casting_mesh").getName()); for (std::string mesh_name : mesh_names) { std::string mesh_path = cnt_group_name + "/" + contact_name + "/" + mesh_name; h5_adapter.createGroup(mesh_path); //Write Summary Contact Metrics if (get_h5_summary_contact_data()) { std::vector<std::string> data_regions; data_regions.push_back("total"); if (get_h5_medial_lateral_summary()) { data_regions.push_back("mediallateral"); } for (std::string region : data_regions) { h5_adapter.createGroup(mesh_path + "/" + region); //Write output doubles h5_adapter.writeDataSetSimTKMatrixColumns(matrix_data, report_labels); //Write output Vec3 h5_adapter.writeDataSetSimTKMatrixVec3Columns(report_vec3.getTable().getMatrix().getAsMatrix(), report_vec3_labels); } } //Write pressure/proximity on every triangle if (get_h5_raw_contact_data()) { h5_adapter.createGroup(mesh_path + "/tri"); if (get_output_pressure()) { std::string data_path = mesh_path + "/tri/" + "pressure"; h5_adapter.writeDataSetVector(report.getTable(), data_path); } if (get_output_proximity()) { std::string data_path = mesh_path + "/tri/" + "proximity"; h5_adapter.writeDataSetVector(report.getTable(), data_path); } } } }*/ } h5_adapter.close(); } void JointMechanicsTool::loadModel(const std::string &aToolSetupFileName) { OPENSIM_THROW_IF(get_model_file().empty(), Exception, "No model file was specified (<model_file> element is empty) in " "the Setup file. "); std::string saveWorkingDirectory = IO::getCwd(); std::string directoryOfSetupFile = IO::getParentDirectory(aToolSetupFileName); IO::chDir(directoryOfSetupFile); std::cout<<"JointMechanicsTool "<< getName() <<" loading model '"<<get_model_file() <<"'"<< std::endl; Model *model = 0; try { model = new Model(get_model_file()); model->finalizeFromProperties(); } catch(...) { // Properly restore current directory if an exception is thrown IO::chDir(saveWorkingDirectory); throw; } _model = model; IO::chDir(saveWorkingDirectory); }
38.502978
172
0.581079
j-d-roth
0c432fde7e0d3200477a78e6ed0ed3cf5cd7b1d4
2,738
c++
C++
tests/css/grammar/semantic/convert_to.test.c++
rubenvb/skui
5bda2d73232eb7a763ba9d788c7603298767a7d7
[ "MIT" ]
19
2016-10-13T22:44:31.000Z
2021-12-28T20:28:15.000Z
tests/css/grammar/semantic/convert_to.test.c++
rubenvb/skui
5bda2d73232eb7a763ba9d788c7603298767a7d7
[ "MIT" ]
1
2021-05-16T15:15:22.000Z
2021-05-16T17:01:26.000Z
tests/css/grammar/semantic/convert_to.test.c++
rubenvb/skui
5bda2d73232eb7a763ba9d788c7603298767a7d7
[ "MIT" ]
4
2017-03-07T05:37:02.000Z
2018-06-05T03:14:48.000Z
/** * The MIT License (MIT) * * Copyright © 2019 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "css/test_rule.h++" #include <core/string.h++> #include <css/grammar/semantic/convert_to.h++> namespace { namespace x3 = boost::spirit::x3; using skui::core::string; using skui::css::grammar::convert_to; struct constructible_from_int { explicit constructible_from_int(int i = 0) : v{i} {} int v; }; struct constructible_from_float { explicit constructible_from_float(float f = 0.f) : v{f} {} float v; }; bool operator==(const constructible_from_int& lhs, const constructible_from_int& rhs) { return lhs.v == rhs.v; } bool operator==(const constructible_from_float& lhs, const constructible_from_float& rhs) { return lhs.v == rhs.v; } std::ostream& operator<<(std::ostream& os, const constructible_from_int& c) { return os << c.v; } std::ostream& operator<<(std::ostream& os, const constructible_from_float& c) { return os << c.v; } const auto conversion1 = x3::rule<struct conversion1, constructible_from_int>{"conversion1"} = x3::int_[convert_to<constructible_from_int>{}]; const auto conversion2 = x3::rule<struct conversion2, constructible_from_float>{"conversion2"} = x3::int_[convert_to<constructible_from_float, float>{}]; const string integer = "42"; } int main() { using skui::test::check_rule_success; using skui::test::check_rule_failure; check_rule_success(conversion1, integer, constructible_from_int{42}); check_rule_success(conversion2, integer, constructible_from_float{42.f}); return skui::test::exit_code; }
31.113636
96
0.71439
rubenvb
0c45416a540bd4eb84a6067dc74093fee62064f0
5,311
inl
C++
src/editor/include/agz/editor/resource/resource_panel.inl
AirGuanZ/Atrc
a0c4bc1b7bb96ddffff8bb1350f88b651b94d993
[ "MIT" ]
358
2018-11-29T08:15:05.000Z
2022-03-31T07:48:37.000Z
src/editor/include/agz/editor/resource/resource_panel.inl
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
23
2019-04-06T17:23:58.000Z
2022-02-08T14:22:46.000Z
src/editor/include/agz/editor/resource/resource_panel.inl
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
22
2019-03-04T01:47:56.000Z
2022-01-13T06:06:49.000Z
#pragma once AGZ_EDITOR_BEGIN template<typename TracerObject> ResourcePanel<TracerObject>::ResourcePanel( ObjectContext &obj_ctx, const QString &default_type) : obj_ctx_(obj_ctx) { type_selector_ = new ComboBoxWithoutWheelFocus(this); type_selector_->addItems(obj_ctx.factory<TracerObject>().get_type_names()); type_selector_->setCurrentText(default_type); auto change_type = [=](const QString &new_type) { if(rsc_widget_) delete rsc_widget_; rsc_widget_ = obj_ctx_.factory<TracerObject>() .create_widget(new_type, obj_ctx_); rsc_widget_->set_dirty_callback([=] { if(dirty_callback_) dirty_callback_(); }); rsc_widget_->set_geometry_vertices_dirty_callback([=] { set_geometry_vertices_dirty(); }); rsc_widget_->set_entity_transform_dirty_callback([=] { set_entity_transform_dirty(); }); layout_->addWidget(rsc_widget_); if(dirty_callback_) dirty_callback_(); set_geometry_vertices_dirty(); set_entity_transform_dirty(); }; signal_to_callback_.connect_callback( type_selector_, &ComboBoxWithoutWheelFocus::currentTextChanged, change_type); layout_ = new QVBoxLayout(this); layout_->addWidget(type_selector_); setContentsMargins(0, 0, 0, 0); layout_->setContentsMargins(0, 0, 0, 0); change_type(default_type); } template<typename TracerObject> ResourcePanel<TracerObject>::ResourcePanel( ObjectContext &obj_ctx, ResourceWidget<TracerObject> *rsc_widget, const QString &current_type_name) : obj_ctx_(obj_ctx) { type_selector_ = new ComboBoxWithoutWheelFocus(this); type_selector_->addItems(obj_ctx.factory<TracerObject>().get_type_names()); type_selector_->setCurrentText(current_type_name); signal_to_callback_.connect_callback( type_selector_, &ComboBoxWithoutWheelFocus::currentTextChanged, [=](const QString &new_type) { on_change_selected_type(); }); rsc_widget_ = rsc_widget; rsc_widget_->set_dirty_callback([=] { if(dirty_callback_) dirty_callback_(); }); rsc_widget_->set_geometry_vertices_dirty_callback([=] { set_geometry_vertices_dirty(); }); rsc_widget_->set_entity_transform_dirty_callback([=] { set_entity_transform_dirty(); }); layout_ = new QVBoxLayout(this); layout_->addWidget(type_selector_); layout_->addWidget(rsc_widget_); setContentsMargins(0, 0, 0, 0); layout_->setContentsMargins(0, 0, 0, 0); } template<typename TracerObject> void ResourcePanel<TracerObject>::set_dirty_callback(std::function<void()> callback) { dirty_callback_ = std::move(callback); } template<typename TracerObject> RC<TracerObject> ResourcePanel<TracerObject>::get_tracer_object() { return rsc_widget_->get_tracer_object(); } template<typename TracerObject> ResourcePanel<TracerObject> *ResourcePanel<TracerObject>::clone() const { return new ResourcePanel( obj_ctx_, rsc_widget_->clone(), type_selector_->currentText()); } template<typename TracerObject> Box<ResourceThumbnailProvider> ResourcePanel<TracerObject>::get_thumbnail( int width, int height) const { return rsc_widget_->get_thumbnail(width, height); } template<typename TracerObject> void ResourcePanel<TracerObject>::save_asset(AssetSaver &saver) const { saver.write_string(type_selector_->currentText()); rsc_widget_->save_asset(saver); } template<typename TracerObject> void ResourcePanel<TracerObject>::load_asset(AssetLoader &loader) { const QString type = loader.read_string(); type_selector_->setCurrentText(type); rsc_widget_->load_asset(loader); } template<typename TracerObject> RC<tracer::ConfigNode> ResourcePanel<TracerObject>::to_config( JSONExportContext &ctx) const { return rsc_widget_->to_config(ctx); } template<typename TracerObject> std::vector<EntityInterface::Vertex> ResourcePanel<TracerObject>::get_vertices() const { return rsc_widget_->get_vertices(); } template<typename TracerObject> DirectTransform ResourcePanel<TracerObject>::get_transform() const { return rsc_widget_->get_transform(); } template<typename TracerObject> void ResourcePanel<TracerObject>::set_transform(const DirectTransform &transform) { rsc_widget_->set_transform(transform); } template<typename TracerObject> void ResourcePanel<TracerObject>::on_change_selected_type() { if(rsc_widget_) delete rsc_widget_; const QString new_type = type_selector_->currentText(); rsc_widget_ = obj_ctx_.factory<TracerObject>() .create_widget(new_type, obj_ctx_); rsc_widget_->set_dirty_callback([=] { if(dirty_callback_) dirty_callback_(); }); rsc_widget_->set_geometry_vertices_dirty_callback([=] { set_geometry_vertices_dirty(); }); rsc_widget_->set_entity_transform_dirty_callback([=] { set_entity_transform_dirty(); }); layout_->addWidget(rsc_widget_); if(dirty_callback_) dirty_callback_(); set_geometry_vertices_dirty(); set_entity_transform_dirty(); } AGZ_EDITOR_END
26.959391
86
0.707211
AirGuanZ
0c4558d91be24b04143ea10613ae3e7e98f4258c
3,115
cc
C++
WinNTKline/KlineUtil/mygl/SDL_text.cc
TsyQi/MyAutomatic
2afd3dcabba818051c7119fac7e6c099ff7954a7
[ "Apache-2.0" ]
4
2016-08-19T08:16:49.000Z
2020-04-15T12:30:25.000Z
WinNTKline/KlineUtil/mygl/SDL_text.cc
TsyQi/Auto-control
d0dda0752d53d28f358346ee7ab217bf05118c96
[ "Apache-2.0" ]
null
null
null
WinNTKline/KlineUtil/mygl/SDL_text.cc
TsyQi/Auto-control
d0dda0752d53d28f358346ee7ab217bf05118c96
[ "Apache-2.0" ]
3
2019-03-23T03:40:24.000Z
2020-04-15T00:57:43.000Z
#include "SDL_text.h" int SDL_GL_init() { if (SDL_Init(SDL_INIT_EVERYTHING) == -1) return -1; //Initialize SDL_ttf return TTF_Init(); } void SDL_GL_Enter2DMode(int w, int h) { /* Note, there may be other things you need to change, depending on how you have your OpenGL state set up. */ glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); /* This allows alpha blending of 2D textures with the scene */ glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0.0, (GLdouble)w, (GLdouble)h, 0.0, 0.0, 1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } void SDL_GL_Leave2DMode() { glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); } /* Quick utility function for texture creation */ static int power_of_two(int input) { int value = 1; while (value < input) { value <<= 1; } return value; } GLuint SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord) { GLuint texture; int w, h; SDL_Surface *image; SDL_Rect area; Uint32 saved_flags; Uint8 saved_alpha; /* Use the surface width and height expanded to powers of 2 */ w = power_of_two(surface->w); h = power_of_two(surface->h); texcoord[0] = 0.0f; /* Min X */ texcoord[1] = 0.0f; /* Min Y */ texcoord[2] = (GLfloat)surface->w / w; /* Max X */ texcoord[3] = (GLfloat)surface->h / h; /* Max Y */ image = SDL_CreateRGBSurface( SDL_SWSURFACE, w, h, 32, #if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */ 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); if (image == NULL) { return 0; } /* Save the alpha blending attributes */ saved_flags = surface->flags&(SDL_SRCALPHA | SDL_RLEACCELOK); #if SDL_VERSION_ATLEAST(1, 3, 0) SDL_GetSurfaceAlphaMod(surface, &saved_alpha); SDL_SetSurfaceAlphaMod(surface, 0xFF); #else saved_alpha = surface->format->alpha; if ((saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA) { SDL_SetAlpha(surface, 0, 0); } #endif /* Copy the surface into the GL texture image */ area.x = 0; area.y = 0; area.w = surface->w; area.h = surface->h; SDL_BlitSurface(surface, &area, image, &area); /* Restore the alpha blending attributes */ #if SDL_VERSION_ATLEAST(1, 3, 0) SDL_SetSurfaceAlphaMod(surface, saved_alpha); #else if ((saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA) { SDL_SetAlpha(surface, saved_flags, saved_alpha); } #endif /* Create an OpenGL texture for the image */ glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels); SDL_FreeSurface(image); /* No longer needed */ return texture; }
22.092199
67
0.709791
TsyQi
0c475987bbe45d7f7c4f5d5c122d8c0ac6853adf
17,922
hpp
C++
include/eixx/connect/transport_msg.hpp
heri16/eixx
4352e356b68d2adbbdd0163ce3aaa93406c15ae2
[ "Apache-2.0" ]
91
2015-01-14T23:05:38.000Z
2022-03-21T07:20:02.000Z
include/eixx/connect/transport_msg.hpp
heri16/eixx
4352e356b68d2adbbdd0163ce3aaa93406c15ae2
[ "Apache-2.0" ]
32
2015-04-20T09:53:24.000Z
2021-09-28T21:39:41.000Z
include/eixx/connect/transport_msg.hpp
heri16/eixx
4352e356b68d2adbbdd0163ce3aaa93406c15ae2
[ "Apache-2.0" ]
21
2015-03-09T08:13:19.000Z
2021-08-09T11:52:44.000Z
//---------------------------------------------------------------------------- /// \file transport_msg.hpp //---------------------------------------------------------------------------- /// \brief Erlang distributed transport message type //---------------------------------------------------------------------------- // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-09-12 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Serge Aleynikov <saleyn at gmail dot com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***** END LICENSE BLOCK ***** */ #ifndef _EIXX_TRANSPORT_MSG_HPP_ #define _EIXX_TRANSPORT_MSG_HPP_ #include <eixx/marshal/eterm.hpp> #include <eixx/util/common.hpp> #include <ei.h> namespace eixx { namespace connect { using eixx::marshal::tuple; using eixx::marshal::list; using eixx::marshal::eterm; using eixx::marshal::epid; using eixx::marshal::ref; using eixx::marshal::trace; /// Erlang distributed transport messages contain message type, /// control message with message routing and other details, and /// optional user message for send and reg_send message types. template <typename Alloc> class transport_msg { public: enum transport_msg_type { UNDEFINED = 0 , LINK = 1 << ERL_LINK , SEND = 1 << ERL_SEND , EXIT = 1 << ERL_EXIT , UNLINK = 1 << ERL_UNLINK , NODE_LINK = 1 << ERL_NODE_LINK , REG_SEND = 1 << ERL_REG_SEND , GROUP_LEADER = 1 << ERL_GROUP_LEADER , EXIT2 = 1 << ERL_EXIT2 , SEND_TT = 1 << ERL_SEND_TT , EXIT_TT = 1 << ERL_EXIT_TT , REG_SEND_TT = 1 << ERL_REG_SEND_TT , EXIT2_TT = 1 << ERL_EXIT2_TT , MONITOR_P = 1 << ERL_MONITOR_P , DEMONITOR_P = 1 << ERL_DEMONITOR_P , MONITOR_P_EXIT = 1 << ERL_MONITOR_P_EXIT //--------------------------- , EXCEPTION = 1 << 31 // Non-Erlang defined code representing // message handling exception , NO_EXCEPTION_MASK = (uint32_t)EXCEPTION-1 }; private: // Note that the m_type is mutable so that we can call set_error_flag() on // constant objects. mutable transport_msg_type m_type; tuple<Alloc> m_cntrl; eterm<Alloc> m_msg; public: transport_msg() : m_type(UNDEFINED) {} transport_msg(int a_msgtype, const tuple<Alloc>& a_cntrl, const eterm<Alloc>* a_msg = NULL) : m_type(1 << a_msgtype), m_cntrl(a_cntrl) { if (a_msg) new (&m_msg) eterm<Alloc>(*a_msg); } transport_msg(const transport_msg& rhs) : m_type(rhs.m_type), m_cntrl(rhs.m_cntrl), m_msg(rhs.m_msg) {} transport_msg(transport_msg&& rhs) : m_type(rhs.m_type), m_cntrl(std::move(rhs.m_cntrl)), m_msg(std::move(rhs.m_msg)) { rhs.m_type = UNDEFINED; } /// Return a string representation of the transport message type. const char* type_string() const; /// Transport message type transport_msg_type type() const { return m_type; } int to_type() const { return m_type == UNDEFINED ? 0 : bit_scan_forward(m_type); } const tuple<Alloc>& cntrl() const { return m_cntrl;} const eterm<Alloc>& msg() const { return m_msg; } /// Returns true when the transport message contains message payload /// associated with SEND or REG_SEND message type. bool has_msg() const { return m_msg.type() != eixx::UNDEFINED; } /// Indicates that there was an error processing this message bool has_error() const { return (m_type & EXCEPTION) == EXCEPTION; } /// Set an error flag indicating a problem processing this message void set_error_flag() const { m_type = static_cast<transport_msg_type>(m_type | EXCEPTION); } /// Return the term representing the message sender. The sender is /// usually a pid, except for MONITOR_P_EXIT message type for which /// the sender can be either pid or atom name. const eterm<Alloc>& sender() const { switch (m_type) { case REG_SEND: case LINK: case UNLINK: case EXIT: case EXIT2: case GROUP_LEADER: case REG_SEND_TT: case EXIT_TT: case EXIT2_TT: case MONITOR_P: case DEMONITOR_P: case MONITOR_P_EXIT: return m_cntrl[1]; default: throw err_wrong_type(m_type, "transport_msg.from()"); } } /// This function may only raise exception for MONITOR_P_EXIT /// message types if the message sender is given by name rather than by pid. /// @throws err_wrong_type const epid<Alloc>& sender_pid() const { return sender().to_pid(); } /// Return the term representing the message sender. The sender is /// usually a pid, except for MONITOR_P|DEMONITOR_P message type for which /// the sender can be either pid or atom name. const eterm<Alloc>& recipient() const { switch (m_type) { case REG_SEND: return m_cntrl[3]; case REG_SEND_TT: return m_cntrl[4]; case SEND: case LINK: case UNLINK: case EXIT: case EXIT2: case GROUP_LEADER: case SEND_TT: case EXIT_TT: case EXIT2_TT: case MONITOR_P: case DEMONITOR_P: case MONITOR_P_EXIT: return m_cntrl[2]; default: throw err_wrong_type(m_type, "transport_msg.to()"); } } /// This function may only raise exception for MONITOR_P|DEMONITOR_P /// message types if the message sender is given by name rather than by pid. /// @throws err_wrong_type const epid<Alloc>& recipient_pid() const { return recipient().to_pid(); } /// @throws err_wrong_type const atom& recipient_name() const { return recipient().to_atom(); } /// @throws err_wrong_type const eterm<Alloc>& trace_token() const { switch (m_type) { case SEND_TT: case EXIT_TT: case EXIT2_TT: return m_cntrl[3]; case REG_SEND_TT: return m_cntrl[4]; default: throw err_wrong_type(m_type, "SEND_TT|EXIT_TT|EXIT2_TT|REG_SEND_TT"); } } /// @throws err_wrong_type const ref<Alloc>& get_ref() const { switch (m_type) { case MONITOR_P: case DEMONITOR_P: case MONITOR_P_EXIT: return m_cntrl[3].to_ref(); default: throw err_wrong_type(m_type, "MONITOR_P|DEMONITOR_P|MONITOR_P_EXIT"); } } /// @throws err_wrong_type const eterm<Alloc>& reason() const { switch (m_type) { case EXIT: case EXIT2: return m_cntrl[3]; case EXIT_TT: case EXIT2_TT: case MONITOR_P_EXIT:return m_cntrl[4]; default: throw err_wrong_type(m_type, "EXIT|EXIT2|EXIT_TT|EXIT2_TT|MONITOR_P_EXIT"); } } /// Initialize the object with given components. void set(int a_msgtype, const tuple<Alloc>& a_cntrl, const eterm<Alloc>* a_msg = NULL) { m_type = static_cast<transport_msg_type>(1 << a_msgtype); m_cntrl = a_cntrl; if (a_msg) m_msg = *a_msg; else m_msg.clear(); } /// Set the current message to represent a SEND message containing \a a_msg to /// be sent to \a a_to pid. void set_send(const epid<Alloc>& a_to, const eterm<Alloc>& a_msg, const Alloc& a_alloc = Alloc()) { const trace<Alloc>* token = trace<Alloc>::tracer(marshal::TRACE_GET); if (unlikely(token)) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(ERL_SEND_TT, atom(), a_to, *token, a_alloc); set(ERL_SEND_TT, l_cntrl, &a_msg); } else { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(ERL_SEND, atom(), a_to, a_alloc); set(ERL_SEND, l_cntrl, &a_msg); } } /// Set the current message to represent a REG_SEND message containing /// \a a_msg to be sent from \a a_from pid to \a a_to registered mailbox. void set_reg_send(const epid<Alloc>& a_from, const atom& a_to, const eterm<Alloc>& a_msg, const Alloc& a_alloc = Alloc()) { const trace<Alloc>* token = trace<Alloc>::tracer(marshal::TRACE_GET); if (unlikely(token)) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(ERL_REG_SEND_TT, a_from, atom(), a_to, *token, a_alloc); set(ERL_REG_SEND_TT, l_cntrl, &a_msg); } else { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(ERL_REG_SEND, a_from, atom(), a_to, a_alloc); set(ERL_REG_SEND, l_cntrl, &a_msg); } } /// Set the current message to represent a LINK message. void set_link(const epid<Alloc>& a_from, const epid<Alloc>& a_to, const Alloc& a_alloc = Alloc()) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(ERL_LINK, a_from, a_to, a_alloc); set(LINK, l_cntrl, NULL); } /// Set the current message to represent an UNLINK message. void set_unlink(const epid<Alloc>& a_from, const epid<Alloc>& a_to, const Alloc& a_alloc = Alloc()) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(ERL_UNLINK, a_from, a_to, a_alloc); set(UNLINK, l_cntrl, NULL); } /// Set the current message to represent an EXIT message with \a a_reason /// sent from \a a_from pid to \a a_to pid. void set_exit(const epid<Alloc>& a_from, const epid<Alloc>& a_to, const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc()) { set_exit_internal(ERL_EXIT, ERL_EXIT_TT, a_from, a_to, a_reason, a_alloc); } /// Set the current message to represent an EXIT2 message. void set_exit2(const epid<Alloc>& a_from, const epid<Alloc>& a_to, const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc()) { set_exit_internal(ERL_EXIT2, ERL_EXIT2_TT, a_from, a_to, a_reason, a_alloc); } /// Set the current message to represent a MONITOR message. void set_monitor(const epid<Alloc>& a_from, const epid<Alloc>& a_to, const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc()) { set_monitor_internal(ERL_MONITOR_P, a_from, a_to, a_ref, a_alloc); } /// Set the current message to represent a MONITOR message. void set_monitor(const epid<Alloc>& a_from, const atom& a_to, const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc()) { set_monitor_internal(ERL_MONITOR_P, a_from, a_to, a_ref, a_alloc); } /// Set the current message to represent a DEMONITOR message. void set_demonitor(const epid<Alloc>& a_from, const epid<Alloc>& a_to, const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc()) { set_monitor_internal(ERL_DEMONITOR_P, a_from, a_to, a_ref, a_alloc); } /// Set the current message to represent a DEMONITOR message. void set_demonitor(const epid<Alloc>& a_from, const atom& a_to, const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc()) { set_monitor_internal(ERL_DEMONITOR_P, a_from, a_to, a_ref, a_alloc); } /// Set the current message to represent a MONITOR_EXIT message. void set_monitor_exit(const epid<Alloc>& a_from, const epid<Alloc>& a_to, const ref<Alloc>& a_ref, const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc()) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make( ERL_MONITOR_P_EXIT, a_from, a_to, a_ref, a_reason, a_alloc); set(ERL_MONITOR_P_EXIT, l_cntrl, NULL); } /// Set the current message to represent a MONITOR_EXIT message. void set_monitor_exit(const atom& a_from, const epid<Alloc>& a_to, const ref<Alloc>& a_ref, const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc()) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make( ERL_MONITOR_P_EXIT, a_from, a_to, a_ref, a_reason, a_alloc); set(ERL_MONITOR_P_EXIT, l_cntrl, NULL); } /// Send RPC call request. /// Result will be delivered to the mailbox of the \a a_from pid. /// The RPC consists of two parts, send and receive. /// Here is the send part: <tt>{ PidFrom, { call, Mod, Fun, Args, user }}</tt> void set_send_rpc(const epid<Alloc>& a_from, const atom& mod, const atom& fun, const list<Alloc>& args, const epid<Alloc>* a_gleader = NULL, const Alloc& a_alloc = Alloc()) { static atom s_cmd("call"); static eterm<Alloc> s_user(atom("user")); eterm<Alloc> gleader(a_gleader == NULL ? s_user : eterm<Alloc>(*a_gleader)); const tuple<Alloc>& inner_tuple = tuple<Alloc>::make(a_from, tuple<Alloc>::make(s_cmd, mod, fun, args, gleader, a_alloc), a_alloc); set_send_rpc_internal(a_from, inner_tuple, a_alloc); } /// Send RPC cast request. /// The result of this RPC cast is discarded. /// Here is the send part: /// <tt>{PidFrom, {'$gen_cast', {cast, Mod, Fun, Args, user}}}</tt> void set_send_rpc_cast(const epid<Alloc>& a_from, const atom& mod, const atom& fun, const list<Alloc>& args, const epid<Alloc>* a_gleader = NULL, const Alloc& a_alloc = Alloc()) { static atom s_gen_cast("$gen_cast"); static atom s_cmd("cast"); static eterm<Alloc> s_user(atom("user")); eterm<Alloc> gleader(a_gleader == NULL ? s_user : eterm<Alloc>(*a_gleader)); const tuple<Alloc>& inner_tuple = tuple<Alloc>::make(s_gen_cast, tuple<Alloc>::make(s_cmd, mod, fun, args, gleader, a_alloc), a_alloc); set_send_rpc_internal(a_from, inner_tuple, a_alloc); } std::ostream& dump(std::ostream& out) const { out << "#DistMsg{" << (has_error() ? "has_error, " : "") << "type=" << type_string() << ", cntrl=" << cntrl(); if (has_msg()) out << ", msg=" << msg().to_string(); return out << '}'; } std::string to_string() const { std::stringstream s; dump(s); return s.str(); } private: void set_exit_internal(int a_type, int a_trace_type, const epid<Alloc>& a_from, const epid<Alloc>& a_to, const eterm<Alloc>& a_reason, const Alloc& a_alloc = Alloc()) { const trace<Alloc>* token = trace<Alloc>::tracer(marshal::TRACE_GET); if (unlikely(token)) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(a_trace_type, a_from, a_to, *token, a_reason, a_alloc); set(a_trace_type, l_cntrl, NULL); } else { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(a_type, a_from, a_to, a_reason, a_alloc); set(a_type, l_cntrl, NULL); } } template <typename FromProc, typename ToProc> void set_monitor_internal(int a_type, FromProc a_from, ToProc a_to, const ref<Alloc>& a_ref, const Alloc& a_alloc = Alloc()) { const tuple<Alloc>& l_cntrl = tuple<Alloc>::make(a_type, a_from, a_to, a_ref, a_alloc); set(a_type, l_cntrl, NULL); } void set_send_rpc_internal(const epid<Alloc>& a_from, const tuple<Alloc>& a_cmd, const Alloc& a_alloc = Alloc()) { static atom rex("rex"); set_reg_send(a_from, rex, eterm<Alloc>(a_cmd), a_alloc); } }; template <typename Alloc> const char* transport_msg<Alloc>::type_string() const { switch (m_type & NO_EXCEPTION_MASK) { case UNDEFINED: return "UNDEFINED"; case LINK: return "LINK"; case SEND: return "SEND"; case EXIT: return "EXIT"; case UNLINK: return "UNLINK"; case NODE_LINK: return "NODE_LINK"; case REG_SEND: return "REG_SEND"; case GROUP_LEADER: return "GROUP_LEADER"; case EXIT2: return "EXIT2"; case SEND_TT: return "SEND_TT"; case EXIT_TT: return "EXIT_TT"; case REG_SEND_TT: return "REG_SEND_TT"; case EXIT2_TT: return "EXIT2_TT"; case MONITOR_P: return "MONITOR_P"; case DEMONITOR_P: return "DEMONITOR_P"; case MONITOR_P_EXIT: return "MONITOR_P_EXIT"; default: { // std::stringstream str; str << "UNSUPPORTED(" << bit_scan_forward(m_type) << ')'; // return str.str().c_str(); return "UNSUPPORTED"; } } } } // namespace connect } // namespace eixx namespace std { template <typename Alloc> ostream& operator<< (ostream& out, eixx::connect::transport_msg<Alloc>& a_msg) { return a_msg.dump(out); } } // namespace std #endif // _EIXX_TRANSPORT_MSG_HPP_
37.572327
104
0.587267
heri16
0c4a16d45949472519183e9243784ba1944d70c6
3,069
cpp
C++
server/src/sink.cpp
imsoo/darknet_server
adb94237804e62bcccbbe5f7810da60640aef1d9
[ "MIT" ]
25
2020-02-08T12:08:20.000Z
2022-03-15T12:17:07.000Z
server/src/sink.cpp
gwnuysw/darknet_server
8b587038a165be23a1c83c32b31e92509de631e2
[ "MIT" ]
12
2020-02-14T09:01:26.000Z
2021-10-30T14:59:49.000Z
server/src/sink.cpp
gwnuysw/darknet_server
8b587038a165be23a1c83c32b31e92509de631e2
[ "MIT" ]
11
2019-12-21T00:30:16.000Z
2021-11-23T09:01:02.000Z
#include <zmq.h> #include <stdio.h> #include <iostream> #include <string> #include <csignal> #include <assert.h> #include <tbb/concurrent_hash_map.h> #include <opencv2/opencv.hpp> #include "share_queue.h" #include "frame.hpp" // ZMQ void *sock_pull; void *sock_pub; // ShareQueue tbb::concurrent_hash_map<int, Frame> frame_map; SharedQueue<Frame> processed_frame_queue; // pool Frame_pool *frame_pool; // signal volatile bool exit_flag = false; void sig_handler(int s) { exit_flag = true; } void *recv_in_thread(void *ptr) { int recv_json_len; unsigned char json_buf[JSON_BUF_LEN]; Frame frame; while(!exit_flag) { recv_json_len = zmq_recv(sock_pull, json_buf, JSON_BUF_LEN, ZMQ_NOBLOCK); if (recv_json_len > 0) { frame = frame_pool->alloc_frame(); json_buf[recv_json_len] = '\0'; json_to_frame(json_buf, frame); #ifdef DEBUG std::cout << "Sink | Recv From Worker | SEQ : " << frame.seq_buf << " LEN : " << frame.msg_len << std::endl; #endif tbb::concurrent_hash_map<int, Frame>::accessor a; while(1) { if(frame_map.insert(a, atoi((char *)frame.seq_buf))) { a->second = frame; break; } } } } } void *send_in_thread(void *ptr) { int send_json_len; unsigned char json_buf[JSON_BUF_LEN]; Frame frame; while(!exit_flag) { if (processed_frame_queue.size() > 0) { frame = processed_frame_queue.front(); processed_frame_queue.pop_front(); #ifdef DEBUG std::cout << "Sink | Pub To Client | SEQ : " << frame.seq_buf << " LEN : " << frame.msg_len << std::endl; #endif send_json_len = frame_to_json(json_buf, frame); zmq_send(sock_pub, json_buf, send_json_len, 0); frame_pool->free_frame(frame); } } } int main() { // ZMQ int ret; void *context = zmq_ctx_new(); sock_pull = zmq_socket(context, ZMQ_PULL); ret = zmq_bind(sock_pull, "ipc://processed"); assert(ret != -1); sock_pub = zmq_socket(context, ZMQ_PUB); ret = zmq_bind(sock_pub, "tcp://*:5570"); assert(ret != -1); // frame_pool frame_pool = new Frame_pool(5000); // Thread pthread_t recv_thread; if (pthread_create(&recv_thread, 0, recv_in_thread, 0)) std::cerr << "Thread creation failed (recv_thread)" << std::endl; pthread_t send_thread; if (pthread_create(&send_thread, 0, send_in_thread, 0)) std::cerr << "Thread creation failed (recv_thread)" << std::endl; pthread_detach(send_thread); pthread_detach(recv_thread); // frame Frame frame; volatile int track_frame = 1; while(!exit_flag) { if (!frame_map.empty()) { tbb::concurrent_hash_map<int, Frame>::accessor c_a; if (frame_map.find(c_a, (const int)track_frame)) { frame = (Frame)c_a->second; while(1) { if (frame_map.erase(c_a)) break; } processed_frame_queue.push_back(frame); track_frame++; } } } delete frame_pool; zmq_close(sock_pull); zmq_close(sock_pub); zmq_ctx_destroy(context); return 0; }
21.612676
77
0.641251
imsoo
0c4b1659eb975da0e7c9e93a05b75480a5b514a8
8,861
cpp
C++
unit/json/json_parser.cpp
MatWise/cbmc
c9284aee34bae53ba2b3dce8810720735e0a94fa
[ "BSD-4-Clause" ]
null
null
null
unit/json/json_parser.cpp
MatWise/cbmc
c9284aee34bae53ba2b3dce8810720735e0a94fa
[ "BSD-4-Clause" ]
null
null
null
unit/json/json_parser.cpp
MatWise/cbmc
c9284aee34bae53ba2b3dce8810720735e0a94fa
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Example Catch Tests Author: Diffblue Ltd. \*******************************************************************/ #include <fstream> #include <json/json_parser.h> #include <testing-utils/message.h> #include <testing-utils/use_catch.h> #include <util/tempfile.h> SCENARIO("Loading JSON files") { GIVEN("A invalid JSON file and a valid JSON file") { temporary_filet valid_json_file("cbmc_unit_json_parser_valid", ".json"); temporary_filet invalid_json_file("cbmc_unit_json_parser_invalid", ".json"); const std::string valid_json_path = valid_json_file(); const std::string invalid_json_path = invalid_json_file(); { std::ofstream valid_json_out(valid_json_path); valid_json_out << "{\n" << " \"hello\": \"world\"\n" << "}\n"; } { std::ofstream invalid_json_out(invalid_json_path); invalid_json_out << "foo\n"; } WHEN("Loading the invalid JSON file") { jsont invalid_json; const auto invalid_parse_error = parse_json(invalid_json_path, null_message_handler, invalid_json); THEN("An error state should be returned") { REQUIRE(invalid_parse_error); REQUIRE(invalid_json.is_null()); AND_WHEN("Loading the valid JSON file") { jsont valid_json; const auto valid_parse_error = parse_json(valid_json_path, null_message_handler, valid_json); THEN("The JSON file should be parsed correctly") { REQUIRE_FALSE(valid_parse_error); REQUIRE(valid_json.is_object()); const json_objectt &json_object = to_json_object(valid_json); REQUIRE(json_object.find("hello") != json_object.end()); REQUIRE(json_object["hello"].value == "world"); } } } } WHEN("Loading the valid JSON file") { jsont valid_json; const auto valid_parse_error = parse_json(valid_json_path, null_message_handler, valid_json); THEN("The JSON file should be parsed correctly") { REQUIRE_FALSE(valid_parse_error); REQUIRE(valid_json.is_object()); const json_objectt &json_object = to_json_object(valid_json); REQUIRE(json_object.find("hello") != json_object.end()); REQUIRE(json_object["hello"].value == "world"); AND_WHEN("Loading the invalid JSON file") { jsont invalid_json; const auto invalid_parse_error = parse_json(invalid_json_path, null_message_handler, invalid_json); THEN("An error state should be returned") { REQUIRE(invalid_parse_error); REQUIRE(invalid_json.is_null()); } } } } } GIVEN("A JSON file containing hexadecimal Unicode symbols") { temporary_filet unicode_json_file("cbmc_unit_json_parser_unicode", ".json"); const std::string unicode_json_path = unicode_json_file(); { std::ofstream unicode_json_out(unicode_json_path); unicode_json_out << "{\n" << " \"one\": \"\\u0001\",\n" << " \"latin\": \"\\u0042\",\n" << " \"grave\": \"\\u00E0\",\n" << " \"trema\": \"\\u00FF\",\n" << " \"high\": \"\\uFFFF\",\n" << " \"several\": \"a\\u0041b\\u2FC3\\uFFFF\"\n" << "}\n"; } WHEN("Loading the JSON file with the Unicode symbols") { jsont unicode_json; const auto unicode_parse_error = parse_json(unicode_json_path, null_message_handler, unicode_json); THEN("The JSON file should be parsed correctly") { REQUIRE_FALSE(unicode_parse_error); REQUIRE(unicode_json.is_object()); const json_objectt &json_object = to_json_object(unicode_json); REQUIRE(json_object.find("one") != json_object.end()); REQUIRE(json_object["one"].value.size() == 1); REQUIRE(json_object["one"].value == u8"\u0001"); REQUIRE(json_object.find("latin") != json_object.end()); REQUIRE(json_object["latin"].value == "B"); REQUIRE(json_object.find("grave") != json_object.end()); REQUIRE(json_object["grave"].value == "à"); REQUIRE(json_object.find("trema") != json_object.end()); REQUIRE(json_object["trema"].value == "ÿ"); REQUIRE(json_object.find("high") != json_object.end()); REQUIRE(json_object["high"].value == u8"\uFFFF"); REQUIRE(json_object.find("several") != json_object.end()); REQUIRE(json_object["several"].value == u8"aAb\u2FC3\uFFFF"); } } } } TEST_CASE("json equality", "[core][util][json]") { SECTION("null") { REQUIRE(jsont::null_json_object == jsont::null_json_object); } SECTION("boolean") { REQUIRE(jsont::json_boolean(false) == jsont::json_boolean(false)); REQUIRE(jsont::json_boolean(true) == jsont::json_boolean(true)); REQUIRE_FALSE(jsont::json_boolean(true) == jsont::json_boolean(false)); REQUIRE_FALSE(jsont::json_boolean(false) == jsont::null_json_object); } SECTION("number") { REQUIRE(json_numbert("0") == json_numbert("0")); REQUIRE(json_numbert("1") == json_numbert("1")); REQUIRE(json_numbert("-1") == json_numbert("-1")); REQUIRE(json_numbert("1.578") == json_numbert("1.578")); REQUIRE_FALSE(json_numbert("0") == json_numbert("1")); REQUIRE_FALSE(json_numbert("1") == json_numbert("-1")); REQUIRE_FALSE(json_numbert("-1") == json_numbert("1")); REQUIRE_FALSE(json_numbert("1.578") == json_numbert("1.5789")); REQUIRE_FALSE(json_numbert("0") == jsont::json_boolean(false)); REQUIRE_FALSE(jsont::json_boolean(false) == json_numbert("0")); REQUIRE_FALSE(json_numbert("0") == jsont::null_json_object); REQUIRE_FALSE(jsont::null_json_object == json_numbert("0")); } SECTION("string") { REQUIRE(json_stringt("") == json_stringt("")); REQUIRE(json_stringt("foo") == json_stringt("foo")); REQUIRE(json_stringt("bar") == json_stringt("bar")); REQUIRE_FALSE(json_stringt("foo") == json_stringt("bar")); REQUIRE_FALSE(json_stringt("bar") == json_stringt("baz")); REQUIRE_FALSE(json_stringt("foo") == json_stringt("food")); REQUIRE_FALSE(json_stringt("1") == json_numbert("1")); REQUIRE_FALSE(json_stringt("true") == jsont::json_boolean("true")); REQUIRE_FALSE(json_stringt("") == jsont::json_boolean("false")); REQUIRE_FALSE(json_stringt("") == jsont::null_json_object); } SECTION("array") { REQUIRE(json_arrayt{} == json_arrayt{}); REQUIRE( json_arrayt{jsont::null_json_object} == json_arrayt{jsont::null_json_object}); REQUIRE( json_arrayt{json_numbert{"9"}, json_numbert{"6"}} == json_arrayt{json_numbert{"9"}, json_numbert{"6"}}); REQUIRE( json_arrayt{ json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}} == json_arrayt{ json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}}); // different lengths REQUIRE_FALSE( json_arrayt{json_stringt{"foo"}, json_stringt{"bar"}} == json_arrayt{ json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}}); // different elements REQUIRE_FALSE( json_arrayt{ json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"foo"}} == json_arrayt{ json_stringt{"foo"}, json_stringt{"bar"}, json_stringt{"baz"}}); // different kind REQUIRE_FALSE(json_arrayt{} == jsont::json_boolean(false)); REQUIRE_FALSE(json_arrayt{} == jsont::null_json_object); } SECTION("object") { REQUIRE(json_objectt{} == json_objectt{}); REQUIRE( json_objectt{{"key", json_stringt{"value"}}} == json_objectt{{"key", json_stringt{"value"}}}); REQUIRE( json_objectt{{"key1", json_stringt{"value1"}}, {"key2", json_stringt{"value2"}}} == json_objectt{{"key1", json_stringt{"value1"}}, {"key2", json_stringt{"value2"}}}); // Extra property REQUIRE_FALSE( json_objectt{{"key1", json_stringt{"value1"}}, {"key2", json_stringt{"value2"}}, {"key3", json_stringt{"value3"}}} == json_objectt{{"key1", json_stringt{"value1"}}, {"key2", json_stringt{"value2"}}}); // different field values REQUIRE_FALSE( json_objectt{{"key1", json_stringt{"foo"}}, {"key2", json_stringt{"bar"}}} == json_objectt{{"key1", json_stringt{"foo"}}, {"key2", json_stringt{"baz"}}}); // different kind REQUIRE_FALSE(json_objectt{} == json_arrayt{}); REQUIRE_FALSE(json_objectt{} == jsont::null_json_object); } }
36.465021
80
0.601061
MatWise
0c4b7f83560a70b80162f8aaf1e2b1d8cc2b0c04
54
hh
C++
RAVL2/MSVC/include/Ravl/Logic/BMinTermListIndex.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/Logic/BMinTermListIndex.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/Logic/BMinTermListIndex.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#include "../.././Logic/Index/BMinTermListIndex.hh"
13.5
51
0.666667
isuhao
0c4c295db47b3a08553e5a74646d2fbd50939d6f
1,823
cpp
C++
CodeForces/educationalNuevo/e.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
CodeForces/educationalNuevo/e.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
CodeForces/educationalNuevo/e.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <stdio.h> #include <string> #include <vector> #include <map> #include <math.h> #include <numeric> #include <queue> #include <stack> #include <utility> #include <queue> #include <set> #include <iomanip> using namespace std; typedef int64_t ll; typedef pair<int,ll> pill; typedef pair<int,int> pii; #define INF 1000000000000 #define MOD 998244353 #define loop(i,a,b) for(int i = a; i < b; ++i) const int maxN = 18, maxNodos = (1<<18)-1; int n, cantNodos; string s; string claseEquivalencia[maxNodos+5]; void calculaEquiv(int id){ if(id<<1 < cantNodos){ calculaEquiv(id<<1); calculaEquiv( (id<<1) +1); if(claseEquivalencia[id<<1] < claseEquivalencia[ (id<<1)+1]) claseEquivalencia[id] = s[id-1] + claseEquivalencia[id<<1] + claseEquivalencia[(id<<1)+1]; else claseEquivalencia[id] = s[id-1] + claseEquivalencia[(id<<1)+1] + claseEquivalencia[id<<1]; } else{ claseEquivalencia[id] = s[id-1]; } } ll dp[maxNodos+5]; void calculaDP(int id){ if( (id<<1) > cantNodos){ dp[id] = 1; } else{ calculaDP(id<<1); calculaDP((id<<1) + 1); if(claseEquivalencia[id<<1] == claseEquivalencia[(id<<1)+1]) dp[id] = (dp[id<<1]*dp[id<<1])%MOD; else{ dp[id] = (dp[id<<1]*dp[(id<<1)+1])%MOD; dp[id] = (2*dp[id])%MOD; } } } void solve(){ cin>>n>>s; cantNodos = (1<<n)-1; //calcula claseEquivalencia calculaEquiv(1); //calculaDP calculaDP(1); cout<<dp[1]<<"\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); //if(fopen("case.txt", "r")) freopen("case.txt", "r", stdin); int t = 1; //int t; cin>>t; loop(i, 0, t){ solve(); } return 0; }
21.963855
102
0.565551
CaDe27
0c5105027af358908eec4130f7d5906348088de6
8,773
cpp
C++
src/UnitTests/TestLagrangeInterpolator/TestLagrangeInterpolator.cpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
src/UnitTests/TestLagrangeInterpolator/TestLagrangeInterpolator.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
src/UnitTests/TestLagrangeInterpolator/TestLagrangeInterpolator.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//$Id$ //------------------------------------------------------------------------------ // TestLagrangeInterpolator //------------------------------------------------------------------------------ // GMAT: Goddard Mission Analysis Tool // // Author: Linda Jun // Created: 2009.09.28 // /** /** * Purpose: * Unit test driver of LagrangeInterpolator class. * * Output file: * TestLagrangeInterpolatorOut.txt * * Description of LagrangeInterpolator: * The LagrangeInterpolator class interpolates data at the desired * interpolation point. (See GMAT Math Spec on Lagrange Interpolation) * * Test Procedure: * + Create LagrangeInterpolator with order of 20. * - buffer size should be set to maximum of 22 * + Create LagrangeInterpolator with order of 7. * + Test exceptions: * - non-monotonic dada * - too few data points * - desired point not within the range * + Test interpolate for points less than buffer size. * + Test interpolate for points more than buffer size. * + Test with some realistic data * * Validation method: * The test driver code knows expected results and throws an exception if the * result is not within the tolerance. */ //------------------------------------------------------------------------------ #include <iostream> #include <string> #include "gmatdefs.hpp" #include "LagrangeInterpolator.hpp" #include "TestOutput.hpp" #include "MessageInterface.hpp" #include "ConsoleMessageReceiver.hpp" using namespace std; using namespace GmatMathUtil; //------------------------------------------------------------------------------ //int RunTest(TestOutput &out) //------------------------------------------------------------------------------ int RunTest(TestOutput &out) { //--------------------------------------------------------------------------- out.Put("========================= Test LagrangeInterpolator constructor"); out.Put("========================= Test order of 20, buffer size should set to maximum of 22"); LagrangeInterpolator lagrange20("MyLagrange", 3, 20); Integer bufSize = lagrange20.GetBufferSize(); out.Put("buffer size is ", bufSize); out.Put(""); out.Put("========================= Now create LagrangeInterpolator of order of 7 and continue"); LagrangeInterpolator lagrangeInterp("MyLagrange", 3, 7); Real xReq, yIn[3], yOut[3]; yIn[0] = 1.0; yIn[1] = 2.0; yIn[2] = 3.0; yOut[0] = -999.999; yOut[1] = -999.999; yOut[2] = -999.999; //----------------------------------------------------------------- // Test non-monotonic datda //----------------------------------------------------------------- out.Put("========================= Test non-monotonic dada"); try { for (int i = 1; i <= 3; i++) lagrangeInterp.AddPoint(Real(i), yIn); lagrangeInterp.AddPoint(1.0, yIn); } catch (BaseException &e) { out.Put(e.GetFullMessage()); } //----------------------------------------------------------------- // Test interpolation feasiblility, data points less than required //----------------------------------------------------------------- out.Put(""); out.Put("========================= Test data points less than required"); lagrangeInterp.Clear(); try { for (int i = 1; i <= 3; i++) lagrangeInterp.AddPoint(Real(i), yIn); lagrangeInterp.Interpolate(2.5, yOut); } catch (BaseException &e) { out.Put(e.GetFullMessage()); } //----------------------------------------------------------------- // Test interpolation feasiblility, data points not within range //----------------------------------------------------------------- out.Put(""); out.Put("========================= Test desired point not within range"); lagrangeInterp.Clear(); try { for (int i = 1; i <= 8; i++) lagrangeInterp.AddPoint(Real(i), yIn); xReq = 9; lagrangeInterp.Interpolate(xReq, yOut); out.Put("*** ERROR *** We shouldn't get this\n" "Interpolated value of ", xReq, " are ", yOut[0]); } catch (BaseException &e) { out.Put(e.GetFullMessage()); } //----------------------------------------------------------------- // Now interpolate for points less than buffer size //----------------------------------------------------------------- out.Put(""); out.Put("========================= Test interpolate for points less than buffer size"); lagrangeInterp.Clear(); try { for (int i = 1; i <= 8; i++) { for (int j=0; j<3; j++) yIn[j] = Real(j + i); lagrangeInterp.AddPoint(Real(i), yIn); } xReq = 3.5; lagrangeInterp.Interpolate(xReq, yOut); out.Put("Interpolated value of ", xReq, " are ", yOut[0], yOut[1], yOut[2]); xReq = 7.5; lagrangeInterp.Interpolate(xReq, yOut); out.Put("Interpolated value of ", xReq, " are ", yOut[0], yOut[1], yOut[2]); } catch (BaseException &e) { out.Put(e.GetFullMessage()); } //----------------------------------------------------------------- // Now add some more points so that it buffers from the beginning //----------------------------------------------------------------- out.Put(""); out.Put("========================= Test interpolate for points more than buffer size"); try { for (int i = 9; i <= 23; i++) { for (int j=0; j<3; j++) yIn[j] = Real(j + i); lagrangeInterp.AddPoint(Real(i), yIn); } xReq = 8.5; lagrangeInterp.Interpolate(xReq, yOut); out.Put("Interpolated value of ", xReq, " are ", yOut[0], yOut[1], yOut[2]); xReq = 15.5; lagrangeInterp.Interpolate(xReq, yOut); out.Put("Interpolated value of ", xReq, " are ", yOut[0], yOut[1], yOut[2]); xReq = 20.5; lagrangeInterp.Interpolate(xReq, yOut); out.Put("Interpolated value of ", xReq, " are ", yOut[0], yOut[1], yOut[2]); } catch (BaseException &e) { out.Put(e.GetFullMessage()); } //----------------------------------------------------------------- // Now try with more meaningful data given from Steve //----------------------------------------------------------------- out.Put(""); out.Put("========================= Test interpolate with some realistic data"); lagrangeInterp.Clear(); try { //----- Create the functions table to be interpolated Real x[8]; Real f[8][3]; Real xi[3], fe[3][3], fi[3]; for (int i = 0; i < 8; i++) { x[i] = Real(i + 1); f[i][0] = Pow(x[i],2) - 2.0*x[i] + 3.0; f[i][1] = Pow(x[i],3) + Exp(x[i]/100); f[i][2] = Sin(x[i]/30); } //----- Create the exact solutions at the interpolation points xi[0] = 3.3415; xi[1] = 5.3333333333333333; xi[2] = 7.3426; for (int i = 0; i < 3; i++) { fe[i][0] = Pow(xi[i],2) - 2*xi[i] + 3; fe[i][1] = Pow(xi[i],3) + Exp(xi[i]/100); fe[i][2] = Sin(xi[i]/30); } //------ Add points for (int i = 0; i < 8; i++) lagrangeInterp.AddPoint(x[i], f[i]); //------ Perform the interpolation for (int i = 0; i < 3; i++) { lagrangeInterp.Interpolate(xi[i], fi); out.Put("Interpolated value of ", xi[i], " are ", fi[0], fi[1], fi[2]); out.Validate(fi[0], fi[1], fi[2], fe[i][0], fe[i][1], fe[i][2]); } } catch (BaseException &e) { out.Put(e.GetFullMessage()); } //--------------------------------------------------------------------------- } //------------------------------------------------------------------------------ // int main(int argc, char *argv[]) //------------------------------------------------------------------------------ int main(int argc, char *argv[]) { ConsoleMessageReceiver *consoleMsg = ConsoleMessageReceiver::Instance(); MessageInterface::SetMessageReceiver(consoleMsg); std::string outPath = "../../TestLagrangeInterpolator/"; MessageInterface::SetLogFile(outPath + "GmatLog.txt"); std::string outFile = outPath + "TestLagrangeInterpolatorOut.txt"; TestOutput out(outFile); try { RunTest(out); out.Put("\nSuccessfully ran unit testing of LagrangeInterpolator!!"); } catch (BaseException &e) { out.Put(e.GetFullMessage()); } catch (...) { out.Put("Unknown error occurred\n"); } cout << endl; cout << "Hit enter to end" << endl; cin.get(); }
31.332143
99
0.453665
IncompleteWorlds
31aad3d400e083b4d2bad549cb8808a3ac12ddb9
14,686
hpp
C++
include/am/mia/raw_map.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
31
2015-03-03T19:13:42.000Z
2020-09-03T08:11:56.000Z
include/am/mia/raw_map.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
1
2016-12-24T00:12:11.000Z
2016-12-24T00:12:11.000Z
include/am/mia/raw_map.hpp
izenecloud/izenelib
9d5958100e2ce763fc75f27217adf982d7c9d902
[ "Apache-2.0" ]
8
2015-09-06T01:55:21.000Z
2021-12-20T02:16:13.000Z
#ifndef RAW_MAP_HPP #define RAW_MAP_HPP #include <string> #include <types.h> #include <vector> #include <assert.h> #include <iostream> #include <stdio.h> //#include "int_hash_table.hpp" NS_IZENELIB_AM_BEGIN template < class size_t = uint32_t > class StringVector { const char* buf_; public: inline StringVector() :buf_(NULL) { } inline StringVector(const char* buf) { buf_ = buf; } inline ~StringVector() { } inline void attach(const char* buf) { buf_ = buf; } inline size_t size()const { return *(size_t*)buf_; } inline size_t length() const { size_t s = size(); size_t k = 0; for (size_t i=0; i<s; ++i) if (*(buf_+sizeof(size_t)+i) == '\0') ++k; return k; } inline const char* operator [] (size_t t)const { size_t s = size(); size_t k = 0; const char* r = buf_+sizeof(size_t); for (size_t i=0; i<s; ++i) { if (*(buf_+sizeof(size_t)+i) == '\0') ++k; if (k-1 == t) return r; r = buf_+sizeof(size_t)+i+1; } } class const_iterator { public: const_iterator(const char* p=NULL) : p_(p) {} ~const_iterator() {} // The assignment and relational operators are straightforward const_iterator& operator=(const const_iterator& other) { p_ = other.p_; return(*this); } bool operator==(const const_iterator& other) const { return(p_ == other.p_); } bool operator < (const const_iterator& other) const { return(p_ < other.p_ ); } bool operator > (const const_iterator& other) const { return(p_ > other.p_); } bool operator!=(const const_iterator& other) const { return(p_ != other.p_); } // Update my state such that I refer to the next element in the // SQueue. const_iterator& operator++() { if (p_ == NULL) return *this; while (*p_!='\0') ++p_; ++p_; return(*this); } const_iterator operator++(int) { const_iterator tmp(*this); while (*p_!='\0') ++p_; ++p_; return(tmp); } // Update my state such that I refer to the next element in the // SQueue. const_iterator& operator--() { if (p_ == NULL) return *this; p_ -= 2; while (*p_ != '\0') --p_; ++p_; return(*this); } const_iterator operator--(int) { const_iterator tmp(*this); p_ -= 2; while (*p_ != '\0') --p_; ++p_; return(tmp); } // Return a reference to the value in the node. I do this instead // of returning by value so a caller can update the value in the // node directly. const char* operator*() const { return (p_); } const_iterator operator + (size_t i)const { const_iterator tmp(*this); for (size_t j=0; j<i;++j) ++tmp; return tmp; } const_iterator operator - (size_t i)const { const_iterator tmp(*this); for (size_t j=0; j<i;++j) --tmp; return tmp; } private: const char* p_; }; const_iterator begin()const { return const_iterator(buf_+sizeof(size_t)); } const_iterator end()const { return const_iterator(buf_+sizeof(size_t)+*(size_t*)buf_); } }; template < class size_t = uint32_t > class IntVector { const size_t* buf_; public: inline IntVector() :buf_(NULL) { } inline IntVector(const size_t* buf) { buf_ = buf; } inline ~IntVector() { } inline void attach(const size_t* buf) { buf_= buf; } inline size_t size()const { return *buf_; } class const_iterator { public: const_iterator(const size_t* p=NULL) : p_(p) {} ~const_iterator() {} // The assignment and relational operators are straightforward const_iterator& operator=(const const_iterator& other) { p_ = other.p_; return(*this); } bool operator==(const const_iterator& other) const { return(p_ == other.p_); } bool operator < (const const_iterator& other) const { return(p_ < other.p_ ); } bool operator > (const const_iterator& other) const { return(p_ > other.p_); } bool operator!=(const const_iterator& other) const { return(p_ != other.p_); } // Update my state such that I refer to the next element in the // SQueue. const_iterator& operator++() { if (p_ == NULL) return *this; ++p_; return(*this); } const_iterator operator++(int) { const_iterator tmp(*this); ++p_; return(tmp); } // Update my state such that I refer to the next element in the // SQueue. const_iterator& operator--() { if (p_ == NULL) return *this; --p_; return(*this); } const_iterator operator--(int) { const_iterator tmp(*this); --p_; return(tmp); } // Return a reference to the value in the node. I do this instead // of returning by value so a caller can update the value in the // node directly. const size_t operator*() const { return *(p_); } const_iterator operator + (size_t i)const { const_iterator tmp(*this); for (size_t j=0; j<i;++j) ++tmp; return tmp; } const_iterator operator - (size_t i)const { const_iterator tmp(*this); for (size_t j=0; j<i;++j) --tmp; return tmp; } private: const size_t* p_; }; const_iterator begin()const { return const_iterator(buf_+1); } const_iterator end()const { return const_iterator(buf_+ 1 +*buf_); } } ; /** @class RawMap, ------------------------------------------------------- docid | content_length| term1\0term2\0term3\0..... docid | content_length| term1\0term2\0term3\0..... . . . ------------------------------------------------------- **/ template< uint32_t STR_CACHE_SIZE = 100, //MB must be larger than one document uint32_t INT_CACHE_SIZE = 100 //MB must be larger than one document > class RawMap { public: typedef uint32_t size_t; typedef StringVector<size_t> str_vector; typedef IntVector<size_t> int_vector; //typedef IntHashTable<1000000, size_t> HashTable; protected: uint8_t* str_buf_; size_t* int_buf_; size_t str_cache_pos_; size_t int_cache_pos_; size_t str_start_addr_; size_t int_start_addr_; size_t count_; FILE* f_str_; FILE* f_pos_; //HashTable* ht_; inline bool str_cache_full(size_t s) { return str_cache_pos_ + s > STR_CACHE_SIZE*1000000; } inline bool int_cache_full(size_t s) { return int_cache_pos_ + s > INT_CACHE_SIZE*1000000/sizeof(size_t); } inline bool str_in_mem() { size_t t = *(size_t*)(str_buf_+str_cache_pos_+sizeof(uint32_t)); return str_cache_pos_ + t + sizeof(uint32_t)+sizeof(size_t) < STR_CACHE_SIZE*1000000; } inline bool int_in_mem() { size_t t = *(int_buf_+int_cache_pos_); return int_cache_pos_ + t +1 < INT_CACHE_SIZE*1000000/sizeof(size_t); } inline void str_load_from(size_t addr) { fseek(f_str_, addr, SEEK_SET); fread(str_buf_, STR_CACHE_SIZE*1000000, 1, f_str_); str_start_addr_ = addr; str_cache_pos_ = 0; } inline void int_load_from(size_t addr=0) { fseek(f_pos_, addr, SEEK_SET); fread(int_buf_, INT_CACHE_SIZE*1000000, 1, f_pos_); int_start_addr_ = addr; int_cache_pos_ = 0; } inline void str_flush() { fseek(f_str_, 0, SEEK_SET); assert(fwrite(&count_, sizeof(size_t), 1, f_str_)==1); fseek(f_str_, str_start_addr_, SEEK_SET); assert(fwrite(str_buf_, str_cache_pos_, 1, f_str_)==1); str_start_addr_ += str_cache_pos_; } inline void int_flush() { fseek(f_pos_, int_start_addr_, SEEK_SET); assert(fwrite(int_buf_, int_cache_pos_*sizeof(size_t), 1, f_pos_)==1); int_start_addr_ += int_cache_pos_*sizeof(size_t); } public: inline RawMap(const char* filenm) :str_buf_(NULL), int_buf_(NULL), str_cache_pos_(0), int_cache_pos_(0), str_start_addr_(0), int_start_addr_(0), count_(0), f_str_(NULL), f_pos_(NULL) { std::string s = filenm; s += ".str"; f_str_ = fopen(s.c_str(), "r+"); if (f_str_ == NULL) { f_str_ = fopen(s.c_str(), "w+"); assert(fwrite(&count_, sizeof(size_t), 1, f_str_)==1); } else assert(fread(&count_, sizeof(size_t), 1, f_str_)==1); if (f_str_ == NULL) { std::cout<<"Can't create file: "<<s<<std::endl; return; } s = filenm; s += ".pos"; f_pos_ = fopen(s.c_str(), "r+"); if (f_pos_ == NULL) f_pos_ = fopen(s.c_str(), "w+"); if (f_pos_ == NULL) { std::cout<<"Can't create file: "<<s<<std::endl; return; } // s = filenm; // s += ".has"; // ht_ = new HashTable(s.c_str()); } inline ~RawMap() { if (str_buf_ != NULL) free(str_buf_); if (int_buf_ != NULL) free(int_buf_); //delete ht_; } inline void ready4Append() { str_cache_pos_ = 0; int_cache_pos_ = 0; fseek(f_str_, 0, SEEK_END); str_start_addr_ = ftell(f_str_); fseek(f_pos_, 0, SEEK_END); int_start_addr_ = ftell(f_pos_); if (str_buf_==NULL) str_buf_ = (uint8_t*)malloc(STR_CACHE_SIZE*1000000); if (int_buf_==NULL) int_buf_ = (uint32_t*)malloc(INT_CACHE_SIZE*1000000); } inline void ready4FetchByTg(size_t t=0) { str_cache_pos_ = 0; int_cache_pos_ = 0; str_start_addr_ = sizeof(size_t); int_start_addr_ = 0; if (str_buf_==NULL) str_buf_ = (uint8_t*)malloc(STR_CACHE_SIZE*1000000); if (int_buf_==NULL) int_buf_ = (size_t*)malloc(INT_CACHE_SIZE*1000000); str_load_from(sizeof(size_t)); int_load_from(); str_vector tmp1; int_vector tmp2; for (size_t i=0; i<t; ++i) next4Tg(tmp1, tmp2); } inline void ready4SearchByTg() { str_cache_pos_ = 0; int_cache_pos_ = 0; str_start_addr_ = sizeof(size_t); int_start_addr_ = 0; if (str_buf_==NULL) str_buf_ = (uint8_t*)malloc(1000000); if (int_buf_==NULL) int_buf_ = (size_t*)malloc(1000000); } inline void ready4FetchByDupD(size_t t=0) { str_cache_pos_ = 0; int_cache_pos_ = 0; str_start_addr_ = sizeof(size_t); int_start_addr_ = 0; if (str_buf_==NULL) str_buf_ = (uint8_t*)malloc(STR_CACHE_SIZE*1000000); if (int_buf_!=NULL) { free(int_buf_); int_buf_ = NULL; } str_load_from(sizeof(size_t)); str_vector v; for (size_t i=0; i<t; ++i) next4DupD(v); } inline void append(uint32_t docid, const std::vector<std::string>& strs) { std::size_t s = 0; if (int_cache_full(strs.size()+1)) int_flush(); if (str_cache_full(s+sizeof(uint32_t)+sizeof(size_t))) str_flush(); //ht_->insert(docid, str_start_addr_+str_cache_pos_, int_start_addr_+int_cache_pos_*sizeof(size_t)); *(int_buf_+int_cache_pos_) = strs.size(); ++int_cache_pos_; size_t j = 0; for (std::vector<std::string>::const_iterator i=strs.begin(); i!=strs.end(); ++i, ++j) { if (false)//drop unessary words continue; s += (*i).length()+1; *(int_buf_+int_cache_pos_++) = j; } if (str_cache_full(s+sizeof(uint32_t)+sizeof(size_t))) str_flush(); *(uint32_t*)(str_buf_ + str_cache_pos_) = docid; str_cache_pos_ += sizeof(uint32_t); *(size_t*)(str_buf_ + str_cache_pos_) = s; str_cache_pos_ += sizeof(size_t); for (std::vector<std::string>::const_iterator i=strs.begin(); i!=strs.end(); ++i) { if (false)//drop unessary words continue; memcpy(str_buf_ + str_cache_pos_, (*i).c_str(), (*i).length()); str_cache_pos_ += (*i).length(); *(str_buf_+str_cache_pos_) = '\0'; ++ str_cache_pos_; } ++count_; } inline void flush() { str_flush(); int_flush(); //ht_->flush(); } inline uint32_t next4DupD(str_vector& v) { if (!str_in_mem()) str_load_from(str_cache_pos_+str_start_addr_); v.attach((const char*)(str_buf_+str_cache_pos_+sizeof(uint32_t))); uint32_t docid = *(uint32_t*)(str_buf_+str_cache_pos_); str_cache_pos_ += sizeof(uint32_t)+sizeof(size_t) + v.size(); return docid; } // inline bool get4DupD(uint32_t docid, str_vector& v) // { // size_t addr1; // size_t addr2; // if (!ht_->find(docid, addr1, addr2)) // return false; // fseek(f_str_, addr1, SEEK_SET); // assert(fread(str_buf_, sizeof(uint32_t)+sizeof(size_t), 1, f_str_)==1); // size_t s = *(size_t*)(str_buf_+sizeof(uint32_t)); // assert(fread(str_buf_+sizeof(uint32_t)+sizeof(size_t), s, 1, f_str_)==1); // v.attach((const char*)(str_buf_+sizeof(uint32_t))); // return true; // } // inline bool get4Tg(uint32_t docid, str_vector& v1, int_vector& v2) // { // size_t addr1; // size_t addr2; // if (!ht_->find(docid, addr1, addr2)) // return false; // fseek(f_str_, addr1, SEEK_SET); // assert(fread(str_buf_, sizeof(uint32_t)+sizeof(size_t), 1, f_str_)==1); // size_t s = *(size_t*)(str_buf_+sizeof(uint32_t)); // assert(fread(str_buf_+sizeof(uint32_t)+sizeof(size_t), s, 1, f_str_)==1); // v1.attach((const char*)(str_buf_+sizeof(uint32_t))); // fseek(f_pos_, addr2, SEEK_SET); // assert(fread(int_buf_, sizeof(size_t), 1, f_pos_)==1); // size_t t = *int_buf_; // assert(fread(int_buf_+1, t*sizeof(size_t), 1, f_pos_)==1); // v2.attach((const size_t*)int_buf_); // return true; // } inline uint32_t next4Tg(str_vector& strs, int_vector& ints) { if (!str_in_mem()) str_load_from(str_cache_pos_+str_start_addr_); strs.attach((const char*)(str_buf_+str_cache_pos_+sizeof(uint32_t))); uint32_t docid = *(uint32_t*)(str_buf_+str_cache_pos_); str_cache_pos_ += sizeof(uint32_t)+sizeof(size_t) + strs.size(); if (!int_in_mem()) int_load_from(int_cache_pos_*sizeof(size_t)+int_start_addr_); ints.attach(int_buf_+int_cache_pos_); int_cache_pos_ += *(int_buf_+int_cache_pos_)+1; return docid; } inline size_t doc_num()const { return count_; } } ; #endif NS_IZENELIB_AM_END
20.684507
104
0.5828
izenecloud
31b1415f1bef9e735ad3321c1204e8df1428a1dc
1,439
cpp
C++
C++/HashTable/HT.cpp
19-2-SKKU-OSS/2019-2-OSS-L5
2b55676c1bcd5d327fc9e304925a05cb70e25904
[ "Apache-2.0" ]
null
null
null
C++/HashTable/HT.cpp
19-2-SKKU-OSS/2019-2-OSS-L5
2b55676c1bcd5d327fc9e304925a05cb70e25904
[ "Apache-2.0" ]
null
null
null
C++/HashTable/HT.cpp
19-2-SKKU-OSS/2019-2-OSS-L5
2b55676c1bcd5d327fc9e304925a05cb70e25904
[ "Apache-2.0" ]
4
2019-11-26T10:04:55.000Z
2020-05-21T09:20:47.000Z
//Given an array of n integers and a number k, print out all pairs of elements in the array that sums to exactly k. For example, given the array [1, 2, 3, 6, 7] and k = 8, you should //print 1, 7 and 2, 6 out. #include <string> #include <unordered_map> #include <iostream> #include <fstream> using namespace std; void savePairs(int arr[], int n, int k, FILE *fpw) { unordered_map<int, int> map; for (int i = 0; i < n; i++) { int cha = k - arr[i]; if (map.find(cha) != map.end()) { int count = map[cha]; for (int j = 0; j < count; j++){ fprintf(fpw, "%d, %d\n", cha, arr[i]); } } map[arr[i]]++; } } int main() { for (int j = 0; j < 5;j++) { char inputarr[20]; char outputarr[20]; printf("write input file name: "); scanf("%s", inputarr); printf("write output file name: "); scanf("%s", outputarr); FILE *fpr; FILE *fpw; fpr = fopen(inputarr, "r"); fpw = fopen(outputarr, "w"); char txt; int num; int k; int t = 0; while (1) { if (t == 0) { fscanf(fpr, "%c %d\n", &txt, &k); t++; } else { fscanf(fpr, "%d\n", &num); t++; } if (feof(fpr)) break; } rewind(fpr); t--; fscanf(fpr, "%c %d\n", &txt, &k); int *arr = (int *)malloc(sizeof(int)*t); int n = 0; while (1) { fscanf(fpr, "%d\n", &num); arr[n] = num; n++; if (feof(fpr)) break; } savePairs(arr, n, k, fpw); fclose(fpr); fclose(fpw); } return 0; }
17.54878
182
0.536484
19-2-SKKU-OSS
31b163ac7a95fe85444d6aefe014324f4638cd2f
1,399
cpp
C++
C++/661. Image Smoother.cpp
WangYang-wy/LeetCode
c92fcb83f86c277de6785d5a950f16bc007ccd31
[ "MIT" ]
3
2018-07-28T15:36:18.000Z
2020-03-17T01:26:22.000Z
C++/661. Image Smoother.cpp
WangYang-wy/LeetCode
c92fcb83f86c277de6785d5a950f16bc007ccd31
[ "MIT" ]
null
null
null
C++/661. Image Smoother.cpp
WangYang-wy/LeetCode
c92fcb83f86c277de6785d5a950f16bc007ccd31
[ "MIT" ]
null
null
null
// // Created by 王阳 on 2018/4/18. // #include "header.h" class Solution { public: vector<vector<int>> imageSmoother(vector<vector<int>> &M) { vector<vector<int>> res; int m = M.size(); int n = M[0].size(); for (int i = 0; i < m; i++) { vector<int> tmp; for (int j = 0; j < n; j++) { tmp.push_back(0); } res.push_back(tmp); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int sum = 0; int count = 0; for (int p = max(0, i - 1); p < min(m, i + 2); p++) { for (int q = max(0, j - 1); q < min(n, j + 2); q++) { sum += M[p][q]; count++; } } res[i][j] = floor(sum / count); } } return res; } int max(int a, int b) { return a > b ? a : b; } int min(int a, int b) { return a < b ? a : b; } }; int main() { Solution *solution = new Solution(); vector<vector<int>> res; int m = 3; int n = 3; for (int i = 0; i < m; i++) { vector<int> tmp; for (int j = 0; j < n; j++) { tmp.push_back(1); } res.push_back(tmp); } solution->imageSmoother(res); return 0; }
22.934426
73
0.36955
WangYang-wy
31b872b5d7246a199ded8d3a31d7903449c2f629
6,781
cpp
C++
leetcode/cpp/qt_perfect_square.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_perfect_square.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_perfect_square.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
// TLE // Need more memory to record status to reduce time expense) /* class Solution { private: int helper(int n, int maxnum) { if(maxnum == 1) return n; if(n == 0) return 0; int sqr = min(maxnum, (int)floor(sqrt(n))); if(pow(sqr, 2) == n) return 1; int count = n; for(int i = sqr; i >= 1; i--) { count = min(count, helper(n - i*i, i)); } return 1 + count; } public: int numSquares(int n) { return helper(n, (int)floor(sqrt(n))); } }; */ // Dynamic Programming (428ms, beats 50%) /* class Solution { public: int numSquares(int n) { if(n < 1) return 0; // cnt[i] = the least number of perfect square numbers // which sum to i. Note that cnt[0] is 0. vector<int> cnt(n + 1, INT_MAX); cnt[0] = 0; for (int i = 1; i <= n; i++) { // For each i, it must be the sum of some number (i - j*j) and // a perfect square number (j*j). for (int j = 1; j*j <= i; j++) cnt[i] = min(cnt[i], cnt[i - j*j] + 1); } return cnt[n]; } }; */ // Static Dynamic Programming (12ms, 85%) class Solution { public: int numSquares(int n) { if (n < 1) return 0; // cnt[i] = the least number of perfect square numbers // which sum to i. Since cnt is a static vector, if // cnt.size() > n, we have already calculated the result // during previous function calls and we can just return the result now. static vector<int> cnt({0}); // While cnt.size() <= n, we need to incrementally // calculate the next result until we get the result for n. while (cnt.size() <= n) { int m = cnt.size(); int sqr = INT_MAX; for (int i = 1; i*i <= m; i++) { sqr = min(sqr, cnt[m - i*i] + 1); } cnt.push_back(sqr); } return cnt[n]; } }; // Mathematical Solution: 4ms class Solution { private: int is_square(int n) { int sqrt_n = (int)(sqrt(n)); return (sqrt_n*sqrt_n == n); } public: // Based on Lagrange's Four Square theorem, there // are only 4 possible results: 1, 2, 3, 4. int numSquares(int n) { // If n is a perfect square, return 1. if(is_square(n)) { return 1; } // The result is 4 if and only if n can be written in the // form of 4^k*(8*m + 7). Please refer to // Legendre's three-square theorem. while ((n & 3) == 0) // n%4 == 0 { n >>= 2; } if ((n & 7) == 7) // n%8 == 7 { return 4; } // Check whether 2 is the result. int sqrt_n = (int)(sqrt(n)); for(int i = 1; i <= sqrt_n; i++) { if (is_square(n - i*i)) { return 2; } } return 3; } }; // Breadth-First Search: 80ms class Solution { public: int numSquares(int n) { if (n <= 0) { return 0; } // perfectSquares contain all perfect square numbers which // are smaller than or equal to n. vector<int> perfectSquares; // cntPerfectSquares[i - 1] = the least number of perfect // square numbers which sum to i. vector<int> cntPerfectSquares(n); // Get all the perfect square numbers which are smaller than // or equal to n. for (int i = 1; i*i <= n; i++) { perfectSquares.push_back(i*i); cntPerfectSquares[i*i - 1] = 1; } // If n is a perfect square number, return 1 immediately. if (perfectSquares.back() == n) { return 1; } // Consider a graph which consists of number 0, 1,...,n as // its nodes. Node j is connected to node i via an edge if // and only if either j = i + (a perfect square number) or // i = j + (a perfect square number). Starting from node 0, // do the breadth-first search. If we reach node n at step // m, then the least number of perfect square numbers which // sum to n is m. Here since we have already obtained the // perfect square numbers, we have actually finished the // search at step 1. queue<int> searchQ; for (auto& i : perfectSquares) { searchQ.push(i); } int currCntPerfectSquares = 1; while (!searchQ.empty()) { currCntPerfectSquares++; int searchQSize = searchQ.size(); for (int i = 0; i < searchQSize; i++) { int tmp = searchQ.front(); // Check the neighbors of node tmp which are the sum // of tmp and a perfect square number. for (auto& j : perfectSquares) { if (tmp + j == n) { // We have reached node n. return currCntPerfectSquares; } else if ((tmp + j < n) && (cntPerfectSquares[tmp + j - 1] == 0)) { // If cntPerfectSquares[tmp + j - 1] > 0, this is not // the first time that we visit this node and we should // skip the node (tmp + j). cntPerfectSquares[tmp + j - 1] = currCntPerfectSquares; searchQ.push(tmp + j); } else if (tmp + j > n) { // We don't need to consider the nodes which are greater ] // than n. break; } } searchQ.pop(); } } return 0; } }; /** * WARNING * 1. MY DFS(TLE) * 实际codeing容易忽略1/2的实际值为0,应该用0.5代替; * * 2. Static DP is much faster than DP * * Static DP is equivalent to DP if you only call function once. * However, if you call it several times, static vector would be reused and make whole test cases much faster. * * If you define a non-static private class vector, * each class instance will have a copy of the vector. * It won't save you time if the test code creates a class instance for each test case. * But if you define a static vector within the class method, * all class instances will share a single copy of the vector. * * * REFERENCE * https://leetcode.com/discuss/58056/summary-of-different-solutions-bfs-static-and-mathematics * /
29.482609
110
0.49152
qiaotian
31bcb2eb78b049353ab9b85429def598bdbe0e10
352
cpp
C++
Vision/ObjectRecognition/src/object.cpp
cxdcxd/sepanta3
a65a3415f046631ac4d6b91f9342966b0c030226
[ "MIT" ]
null
null
null
Vision/ObjectRecognition/src/object.cpp
cxdcxd/sepanta3
a65a3415f046631ac4d6b91f9342966b0c030226
[ "MIT" ]
null
null
null
Vision/ObjectRecognition/src/object.cpp
cxdcxd/sepanta3
a65a3415f046631ac4d6b91f9342966b0c030226
[ "MIT" ]
null
null
null
#include <object.hpp> Object::Object() : cloud(new pcl::PointCloud<pcl::PointXYZRGB>), normals(new pcl::PointCloud<pcl::PointNormal>), keypoints(new pcl::PointCloud<pcl::PointXYZRGB>), descriptors(new pcl::PointCloud<pcl::SHOT1344>), correspondences(new pcl::Correspondences()) { }
35.2
66
0.605114
cxdcxd
31c0fb6840bfefa8006d3111b7c03a7d4f8f7b21
161
hpp
C++
src/shared/IServerConnection.hpp
sathwikmatsa/ndn-agar.io
a758414d0bb221a6183f20d332f101f3850505cf
[ "MIT" ]
1
2020-06-10T07:44:43.000Z
2020-06-10T07:44:43.000Z
src/shared/IServerConnection.hpp
sathwikmatsa/ndn-agar.io
a758414d0bb221a6183f20d332f101f3850505cf
[ "MIT" ]
null
null
null
src/shared/IServerConnection.hpp
sathwikmatsa/ndn-agar.io
a758414d0bb221a6183f20d332f101f3850505cf
[ "MIT" ]
null
null
null
#pragma once class IServerConnection { public: virtual void client_connected(int clientIndex) = 0; virtual void client_disconnected(int clientIndex) = 0; };
23
56
0.776398
sathwikmatsa
31c224511a4e753ed26719be20cc40087eb94988
2,354
cpp
C++
scratch/projects/kinematics/xParabolicDish.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
scratch/projects/kinematics/xParabolicDish.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
scratch/projects/kinematics/xParabolicDish.cpp
tingelst/versor
c831231e5011cfd1f62da8948cff7956d2f6670b
[ "BSD-3-Clause" ]
null
null
null
/* * ===================================================================================== * * Filename: xParabolicDish.cpp * * Description: folding of a parabolic dish * * Version: 1.0 * Created: 04/08/2014 17:48:57 * Revision: none * Compiler: gcc * * Author: Pablo Colapinto (), gmail -> wolftype * Organization: * * ===================================================================================== */ #include "vsr_cga3D.h" #include "vsr_GLVimpl.h" #include "vsr_conic.h" #include "gfx/gfx_mesh.h" using namespace vsr; using namespace vsr::cga3D; struct MyApp : App { Pnt mouse; Lin ray; float time; float amt,beta,gamma; MyApp(Window * win ) : App(win){ scene.camera.pos( 0,0,10 ); time = 0; } void initGui(){ gui(amt,"amt",-100,100); gui(beta,"beta",-1,1); gui(gamma,"gamma",-1,1); } void getMouse(){ auto tv = interface.vd().ray; Vec z (tv[0], tv[1], tv[2] ); auto tm = interface.mouse.projectMid; ray = Round::point( tm[0], tm[1], tm[2] ) ^ z ^ Inf(1); mouse = Round::point( ray, Ori(1) ); } virtual void onDraw(){ getMouse(); vector<Point> vp; int num = 20; //Transformed Points on Bottom half of a Sphere Dls dls = Ro::dls(1,0,0,0); for (int i = 0; i <= num; ++i){ for (int j = 0; j < num; ++j){ float tu= PI * i/num; float tv = -PIOVERFOUR + PIOVERFOUR * j/num; Point p1 = Ro::pnt(dls, Vec::x.sp(Gen::rot(tu, tv))); Point ap = Conic::Transform( p1, Vec(0,-1,0), amt ); vp.push_back(ap); } } Mesh mesh = Mesh::UV( vp.data(), num+1, num ); mesh.drawElements(); for (int i = 0; i < num; ++i){ Point mp = Ro::pnt_cir( meet, PI * i/num ); mp = Conic::Transform( mp, mv, amt); Draw(mp,0,1,0); } Draw( Conic::ITransform( Fl::loc( td, mouse, true).null(), mv, amt ), 0,1,1); } }; MyApp * app; int main(){ GLV glv(0,0); Window * win = new Window(500,500,"Versor",&glv); app = new MyApp( win ); app -> initGui(); glv << *app; Application::run(); return 0; }
20.649123
88
0.448598
tingelst
31c73bcca22ef514ea7e8bf12579bd8e3891e4ae
78
hh
C++
Include/AcpiCa.hh
ahoka/esrtk
bb5ff7f9caa22b6d6d91e660c6d78e471394a0cc
[ "BSD-2-Clause" ]
1
2018-07-08T15:47:57.000Z
2018-07-08T15:47:57.000Z
Include/AcpiCa.hh
ahoka/esrtk
bb5ff7f9caa22b6d6d91e660c6d78e471394a0cc
[ "BSD-2-Clause" ]
null
null
null
Include/AcpiCa.hh
ahoka/esrtk
bb5ff7f9caa22b6d6d91e660c6d78e471394a0cc
[ "BSD-2-Clause" ]
null
null
null
#ifndef ACPICA_HH #define ACPICA_HH extern "C" { #include <acpi.h> } #endif
7.8
17
0.692308
ahoka
31cdacc3946022055e7d346eb258829294954eb3
1,519
cpp
C++
code/History.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
1
2022-02-10T01:41:32.000Z
2022-02-10T01:41:32.000Z
code/History.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
null
null
null
code/History.cpp
omerdagan84/neomem
7d2f782bb37f1ab0ac6580d00672e114605afab7
[ "MIT" ]
null
null
null
// CHistory #include "precompiled.h" #include "NeoMem.h" #include "History.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif CHistory::CHistory() : m_nStart (0), m_nStop (-1), m_nPos (-1), m_nPositions (0) { } CHistory::~CHistory() { } BOOL CHistory::SetSize(int nPositions) { m_nPositions = nPositions; CObArray::SetSize(nPositions); return TRUE; } BOOL CHistory::IsForwardValid() { return (GetForwardPositions() > 0); } BOOL CHistory::IsBackValid() { return (GetBackPositions() > 0); } // Set current position to the specified object BOOL CHistory::SetCurrent(CObject* pobj) { m_nPos++; SetAt(m_nPos % m_nPositions, pobj); m_nStop = m_nPos; // save stop position (max forward) // Move start position up if we're exceeding the number of positions in array if (m_nPos - m_nStart >= m_nPositions) m_nStart++; return TRUE; } // How many back positions are available? int CHistory::GetBackPositions() { return (m_nPos - m_nStart); } // How many forward positions are available? int CHistory::GetForwardPositions() { return (m_nStop - m_nPos); } // Get previous object in history list CObject* CHistory::GoBack() { CObject* pobj = 0; if (GetBackPositions() > 0) { m_nPos--; pobj = GetAt(m_nPos % m_nPositions); } return pobj; } // Get next object in history list CObject* CHistory::GoForward() { CObject* pobj = 0; if (GetForwardPositions() > 0) { m_nPos++; pobj = GetAt(m_nPos % m_nPositions); } return pobj; }
14.747573
78
0.692561
omerdagan84
31ce7147b5c6cd02338b6d7d205fc1da6b21cc88
1,126
cpp
C++
libs/fnd/config/test/src/unit_test_fnd_config_noexcept.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/config/test/src/unit_test_fnd_config_noexcept.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/config/test/src/unit_test_fnd_config_noexcept.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file unit_test_fnd_config_noexcept.cpp * * @brief * * @author myoukaku */ #include <bksge/fnd/config.hpp> #include <gtest/gtest.h> namespace bksge_config_noexcept_test { void f1(); void f2() BKSGE_NOEXCEPT; void f3() BKSGE_NOEXCEPT_OR_NOTHROW; void f4() BKSGE_NOEXCEPT_IF(true); void f5() BKSGE_NOEXCEPT_IF(false); void f6() BKSGE_NOEXCEPT_IF(BKSGE_NOEXCEPT_EXPR(f1())); void f7() BKSGE_NOEXCEPT_IF(BKSGE_NOEXCEPT_EXPR(f2())); void f8() BKSGE_NOEXCEPT_IF_EXPR(f1()); void f9() BKSGE_NOEXCEPT_IF_EXPR(f2()); GTEST_TEST(ConfigTest, NoexceptTest) { #if defined(BKSGE_HAS_CXX11_NOEXCEPT) static_assert(!BKSGE_NOEXCEPT_EXPR(f1()), ""); static_assert( BKSGE_NOEXCEPT_EXPR(f2()), ""); static_assert( BKSGE_NOEXCEPT_EXPR(f3()), ""); static_assert( BKSGE_NOEXCEPT_EXPR(f4()), ""); static_assert(!BKSGE_NOEXCEPT_EXPR(f5()), ""); static_assert(!BKSGE_NOEXCEPT_EXPR(f6()), ""); static_assert( BKSGE_NOEXCEPT_EXPR(f7()), ""); static_assert(!BKSGE_NOEXCEPT_EXPR(f8()), ""); static_assert( BKSGE_NOEXCEPT_EXPR(f9()), ""); #endif } } // namespace bksge_config_noexcept_test
27.463415
56
0.713144
myoukaku
31d00b21ab21f9c5c79948a86f00a4e7e9f8118d
5,653
cpp
C++
cpp/oneapi/dal/test/engine/linalg/test/dot.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
188
2016-04-16T12:11:48.000Z
2018-01-12T12:42:55.000Z
cpp/oneapi/dal/test/engine/linalg/test/dot.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
1,198
2020-03-24T17:26:18.000Z
2022-03-31T08:06:15.000Z
cpp/oneapi/dal/test/engine/linalg/test/dot.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
93
2018-01-23T01:59:23.000Z
2020-03-16T11:04:19.000Z
/******************************************************************************* * Copyright 2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "oneapi/dal/test/engine/common.hpp" #include "oneapi/dal/test/engine/linalg/dot.hpp" #include "oneapi/dal/test/engine/linalg/loops.hpp" namespace oneapi::dal::test::engine::linalg::test { template <layout lyt_a, layout lyt_b, layout lyt_c> class dot_test { public: dot_test() { m_ = GENERATE(3, 4, 5); n_ = GENERATE(4, 5, 6); k_ = GENERATE(5, 6, 7); CAPTURE(m_, n_, k_); } auto A() const { return matrix<float, lyt_a>::ones({ m_, k_ }); } auto At() const { return matrix<float, lyt_a>::ones({ k_, m_ }).t(); } auto B() const { return matrix<float, lyt_b>::ones({ k_, n_ }); } auto Bt() const { return matrix<float, lyt_b>::ones({ n_, k_ }).t(); } auto C() const { return matrix<float, lyt_c>::empty({ m_, n_ }); } void check_ones_matrix_dot(const matrix<float, lyt_c>& mat) const { REQUIRE(mat.get_shape() == shape{ m_, n_ }); for_each(mat, [&](float x) { REQUIRE(std::int64_t(x) == k_); }); } private: std::int64_t m_; std::int64_t n_; std::int64_t k_; }; #define LAYOUT_VEC2(x, y) (layout::x, layout::y) #define LAYOUT_VEC3(x, y, z) (layout::x, layout::y, layout::z) #define LAYOUTS_AB \ LAYOUT_VEC3(row_major, row_major, row_major), LAYOUT_VEC3(row_major, column_major, row_major), \ LAYOUT_VEC3(column_major, row_major, row_major), \ LAYOUT_VEC3(column_major, column_major, row_major) #define LAYOUTS_ABC \ LAYOUT_VEC3(row_major, row_major, row_major), LAYOUT_VEC3(row_major, row_major, column_major), \ LAYOUT_VEC3(row_major, column_major, row_major), \ LAYOUT_VEC3(row_major, column_major, column_major), \ LAYOUT_VEC3(column_major, row_major, row_major), \ LAYOUT_VEC3(column_major, row_major, column_major), \ LAYOUT_VEC3(column_major, column_major, row_major), \ LAYOUT_VEC3(column_major, column_major, column_major) #define DOT_TEST_TEMPLATE_SIG ((layout lyt_a, layout lyt_b, layout lyt_c), lyt_a, lyt_b, lyt_c) #define DOT_TEST(name, tags, layouts) \ TEMPLATE_SIG_TEST_M(dot_test, name, tags, DOT_TEST_TEMPLATE_SIG, layouts) DOT_TEST("dot simple", "[linalg][dot]", LAYOUTS_AB) { SECTION("A x B") { const auto C = dot(this->A(), this->B()); this->check_ones_matrix_dot(C); } SECTION("A x Bt") { const auto C = dot(this->A(), this->Bt()); this->check_ones_matrix_dot(C); } SECTION("At x B") { const auto C = dot(this->At(), this->B()); this->check_ones_matrix_dot(C); } SECTION("At x Bt") { const auto C = dot(this->At(), this->Bt()); this->check_ones_matrix_dot(C); } } DOT_TEST("dot in-place", "[linalg][dot]", LAYOUTS_ABC) { auto C = this->C(); SECTION("A x B") { dot(this->A(), this->B(), C); this->check_ones_matrix_dot(C); } SECTION("A x Bt") { dot(this->A(), this->Bt(), C); this->check_ones_matrix_dot(C); } SECTION("At x B") { dot(this->At(), this->B(), C); this->check_ones_matrix_dot(C); } SECTION("At x Bt") { dot(this->At(), this->Bt(), C); this->check_ones_matrix_dot(C); } } TEST("dot orthogonal matrix", "[linalg][dot]") { const std::int64_t row_count = 5; const std::int64_t column_count = 5; const std::int64_t element_count = row_count * column_count; const double X_ptr[element_count] = { 0.5728966506, 0.5677902077, -0.4104886344, 0.0993844187, 0.4135523258, -0.4590520326, 0.2834513205, -0.6214677550, -0.5114715156, -0.2471867686, 0.0506571111, -0.3713048334, 0.0645569868, -0.6484125926, 0.6595150363, 0.3318135734, 0.4178413295, 0.5362188809, -0.5381061517, -0.3717787744, -0.5902493276, 0.5336768432, 0.3918910789, 0.1360974115, 0.4412410170 }; const auto X = matrix<double>::wrap(array<double>::wrap(X_ptr, element_count), { row_count, column_count }); const auto C = dot(X, X.t()); SECTION("result is ones matrix") { enumerate(C, [&](std::int64_t i, std::int64_t j, double x) { CAPTURE(i, j); if (i == j) { REQUIRE(std::abs(x - 1.0) < 1e-9); } else { REQUIRE(std::abs(x) < 1e-9); } }); } } } // namespace oneapi::dal::test::engine::linalg::test
34.054217
100
0.545905
cmsxbc
31d39f996c423a51578a99c36ebc1de204caee0c
11,354
cpp
C++
src/OpenCV/library.cpp
TORU777/OpenR8
be3de459e30ffcf6234cd4d6a0d169cc4ad18aa0
[ "Unlicense" ]
null
null
null
src/OpenCV/library.cpp
TORU777/OpenR8
be3de459e30ffcf6234cd4d6a0d169cc4ad18aa0
[ "Unlicense" ]
null
null
null
src/OpenCV/library.cpp
TORU777/OpenR8
be3de459e30ffcf6234cd4d6a0d169cc4ad18aa0
[ "Unlicense" ]
3
2019-03-30T01:45:28.000Z
2021-04-24T04:37:39.000Z
/* Copyright (c) 2004-2017 Open Robot Club. All rights reserved. OpenCV library for R7. */ #include <opencv2/opencv.hpp> #include "R7.hpp" using namespace std; using namespace cv; typedef struct { VideoCapture *videoCapture; int deviceNum; int apiID; Mat capturedImage; } OpenCV_t; vector<VideoCapture *> videoCapture_Vector; #ifdef __cplusplus extern "C" { #endif static int OpenCV_VideoCapture_Init(int r7Sn, int functionSn) { int res; void *variableObject = NULL; res = R7_InitVariableObject(r7Sn, functionSn, 1, sizeof(OpenCV_t)); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_InitVariableObject = %d", res); return -1; } res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res); return -2; } OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject); // Initial values of OpenCV_t. videoCapturePtr->videoCapture = new VideoCapture(); videoCapturePtr->deviceNum = 0; videoCapturePtr->apiID = CAP_ANY; videoCapturePtr->capturedImage = Mat(); videoCapture_Vector.push_back(videoCapturePtr->videoCapture); return 1; } static int OpenCV_VideoCapture_Release(int r7Sn, int functionSn) { int res; void *variableObject = NULL; res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res); return -1; } if (variableObject == NULL) { R7_Printf(r7Sn, "ERROR! variableObject == NULL"); return -2; } OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject); videoCapturePtr->capturedImage.release(); videoCapturePtr->videoCapture->~VideoCapture(); videoCapturePtr->videoCapture = NULL; res = R7_ReleaseVariableObject(r7Sn, functionSn, 1); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_ReleaseVariableObject = %d", res); return -3; } return 1; } static int OpenCV_VideoCapture_Open(int r7Sn, int functionSn) { int res; void *variableObject = NULL; res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res); return -1; } if (variableObject == NULL) { R7_Printf(r7Sn, "ERROR! variableObject == NULL"); return -2; } OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject); int deviceID = 0; res = R7_GetVariableInt(r7Sn, functionSn, 2, &deviceID); if (res > 0) { videoCapturePtr->deviceNum = deviceID; } videoCapturePtr->videoCapture->open(videoCapturePtr->deviceNum + videoCapturePtr->apiID); if (!videoCapturePtr->videoCapture->isOpened()) { R7_Printf(r7Sn, "ERROR! Unable to open the Camera!"); return -4; } // Workaround for dark image at beginning. Mat frame; for (int i = 0; i < 10; i++) { videoCapturePtr->videoCapture->grab(); videoCapturePtr->videoCapture->retrieve(frame); } frame.release(); return 1; } static int OpenCV_VideoCapture_SetResolution(int r7Sn, int functionSn) { int res; void *variableObject = NULL; res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res); return -1; } if (variableObject == NULL) { R7_Printf(r7Sn, "ERROR! variableObject == NULL"); return -2; } OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject); int frameWidth = 0; int frameHeight = 0; res = R7_GetVariableInt(r7Sn, functionSn, 2, &frameWidth); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableInt = %d", res); return -3; } res = R7_GetVariableInt(r7Sn, functionSn, 3, &frameHeight); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableInt = %d", res); return -3; } //R7_Printf(r7Sn, "frameWidth = %d\n", frameWidth); //R7_Printf(r7Sn, "frameHeight = %d\n", frameHeight); if (frameWidth < 0) { R7_Printf(r7Sn, "ERROR! frameWidth must be a positive value.\n"); return -3; } else if (frameHeight < 0) { R7_Printf(r7Sn, "ERROR! frameHeight must be a positive value.\n"); return -3; } // Set resolution of frame videoCapturePtr->videoCapture->set(cv::CAP_PROP_FRAME_WIDTH, frameWidth); videoCapturePtr->videoCapture->set(cv::CAP_PROP_FRAME_HEIGHT, frameHeight); return 1; } static int OpenCV_VideoCapture_Grab(int r7Sn, int functionSn) { int res; void *variableObject = NULL; res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res); return -1; } if (variableObject == NULL) { R7_Printf(r7Sn, "ERROR! variableObject == NULL"); return -2; } OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject); videoCapturePtr->videoCapture->grab(); return 1; } static int OpenCV_VideoCapture_Retrieve(int r7Sn, int functionSn) { int res; void *variableObject = NULL; res = R7_GetVariableObject(r7Sn, functionSn, 1, &variableObject); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_GetVariableObject = %d", res); return -1; } if (variableObject == NULL) { R7_Printf(r7Sn, "ERROR! variableObject == NULL"); return -2; } OpenCV_t *videoCapturePtr = ((OpenCV_t*)variableObject); videoCapturePtr->videoCapture->retrieve(videoCapturePtr->capturedImage); if (videoCapturePtr->capturedImage.empty()) { R7_Printf(r7Sn, "ERROR! Retrieved image is empty!"); return -3; } res = R7_SetVariableMat(r7Sn, functionSn, 2, videoCapturePtr->capturedImage); if (res <= 0) { R7_Printf(r7Sn, "ERROR! R7_SetVariableMat = %d", res); return -4; } return 1; } R7_API int R7Library_Init(void) { // Register your functions in this API. R7_RegisterFunction("OpenCV_VideoCapture_Grab", (R7Function_t)&OpenCV_VideoCapture_Grab); R7_RegisterFunction("OpenCV_VideoCapture_Init", (R7Function_t)&OpenCV_VideoCapture_Init); R7_RegisterFunction("OpenCV_VideoCapture_Open", (R7Function_t)&OpenCV_VideoCapture_Open); R7_RegisterFunction("OpenCV_VideoCapture_SetResolution", (R7Function_t)&OpenCV_VideoCapture_SetResolution); R7_RegisterFunction("OpenCV_VideoCapture_Release", (R7Function_t)&OpenCV_VideoCapture_Release); R7_RegisterFunction("OpenCV_VideoCapture_Retrieve", (R7Function_t)&OpenCV_VideoCapture_Retrieve); return 1; } R7_API int R7Library_Close(void) { // If you have something to do before close R7(ex: free memory), you should handle them in this API. for (int i = 0; i < (int)videoCapture_Vector.size(); i++) { if (videoCapture_Vector[i] != NULL) { videoCapture_Vector[i]->~VideoCapture(); videoCapture_Vector[i] = NULL; } } videoCapture_Vector.clear(); return 1; } inline void r7_AppendVariable(json_t *variableArray, const char *name, const char *type, const char *option) { if (!variableArray) { return; } json_t *variable; json_t *variableObject; variableObject = json_object(); variable = json_object(); json_object_set_new(variable, "variable", variableObject); json_object_set_new(variableObject, "name", json_string(name)); json_object_set_new(variableObject, "type", json_string(type)); json_object_set_new(variableObject, "option", json_string(option)); json_array_append(variableArray, variable); return; } R7_API int R7Library_GetSupportList(char *str, int strSize) { // Define your functions and parameters in this API. json_t *root = json_object(); json_t *functionGroupArray; json_t *functionGroup; json_t *functionGroupObject; json_t *functionArray; json_t *function; json_t *functionObject; json_t *variableArray; functionGroupArray = json_array(); json_object_set_new(root, "functionGroups", functionGroupArray); functionGroup = json_object(); functionGroupObject = json_object(); json_object_set_new(functionGroup, "functionGroup", functionGroupObject); json_object_set_new(functionGroupObject, "name", json_string("OpenCV")); json_array_append(functionGroupArray, functionGroup); functionArray = json_array(); json_object_set_new(functionGroupObject, "functions", functionArray); // OpenCV_VideoCapture_Grab function = json_object(); functionObject = json_object(); json_object_set_new(function, "function", functionObject); json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Grab")); json_object_set_new(functionObject, "doc", json_string("")); json_array_append(functionArray, function); variableArray = json_array(); json_object_set_new(functionObject, "variables", variableArray); r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN"); // OpenCV_VideoCapture_Init function = json_object(); functionObject = json_object(); json_object_set_new(function, "function", functionObject); json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Init")); json_object_set_new(functionObject, "doc", json_string("")); json_array_append(functionArray, function); variableArray = json_array(); json_object_set_new(functionObject, "variables", variableArray); r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "INOUT"); // OpenCV_VideoCapture_Open function = json_object(); functionObject = json_object(); json_object_set_new(function, "function", functionObject); json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Open")); json_object_set_new(functionObject, "doc", json_string("")); json_array_append(functionArray, function); variableArray = json_array(); json_object_set_new(functionObject, "variables", variableArray); r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN"); r7_AppendVariable(variableArray, "deviceNumber", "Int", "IN"); // OpenCV_VideoCapture_SetResolution function = json_object(); functionObject = json_object(); json_object_set_new(function, "function", functionObject); json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_SetResolution")); json_object_set_new(functionObject, "doc", json_string("")); json_array_append(functionArray, function); variableArray = json_array(); json_object_set_new(functionObject, "variables", variableArray); r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN"); r7_AppendVariable(variableArray, "frameWidth", "Int", "IN"); r7_AppendVariable(variableArray, "frameHeight", "Int", "IN"); // OpenCV_VideoCapture_Release function = json_object(); functionObject = json_object(); json_object_set_new(function, "function", functionObject); json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Release")); json_object_set_new(functionObject, "doc", json_string("")); json_array_append(functionArray, function); variableArray = json_array(); json_object_set_new(functionObject, "variables", variableArray); r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "INOUT"); // OpenCV_VideoCapture_Retrieve function = json_object(); functionObject = json_object(); json_object_set_new(function, "function", functionObject); json_object_set_new(functionObject, "name", json_string("OpenCV_VideoCapture_Retrieve")); json_object_set_new(functionObject, "doc", json_string("")); json_array_append(functionArray, function); variableArray = json_array(); json_object_set_new(functionObject, "variables", variableArray); r7_AppendVariable(variableArray, "videoCaptureObject", "Object", "IN"); r7_AppendVariable(variableArray, "grabbedImage", "Image", "OUT"); sprintf_s(str, strSize, "%s", json_dumps(root, 0)); json_decref(root); return 1; } #ifdef __cplusplus } #endif
30.686486
110
0.747578
TORU777
31d428bd8e8fb3e91465f8c947d6dd05ae1740f2
1,318
hpp
C++
include/bg2e/platform.hpp
ferserc1/bg2e-cpp
f3a04c5202161846b1329918c5070a2e930bec42
[ "MIT" ]
null
null
null
include/bg2e/platform.hpp
ferserc1/bg2e-cpp
f3a04c5202161846b1329918c5070a2e930bec42
[ "MIT" ]
null
null
null
include/bg2e/platform.hpp
ferserc1/bg2e-cpp
f3a04c5202161846b1329918c5070a2e930bec42
[ "MIT" ]
null
null
null
#ifndef _bg2e_platform_hpp_ #define _bg2e_platform_hpp_ #include <bx/bx.h> #define BG2E_PLATFORM_ANDROID 0 #define BG2E_PLATFORM_BSD 0 #define BG2E_PLATFORM_EMSCRIPTEN 0 #define BG2E_PLATFORM_IOS 0 #define BG2E_PLATFORM_LINUX 0 #define BG2E_PLATFORM_OSX 0 #define BG2E_PLATFORM_RPI 0 #define BG2E_PLATFORM_STEAMLINK 0 #define BG2E_PLATFORM_WINDOWS 0 #if BX_PLATFORM_ANDROID #undef BG2E_PLATFORM_ANDROID #define BG2E_PLATFORM_ANDROID 1 #elif BX_PLATFORM_BSD #undef BG2E_PLATFORM_BSD #define BG2E_PLATFORM_BSD 1 #elif BX_PLATFORM_EMSCRIPTEN #define BG2E_PLATFORM_EMSCRIPTEN 1 #elif BX_PLATFORM_IOS #undef BG2E_PLATFORM_IOS #define BG2E_PLATFORM_IOS 1 #elif BX_PLATFORM_LINUX #undef BG2E_PLATFORM_LINUX #define BG2E_PLATFORM_LINUX 1 #elif BX_PLATFORM_OSX #undef BG2E_PLATFORM_OSX #define BG2E_PLATFORM_OSX 1 #elif BX_PLATFORM_RPI #undef BG2E_PLATFORM_RPI #define BG2E_PLATFORM_RPI 1 #elif BX_PLATFORM_STEAMLINK #undef BG2E_PLATFORM_STEAMLINK #define BG2E_PLATFORM_STEAMLINK 1 #elif BX_PLATFORM_WINDOWS #undef BG2E_PLATFORM_WINDOWS #define BG2E_PLATFORM_WINDOWS 1 #endif #endif
28.042553
41
0.708649
ferserc1
31d4321544086c76173ffd7e85b0d214d666b9a1
4,508
cpp
C++
rtsp-streamer/screenshot.cpp
alexeyz041/toolbox
dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc
[ "CC0-1.0" ]
1
2022-02-17T22:23:59.000Z
2022-02-17T22:23:59.000Z
rtsp-streamer/screenshot.cpp
alexeyz041/toolbox
dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc
[ "CC0-1.0" ]
null
null
null
rtsp-streamer/screenshot.cpp
alexeyz041/toolbox
dbb6efff6eb0bcf56fe5b29a0a98d86b5971ddbc
[ "CC0-1.0" ]
null
null
null
#include "screenshot.h" void initimage( struct shmimage * image ) { image->ximage = NULL ; image->shminfo.shmaddr = (char *) -1 ; } void destroyimage( Display * dsp, struct shmimage * image ) { if( image->ximage ) { XShmDetach( dsp, &image->shminfo ) ; XDestroyImage( image->ximage ) ; image->ximage = NULL ; } if( image->shminfo.shmaddr != ( char * ) -1 ) { shmdt( image->shminfo.shmaddr ) ; image->shminfo.shmaddr = ( char * ) -1 ; } } int createimage( Display * dsp, struct shmimage * image, int width, int height ) { // Create a shared memory area image->shminfo.shmid = shmget( IPC_PRIVATE, width * height * BPP, IPC_CREAT | 0600 ) ; if( image->shminfo.shmid == -1 ) { perror( "screenshot" ) ; return false ; } // Map the shared memory segment into the address space of this process image->shminfo.shmaddr = (char *) shmat( image->shminfo.shmid, 0, 0 ) ; if( image->shminfo.shmaddr == (char *) -1 ) { perror( "screenshot 2" ) ; return false ; } image->data = (unsigned int*) image->shminfo.shmaddr ; image->shminfo.readOnly = false ; // Mark the shared memory segment for removal // It will be removed even if this program crashes shmctl( image->shminfo.shmid, IPC_RMID, 0 ) ; // Allocate the memory needed for the XImage structure image->ximage = XShmCreateImage( dsp, XDefaultVisual( dsp, XDefaultScreen( dsp ) ), DefaultDepth( dsp, XDefaultScreen( dsp ) ), ZPixmap, 0, &image->shminfo, 0, 0 ) ; if( !image->ximage ) { destroyimage( dsp, image ) ; printf("could not allocate the XImage structure\n" ) ; return false ; } image->ximage->data = (char *)image->data ; image->ximage->width = width ; image->ximage->height = height ; // Ask the X server to attach the shared memory segment and sync XShmAttach( dsp, &image->shminfo ) ; XSync( dsp, false ) ; return true ; } void getrootwindow( Display * dsp, struct shmimage * image ) { XShmGetImage( dsp, XDefaultRootWindow( dsp ), image->ximage, 0, 0, AllPlanes ) ; // This is how you access the image's BGRA packed pixels // Lets set the alpha channel of each pixel to 0xff int x, y ; unsigned int * p = image->data ; for( y = 0 ; y < image->ximage->height; ++y ) { for( x = 0 ; x < image->ximage->width; ++x ) { *p++ |= 0xff000000 ; } } } /* void initpngimage( png_image * pi, struct shmimage * image ) { bzero( pi, sizeof( png_image ) ) ; pi->version = PNG_IMAGE_VERSION ; pi->width = image->ximage->width ; pi->height = image->ximage->height ; pi->format = PNG_FORMAT_BGRA ; } int savepng( struct shmimage * image, char * path ) { FILE * f = fopen( path, "w" ) ; if( !f ) { perror( "screenshot" ) ; return false ; } png_image pi ; initpngimage( &pi, image ) ; unsigned int scanline = pi.width * BPP ; if( !png_image_write_to_stdio( &pi, f, 0, image->data, scanline, NULL) ) { fclose( f ) ; printf( "could not save the png image\n" ) ; return false ; } fclose( f ) ; return true ; } */ int ScreenShot::init() { dsp = XOpenDisplay( NULL ) ; if( !dsp ) { printf("could not open a connection to the X server\n" ) ; return -1; } if( !XShmQueryExtension( dsp ) ) { XCloseDisplay( dsp ) ; printf("the X server does not support the XSHM extension\n" ) ; return -1 ; } int screen = XDefaultScreen( dsp ) ; initimage( &image ) ; if( !createimage( dsp, &image, XDisplayWidth( dsp, screen ), XDisplayHeight( dsp, screen ) ) ) { XCloseDisplay( dsp ) ; return -1; } return 0; } void ScreenShot::get(int *width,int *height,uint32_t **buf) { getrootwindow(dsp, &image ); *width = image.ximage->width; *height = image.ximage->height; *buf = image.data; // printf("%d x %d\n", image.ximage->width,image.ximage->height); } void ScreenShot::release() { destroyimage( dsp, &image ) ; XCloseDisplay( dsp ) ; } //============================================================================= ScreenShot::ScreenShot() { if(init() != 0) { fprintf(stderr,"screenshot init failed\n"); exit(1); } } ScreenShot::~ScreenShot() { release(); }
23.726316
98
0.564996
alexeyz041
31d445159dc8c0152bbef158390e2f54c391a136
5,054
cxx
C++
Testing/Code/Common/itkBinaryThresholdSpatialFunctionTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
1
2018-04-15T13:32:43.000Z
2018-04-15T13:32:43.000Z
Testing/Code/Common/itkBinaryThresholdSpatialFunctionTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
Testing/Code/Common/itkBinaryThresholdSpatialFunctionTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkBinaryThresholdSpatialFunctionTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkBinaryThresholdSpatialFunction.h" #include "itkSphereSignedDistanceFunction.h" #include "itkFloodFilledSpatialFunctionConditionalConstIterator.h" #include "itkImage.h" /** * This module tests the sphereality of the * BinaryThresholdSpatialFunction class. * * In particular, it creates a SphereSignedDistanceFunction object * connect it to a BinaryThresholdSpatialFunction class. * * The sphere parameters are set at radius of 5 and center of (0,0). * Memebership (i.e. with user specified threshold) is evaluated at * several point and compared to expected values. * The test fails if the evaluated results is not the same as expected * results. * */ int itkBinaryThresholdSpatialFunctionTest( int, char *[]) { typedef double CoordRep; const unsigned int Dimension = 2; typedef itk::SphereSignedDistanceFunction<CoordRep,Dimension> SphereFunctionType; typedef itk::BinaryThresholdSpatialFunction<SphereFunctionType> FunctionType; typedef SphereFunctionType::PointType PointType; typedef SphereFunctionType::ParametersType ParametersType; SphereFunctionType::Pointer sphere = SphereFunctionType::New(); // we must initialize the sphere before use sphere->Initialize(); ParametersType parameters( sphere->GetNumberOfParameters() ); parameters.Fill( 0.0 ); parameters[0] = 5.0; sphere->SetParameters( parameters ); std::cout << "SphereParameters: " << sphere->GetParameters() << std::endl; // create a binary threshold function FunctionType::Pointer function = FunctionType::New(); // connect the sphere function function->SetFunction( sphere ); // set the thresholds double lowerThreshold = -3.0; double upperThreshold = 4.0; function->SetLowerThreshold( lowerThreshold ); function->SetUpperThreshold( upperThreshold ); std::cout << "LowerThreshold: " << function->GetLowerThreshold() << std::endl; std::cout << "UpperThreshold: " << function->GetUpperThreshold() << std::endl; PointType point; for ( double p = 0.0; p < 10.0; p += 1.0 ) { point.Fill( p ); FunctionType::OutputType output = function->Evaluate( point ); std::cout << "f( " << point << ") = " << output; std::cout << " [" << function->GetFunction()->Evaluate( point ); std::cout << "] " << std::endl; // check results CoordRep val = p * vcl_sqrt( 2.0 ) - parameters[0]; bool expected = ( lowerThreshold <= val && upperThreshold >= val ); if( output != expected ) { std::cout << "But expected value is: " << expected << std::endl; return EXIT_FAILURE; } } /** * In the following, we demsonstrate how BinaryThresholdSpatialFunction * can be used to iterate over pixels whose signed distance is * within [lowerThreshold,upperThreshold] of the zero level set defining * the sphere. */ // set up a dummy image typedef itk::Image<unsigned char,Dimension> ImageType; ImageType::Pointer image = ImageType::New(); ImageType::SizeType size; size.Fill( 10 ); image->SetRegions( size ); image->Allocate(); image->FillBuffer( 255 ); // set up the conditional iterator typedef itk::FloodFilledSpatialFunctionConditionalConstIterator< ImageType, FunctionType> IteratorType; IteratorType iterator( image, function ); iterator.SetOriginInclusionStrategy(); // add a seed that already inside the region ImageType::IndexType index; index[0] = 0; index[1] = 3; iterator.AddSeed( index ); unsigned int counter = 0; iterator.GoToBegin(); while( !iterator.IsAtEnd() ) { index = iterator.GetIndex(); image->TransformIndexToPhysicalPoint( index, point ); double value = sphere->Evaluate( point ); std::cout << counter++ << ": "; std::cout << index << " "; std::cout << value << " "; std::cout << std::endl; // check if value is within range if ( value < lowerThreshold || value > upperThreshold ) { std::cout << "Point value is not within thresholds ["; std::cout << lowerThreshold << "," << upperThreshold << "]" << std::endl; return EXIT_FAILURE; } ++iterator; }; function->Print(std::cout); std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; }
31.391304
83
0.658686
kiranhs
31d666cde3c384ff29df1851cbfb700f4b047df1
9,862
hpp
C++
Data/UnevenBlock.hpp
AnabelSMRuggiero/ann
edbd9dc1e2080e2dece31ed55dc36e6cd6f2aa45
[ "Apache-2.0" ]
null
null
null
Data/UnevenBlock.hpp
AnabelSMRuggiero/ann
edbd9dc1e2080e2dece31ed55dc36e6cd6f2aa45
[ "Apache-2.0" ]
null
null
null
Data/UnevenBlock.hpp
AnabelSMRuggiero/ann
edbd9dc1e2080e2dece31ed55dc36e6cd6f2aa45
[ "Apache-2.0" ]
null
null
null
/* NNDescent.cpp: Copyright (c) Anabel Ruggiero At the time of writting, this code is unreleased and not published under a license. As a result, I currently retain all legal rights I am legally entitled to. I am currently considering a permissive license for releasing this code, such as the Apache 2.0 w/LLVM exception. Please refer to the project repo for any updates regarding liscensing. https://github.com/AnabelSMRuggiero/NNDescent.cpp */ #ifndef NND_UNEVENBLOCK_HPP #define NND_UNEVENBLOCK_HPP #include <cstddef> #include <memory_resource> #include <type_traits> #include <new> #include "../Type.hpp" #include "../DataSerialization.hpp" #include "../DataDeserialization.hpp" #include "../AlignedMemory/DynamicArray.hpp" namespace nnd{ template<typename ElementType> struct UnevenBlockIterator{ using value_type = std::span<ElementType>; using difference_type = std::ptrdiff_t; using reference = std::span<ElementType>; using const_reference = const std::span<const ElementType>; UnevenBlockIterator(const size_t* vertexStart, ElementType* vertexNeighbors): vertexStart(vertexStart), vertexNeighbors(vertexNeighbors) {} private: const size_t* vertexStart; ElementType* vertexNeighbors; public: UnevenBlockIterator& operator++(){ vertexNeighbors += *(vertexStart+1) - *vertexStart; ++vertexStart; return *this; } UnevenBlockIterator operator++(int){ UnevenBlockIterator copy = *this; vertexNeighbors += *(vertexStart+1) - *vertexStart; ++vertexStart; return copy; } UnevenBlockIterator& operator--(){ vertexNeighbors -= *vertexStart - *(vertexStart-1); --vertexStart; return *this; } UnevenBlockIterator operator--(int){ UnevenBlockIterator copy = *this; vertexNeighbors -= *vertexStart - *(vertexStart-1); --vertexStart; return copy; } UnevenBlockIterator operator+(std::ptrdiff_t inc) const { UnevenBlockIterator copy{vertexStart+inc, vertexNeighbors + (*(vertexStart+inc) - *vertexStart)}; return copy; } UnevenBlockIterator operator-(std::ptrdiff_t inc) const { UnevenBlockIterator copy{vertexStart-inc, vertexNeighbors - (*vertexStart - *(vertexStart-inc))}; return copy; } std::ptrdiff_t operator-(UnevenBlockIterator other) const { return vertexStart - other.vertexStart; } bool operator==(UnevenBlockIterator other) const { return vertexStart == other.vertexStart; } reference operator*(){ return reference{vertexNeighbors, *(vertexStart+1) - *vertexStart}; } const_reference operator*()const{ return reference{vertexNeighbors, *(vertexStart+1) - *vertexStart}; } reference operator[](size_t i) { return *(*this + i); } const_reference operator[](size_t i)const { return *(*this + i); } UnevenBlockIterator& operator+=(std::ptrdiff_t inc){ *this = *this + inc; return *this; } UnevenBlockIterator& operator-=(std::ptrdiff_t inc){ *this = *this - inc; return *this; } auto operator<=>(UnevenBlockIterator& rhs) const { return vertexStart<=> rhs.vertexStart; } }; template<typename ElementType> requires std::is_trivially_constructible_v<ElementType> && std::is_trivially_destructible_v<ElementType> struct UnevenBlock{ using iterator = UnevenBlockIterator<ElementType>; using const_iterator = UnevenBlockIterator<const ElementType>; using reference = std::span<ElementType>; using const_reference = std::span<const ElementType>; ann::aligned_array<std::byte, static_cast<std::align_val_t>(std::max(alignof(size_t), alignof(ElementType)))> dataStorage; size_t numArrays; ElementType* firstIndex; template<std::endian dataEndianess = std::endian::native> static UnevenBlock deserialize(std::ifstream& inFile){ static_assert(dataEndianess == std::endian::native, "reverseEndianess not implemented yet for this class"); struct DeserializationArgs{ size_t numBytes; size_t numArrays; std::ptrdiff_t indexOffset; }; DeserializationArgs args = Extract<DeserializationArgs>(inFile); UnevenBlock retBlock{args.numBytes, args.numArrays, args.indexOffset}; Extract<std::byte>(inFile, retBlock.dataStorage.begin(), retBlock.dataStorage.end()); return retBlock; } UnevenBlock() = default; //Default Copy Constructor is buggy UnevenBlock(const UnevenBlock& other): dataStorage(other.dataStorage), numArrays(other.numArrays), firstIndex(nullptr){ this->firstIndex = static_cast<ElementType*>(static_cast<void*>(this->dataStorage.data() + other.IndexOffset())); } UnevenBlock& operator=(const UnevenBlock& other){ dataStorage = ann::aligned_array<std::byte, std::align_val_t{std::max(alignof(size_t), alignof(ElementType))}>(other.dataStorage.size()); numArrays = other.numArrays; size_t* vertexStart = new (dataStorage.begin()) size_t[numArrays+1]; std::ptrdiff_t indexOffset = static_cast<const std::byte*>(static_cast<const void*>(other.firstIndex)) - other.dataStorage.begin(); size_t numElements = static_cast<const ElementType*>(static_cast<const void*>(other.dataStorage.end())) - other.firstIndex; firstIndex = new (dataStorage.begin() + indexOffset) ElementType[numElements]; std::copy(other.dataStorage.begin(), other.dataStorage.end(), dataStorage.begin()); return *this; } //NewUndirectedGraph(size_t numVerticies, size_t numNeighbors): // verticies(numVerticies, std::vector<IndexType>(numNeighbors)){}; //template<typename DistType> UnevenBlock(const size_t numBytes, const size_t numArrays, const size_t headerPadding, const size_t numIndecies): dataStorage(numBytes), numArrays(numArrays), firstIndex(nullptr){ size_t* vertexStart = new (dataStorage.begin()) size_t[numArrays+1]; firstIndex = new (dataStorage.begin() + sizeof(size_t)*(numArrays+1) + headerPadding) ElementType[numIndecies]; } UnevenBlock(const size_t numBytes, const size_t numArrays, const std::ptrdiff_t indexOffset): dataStorage(numBytes), numArrays(numArrays), firstIndex(nullptr){ size_t* vertexStart = new (dataStorage.begin()) size_t[numArrays+1]; size_t numIndecies = (dataStorage.end() - (dataStorage.begin() + indexOffset))/sizeof(ElementType); firstIndex = new (dataStorage.begin() + indexOffset) ElementType[numIndecies]; } size_t size() const noexcept{ return numArrays; } constexpr iterator begin() noexcept{ return iterator{std::launder(static_cast<size_t*>(static_cast<void*>(dataStorage.begin()))), firstIndex}; } constexpr const_iterator begin() const noexcept{ return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))), firstIndex}; } constexpr const_iterator cbegin() const noexcept{ return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))), firstIndex}; } constexpr iterator end() noexcept{ return iterator{std::launder(static_cast<size_t*>(static_cast<void*>(dataStorage.begin()))+numArrays), std::launder(static_cast<ElementType*>(static_cast<void*>(dataStorage.end())))}; } constexpr const_iterator end() const noexcept{ return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))+numArrays), std::launder(static_cast<const ElementType*>(static_cast<const void*>(dataStorage.end())))}; } constexpr const_iterator cend() const noexcept{ return const_iterator{std::launder(static_cast<const size_t*>(static_cast<const void*>(dataStorage.begin()))+numArrays), std::launder(static_cast<const ElementType*>(static_cast<const void*>(dataStorage.end())))}; } reference operator[](size_t i){ return this->begin()[i]; } constexpr const_reference operator[](size_t i) const{ return this->cbegin()[i]; } std::byte* data(){ return dataStorage.data(); } std::ptrdiff_t IndexOffset() const{ return static_cast<std::byte*>(static_cast<void*>(firstIndex)) - dataStorage.data(); } }; template<typename ElementType> requires std::is_trivially_constructible_v<ElementType> && std::is_trivially_destructible_v<ElementType> UnevenBlock<ElementType> UninitUnevenBlock(const size_t numArrays, const size_t numElements){ size_t numberOfBytes = 0; size_t headerBytes = sizeof(size_t)*(numArrays+1); size_t headerPadding = 0; if constexpr(alignof(ElementType)>alignof(size_t)){ size_t headerExcess = headerBytes%alignof(ElementType); headerPadding = (headerExcess == 0) ? 0 : alignof(ElementType) - headerBytes%alignof(ElementType); numberOfBytes = headerBytes + headerPadding + sizeof(ElementType)*numElements; } else { numberOfBytes = headerBytes + sizeof(ElementType)*numElements; } return UnevenBlock<ElementType>(numberOfBytes, numArrays, headerPadding, numElements); } template<typename BlockDataType> void Serialize(const UnevenBlock<BlockDataType>& block, std::ofstream& outputFile){ auto outputFunc = BindSerializer(outputFile); outputFunc(block.dataStorage.size()); outputFunc(block.size()); outputFunc(block.IndexOffset()); //this is already the size in bytes outputFile.write(reinterpret_cast<const char*>(block.dataStorage.data()), block.dataStorage.size()); } } #endif
36.257353
221
0.692253
AnabelSMRuggiero
31d933ab08d787839c96b18d68f21d42c08e803d
36,240
cpp
C++
STF/Source/Types/STFString.cpp
rerunner/STCM_driver
8fef3dd7327812fd317fdb0e6fab8d36e345a505
[ "BSD-3-Clause" ]
null
null
null
STF/Source/Types/STFString.cpp
rerunner/STCM_driver
8fef3dd7327812fd317fdb0e6fab8d36e345a505
[ "BSD-3-Clause" ]
null
null
null
STF/Source/Types/STFString.cpp
rerunner/STCM_driver
8fef3dd7327812fd317fdb0e6fab8d36e345a505
[ "BSD-3-Clause" ]
null
null
null
/// /// @brief Foundation classes for string handling /// #include "STF/Interface/Types/STFString.h" #include "STF/Interface/STFMemoryManagement.h" #include "STF/Interface/STFCallingConventions.h" #include "STF/Interface/STFDataManipulationMacros.h" #include "STF/Interface/STFDebug.h" #include <stdio.h> #include <stdarg.h> //////////////////////////////////////////////////////////////////// // // Kernel String Buffer Class Declaration // //////////////////////////////////////////////////////////////////// class STFStringBuffer { protected: char * GetNewBuffer(uint32 size); public: int32 useCnt; int32 length; char * buffer; STFStringBuffer(const char * str); STFStringBuffer(const char ch); STFStringBuffer(STFStringBuffer * u, STFStringBuffer * v); STFStringBuffer(STFStringBuffer * u, int32 start, int32 num); STFStringBuffer(STFStringBuffer * u, int32 num); STFStringBuffer(bool sign, uint32 value, int32 digits, int32 base, char fill); ~STFStringBuffer(void); int32 Compare(STFStringBuffer * u); void Obtain(void) { useCnt++; } void Release(void) { if (!--useCnt) delete this; } }; //////////////////////////////////////////////////////////////////// // // Kernel String Buffer Class Implementation // //////////////////////////////////////////////////////////////////// // // OS Specific Memory Allocator // inline char * STFStringBuffer::GetNewBuffer(uint32 size) { return new (PagedPool) char[size]; } // // Constructor (by character string) // STFStringBuffer::STFStringBuffer(const char * str) { const char * p; char * q; //lint --e{613} ASSERT(str); useCnt = 1; length = 0; p = str; while ((*p++) != 0) length++; buffer = GetNewBuffer(length + 2); p = str; q = buffer; while ((*q++ = *p++) != 0) ; } // // Constructor (by character) // STFStringBuffer::STFStringBuffer(const char ch) { useCnt = 1; length = 1; buffer = GetNewBuffer(2); buffer[0] = ch; buffer[1] = 0; } // // Constructor (by two String buffers) // STFStringBuffer::STFStringBuffer(STFStringBuffer * u, STFStringBuffer * v) { char * p, * q; useCnt = 1; length = u->length + v->length; buffer = GetNewBuffer(length + 1); p = buffer; q = u->buffer; while ((*p++ = *q++) != 0) ; p--; q = v->buffer; while ((*p++ = *q++) != 0) ; } // // Constructor (by part of other buffer) // NOTE: start and num are specified in characters here // STFStringBuffer::STFStringBuffer(STFStringBuffer * u, int32 start, int32 num) { char * p, * q; int32 i; useCnt = 1; length = u->length - start; if (length > num) length = num; buffer = GetNewBuffer(length + 1); p = buffer; q = u->buffer + start; for(i=0; i<length; i++) *p++ = *q++; *p = 0; } // // Constructor (put u n-times into new string buffer) // STFStringBuffer::STFStringBuffer(STFStringBuffer * u, int32 num) { char * p, * q; int32 i; useCnt = 1; length = u->length * num; buffer = GetNewBuffer(length + 1); p = buffer; for(i=0; i<num; i++) { q = u->buffer; while ((*p++ = *q++) != 0) ; p--; } p++; } // // Constructor (by number) // STFStringBuffer::STFStringBuffer(bool sign, uint32 value, int32 digits, int32 base, char fill) { char lbuffer[12]; int32 pos = digits; int32 i; useCnt = 1; if (!pos) pos = 10; do { i = (int32)(value % base); if (i < 10) lbuffer[--pos] = '0' + i; else lbuffer[--pos] = 'A' + i - 10; value /= base; } while (value && pos); if (digits) { buffer = GetNewBuffer(digits + 1); for(i=0; i<pos; i++) buffer[i] = fill; if (sign) buffer[0] = '-'; for (i=pos; i<digits; i++) buffer[i] = lbuffer[i]; buffer[digits] = 0; length = digits; } else { if (sign) { buffer = GetNewBuffer(10 - pos + 2); buffer[0] = '-'; i = 1; length = 10 - pos + 1; } else { buffer = GetNewBuffer(10 - pos + 1); i = 0; length = 10 - pos; } while (pos < 10) { buffer[i++] = lbuffer[pos++]; } buffer[i] = 0; } } // // Destructor // STFStringBuffer::~STFStringBuffer(void) { if (buffer) delete[] buffer; } // // Compare two STFStringBuffers // int32 STFStringBuffer::Compare(STFStringBuffer * u) { char * p, * q; char cp, cq; p = buffer; q = u->buffer; do { cp = *p++; cq = *q++; if (cp < cq) return -1; else if (cp > cq) return 1; } while (cp != 0); return 0; } //////////////////////////////////////////////////////////////////// // // Kernel String Class // //////////////////////////////////////////////////////////////////// // // Constructor (no init) // STFString::STFString(void) { buffer = NULL; } // // Constructor (by character string) // STFString::STFString(const char * str) { if (str == NULL) buffer = NULL; else { buffer = new (PagedPool) STFStringBuffer(str); } } // // Constructor (by character) // STFString::STFString(const char ch) { buffer = new (PagedPool) STFStringBuffer(ch); } // // Constructor (by INT) // STFString::STFString(int32 value, int32 digits, int32 base, char fill) { if (value < 0) buffer = new (PagedPool) STFStringBuffer(true, (uint32)(-value), digits, base, fill); else buffer = new (PagedPool) STFStringBuffer(false, (uint32)(value), digits, base, fill); } // // Constructor (by uint16) // STFString::STFString(uint16 value, int32 digits, int32 base, char fill) { buffer = new (PagedPool) STFStringBuffer(false, value, digits, base, fill); } // // Constructor (by uint32) // STFString::STFString(uint32 value, int32 digits, int32 base, char fill) { buffer = new (PagedPool) STFStringBuffer(false, value, digits, base, fill); } // // Copy Constructor // STFString::STFString(const STFString & str) { buffer = str.buffer; if (buffer) buffer->Obtain(); } // // Destructor // STFString::~STFString(void) { if (buffer) buffer->Release(); } // // Return length (in characters) // int32 STFString::Length(void) const { if (buffer) return buffer->length; else return 0; } // // Convert string to long // int32 STFString::ToInt(uint32 base) { long val = 0; bool sign; char c, * p; if (buffer && buffer->length) { p = buffer->buffer; if (*p == '-') { sign = true; p++; } else sign = false; while ((c = *p++) != 0) { if (c >= '0' && c <= '9') val = val * base + c - '0'; else if (c >= 'a' && c <= 'f') val = val * base + c - 'a' + 10; else if (c >= 'A' && c <= 'F') val = val * base + c - 'A' + 10; else return 0; } if (sign) return -val; else return val; } else return 0; } // // Convert string to uint32 // uint32 STFString::ToUnsigned(uint32 base) { uint32 val = 0; char c, * p; if (buffer && buffer->length) { p = buffer->buffer; while ((c = *p++) != 0) { if (c>='0' && c<= '9') val = val * base + c - '0'; else if (c>='a' && c<='f') val = val * base + c - 'a' + 10; else if (c>='A' && c<='F') val = val * base + c - 'A' + 10; else return 0; } return val; } else return 0; } // // Copy string into character array // Return values signals success // len is length of char * str bool STFString::Get(char * str, int32 len) { char * p, * q; if (buffer) { if (len > buffer->length) { p = str; q = buffer->buffer; while ((*p++ = * q++) != 0) ; return true; } else return false; } else if (len > 0) { str[0] = 0; return true; } else return false; } // // Operator = (by char string) // STFString & STFString::operator= (const char * str) { if (buffer) buffer->Release(); buffer = new (PagedPool) STFStringBuffer(str); return * this; } // // Operator = (by STFString) // STFString & STFString::operator= (const STFString str) { if (buffer) buffer->Release(); buffer = str.buffer; if (buffer) buffer->Obtain(); return * this; } // // Operator + (Concatenation) // LIBRARYCALL STFString operator+ (const STFString u, const STFString v) { STFString str = u; str += v; return str; } // // Operator += (Append) // STFString & STFString::operator += (const STFString u) { STFStringBuffer * bp; if (buffer) { if (u.buffer) { bp = new (PagedPool) STFStringBuffer(buffer, u.buffer); buffer->Release(); buffer = bp; } } else { buffer = u.buffer; if (buffer) buffer->Obtain(); } return *this; } // // Operator * // LIBRARYCALL STFString operator* (const STFString u, const int32 num) { STFString str = u; str *= num; return str; } // // Operator *= // STFString & STFString::operator *= (const int32 num) { STFStringBuffer * bp; if (buffer) { if (num) { bp = new (PagedPool) STFStringBuffer(buffer, num); buffer->Release(); buffer = bp; } else { buffer->Release(); buffer = NULL; } } return *this; } // // Compare two STFStrings // int32 STFString::Compare(const STFString str) { if (buffer == str.buffer) return 0; else if (!buffer) return -1; else if (!str.buffer) return 1; else return buffer->Compare(str.buffer); } // // Operator == // LIBRARYCALL bool operator==(const STFString u, const STFString v) { return ((STFString)u).Compare(v) == 0; } // // Operator != // LIBRARYCALL bool operator!=(const STFString u, const STFString v) { return ((STFString)u).Compare(v) != 0; } // // Operator <= // LIBRARYCALL bool operator<=(const STFString u, const STFString v) { return ((STFString)u).Compare(v) <= 0; } // // Operator >= // LIBRARYCALL bool operator>=(const STFString u, const STFString v) { return ((STFString)u).Compare(v) >= 0; } // // Operator < // LIBRARYCALL bool operator<(const STFString u, const STFString v) { return ((STFString)u).Compare(v) < 0; } // // Operator > // LIBRARYCALL bool operator>(const STFString u, const STFString v) { return ((STFString)u).Compare(v) > 0; } // // Operator [] // char STFString::operator[] (const int32 index) const { if (buffer) return buffer->buffer[index]; else return 0; } void STFString::Set(int32 pos, char val) { if (pos < this->Length()) { STFString str = *this; str.buffer[pos] = val; *this = str; } } // // Operator >> // LIBRARYCALL STFString operator >> (const STFString u, int32 num) { STFString str = u; str >>= num; return str; } // // Operator << // LIBRARYCALL STFString operator << (const STFString u, int32 num) { STFString str = u; str <<= num; return str; } // // Operator <<= // STFString & STFString::operator <<= (int32 index) { STFStringBuffer * pb; if (buffer) { if (index < buffer->length) pb = new (PagedPool) STFStringBuffer(buffer, index, buffer->length - index); else pb = NULL; buffer->Release(); buffer = pb; } return * this; } // // Operator >> // STFString & STFString::operator >>= (int32 index) { STFStringBuffer * pb; if (buffer) { if (index < buffer->length) pb = new (PagedPool) STFStringBuffer(buffer, 0, buffer->length - index); else pb = NULL; buffer->Release(); buffer = pb; } return * this; } // // Return segment of string // STFString STFString::Seg(int32 start, int32 num) const { STFString str; if (buffer) { if (start + num > buffer->length) num = buffer->length - start; if (num > 0) str.buffer = new (PagedPool) STFStringBuffer(buffer, start, num); } return str; } // // Return first num characters // STFString STFString::Head(int32 num) const { STFString str; if (buffer && num > 0) { if (num > buffer->length) num = buffer->length; str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, num); } return str; } // // Return last num characters // STFString STFString::Tail(int32 num) const { STFString str; if (buffer && num > 0) { if (num <= buffer->length) str.buffer = new (PagedPool) STFStringBuffer(buffer, buffer->length - num, num); else str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, num); } return str; } // // Delete whitespaces at beginning or end of string // STFString STFString::Trim(void) { int32 i = 0; STFString str = *this; // delete leading tabs and spaces... i = 0; while ((str[i] == ' ') || (str[i] == '\t')) i++; str <<= i; // delete trailing tabs and spaces ... i = str.Length()-1; while ((str[i] == ' ') || (str[i] == '\t')) i--; str = str.Seg(0, i + 1); return str; } // // Return upper case version of string // STFString STFString::Caps(void) const { STFString str; int32 i; char c; if (Length()) { str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, Length()); for (i=0; i<str.Length(); i++) { c = str[i]; if (c >= 'a' && c <= 'z') str.buffer->buffer[i] = c + 'A' - 'a'; } } return str; } // // Return lower case version of string // STFString STFString::DeCaps(void) const { STFString str; int32 i; char c; if (Length()) { str.buffer = new (PagedPool) STFStringBuffer(buffer, 0, Length()); for (i=0; i<str.Length(); i++) { c = str[i]; if (c >= 'A' && c <= 'Z') str.buffer->buffer[i] = c - ('A' - 'a'); } } return str; } // // Find first occurrence of str // int32 STFString::First(STFString str) const { int32 i = 0; while (i <= Length()-str.Length() && Seg(i, str.Length()) != str) i++; if (Seg(i, str.Length()) != str) return -1; else return i; } // // Find next occurrence of str // int32 STFString::Next(STFString str, int32 pos) const { int32 i = pos + 1; while (i <= Length()-str.Length() && Seg(i, str.Length()) != str) i++; if (Seg(i, str.Length()) != str) return -1; else return i; } // // Find last occurrence of str // int32 STFString::Last(STFString str) const { int32 i = Length() - str.Length(); while (i>=0 && Seg(i, str.Length()) != str) i--; if (Seg(i, str.Length()) != str) return -1; else return i; } // // Find previous occurrence of str // int32 STFString::Prev(STFString str, int32 pos) const { int32 i = pos - 1; while (i>=0 && Seg(i, str.Length()) != str) i--; if (Seg(i, str.Length()) != str) return -1; else return i; } // // Find first occurrence of c (-1 if not found) // int32 STFString::First(char c) const { int32 i = 0; if (buffer) { while (i < Length()) { if (buffer->buffer[i] == c) return i; i++; } } return -1; } // // Find next occurrence of c (-1 if not found) // int32 STFString::Next(char c, int32 pos) const { int32 i = 0; if (buffer) { i = pos + 1; while (i < Length()) { if (buffer->buffer[i] == c) return i; i++; } } return -1; } // // Find last occurrence of c (-1 if not found) // int32 STFString::Last(char c) const { int32 i = 0; if (buffer) { i = Length() - 1; while (i >= 0) { if (buffer->buffer[i] == c) return i; i--; } } return -1; } // // Find previous occurrence of c (-1 if not found) // int32 STFString::Prev(char c, int32 pos) const { int32 i = 0; if (buffer) { i = pos - 1; while (i >= 0) { if (buffer->buffer[i] == c) return i; i--; } } return -1; } // // Test if string contains c // bool STFString::Contains(char c) const { int32 i; if (buffer) { for (i=0; i<Length(); i++) { if (buffer->buffer[i] == c) return true; } } return false; } // // Format string // static const uint32 MAXFORMATSTRINGLENGTH = 2000; void STFString::Format(const char * format, ...) { va_list varArgs; va_start(varArgs, format); char str[MAXFORMATSTRINGLENGTH]; uint32 numWritten = vsprintf(str, format, varArgs); ASSERT(numWritten < MAXFORMATSTRINGLENGTH); // if this assertion fails, the stack is most likely corrupted! va_end(varArgs); *this = str; } void STFString::Format(const char * format, va_list varArgs) { char str[MAXFORMATSTRINGLENGTH] ; // if this assertion fails, the stack is most likely corrupted! uint32 numWritten = vsprintf(str, format, varArgs); ASSERT(numWritten < MAXFORMATSTRINGLENGTH); va_end(varArgs); *this = str; } // // Return pointer to string // STFString::operator char * (void) const { if (buffer) return buffer->buffer; else return NULL; } //////////////////////////////////////////////////////////////////// // // Kernel String Buffer (uint16 characters) Class Declaration // //////////////////////////////////////////////////////////////////// class STFStringBufferW { protected: uint16 * GetNewBuffer(uint32 size); public: uint16 useCnt; uint32 length; uint16 * buffer; STFStringBufferW(const char * str, bool fromUnicode = false); STFStringBufferW(const char * str, uint32 len, bool fromUnicode = false); STFStringBufferW(const uint16 ch); STFStringBufferW(uint32 size); // Creates an UNINITIALIZED string with certain size STFStringBufferW(STFStringBufferW * u, STFStringBufferW * v); STFStringBufferW(STFStringBufferW * u, uint32 start, uint32 num); STFStringBufferW(bool sign, uint32 value, int32 digits, int32 base, uint16 fill); STFStringBufferW(const STFStringBufferW * u); ~STFStringBufferW(void); uint32 Length(void) const { return length; } int32 Compare(STFStringBufferW * u); void Obtain(void) { useCnt++; } void Release(void) { if (!--useCnt) delete this; } }; //////////////////////////////////////////////////////////////////// // // Kernel String Buffer (uint16) Class Implementation // //////////////////////////////////////////////////////////////////// // // OS Specific Memory Allocator (allocates space for trailing 0) // inline uint16 * STFStringBufferW::GetNewBuffer(uint32 size) { return new (PagedPool) uint16[size + 1]; } // // Constructor (by character string) // STFStringBufferW::STFStringBufferW(const char * str, bool fromUnicode) { const char * src; uint16 * dest; uint32 i; useCnt = 1; length = 0; src = str; if (fromUnicode) { while (*src++ || *src++) length++; } else { while (*src++) length++; } buffer = GetNewBuffer(length); src = str; dest = buffer; if (fromUnicode) { for (i=0; i<length; i++) { *dest++ = (src[0] << 8) | src[1]; src += 2; } } else { for (i=0; i<length; i++) *dest++ = (uint16)(*src++); } *dest = 0; } // // Constructor (by character string with length in bytes) // STFStringBufferW::STFStringBufferW(const char * str, uint32 len, bool fromUnicode) { const char * src; uint16 * dest; uint32 i; uint32 calcLen; useCnt = 1; // calculate the actual length. This is necessary to avoid wrong string length // due to zeros in the characters given (Fixes GNBvd29973) if (fromUnicode) { calcLen = 0; src = str; while ((*src++ || *src++) && (calcLen < len)) { calcLen += 2; } } else { calcLen = 0; const char * s = str; while ((*s) && (calcLen < len)) { calcLen++; s++; } } // our length is the minimum of the length passed in and the character length if (fromUnicode) length = min(calcLen,len) >> 1; else length = min(calcLen, len); buffer = GetNewBuffer(length); src = str; dest = buffer; if (fromUnicode) { for (i=0; i<length; i++) { *dest++ = (src[0] << 8) | src[1]; src += 2; } } else { for (i=0; i<length; i++) *dest++ = (uint16)(*src++); } *dest = 0; } // // Constructor (by character) // STFStringBufferW::STFStringBufferW(const uint16 ch) { useCnt = 1; length = 1; buffer = GetNewBuffer(2); buffer[0] = ch; buffer[1] = 0; } // // Constructor (by size). Creates an UNINITIALIZED string. // STFStringBufferW::STFStringBufferW(uint32 size) { useCnt = 1; length = size; buffer = GetNewBuffer(size); buffer[0] = 0; } // // Constructor (by two string buffers) // STFStringBufferW::STFStringBufferW(STFStringBufferW * u, STFStringBufferW * v) { uint16 * src; uint16 * dest; useCnt = 1; length = u->length + v->length; buffer = GetNewBuffer(length); src = u->buffer; dest = buffer; while ((*dest++ = *src++) != 0) ; dest--; // Compensate trailing 0 src = v->buffer; while ((*dest++ = *src++) != 0) ; } // // Constructor (by part of other buffer) // NOTE: start and num are specified in characters here // STFStringBufferW::STFStringBufferW(STFStringBufferW * u, uint32 start, uint32 num) { uint16 * src; uint16 * dest; uint32 i; useCnt = 1; // // Make sure we don't copy too much // if (start + num > u->Length()) num = u->Length() - start; length = num; buffer = GetNewBuffer(length); dest = buffer; src = u->buffer + start; for (i=0; i<length; i++) *dest++ = *src++; *dest = 0; } // // Constructor (by number) // 'digits' includes preceeding fill values and a sign (if -) // #define KSTRW_MAX_NUM_LENGTH 10 STFStringBufferW::STFStringBufferW(bool sign, uint32 value, int32 digits, int32 base, uint16 fill) { uint16 lbuffer[KSTRW_MAX_NUM_LENGTH + 2]; int32 pos = digits; int32 i; useCnt = 1; if (!pos) pos = KSTRW_MAX_NUM_LENGTH; // Pos 11 is for '\0' do { i = (int32)(value % base); if (i < 10) lbuffer[--pos] = '0' + i; else lbuffer[--pos] = 'A' + i - 10; value /= base; } while (value && pos); // // Now fill calculated digits into buffer // if (digits) { buffer = GetNewBuffer(digits + 1); for (i=0; i<pos; i++) buffer[i] = fill; if (sign) buffer[0] = '-'; for (i=pos; i<digits; i++) buffer[i] = lbuffer[i]; buffer[digits] = 0; length = digits; } else { if (sign) { buffer = GetNewBuffer(KSTRW_MAX_NUM_LENGTH - pos + 2); // Incl. sign and '\0' buffer[0] = '-'; i = 1; length = KSTRW_MAX_NUM_LENGTH - pos + 1; } else { buffer = GetNewBuffer(KSTRW_MAX_NUM_LENGTH - pos + 1); // Incl. '\0' i = 0; length = KSTRW_MAX_NUM_LENGTH - pos; } while (pos < KSTRW_MAX_NUM_LENGTH) { buffer[i++] = lbuffer[pos++]; } buffer[i] = 0; } } // // Copy constructor // STFStringBufferW::STFStringBufferW(const STFStringBufferW * u) { uint16 * src; uint16 * dest; useCnt = 1; length = u->Length(); buffer = GetNewBuffer(length); src = u->buffer; dest = buffer; while ((*dest++ = *src++) != 0) ; } // // Destructor // STFStringBufferW::~STFStringBufferW(void) { if (buffer) delete[] buffer; } // // Compare two STFStringBuffers // int32 STFStringBufferW::Compare(STFStringBufferW * u) { uint16 * strA; uint16 * strB; strA = buffer; strB = u->buffer; while (*strA && *strB) { if (*strA < *strB) return -1; else if (*strA > *strB) return 1; strA++; strB++; } if (length < u->length) return -1; else if (length > u->length) return 1; else return 0; } //////////////////////////////////////////////////////////////////// // // Kernel String (uint16) Class // //////////////////////////////////////////////////////////////////// // // Constructor (no init) // STFStringW::STFStringW(void) { buffer = NULL; } // // Constructor (by character string) // STFStringW::STFStringW(const char * str, bool fromUnicode) { buffer = new (PagedPool) STFStringBufferW(str, fromUnicode); } // // Constructor (by character string and length, probably Unicode) // STFStringW::STFStringW(const char * str, uint32 len, bool fromUnicode) { buffer = new (PagedPool) STFStringBufferW(str, len, fromUnicode); } // // Constructor (by character) // STFStringW::STFStringW(const uint16 ch) { buffer = new (PagedPool) STFStringBufferW(ch); } // // Constructor (by STFString) // STFStringW::STFStringW(const STFString & str) { uint32 i; buffer = new (PagedPool) STFStringBufferW((uint32)str.Length()); for (i=0; i<(uint32)str.Length(); i++) { buffer->buffer[i] = (uint16)(/*(const uint8)*/ str[(int32)i]); } buffer->buffer[Length()] = 0; } // // Copy Constructor // STFStringW::STFStringW(const STFStringW & str) { buffer = str.buffer; if (buffer) buffer->Obtain(); } // // Constructor (by uint32) // STFStringW::STFStringW(uint32 value, int32 digits, int32 base, uint16 fill) { buffer = new (PagedPool) STFStringBufferW(false, value, digits, base, fill); } // // Constructor (by INT) // STFStringW::STFStringW(int32 value, int32 digits, int32 base, uint16 fill) { if (value < 0) buffer = new (PagedPool) STFStringBufferW(true, (uint32)(-value), digits, base, fill); else buffer = new (PagedPool) STFStringBufferW(false, (uint32)(value), digits, base, fill); } // // Destructor // STFStringW::~STFStringW(void) { if (buffer) buffer->Release(); } // // Return length (in characters) // uint32 STFStringW::Length(void) const { if (buffer) return buffer->Length(); else return 0; } // // Copy string into character array // If there is not enough room to hold the string then as much as fits is filled in // and GNR_NOT_ENOUGH_MEMORY is returned // STFResult STFStringW::Get(char * str, uint32 & len) const { STFResult err = STFRES_OK; uint16 * src; uint32 i; if (buffer) { if ((len >> 1) > buffer->Length()) len = buffer->Length(); else { if ((len >> 1) - 1 < buffer->Length()) len = (len >> 1) - 1; else len = buffer->Length(); err = STFRES_NOT_ENOUGH_MEMORY; } src = buffer->buffer; i = len; while (i) { *str++ = (*src) & 0xff; *str++ = (*src++) >> 8; i--; } *str++ = 0; *str = 0; } else { if (len > 1) { // // STFStringW is empty and there is enough room for the 0 bytes // str[0] = 0; str[1] = 0; } else err = STFRES_NOT_ENOUGH_MEMORY; len = 0; } STFRES_RAISE(err); } // // Copy string as ASCII into character array (even bytes only) // Return values signals success // STFResult STFStringW::GetAsAscii(char * str, uint32 & len) const { STFResult err = STFRES_OK; uint16 * src; uint32 i; if (buffer) { if (len >= buffer->Length() +1) len = buffer->Length(); else { if (len - 1 < buffer->Length()) len--; else len = buffer->Length(); STFRES_RAISE(STFRES_NOT_ENOUGH_MEMORY); } src = buffer->buffer; i = len; while (i) { *str++ = (*src++) & 0xff; i--; } *str = 0; } else { if (len > 1) { // // STFStringW is empty and there is enough room for the 0 bytes // str[0] = 0; } else STFRES_RAISE(STFRES_NOT_ENOUGH_MEMORY); len = 0; } STFRES_RAISE(err); } // // Get single character // uint16 STFStringW::GetChar(uint32 index) const { //lint --e{613} if (index < buffer->Length()) return buffer->buffer[index]; else return 0; } // // Operator = (by BYTE string) // STFStringW & STFStringW::operator= (const char * str) { if (buffer) buffer->Release(); buffer = new (PagedPool) STFStringBufferW(str); return * this; } // // Operator = (by STFStringW) // STFStringW & STFStringW::operator= (const STFStringW & str) { if (buffer) buffer->Release(); buffer = str.buffer; if (buffer) buffer->Obtain(); return * this; } // // Operator + (Concatenation) // STFStringW operator+ (const STFStringW & u, const STFStringW & v) { STFStringW str = u; str += v; return str; } // // Operator += (Append) // STFStringW & STFStringW::operator += (const STFStringW & u) { STFStringBufferW * bp; if (buffer) { if (u.buffer) { bp = new (PagedPool) STFStringBufferW(buffer, u.buffer); buffer->Release(); buffer = bp; } } else { buffer = u.buffer; if (buffer) buffer->Obtain(); } return *this; } // // Compare two STFStringWs // int32 STFStringW::Compare(const STFStringW & str) const { if (buffer == str.buffer) return 0; else if (!buffer) return -1; else if (!str.buffer) return 1; else return buffer->Compare(str.buffer); } // // Operator == // bool operator==(const STFStringW & u, const STFStringW & v) { return u.Compare(v) == 0; } // // Operator != // bool operator!=(const STFStringW & u, const STFStringW & v) { return u.Compare(v) != 0; } // // Operator <= // bool operator<=(const STFStringW & u, const STFStringW & v) { return u.Compare(v) <= 0; } // // Operator >= // bool operator>=(const STFStringW & u, const STFStringW & v) { return u.Compare(v) >= 0; } // // Operator < // bool operator<(const STFStringW & u, const STFStringW & v) { return u.Compare(v) < 0; } // // Operator > // bool operator>(const STFStringW & u, const STFStringW & v) { return u.Compare(v) > 0; } // // Return segment of string // STFStringW STFStringW::Seg(uint32 start, uint32 num) const { STFStringW str; if (buffer) { if (start + num > buffer->Length()) num = buffer->Length() - start; if (num > 0) str.buffer = new (PagedPool) STFStringBufferW(buffer, start, num); } return str; } // // Return first num characters // STFStringW STFStringW::Head(uint32 num) const { STFStringW str; if (buffer && num > 0) { if (num > buffer->Length()) num = buffer->Length(); str.buffer = new (PagedPool) STFStringBufferW(buffer, 0, num); } return str; } // // Return last num characters // STFStringW STFStringW::Tail(uint32 num) const { STFStringW str; if (buffer && num > 0) { if (num <= buffer->Length()) str.buffer = new (PagedPool) STFStringBufferW(buffer, buffer->Length() - num, num); else str.buffer = new (PagedPool) STFStringBufferW(buffer, 0, num); } return str; } // // Delete whitespaces at beginning or end of string // STFStringW STFStringW::Trim(void) const { STFStringW str; uint32 start = 0; uint32 end; if (buffer) { // // Find leading tabs and spaces ... // while ((buffer->buffer[start] == ' ') || (buffer->buffer[start] == '\t')) start++; if (start >= Length()) { str.buffer = new (PagedPool) STFStringBufferW((uint32)0); } else { // // Find trailing tabs and spaces ... // end = Length() - 1; while ((buffer->buffer[end] == ' ') || (buffer->buffer[end] == '\t')) end--; str = Seg(start, end - start + 1); } } return str; } // // Replace all occurrences of characters in 'what' with 'with', remove doubles // STFStringW STFStringW::Normalize(const uint16 * what, uint32 howManyWhats, uint16 with) { STFStringW str; uint32 i; uint32 j; uint32 write = 0; if (buffer) { str.buffer = new STFStringBufferW(Length()); for (i=0; i<Length(); i++) { for (j=0; j<howManyWhats; j++) { if (what[j] == buffer->buffer[i]) break; } // // If we found a character inside 'what', then replace it // if (j < howManyWhats) { str.buffer->buffer[write] = with; if (!write || str.buffer->buffer[write - 1] != with) write++; else str.buffer->length--; } else { str.buffer->buffer[write] = buffer->buffer[i]; write++; } } str.buffer->buffer[write] = 0; } return str; } // // Return upper case version of string // STFStringW STFStringW::Caps(void) const { STFStringW str; uint16 * p; if (Length()) { str.buffer = new STFStringBufferW(buffer); p = str.buffer->buffer; do { if (*p >= 'a' && *p <= 'z') *p = *p + 'A' - 'a'; p++; } while (*p); } return str; } // // Return lower case version of string // STFStringW STFStringW::DeCaps(void) const { STFStringW str; uint16 * p; if (Length()) { str.buffer = new STFStringBufferW(buffer); p = str.buffer->buffer; do { if (*p >= 'A' && *p <= 'Z') *p = *p + 'a' - 'A'; p++; } while (*p); } return str; } // // Find first occurrence of str // uint32 STFStringW::First(const STFStringW & str) const { uint32 i = 0; while (i <= Length() - str.Length() && Seg(i, str.Length()) != str) i++; if (i <= Length() - str.Length()) return i; else return KSTRW_NOT_FOUND; } // // Find next occurrence of str // uint32 STFStringW::Next(const STFStringW & str, uint32 pos) const { uint32 i = pos+1; while (i <= Length() - str.Length() && Seg(i, str.Length()) != str) i++; if (i <= Length() - str.Length()) return i; else return KSTRW_NOT_FOUND; } // // Find last occurrence of str // uint32 STFStringW::Last(const STFStringW & str) const { int32 i = Length() - str.Length(); while (i >= 0 && Seg(i, str.Length()) != str) i--; if (i >= 0) return (uint32)i; else return KSTRW_NOT_FOUND; } // // Find previous occurrence of str // uint32 STFStringW::Prev(const STFStringW & str, uint32 pos) const { int32 i = pos - 1; while (i >= 0 && Seg(i, str.Length()) != str) i--; if (i >= 0) return (uint32)i; else return KSTRW_NOT_FOUND; } // // Find first occurrence of c (KSTRW_NOT_FOUND if not found) // uint32 STFStringW::First(uint16 c) const { uint32 i = 0; if (buffer) { while (i < Length()) { if (buffer->buffer[i] == c) return i; i++; } } return KSTRW_NOT_FOUND; } // // Find next occurrence of c (KSTRW_NOT_FOUND if not found) // uint32 STFStringW::Next(uint16 c, uint32 pos) const { uint32 i; if (buffer) { i = pos + 1; while (i < Length()) { if (buffer->buffer[i] == c) return i; i++; } } return KSTRW_NOT_FOUND; } // // Find last occurrence of c (KSTRW_NOT_FOUND if not found) // uint32 STFStringW::Last(uint16 c) const { int32 i = 0; if (buffer) { i = Length() - 1; while (i >= 0) { if (buffer->buffer[i] == c) return (uint32)i; i--; } } return KSTRW_NOT_FOUND; } // // Find previous occurrence of c (KSTRW_NOT_FOUND if not found) // uint32 STFStringW::Prev(uint16 c, uint32 pos) const { int32 i; if (buffer) { i = pos - 1; while (i >= 0) { if (buffer->buffer[i] == c) return (uint32)i; i--; } } return KSTRW_NOT_FOUND; } // // Test if string contains c // bool STFStringW::Contains(uint16 c) const { uint32 i = 0; if (buffer) { while (buffer->buffer[i]) { if (buffer->buffer[i] == c) return true; i++; } } return false; }
16.37596
109
0.544123
rerunner
31dc3ec907cfbc8ff5e912e7008b046477e3297c
57
cpp
C++
code archive/TIOJ/1605.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
4
2018-04-08T08:07:58.000Z
2021-06-07T14:55:24.000Z
code archive/TIOJ/1605.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
null
null
null
code archive/TIOJ/1605.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
1
2018-10-29T12:37:25.000Z
2018-10-29T12:37:25.000Z
#include<stdio.h> int main(){puts("APRIL FOOL'S DAY!");}
19
38
0.649123
brianbbsu
31e421fff97882e8a84c98ebf06a104491621c4d
3,403
cpp
C++
src/common/tzplatform-config.cpp
Samsung/security-manager
10b062f317d5d5a7b88ed13242540e9034fd019f
[ "Apache-2.0" ]
14
2015-09-17T19:30:34.000Z
2021-11-11T14:10:43.000Z
src/common/tzplatform-config.cpp
Samsung/security-manager
10b062f317d5d5a7b88ed13242540e9034fd019f
[ "Apache-2.0" ]
5
2015-09-17T13:33:39.000Z
2015-11-12T21:37:09.000Z
src/common/tzplatform-config.cpp
Samsung/security-manager
10b062f317d5d5a7b88ed13242540e9034fd019f
[ "Apache-2.0" ]
14
2015-06-08T07:40:24.000Z
2020-01-20T18:58:13.000Z
/* * Copyright (c) 2014-2016 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Rafal Krypa <r.krypa@samsung.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ /* * @file tzplatform-config.cpp * @author Rafal Krypa <r.krypa@samsung.com> * @brief Interface for tizenplatform-config module */ #include "tzplatform-config.h" namespace SecurityManager { TizenPlatformConfig::TizenPlatformConfig(uid_t uid) { if (tzplatform_context_create(&m_ctx) || m_ctx == nullptr) ThrowMsg(Exception::ContextError, "Error in tzplatform_context_create()"); if (tzplatform_context_set_user(m_ctx, uid)) { tzplatform_context_destroy(m_ctx); ThrowMsg(Exception::ContextError, "Error in tzplatform_context_set_user()"); } } TizenPlatformConfig::~TizenPlatformConfig() { tzplatform_context_destroy(m_ctx); } static std::string validate(const char *str) { if (str == nullptr) ThrowMsg(TizenPlatformConfig::Exception::ValueError, "Invalid value returned by tzplatform-config"); return str; } static uid_t validate(uid_t uid) { if (uid == static_cast<uid_t>(-1)) ThrowMsg(TizenPlatformConfig::Exception::ValueError, "Invalid value returned by tzplatform-config"); return uid; } std::string TizenPlatformConfig::ctxGetEnv(enum tzplatform_variable id) { return validate(tzplatform_context_getenv(m_ctx, id)); } std::string TizenPlatformConfig::ctxMakePath(enum tzplatform_variable id, const std::string &p) { return validate(tzplatform_context_mkpath(m_ctx, id, p.c_str())); } std::string TizenPlatformConfig::ctxMakePath(enum tzplatform_variable id, const std::string &p1, const std::string &p2) { return validate(tzplatform_context_mkpath3(m_ctx, id, p1.c_str(), p2.c_str())); } std::string TizenPlatformConfig::ctxMakePath(enum tzplatform_variable id, const std::string &p1, const std::string &p2, const std::string &p3) { return validate(tzplatform_context_mkpath4(m_ctx, id, p1.c_str(), p2.c_str(), p3.c_str())); } std::string TizenPlatformConfig::getEnv(enum tzplatform_variable id) { return validate(tzplatform_getenv(id)); } std::string TizenPlatformConfig::makePath(enum tzplatform_variable id, const std::string &p) { return validate(tzplatform_mkpath(id, p.c_str())); } std::string TizenPlatformConfig::makePath(enum tzplatform_variable id, const std::string &p1, const std::string &p2) { return validate(tzplatform_mkpath3(id, p1.c_str(), p2.c_str())); } std::string TizenPlatformConfig::makePath(enum tzplatform_variable id, const std::string &p1, const std::string &p2, const std::string &p3) { return validate(tzplatform_mkpath4(id, p1.c_str(), p2.c_str(), p3.c_str())); } uid_t TizenPlatformConfig::getUid(enum tzplatform_variable id) { return validate(tzplatform_getuid(id)); } }
30.383929
95
0.723185
Samsung
31e4db34d89d694ac261facf677a297b7c6e4912
2,715
cpp
C++
osc/reader/types/OscBlob.cpp
MugenSAS/osc-cpp-qt
4dc24d2e073c614ecdcd8de9db4a44f155b4d2b5
[ "MIT" ]
22
2015-03-05T17:00:41.000Z
2022-03-19T19:39:21.000Z
osc/reader/types/OscBlob.cpp
MugenSAS/osc-cpp-qt
4dc24d2e073c614ecdcd8de9db4a44f155b4d2b5
[ "MIT" ]
3
2016-02-20T02:33:01.000Z
2016-06-07T22:00:56.000Z
osc/reader/types/OscBlob.cpp
MugenSAS/osc-cpp-qt
4dc24d2e073c614ecdcd8de9db4a44f155b4d2b5
[ "MIT" ]
3
2016-12-05T19:16:47.000Z
2021-02-01T08:22:06.000Z
/* * Copyright (c) 2014 MUGEN SAS * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <osc/reader/types/OscBlob.h> #include <tools/ByteBuffer.h> #include <osc/exceptions/CharConversionException.h> #include <osc/exceptions/DoubleConversionException.h> #include <osc/exceptions/IntegerConversionException.h> #include <osc/exceptions/FloatConversionException.h> #include <osc/exceptions/LongConversionException.h> #include <osc/exceptions/StringConversionException.h> OscBlob::OscBlob(ByteBuffer* packet, qint32 pos) : OscValue('b', packet, pos) { try { get(); } catch (const QException& e) { throw e; } } /** * Returns the blob data. * * @return a blob data. */ QByteArray& OscBlob::get() { try { mBlobSize = mPacket->getInt(mPos); if (mBlobSize != 0) { mData = QByteArray(mBlobSize, 0); mPacket->setPosition(mPos + 4); mPacket->get(&mData, 0, mBlobSize); qint32 rem = 4 - (mBlobSize % 4); if (rem == 4) rem = 0; mPacket->setPosition(mPos + 4 + mBlobSize + rem); } return mData; } catch (const QException& e) { throw e; } } bool OscBlob::toBoolean() { return (get().length() != 0); } QByteArray OscBlob::toBytes() { return get(); } char OscBlob::toChar() { throw CharConversionException(); } double OscBlob::toDouble() { throw DoubleConversionException(); } float OscBlob::toFloat() { throw FloatConversionException(); } qint32 OscBlob::toInteger() { throw IntegerConversionException(); } qint64 OscBlob::toLong() { throw LongConversionException(); } QString OscBlob::toString() { throw StringConversionException(); }
23.405172
80
0.698711
MugenSAS
31e7f6f0d0213cfceea35eb9f5d1243ca634f060
4,893
cpp
C++
src/Chemin.cpp
prise-3d/pbrt-v3-ray
083dac85191a464e74fc78f035c9f60e9d972917
[ "MIT" ]
null
null
null
src/Chemin.cpp
prise-3d/pbrt-v3-ray
083dac85191a464e74fc78f035c9f60e9d972917
[ "MIT" ]
null
null
null
src/Chemin.cpp
prise-3d/pbrt-v3-ray
083dac85191a464e74fc78f035c9f60e9d972917
[ "MIT" ]
null
null
null
#include "Chemin.hpp" #include <cmath> bool Chemin::readPath(std::ifstream &in){ char k; // utiliser pour récupérer le caractère séparateur // récupération éventuelle des coordonnées du pixel in >> x >> k >> y >> k; if(in.eof()) return false; std::cout << "==============================================================================" << std::endl; std::cout << "Origin(" << x << ", " << y << ")" << std::endl; // récupération des noeuds du chemin std::string ligne; getline(in, ligne); std::istringstream iss(ligne); Point s; Color currentL; unsigned counter = 0; iss >> s.x;// on tente un premier sommet while(iss){// il y a un sommet à lire // récupération des coordonées iss >> k >> s.y >> k >> s.z >> k; sommets.push_back(s); std::cout << "Point(" << s.x << ", " << s.y << ", " << s.z << ")"; // récupération des luminances // La première luminance correspond à la somme, on la stocke donc en information globale if (counter == 0) { iss >> l.r >> k >> l.g >> k >> l.b >> k; std::cout << " => Sum of L(" << l.r << ", " << l.g << ", " << l.b << ")" << std::endl; } else{ iss >> currentL.r >> k >> currentL.g >> k >> currentL.b >> k; luminances.push_back(currentL); std::cout << " => L(" << currentL.r << ", " << currentL.g << ", " << currentL.b << ")" << std::endl; } iss >> s.x;// on tente le sommet suivant counter++; } return true; } void Chemin::toPbrt(std::string filename){ std::cout << "sortie dans " << filename << std::endl; std::ofstream out(filename); if(!out.is_open()){ std::cerr << "erreur d'ouverture du fichier " << filename << std::endl; return; } // export du materiau des cylindres out << "MakeNamedMaterial \"HighRayon\"" << std::endl; out << "\t\"string type\" [\"uber\"]" << std::endl; out << "\t\"color Kd\" [0.43298 0.043298 0.043298]" << std::endl; out << "\t\"color Ks\" [0.47366 0.047366 0.047366]" << std::endl; out << "\t\"color Kr\" [0.000000 0.000000 0.000000]" << std::endl; out << std::endl; out << "MakeNamedMaterial \"Rayon\"" << std::endl; out << "\t\"string type\" [\"uber\"]" << std::endl; out << "\t\"color Kd\" [0.20 0.043298 0.743298]" << std::endl; out << "\t\"color Ks\" [0.20 0.047366 0.77366]" << std::endl; out << "\t\"color Kr\" [0.000000 0.000000 0.000000]" << std::endl; out << std::endl; // insert camera overview as sphere out << "AttributeBegin" << std::endl; out << "\tNamedMaterial \"Rayon\"" << std::endl; out << "\tTranslate " << sommets[0].x << " " << sommets[0].y << " " << sommets[0].z << std::endl; out << "\tShape \"sphere\" \"float radius\" 0.5" << std::endl; out << "AttributeEnd" << std::endl; out << std::endl; // export de chaque élément du chemin sous forme d'un cylindre // passage des luminances acquises au rebond for(int i=0; i<sommets.size()-1; i++) exportCylindre(sommets[i], sommets[i+1], luminances[i], out); out.close(); } void Chemin::exportCylindre(const Point &c1, const Point &c2, const Color &l, std::ofstream &out){ // on translate le cylindre à l'origine Point t = c1; Point o1 = c1-t; Point o2 = c2-t; // on stocke la hauteur du cylindre Vecteur u(o1, o2); float hauteur = u.norme(); // calcul du vecteur perpendiculaire à Oz et u u.normalise(); Vecteur oz(0,0,1); Vecteur v; v = u.cross(oz); // calcul de l'angle de rotation de u vers oz autour de v float angle = std::asin(v.norme()); // valeur en radian angle = angle * 180.0 / M_PI; // valeur en degré // mise à jour de l'angle de rotation pbrt if(u.z <0) // axe z en sens inverse de l'axe du cylindre angle = -180.0 + angle; else angle = -angle; // sortie du cylindre pbrt out << "AttributeBegin" << std::endl; // Ray cylinder color depending on contribution if (l.r > limit || l.g > limit || l.b > limit) out << "\tNamedMaterial \"HighRayon\"" << std::endl; else out << "\tNamedMaterial \"Rayon\"" << std::endl; out << "\tTranslate " << t.x << " " << t.y << " " << t.z << std::endl; out << "\tRotate " << angle << " " << v.x << " " << v.y << " " << v.z << std::endl; out << "\tShape \"cylinder\" \"float radius\" [0.01] \"float zmin\" [0.0] "; out << "\"float zmax\" [" << hauteur << "]" << std::endl; out << "AttributeEnd" << std::endl << std::endl; // out << c1.x << " " << c1.y << " " << c1.z << " - "; // out << c2.x << " " << c2.y << " " << c2.z << std::endl; } std::ostream& operator<<(std::ostream& out, const Chemin& path){ out << path.x << "-" << path.y << " ("; out << path.l.r << "-" << path.l.g << "-" << path.l.b << ") "; for(int i=0; i<path.sommets.size(); i++){ out << "[" << path.sommets[i].x; out << "," << path.sommets[i].y; out << "," << path.sommets[i].z; out << "] "; } return out; }
33.285714
109
0.536685
prise-3d
31e9f6a70f562dd59052bd5442b2ee7d4f7870de
6,339
cpp
C++
data/train/cpp/31e9f6a70f562dd59052bd5442b2ee7d4f7870deModelScene.cpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/cpp/31e9f6a70f562dd59052bd5442b2ee7d4f7870deModelScene.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/cpp/31e9f6a70f562dd59052bd5442b2ee7d4f7870deModelScene.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#include "Scene/ModelScene.h" #include "Model/StlModel.h" #include "Model/VolumeModel.h" #include "Model/PointsModel.h" #include "Model/EvaluatorModel.h" #include "Model/AxesModel.h" namespace Scene { ModelScene::ModelScene() : AbstractScene() { } ModelScene::~ModelScene() { } Viewport::ViewportArray * ModelScene::viewportArray() const { return _viewportArray; } Model::AbstractModel * ModelScene::selectedModel() const { return qobject_cast<Model::AbstractModel *>(_models.selectedObject()); } void ModelScene::setViewportArray(Viewport::ViewportArray * viewportArray) { _viewportArray = viewportArray; emit viewportArrayChanged(); } void ModelScene::updateScene() { while (!_blueprints.isEmpty()) { unpackBlueprint(_blueprints.dequeue()); } for (Model::AbstractModel * model : _models.list()) { if (model->updateNeeded()) { model->update(); } } } void ModelScene::renderScene(const QSize & surfaceSize) { viewportArray()->resize(surfaceSize); updateScene(); render(); /* some children, like pointsmodel can change its values after rendering - * for example depth buffer check affects values of points (z-coordinate) */ if (postProcess()) { emit redraw(); } } void ModelScene::render(const Model::AbstractModel::RenderState & state) { Viewport::ViewportRect boundingRect; for (const Viewport::Viewport * viewport : _viewportArray->array()) { boundingRect = viewport->boundingRect(); glViewport(boundingRect.x(), boundingRect.y(), boundingRect.width(), boundingRect.height()); for (Model::AbstractModel * model : _models.list()) { model->drawModel(viewport, state); } } } bool ModelScene::postProcess() { //render(Model::AbstractModel::RenderState::CONTOUR_RENDER); bool redraw = false; for (Model::AbstractModel * model : _models.list()) { for (const Viewport::Viewport * viewport : _viewportArray->array()) { redraw |= model->checkBuffers(viewport); } if (redraw) { model->update(); } } return redraw; } void ModelScene::cleanUp() { _models.clear(); AbstractScene::cleanUp(); } QVariant ModelScene::blueprint() const { return _blueprint; } void ModelScene::setBlueprint(const QVariant & blueprint) { _blueprints.enqueue(blueprint.value<Blueprint>()); _blueprint = blueprint; emit blueprintChanged(blueprint); } void ModelScene::selectModel(Model::AbstractModel * model) { Model::AbstractModel * prevSelected = _models.selectedObject(); if (prevSelected) { prevSelected->unselectModel(); } _models.selectObject(model); uint selectedID = 0; for (const Model::AbstractModel * model : _models.list()) { selectedID = std::max(selectedID, model->numberedID()); } // this is for stencil model->selectModel(selectedID); Message::SettingsMessage message( Message::Sender(_models.selectedObject()->id()), Message::Reciever("sidebar") ); message.data["action"] = "changeModelID"; emit post(message); } Model::AbstractModel * ModelScene::addModel(const ModelInfo::Model & model) { ModelInfo::Params params; Model::AbstractModel * modelI = Model::AbstractModel::createModel(model.first, this); params = model.second; modelI->init(params); QVariantList children = params["children"].toList(); QVariantMap childsMap; for (const QVariant & child : children) { childsMap = child.toMap(); modelI->addChild(addModel(ModelInfo::Model( childsMap["type"].value<ModelInfo::Type>(), childsMap["params"].value<ModelInfo::Params>() ) ) ); } QObject::connect(modelI, &Model::AbstractModel::post, this, &ModelScene::post, Qt::DirectConnection); return modelI; } void ModelScene::initScene() { unpackBlueprint(_blueprints.dequeue(), true); } void ModelScene::unpackBlueprint(const Blueprint & blueprint, const bool & resetScene) { if (resetScene) { cleanUp(); } QVariantMap helper; for (const QVariant & lightSource : blueprint["lightSources"].toList()) { lightSources.append(new LightSource(lightSource.toMap())); } for (const QVariant & material : blueprint["materials"].toList()) { materials.append(new Material(material.toMap())); } for (const QVariant & texture : blueprint["textures"].toList()) { textures.append(new Texture(texture.toMap())); } Model::AbstractModel * newModel; for (const QVariant & model : blueprint["models"].toList()) { helper = model.toMap(); newModel = addModel(ModelInfo::Model( helper["type"].value<ModelInfo::Type>(), helper["params"].value<ModelInfo::Params>() ) ); _models.append(newModel); selectModel(newModel); } } void ModelScene::recieve(const Message::SettingsMessage & message) { if (message.reciever().startsWith("Scene")) { if (message.data["action"] == "add") { _blueprints.enqueue(message.data["blueprint"].value<Blueprint>()); return; } return; } Model::AbstractModel * model = _models[message.reciever()]; if (model) { model->invoke( message.data["action"].toString(), message.data["params"].value<ModelInfo::Params>() ); return; } } }
28.048673
109
0.557343
harshp8l
31ef67de141a8c3f10773da7059d7bb3434f17a3
794
cpp
C++
src/event/from_string.cpp
cbosoft/aite
61c0a108da9884e6c2d290ca87eafa5521326acc
[ "MIT" ]
null
null
null
src/event/from_string.cpp
cbosoft/aite
61c0a108da9884e6c2d290ca87eafa5521326acc
[ "MIT" ]
null
null
null
src/event/from_string.cpp
cbosoft/aite
61c0a108da9884e6c2d290ca87eafa5521326acc
[ "MIT" ]
null
null
null
#include <sstream> #include <vector> #include "event.hpp" #include "new_colony_event.hpp" #include "../util/exception.hpp" // Manages creation of event object pointers given the name of the event to // create. Event_ptr Event::from_string(std::string s) { std::stringstream ss(s); std::string evname, args_raw; std::vector<std::string> args; getline(ss, evname, '('); getline(ss, args_raw, ','); ss.str(args_raw); for (std::string arg; getline(ss, arg, ',');){ args.push_back(arg); } Event_ptr rv = nullptr; if (evname.compare("NewColonyEvent") == 0) { if (args.size() != 1) { throw ArgumentError(Formatter() << "Wrong number of arguments; expected 1, got " << args.size() << "."); } rv = NewColonyEvent::create(args[0]); } return rv; }
20.358974
110
0.63728
cbosoft
31f140576d417e6fc6adb77286281f32c3af1028
20,725
cpp
C++
xmlcc/xmlccCfgConfig.cpp
cscheiblich/XMLCC
efda13ae7261b22304907432d1298a865d14bcdc
[ "MIT" ]
1
2020-02-07T09:12:50.000Z
2020-02-07T09:12:50.000Z
xmlcc/xmlccCfgConfig.cpp
cscheiblich/XMLCC
efda13ae7261b22304907432d1298a865d14bcdc
[ "MIT" ]
null
null
null
xmlcc/xmlccCfgConfig.cpp
cscheiblich/XMLCC
efda13ae7261b22304907432d1298a865d14bcdc
[ "MIT" ]
null
null
null
/** * @file xmlccCfgConfig.cpp * @author Christian (graetz23@gmail.com) * * XMLCC is distributed under the MIT License (MIT); this file is part of. * * Copyright (c) 2008-2022 Christian (graetz23@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "./xmlccCfgConfig.h" // header /******************************************************************************/ namespace XMLCC { namespace CFG { /******************************************************************************/ /// constructor Config::Config( void ) { _root = read( ); // one strategy, take DOM tree to mem } // Config /// destructor Config::~Config( void ) { if( _root != 0 ) delete _root; // delete DOM tree if read; always } // ~Config /******************************************************************************/ bool // check if config file is existing Config::exists( void ) { bool isExisting = false; Str fileName = "xmlcc.xml"; // static file name FileStr file; // standard file stream file.open( (char*)fileName.c_str( ), std::ios::in ); if( !file.fail( ) ) isExisting = true; file.close( ); return isExisting; } // Config::isExisting /******************************************************************************/ DOM::Root* // use this method in static way; Config::parseFile( "file.xml" ); Config::generate( void ) { DOM::Root* xml = 0; try { // try everything .. like chicken's road rash ~8> xml = new DOM::Root( "xmlcc.xml", new DOM::Header( new DOM::Attribute( "version", "1.0" ) ), new DOM::Comment( "XMLCC 1.00 20150101 Amara Faith" ), new DOM::Comment( "config file of the xmlcc library" ), new DOM::Element( "xmlcc:xmlcc", new DOM::Comment( "library configuration; set by user" ), new DOM::Element( "xmlcc:config", new DOM::Comment( "parser configuration" ), new DOM::Element( "xmlcc:parser", new DOM::Element( "xmlcc:console", new DOM::Attribute( "talk", "no" ) ), new DOM::Element( "xmlcc:clean", new DOM::Attribute( "tags", "yes" ), new DOM::Attribute( "attributes", "yes" ), new DOM::Attribute( "comments", "yes" ) ), new DOM::Element( "xmlcc:memory", new DOM::Attribute( "preallocation", "999" ) ) ), new DOM::Comment( "tokenizer configuration" ), new DOM::Element( "xmlcc:tokenizer", new DOM::Element( "xmlcc:console", new DOM::Attribute( "talk", "no" ) ) ) ), new DOM::Comment( "library information; refreshed by each call" ), new DOM::Element( "xmlcc:info", new DOM::Element( "xmlcc:built", new DOM::Attribute( "date", "01.01.2015" ) ), new DOM::Element( "xmlcc:version", new DOM::Attribute( "number", "1.00" ) ), new DOM::Element( "xmlcc:package", new DOM::Attribute( "name", "Amara Faith" ) ), new DOM::Element( "xmlcc:license", new DOM::Attribute( "type", "The MIT License (MIT)" ) ), new DOM::Element( "xmlcc:project", new DOM::Attribute( "url", "https://github.com/graetz23/xmlcc/" ) ), new DOM::Element( "xmlcc:user", new DOM::Attribute( "name", "Christian" ), new DOM::Attribute( "email", "graetz23@gmail.com" ) ) ), new DOM::Comment( "library system; run unit tests, etc." ), new DOM::Element( "xmlcc:system", new DOM::Comment( "unit test framework configuration" ), new DOM::Element( "xmlcc:test", new DOM::Comment( "unit test framework configuration" ), new DOM::Element( "xmlcc:sysList", new DOM::Attribute( "run", "no" ) ), new DOM::Element( "xmlcc:sysStrTool", new DOM::Attribute( "run", "no" ) ), new DOM::Element( "xmlcc:sysXmlTool", new DOM::Attribute( "run", "no" ) ), new DOM::Element( "xmlcc:sysXmlParser", new DOM::Attribute( "run", "no" ) ), new DOM::Element( "xmlcc:domTokenizer", new DOM::Attribute( "run", "no" ) ), new DOM::Element( "xmlcc:domController", new DOM::Attribute( "run", "no" ) ), new DOM::Element( "xmlcc:xmlcc", new DOM::Attribute( "run", "no" ) ), new DOM::Comment( "reads chars &compares them; due to use of STL file encoding" ), new DOM::CData( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ) ) ) ) ); } catch( SYS::Failure& f ) { Str msg = "XMLCC::CFG::Config::generate - "; throw SYS::Failure( msg.append( f.declare( ) ) ); } catch( SYS::Error& e ) { Str msg = "XMLCC::CFG::Config::generate - "; throw SYS::Error( msg.append( e.declare( ) ) ); } catch( SYS::Exception& e ) { Str msg = "XMLCC::CFG::Config::generate - "; throw SYS::Error( msg.append( e.declare( ) ) ); } catch( std::exception& e ) { throw SYS::Exception( "XMLCC::CFG::Config::generate - std::exception caught!" ); } catch( ... ) { throw SYS::Exception( "XMLCC::CFG::Config::generate - unknown caught!" ); } // try return xml; } // Config::generate /******************************************************************************/ void // use this method in static way; Config::parseFile( "file.xml" ); Config::write( DOM::Root* xml ) { try { // try everything .. like chicken's road rash ~8> std::fstream file; // open file file.open( "xmlcc.xml", std::ios::out ); file << xml; // DOM::Node* 2 std::fstream or write XML file to drive file.close( ); delete xml; } catch( SYS::Failure& f ) { Str msg = "XMLCC::CFG::Config::write - "; throw SYS::Failure( msg.append( f.declare( ) ) ); } catch( SYS::Error& e ) { Str msg = "XMLCC::CFG::Config::write - "; throw SYS::Error( msg.append( e.declare( ) ) ); } catch( SYS::Exception& e ) { Str msg = "XMLCC::CFG::Config::write - "; throw SYS::Error( msg.append( e.declare( ) ) ); } catch( std::exception& e ) { throw SYS::Exception( "XMLCC::CFG::Config::write - std::exception caught!" ); } catch( ... ) { throw SYS::Exception( "XMLCC::CFG::Config::write - unknown caught!" ); } // try } // Config::write /******************************************************************************/ DOM::Root* // use this method in static way; Config::parseFile( "file.xml" ); Config::read( void ) { DOM::Root* xml = 0; try { // try everything .. like chicken's road rash ~8> DOM::Core core; // parsing, cleaning, tokenizing, and model building xml = core.parseFile2DomTree( "xmlcc.xml" ); // parse 2 model tree } catch( SYS::Failure& f ) { // recovery might be a dead lock ;-) if( xml != 0 ) delete xml; f.report( ); std::cout << "generating config file for xmlcc .. " << std::flush; write( generate( ) ); std::cout << "done!" << std::endl << std::flush; xml = read( ); // recovery } catch( SYS::Error& e ) { if( xml != 0 ) delete xml; e.report( ); std::cout << "generating config file for xmlcc .. " << std::flush; write( generate( ) ); std::cout << "done!" << std::endl << std::flush; xml = read( ); // recovery } catch( SYS::Exception& e ) { if( xml != 0 ) delete xml; e.report( ); std::cout << "generating config file for xmlcc .. " << std::flush; write( generate( ) ); std::cout << "done!" << std::endl << std::flush; xml = read( ); // recovery } catch( std::exception& e ) { if( xml != 0 ) delete xml; std::cout << "generating config file for xmlcc .. " << std::flush; write( generate( ) ); std::cout << "done!" << std::endl << std::flush; xml = read( ); // recovery } catch( ... ) { if( xml != 0 ) delete xml; std::cout << "generating config file for xmlcc .. " << std::flush; write( generate( ) ); std::cout << "done!" << std::endl << std::flush; xml = read( ); // recovery } // try return xml; } // Config::read /******************************************************************************/ /// <config><parser> .. </parser></config> bool // get config parameter Config::getConfigParserConsoleTalk( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:config", "xmlcc:parser", "xmlcc:console", "talk" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getConfigParserConsoleTalk bool // get config parameter Config::getConfigParserCleanTag( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:config", "xmlcc:parser", "xmlcc:clean", "tags" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getConfigParserCleanTag bool // get config parameter Config::getConfigParserCleanAttributes( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:config", "xmlcc:parser", "xmlcc:clean", "attribute" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getConfigParserCleanAttributes bool // get config parameter Config::getConfigParserCleanComments( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:config", "xmlcc:parser", "xmlcc:clean", "comments" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getConfigParserCleanComments int // get config parameter Config::getConfigParserMemoryPreallocation( void ) { int parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:config", "xmlcc:parser", "xmlcc:memory", "preallocation" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2I( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getConfigParserMemoryPreallocation /******************************************************************************/ /// <config><tokenizer> .. </tokenizer></config> bool // get config parameter Config::getConfigTokenizerTalk( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:config", "xmlcc:tokenizer", "xmlcc:console", "talk" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getConfigTokenizerTalk /******************************************************************************/ /// <config><info> .. </info></config> Str // get info parameter Config::getInfoBuiltDate( void ) { Str parameter = ""; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:info", "xmlcc:built", "date" ); if( res != 0 ) Str readParameter = ( (DOM::Attribute*)res )->getValue( ); _controller.erase( xmlConfigFile ); return parameter; } // Config::getInfoBuiltDate Str // get info parameter Config::getInfoVersionNumber( void ) { Str parameter = ""; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:info", "xmlcc:version", "number" ); if( res != 0 ) Str readParameter = ( (DOM::Attribute*)res )->getValue( ); _controller.erase( xmlConfigFile ); return parameter; } // Config::getInfoVersionNumber Str // get info parameter Config::getInfoPackageName( void ) { Str parameter = ""; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:info", "xmlcc:package", "name" ); if( res != 0 ) Str readParameter = ( (DOM::Attribute*)res )->getValue( ); _controller.erase( xmlConfigFile ); return parameter; } // Config::getInfoPackageName Str // get info parameter Config::getInfoLicenseType( void ) { Str parameter = ""; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:info", "xmlcc:license", "type" ); if( res != 0 ) Str readParameter = ( (DOM::Attribute*)res )->getValue( ); _controller.erase( xmlConfigFile ); return parameter; } // Config::getInfoLicenseType Str // get info parameter Config::getInfoProjectUrl( void ) { Str parameter = ""; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:info", "xmlcc:project", "url" ); if( res != 0 ) Str readParameter = ( (DOM::Attribute*)res )->getValue( ); _controller.erase( xmlConfigFile ); return parameter; } // Config::getInfoProjectUrl Str // get info parameter Config::getInfoUserName( void ) { Str parameter = ""; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:info", "xmlcc:user", "name" ); if( res != 0 ) Str readParameter = ( (DOM::Attribute*)res )->getValue( ); _controller.erase( xmlConfigFile ); return parameter; } // Config::getInfoUserName Str // get info parameter Config::getInfoUserEmail( void ) { Str parameter = ""; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:info", "xmlcc:user", "email" ); if( res != 0 ) Str readParameter = ( (DOM::Attribute*)res )->getValue( ); _controller.erase( xmlConfigFile ); return parameter; } // Config::getInfoUserEmail /******************************************************************************/ /// <config><system> .. </system></config> bool // get system parameter Config::getSystemTestSysList( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:system", "xmlcc:test", "xmlcc:sysList", "run" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getSystemTestSysList bool // get system parameter Config::getSystemTestSysStrTool( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:system", "xmlcc:test", "xmlcc:sysStrTool", "run" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getSystemTestStrTool bool // get system parameter Config::getSystemTestSysXmlTool( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:system", "xmlcc:test", "xmlcc:sysXmlTool", "run" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getSystemTestXmlTool bool // get system parameter Config::getSystemTestSysXmlParser( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:system", "xmlcc:test", "xmlcc:sysXmlParser", "run" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getSystemTestXmlParser bool // get system parameter Config::getSystemTestDomTokenizer( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:system", "xmlcc:test", "xmlcc:domTokenizer", "run" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getSystemTestDomTokenizer bool // get system parameter Config::getSystemTestDomController( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:system", "xmlcc:test", "xmlcc:domController", "run" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getSystemTestDomController bool // get system parameter Config::getSystemTestXmlcc( void ) { bool parameter = true; // default DOM::Root* xmlConfigFile = read( ); // load config file from drive DOM::Node* res = _controller.search( xmlConfigFile, "xmlcc:xmlcc", "xmlcc:system", "xmlcc:test", "xmlcc:xmlcc", "run" ); if( res != 0 ) { Str readParameter = ( (DOM::Attribute*)res )->getValue( ); parameter = _strTool.doS2B( readParameter ); // conversion } // if _controller.erase( xmlConfigFile ); return parameter; } // Config::getSystemTestXmlcc Str // get system parameter Config::getSystemCData( void ) { Str parameter = ""; throw SYS::Error( "CFG::Config::getSystemCData - not implemented yet!" ); return parameter; } // Config::getSystemCData /******************************************************************************/ } // namespace CFG } // namespace XMLCC /******************************************************************************/
38.738318
91
0.598022
cscheiblich
31f1e804b10fb855c07d7113d35ff593b137157a
4,500
cpp
C++
tide/wall/qml/TextureNodeRGBA.cpp
BlueBrain/Tide
01e0518117509eaa0ccd9d79f067f385b641247c
[ "BSD-2-Clause" ]
47
2016-07-12T02:00:11.000Z
2021-07-06T17:50:53.000Z
tide/wall/qml/TextureNodeRGBA.cpp
BlueBrain/Tide
01e0518117509eaa0ccd9d79f067f385b641247c
[ "BSD-2-Clause" ]
135
2016-03-24T14:02:26.000Z
2019-10-25T09:43:59.000Z
tide/wall/qml/TextureNodeRGBA.cpp
BlueBrain/Tide
01e0518117509eaa0ccd9d79f067f385b641247c
[ "BSD-2-Clause" ]
17
2016-03-23T13:34:48.000Z
2022-03-21T03:21:54.000Z
/*********************************************************************/ /* Copyright (c) 2016-2017, EPFL/Blue Brain Project */ /* Raphael Dumusc <raphael.dumusc@epfl.ch> */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE ECOLE POLYTECHNIQUE */ /* FEDERALE DE LAUSANNE ''AS IS'' AND ANY EXPRESS OR IMPLIED */ /* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR */ /* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ECOLE */ /* POLYTECHNIQUE FEDERALE DE LAUSANNE OR CONTRIBUTORS BE */ /* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */ /* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ /* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) */ /* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN */ /* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ /* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of Ecole polytechnique federale de Lausanne. */ /*********************************************************************/ #include "TextureNodeRGBA.h" #include "data/Image.h" #include "textureUtils.h" #include <QQuickWindow> TextureNodeRGBA::TextureNodeRGBA(QQuickWindow& window, const bool dynamic) : _window(window) , _dynamicTexture(dynamic) , _texture(window.createTextureFromId(0, QSize(1, 1))) { if (_texture) // needed for null texture in unit tests without a scene graph setTexture(_texture.get()); setFiltering(QSGTexture::Linear); setMipmapFiltering(QSGTexture::Linear); } void TextureNodeRGBA::setMipmapFiltering(const QSGTexture::Filtering filtering_) { auto mat = static_cast<QSGOpaqueTextureMaterial*>(material()); auto opaqueMat = static_cast<QSGOpaqueTextureMaterial*>(opaqueMaterial()); mat->setMipmapFiltering(filtering_); opaqueMat->setMipmapFiltering(filtering_); } void TextureNodeRGBA::uploadTexture(const Image& image) { if (!image.getTextureSize().isValid()) throw std::runtime_error("image texture has invalid size"); if (image.getRowOrder() == deflect::RowOrder::bottom_up) setTextureCoordinatesTransform(QSGSimpleTextureNode::MirrorVertically); else setTextureCoordinatesTransform(QSGSimpleTextureNode::NoTransform); if (!_pbo) _pbo = textureUtils::createPbo(_dynamicTexture); textureUtils::upload(image, 0, *_pbo); _nextTextureSize = image.getTextureSize(); _glImageFormat = image.getGLPixelFormat(); } void TextureNodeRGBA::swap() { if (_texture->textureSize() != _nextTextureSize) _texture = textureUtils::createTextureRgba(_nextTextureSize, _window); textureUtils::copy(*_pbo, *_texture, _glImageFormat); setTexture(_texture.get()); markDirty(DirtyMaterial); if (!_dynamicTexture) _pbo.reset(); }
45.918367
80
0.578667
BlueBrain
31f30624876c29b0e9a328b20a50ca8beba7870d
22
cpp
C++
src/module.cpp
claremacrae/eml
d10eb7fcfc51abb277c1edbec8f15a7ed806ceb1
[ "MIT" ]
3
2020-11-03T19:22:11.000Z
2021-05-05T13:16:15.000Z
src/module.cpp
claremacrae/eml
d10eb7fcfc51abb277c1edbec8f15a7ed806ceb1
[ "MIT" ]
2
2020-04-01T12:57:24.000Z
2021-02-19T10:17:30.000Z
src/module.cpp
claremacrae/eml
d10eb7fcfc51abb277c1edbec8f15a7ed806ceb1
[ "MIT" ]
2
2020-10-15T18:28:18.000Z
2020-10-25T16:44:17.000Z
#include "module.hpp"
11
21
0.727273
claremacrae
31f38a5f572b3e8035aa9eac0307304738e3aab9
5,778
cpp
C++
3rdparty/Floating-Point-Root-Finder/src/KDOPBroadPhase.cpp
LamWS/ClothSimulation
008b24fa96005cbe7ccae27a765d19e5f68a3ef2
[ "MIT" ]
5
2021-11-10T08:39:34.000Z
2022-03-06T10:21:49.000Z
3rdparty/Floating-Point-Root-Finder/src/KDOPBroadPhase.cpp
LamWS/ClothSimulation
008b24fa96005cbe7ccae27a765d19e5f68a3ef2
[ "MIT" ]
null
null
null
3rdparty/Floating-Point-Root-Finder/src/KDOPBroadPhase.cpp
LamWS/ClothSimulation
008b24fa96005cbe7ccae27a765d19e5f68a3ef2
[ "MIT" ]
null
null
null
#include "KDOPBroadPhase.h" #include <set> #include "History.h" #include "Mesh.h" #include <iostream> using namespace std; using namespace Eigen; KDOPBroadPhase::KDOPBroadPhase() { DOPaxis.push_back(Vector3d(1.0, 0, 0)); DOPaxis.push_back(Vector3d(0, 1.0, 0)); DOPaxis.push_back(Vector3d(0, 0, 1.0)); DOPaxis.push_back(Vector3d(1.0, 1.0, 0)); DOPaxis.push_back(Vector3d(1.0, -1.0, 0)); DOPaxis.push_back(Vector3d(0, 1.0, 1.0)); DOPaxis.push_back(Vector3d(0, 1.0, -1.0)); DOPaxis.push_back(Vector3d(1.0, 0, 1.0)); DOPaxis.push_back(Vector3d(1.0, 0, -1.0)); DOPaxis.push_back(Vector3d(1.0, 1.0, 1.0)); DOPaxis.push_back(Vector3d(1.0, 1.0, -1.0)); DOPaxis.push_back(Vector3d(1.0, -1.0, 1.0)); DOPaxis.push_back(Vector3d(1.0, -1.0, -1.0)); if(K>DOPaxis.size()) exit(0); for(int i=0; i<(int)DOPaxis.size(); i++) { DOPaxis[i] /= DOPaxis[i].norm(); } } void KDOPBroadPhase::findCollisionCandidates(const History &h, const Mesh &m, double outerEta, set<VertexFaceStencil> &vfs, set<EdgeEdgeStencil> &ees, const std::set<int> &fixedVerts) { vfs.clear(); ees.clear(); KDOPNode *tree = buildKDOPTree(h, m, outerEta); intersect(tree, tree, m, vfs, ees, fixedVerts); delete tree; } KDOPNode *KDOPBroadPhase::buildKDOPTree(const History &h, const Mesh &m, double outerEta) { vector<KDOPNode *> leaves; for(int i=0; i<(int)m.faces.cols(); i++) { KDOPLeafNode *node = new KDOPLeafNode; node->face = i; int verts[3]; for(int j=0; j<3; j++) { verts[j] = m.faces.coeff(j, i); } for(int j=0; j<K; j++) { node->mins[j] = std::numeric_limits<double>::infinity(); node->maxs[j] = -std::numeric_limits<double>::infinity(); } for(int j=0; j<3; j++) { for(vector<HistoryEntry>::const_iterator it = h.getVertexHistory(verts[j]).begin(); it != h.getVertexHistory(verts[j]).end(); ++it) { for(int k=0; k<K; k++) { node->mins[k] = min(it->pos.dot(DOPaxis[k]) - outerEta, node->mins[k]); node->maxs[k] = max(it->pos.dot(DOPaxis[k]) + outerEta, node->maxs[k]); } } } leaves.push_back(node); } return buildKDOPInterior(leaves); } KDOPNode *KDOPBroadPhase::buildKDOPInterior(vector<KDOPNode *> &children) { int nchildren = children.size(); assert(nchildren > 0); if(nchildren == 1) return children[0]; KDOPInteriorNode *node = new KDOPInteriorNode; for(int i=0; i<K; i++) { node->mins[i] = std::numeric_limits<double>::infinity(); node->maxs[i] = -std::numeric_limits<double>::infinity(); } for(vector<KDOPNode *>::iterator it = children.begin(); it != children.end(); ++it) { for(int j=0; j<K; j++) { node->mins[j] = min((*it)->mins[j], node->mins[j]); node->maxs[j] = max((*it)->maxs[j], node->maxs[j]); } } double lengths[K]; for(int i=0; i<K; i++) { lengths[i] = node->maxs[i] - node->mins[i]; } int greatest = -1; double greatestlen = 0; for(int i=0; i<K; i++) { if(lengths[i] > greatestlen) { greatestlen = lengths[i]; greatest = i; } } node->splitaxis = greatest; sort(children.begin(), children.end(), NodeComparator(node->splitaxis)); vector<KDOPNode *> left; int child=0; for(; child<nchildren/2; child++) left.push_back(children[child]); node->left = buildKDOPInterior(left); vector<KDOPNode *> right; for(; child<nchildren; child++) right.push_back(children[child]); node->right = buildKDOPInterior(right); return node; } void KDOPBroadPhase::intersect(KDOPNode *left, KDOPNode *right, const Mesh &m, std::set<VertexFaceStencil> &vfs, std::set<EdgeEdgeStencil> &ees, const std::set<int> &fixedVerts) { for(int axis=0; axis<K; axis++) { if(left->maxs[axis] < right->mins[axis] || right->maxs[axis] < left->mins[axis]) return; } if(!left->isLeaf()) { KDOPInteriorNode *ileft = (KDOPInteriorNode *)left; intersect(ileft->left, right, m, vfs, ees, fixedVerts); intersect(ileft->right, right, m, vfs, ees, fixedVerts); } else if(!right->isLeaf()) { KDOPInteriorNode *iright = (KDOPInteriorNode *)right; intersect(left, iright->left, m, vfs, ees, fixedVerts); intersect(left, iright->right, m, vfs, ees, fixedVerts); } else { KDOPLeafNode *lleft = (KDOPLeafNode *)left; KDOPLeafNode *lright = (KDOPLeafNode *)right; if(m.neighboringFaces(lleft->face, lright->face)) return; // 6 vertex-face and 9 edge-edge for(int i=0; i<3; i++) { bool alllfixed = true; bool allrfixed = true; alllfixed = alllfixed && fixedVerts.count(m.faces.coeff(i, lleft->face)); allrfixed = allrfixed && fixedVerts.count(m.faces.coeff(i, lright->face)); for(int j=0; j<3; j++) { alllfixed = alllfixed && fixedVerts.count(m.faces.coeff(j, lright->face)); allrfixed = allrfixed && fixedVerts.count(m.faces.coeff(j, lleft->face)); } if(!alllfixed) vfs.insert(VertexFaceStencil(m.faces.coeff(i, lleft->face), m.faces.coeff(0, lright->face), m.faces.coeff(1, lright->face), m.faces.coeff(2, lright->face))); if(!allrfixed) vfs.insert(VertexFaceStencil(m.faces.coeff(i, lright->face), m.faces.coeff(0, lleft->face), m.faces.coeff(1, lleft->face), m.faces.coeff(2, lleft->face))); for(int j=0; j<3; j++) { bool allefixed = true; allefixed = allefixed && fixedVerts.count(m.faces.coeff(i, lleft->face)); allefixed = allefixed && fixedVerts.count(m.faces.coeff((i+1)%3, lleft->face)); allefixed = allefixed && fixedVerts.count(m.faces.coeff(j, lright->face)); allefixed = allefixed && fixedVerts.count(m.faces.coeff((j+1)%3, lright->face)); if(!allefixed) ees.insert(EdgeEdgeStencil(m.faces.coeff(i, lleft->face), m.faces.coeff((i+1)%3, lleft->face), m.faces.coeff(j, lright->face), m.faces.coeff((j+1)%3, lright->face))); } } } }
31.064516
183
0.639322
LamWS
31f732a5b64e8278b8eccc43b4c15a8b373e9ef4
1,038
hpp
C++
macos/MersenneTwisterRandomizer.hpp
BoysTownorg/av-speech-in-noise
71178c1f920e300f05c9da2d582d64035c591284
[ "MIT" ]
null
null
null
macos/MersenneTwisterRandomizer.hpp
BoysTownorg/av-speech-in-noise
71178c1f920e300f05c9da2d582d64035c591284
[ "MIT" ]
null
null
null
macos/MersenneTwisterRandomizer.hpp
BoysTownorg/av-speech-in-noise
71178c1f920e300f05c9da2d582d64035c591284
[ "MIT" ]
null
null
null
#ifndef MACOS_MAIN_MERSENNETWISTERRANDOMIZER_HPP_ #define MACOS_MAIN_MERSENNETWISTERRANDOMIZER_HPP_ #include <av-speech-in-noise/playlist/RandomizedTargetPlaylists.hpp> #include <av-speech-in-noise/core/RecognitionTestModel.hpp> #include <random> namespace av_speech_in_noise { class MersenneTwisterRandomizer : public target_list::Randomizer, public Randomizer { std::mt19937 engine{std::random_device{}()}; public: void shuffle(gsl::span<av_speech_in_noise::LocalUrl> s) override { std::shuffle(s.begin(), s.end(), engine); } void shuffle(gsl::span<int> s) override { std::shuffle(s.begin(), s.end(), engine); } auto betweenInclusive(double a, double b) -> double override { std::uniform_real_distribution<> distribution{a, b}; return distribution(engine); } auto betweenInclusive(int a, int b) -> int override { std::uniform_int_distribution<> distribution{a, b}; return distribution(engine); } }; } #endif
28.833333
70
0.684008
BoysTownorg
31f8925b9ec4468bddf0b4a0e3d0c79fc554b481
776
cpp
C++
src/libugly/edge/edge_undirected.cpp
JoshuaSBrown/GraphCluster
d9c28204b276165cf59137c9668c4dfcfa397089
[ "MIT" ]
null
null
null
src/libugly/edge/edge_undirected.cpp
JoshuaSBrown/GraphCluster
d9c28204b276165cf59137c9668c4dfcfa397089
[ "MIT" ]
null
null
null
src/libugly/edge/edge_undirected.cpp
JoshuaSBrown/GraphCluster
d9c28204b276165cf59137c9668c4dfcfa397089
[ "MIT" ]
null
null
null
#include "../../../include/ugly/edge_undirected.hpp" namespace ugly { const constants::EdgeType EdgeUndirected::class_type_ = constants::EdgeType::undirected; constants::EdgeType EdgeUndirected::getClassType() { return EdgeUndirected::class_type_; } EdgeUndirected::EdgeUndirected(int vertex1, int vertex2) { if (vertex1 < vertex2) { vertex1_ = vertex1; vertex2_ = vertex2; } else { vertex1_ = vertex2; vertex2_ = vertex1; } edge_directed_ = false; object_type_ = constants::EdgeType::undirected; } EdgeUndirected& EdgeUndirected::operator=(const EdgeUndirected& edge) { vertex1_ = edge.vertex1_; vertex2_ = edge.vertex2_; edge_directed_ = edge.edge_directed_; object_type_ = edge.object_type_; return *this; } }
24.25
71
0.71134
JoshuaSBrown
31f910df850174b6c416aa9f8d7948b161dd94f0
4,966
cpp
C++
qtcreator/OpensslServer/main.cpp
fasShare/cpp-study
b7d691a02324260e09e5e35c0a71650ddb37fd97
[ "MIT" ]
null
null
null
qtcreator/OpensslServer/main.cpp
fasShare/cpp-study
b7d691a02324260e09e5e35c0a71650ddb37fd97
[ "MIT" ]
null
null
null
qtcreator/OpensslServer/main.cpp
fasShare/cpp-study
b7d691a02324260e09e5e35c0a71650ddb37fd97
[ "MIT" ]
null
null
null
#include <errno.h> #include <unistd.h> #include <malloc.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <resolv.h> #include "openssl/ssl.h" #include "openssl/err.h" #define FAIL -1 using namespace std; int OpenListener(int port) { int sd; struct sockaddr_in addr; sd = socket(PF_INET, SOCK_STREAM, 0); bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 ) { perror("can't bind port"); abort(); } if ( listen(sd, 10) != 0 ) { perror("Can't configure listening port"); abort(); } return sd; } SSL_CTX* InitServerCTX(void) { SSL_CTX *ctx = NULL; #if OPENSSL_VERSION_NUMBER >= 0x10000000L const SSL_METHOD *method; #else SSL_METHOD *method; #endif SSL_library_init(); OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */ SSL_load_error_strings(); /* load all error messages */ method = SSLv23_client_method(); /* create new server-method instance */ ctx = SSL_CTX_new(method); /* create new context from method */ if ( ctx == NULL ) { ERR_print_errors_fp(stderr); abort(); } return ctx; } void LoadCertificates(SSL_CTX* ctx, const char* CertFile, const char* KeyFile) { //New lines if (SSL_CTX_load_verify_locations(ctx, CertFile, KeyFile) != 1) ERR_print_errors_fp(stderr); if (SSL_CTX_set_default_verify_paths(ctx) != 1) ERR_print_errors_fp(stderr); //End new lines /* set the local certificate from CertFile */ if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); abort(); } /* set the private key from KeyFile (may be the same as CertFile) */ if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); abort(); } /* verify private key */ if ( !SSL_CTX_check_private_key(ctx) ) { fprintf(stderr, "Private key does not match the public certificate\n"); abort(); } printf("LoadCertificates Compleate Successfully.....\n"); } void ShowCertsClient(SSL* ssl) { X509 *cert; char *line; cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */ if ( cert != NULL ) { printf("Server certificates:\n"); line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); printf("Subject: %s\n", line); free(line); line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); printf("Issuer: %s\n", line); free(line); X509_free(cert); } else printf("No certificates.\n"); } void Servlet(SSL* ssl) /* Serve the connection -- threadable */ { char buf[1024]; char reply[1024]; int sd, bytes; const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n"; if ( SSL_accept(ssl) == FAIL ) /* do SSL-protocol accept */ ERR_print_errors_fp(stderr); else { ShowCertsClient(ssl); /* get any certificates */ bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */ if ( bytes > 0 ) { buf[bytes] = 0; printf("Client msg: \"%s\"\n", buf); sprintf(reply, HTMLecho, buf); /* construct reply */ SSL_write(ssl, reply, strlen(reply)); /* send reply */ } else ERR_print_errors_fp(stderr); } sd = SSL_get_fd(ssl); /* get socket connection */ SSL_free(ssl); /* release SSL state */ close(sd); /* close connection */ } int MainServer(int count, char *strings[]) { SSL_CTX *ctx; int server; char *portnum; if ( count != 2 ) { printf("Usage: %s <portnum>\n", strings[0]); exit(0); } else { printf("Usage: %s <portnum>\n", strings[1]); } SSL_library_init(); portnum = strings[1]; ctx = InitServerCTX(); /* initialize SSL */ LoadCertificates(ctx, "/home/stud/kawsar/mycert.pem", "/home/stud/kawsar/mycert.pem"); /* load certs */ server = OpenListener(atoi(portnum)); /* create server socket */ while (1) { struct sockaddr_in addr; socklen_t len = sizeof(addr); SSL *ssl; int client = accept(server, (struct sockaddr*)&addr, &len); /* accept connection as usual */ printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); ssl = SSL_new(ctx); /* get new SSL state with context */ SSL_set_fd(ssl, client); /* set connection socket to SSL state */ Servlet(ssl); /* service connection */ } close(server); /* close server socket */ SSL_CTX_free(ctx); /* release context */ }
29.736527
108
0.594442
fasShare
31fc7a1ec8a5514626b68b4263578cda4e91d600
1,146
cpp
C++
tests/map.cpp
Enhex/Deco
e730ad7e61d74be56237dc2a5eb7cf807a0fa305
[ "Apache-2.0" ]
62
2017-12-27T16:25:05.000Z
2022-02-23T15:21:10.000Z
tests/map.cpp
Enhex/Deco
e730ad7e61d74be56237dc2a5eb7cf807a0fa305
[ "Apache-2.0" ]
2
2017-12-27T20:31:45.000Z
2017-12-28T21:15:01.000Z
tests/map.cpp
Enhex/Deco
e730ad7e61d74be56237dc2a5eb7cf807a0fa305
[ "Apache-2.0" ]
2
2017-12-28T14:59:03.000Z
2019-01-07T04:12:18.000Z
#include <deco/list.h> #include <deco/types/map.h> #include <gs/serializer.h> #include <cassert> #include <fstream> #include <iostream> int main() { using T1 = std::map<std::string, std::string>; const T1 val{ {"a", "1"}, {"b", "2"}, {"c", "3"}, {"d", "4"}, {"e", "5"} }; using T2 = std::map<std::string, std::map<std::string, std::string>>; const T2 val2{ { "a", { { "1", "1" } } }, { "b", { { "2", "2" } } } }; // write { deco::OutputStream_indent stream; deco::serialize(stream, deco::make_list("std::map", val)); deco::serialize(stream, deco::make_list("std::map2", val2)); std::ofstream os("out.deco", std::ios::binary); os << stream.str; } // read { auto file = std::ifstream("out.deco", std::ios::binary); std::string file_str{ std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>() }; std::cout << file_str; auto stream = deco::make_InputStream(file_str.cbegin()); T1 in_val; deco::serialize(stream, deco::make_list("std::map", in_val)); assert(in_val == val); T2 in_val2; deco::serialize(stream, deco::make_list("std::map2", in_val2)); assert(in_val2 == val2); } }
24.382979
90
0.605585
Enhex
31fcf4e81b3f3cf3db97cdb905df7fa14a19d415
376
cpp
C++
Group E/Round I/tests & author/tests & author/E/RABBIT/author/rabbit.cpp
riki00000/NOI-Compets-2008
8916dc9266c0b68853944a0c75d133dc08e0d00a
[ "MIT" ]
null
null
null
Group E/Round I/tests & author/tests & author/E/RABBIT/author/rabbit.cpp
riki00000/NOI-Compets-2008
8916dc9266c0b68853944a0c75d133dc08e0d00a
[ "MIT" ]
null
null
null
Group E/Round I/tests & author/tests & author/E/RABBIT/author/rabbit.cpp
riki00000/NOI-Compets-2008
8916dc9266c0b68853944a0c75d133dc08e0d00a
[ "MIT" ]
1
2019-02-27T16:16:17.000Z
2019-02-27T16:16:17.000Z
#include <iostream> using namespace std; int main() { int a,b,c; cin>>a>>b>>c; if (a == 1) cout<<"(\\_/)\n"; else if (a == 2) cout<<"(o.o)\n"; else if (a == 3) cout<<"(_._)\n"; if (b == 1) cout<<"(\\_/)\n"; else if (b == 2) cout<<"(o.o)\n"; else if (b == 3) cout<<"(_._)\n"; if (c == 1) cout<<"(\\_/)\n"; else if (c == 2) cout<<"(o.o)\n"; else if (c == 3) cout<<"(_._)\n"; }
23.5
34
0.454787
riki00000
ee004e706213d86f351debe87992363878941297
3,163
cpp
C++
pnc/atlas_pnc/atlas_state_machine/single_support_swing.cpp
junhyeokahn/PnC
388440f7db7b2aedf1e397d0130d806090865c35
[ "MIT" ]
25
2019-01-31T13:51:34.000Z
2022-02-08T13:19:01.000Z
pnc/atlas_pnc/atlas_state_machine/single_support_swing.cpp
junhyeokahn/PnC
388440f7db7b2aedf1e397d0130d806090865c35
[ "MIT" ]
5
2020-06-01T20:48:46.000Z
2022-02-08T11:42:02.000Z
pnc/atlas_pnc/atlas_state_machine/single_support_swing.cpp
junhyeokahn/PnC
388440f7db7b2aedf1e397d0130d806090865c35
[ "MIT" ]
9
2018-11-20T22:37:50.000Z
2021-09-14T17:17:27.000Z
#include <pnc/atlas_pnc/atlas_state_machine/single_support_swing.hpp> SingleSupportSwing::SingleSupportSwing(const StateIdentifier _state_identifier, AtlasControlArchitecture *_ctrl_arch, int _leg_side, RobotSystem *_robot) : StateMachine(_state_identifier, _robot) { util::PrettyConstructor(2, "SingleSupportSwing"); atlas_ctrl_arch_ = _ctrl_arch; leg_side_ = _leg_side; sp_ = AtlasStateProvider::getStateProvider(_robot); } SingleSupportSwing::~SingleSupportSwing() {} void SingleSupportSwing::firstVisit() { if (leg_side_ == EndEffector::RFoot) { std::cout << "AtlasState::RFootSwing" << std::endl; } else { std::cout << "AtlasState::LFootSwing" << std::endl; } ctrl_start_time_ = sp_->curr_time; end_time_ = atlas_ctrl_arch_->dcm_tm->getSwingTime(); int footstep_idx = atlas_ctrl_arch_->dcm_tm->current_footstep_idx; if (leg_side_ == EndEffector::RFoot) { atlas_ctrl_arch_->rfoot_tm->InitializeSwingTrajectory( sp_->curr_time, end_time_, atlas_ctrl_arch_->dcm_tm->footstep_list[footstep_idx]); } else if (leg_side_ == EndEffector::LFoot) { atlas_ctrl_arch_->lfoot_tm->InitializeSwingTrajectory( sp_->curr_time, end_time_, atlas_ctrl_arch_->dcm_tm->footstep_list[footstep_idx]); } else { assert(false); } } void SingleSupportSwing::oneStep() { state_machine_time_ = sp_->curr_time - ctrl_start_time_; // Update Foot Task if (leg_side_ == EndEffector::LFoot) { atlas_ctrl_arch_->lfoot_tm->UpdateDesired(sp_->curr_time); atlas_ctrl_arch_->rfoot_tm->UpdateZeroAccCmd(); } else { atlas_ctrl_arch_->rfoot_tm->UpdateDesired(sp_->curr_time); atlas_ctrl_arch_->lfoot_tm->UpdateZeroAccCmd(); } // Update floating base task atlas_ctrl_arch_->dcm_tm->updateDCMTasksDesired(sp_->curr_time); } void SingleSupportSwing::lastVisit() { atlas_ctrl_arch_->dcm_tm->incrementStepIndex(); } bool SingleSupportSwing::endOfState() { // if (state_machine_time_ >= end_time_) { // return true; //} else { // if (state_machine_time_ >= 0.5 * end_time_) { // if (leg_side_ == EndEffector::LFoot) { // if (sp_->b_lf_contact) { // printf("Early left foot contact at %f/%f\n", state_machine_time_, // end_time_); // return true; //} //} else { // if (sp_->b_rf_contact) { // printf("Early right foot contact at %f/%f\n", state_machine_time_, // end_time_); // return true; //} //} //} // return false; //} if (state_machine_time_ >= end_time_) { return true; } else { return false; } } StateIdentifier SingleSupportSwing::getNextState() { int next_footstep_robot_side; if (atlas_ctrl_arch_->dcm_tm->nextStepRobotSide(next_footstep_robot_side)) { if (next_footstep_robot_side == EndEffector::LFoot) { return AtlasStates::LFootContactTransitionStart; } else { return AtlasStates::RFootContactTransitionStart; } } else { if (leg_side_ == EndEffector::LFoot) { return AtlasStates::LFootContactTransitionStart; } else { return AtlasStates::RFootContactTransitionStart; } } }
29.287037
79
0.689219
junhyeokahn
ee01f01a415005bdbfbf3b595d82a1f10ede00c5
15,926
cpp
C++
src/DesignRuleChecker.cpp
k2973363/PcbRouter
ec7befb1ff924dbe398cccb93088ccbbfff9dfd8
[ "BSD-3-Clause" ]
11
2020-02-13T22:15:53.000Z
2021-11-04T02:37:46.000Z
src/DesignRuleChecker.cpp
k2973363/PcbRouter
ec7befb1ff924dbe398cccb93088ccbbfff9dfd8
[ "BSD-3-Clause" ]
4
2019-12-23T17:17:05.000Z
2020-11-04T16:05:42.000Z
src/DesignRuleChecker.cpp
k2973363/PcbRouter
ec7befb1ff924dbe398cccb93088ccbbfff9dfd8
[ "BSD-3-Clause" ]
7
2020-05-23T01:49:19.000Z
2021-09-08T09:56:34.000Z
#include "DesignRuleChecker.h" int DesignRuleChecker::checkAcuteAngleViolationBetweenTracesAndPads() { std::cout << "Starting " << __FUNCTION__ << "()..." << std::endl; std::cout << std::fixed << std::setprecision((int)round(std::log(mInputPrecision))); int numViolations = 0; // Iterate nets for (auto &net : mDb.getNets()) { if (GlobalParam::gVerboseLevel <= VerboseLevel::DEBUG) { std::cout << "\nNet: " << net.getName() << ", netId: " << net.getId() << ", netDegree: " << net.getPins().size() << "..." << std::endl; } auto &pins = net.getPins(); for (auto &pin : pins) { // DB elements auto &comp = mDb.getComponent(pin.getCompId()); auto &inst = mDb.getInstance(pin.getInstId()); auto &pad = comp.getPadstack(pin.getPadstackId()); // Handle GridPin's pinPolygon, which should be expanded by clearance Point_2D<double> polyPadSize = pad.getSize(); Point_2D<double> pinDbLocation; mDb.getPinPosition(pad, inst, &pinDbLocation); // Get a exact locations expanded polygon in db's coordinates std::vector<Point_2D<double>> exactDbLocPadPoly; if (pad.getPadShape() == padShape::CIRCLE || pad.getPadShape() == padShape::OVAL) { // WARNING!! shape_to_coords's pos can be origin only!!! Otherwise the rotate function will be wrong exactDbLocPadPoly = shape_to_coords(polyPadSize, point_2d{0, 0}, padShape::CIRCLE, inst.getAngle(), pad.getAngle(), pad.getRoundRectRatio(), 32); } else { exactDbLocPadPoly = shape_to_coords(polyPadSize, point_2d{0, 0}, padShape::RECT, inst.getAngle(), pad.getAngle(), pad.getRoundRectRatio(), 32); } // Shift to exact location for (auto &&pt : exactDbLocPadPoly) { pt.m_x += pinDbLocation.m_x; pt.m_y += pinDbLocation.m_y; } // Transform this into Boost's polygon in db's coordinates polygon_double_t exactLocGridPadShapePoly; for (const auto &pt : exactDbLocPadPoly) { bg::append(exactLocGridPadShapePoly.outer(), point_double_t(pt.x(), pt.y())); } bg::correct(exactLocGridPadShapePoly); // box_double_t pinBoundingBox; // bg::envelope(exactLocGridPadShapePoly, pinBoundingBox); // std::cout << "Pin's Polygon: " << boost::geometry::wkt(exactLocGridPadShapePoly) << std::endl; //Iterate all the segments for (auto &seg : net.getSegments()) { if (!isPadstackAndSegmentHaveSameLayer(inst, pad, seg)) { continue; } points_2d &points = seg.getPos(); if (points.size() < 2) { std::cout << __FUNCTION__ << "(): Invalid # segment's points." << std::endl; continue; } linestring_double_t bgLs{point_double_t(points[0].x(), points[0].y()), point_double_t(points[1].x(), points[1].y())}; // std::cout << "Seg: (" << bg::get<0>(bgLs.front()) << ", " << bg::get<1>(bgLs.front()) // << "), (" << bg::get<0>(bgLs.back()) << ", " << bg::get<1>(bgLs.back()) << ")" << std::endl; if (bg::crosses(bgLs, exactLocGridPadShapePoly)) { Point_2D<long long> pt1{(long long)round(points[0].x() * mInputPrecision), (long long)round(points[0].y() * mInputPrecision)}; Point_2D<long long> pt2{(long long)round(points[1].x() * mInputPrecision), (long long)round(points[1].y() * mInputPrecision)}; if (pad.getPadShape() == padShape::RECT) { if (!isOrthogonalSegment(pt1, pt2)) { // Get intersection point std::vector<point_double_t> intersectPts; bg::intersection(bgLs, exactLocGridPadShapePoly, intersectPts); if (!intersectPts.empty()) { if (!isIntersectionPointOnTheBoxCorner(intersectPts.front(), exactLocGridPadShapePoly, seg.getWidth(), mAcuteAngleTol)) { std::cout << __FUNCTION__ << "(): Violation between segment: (" << points[0].x() << ", " << points[0].y() << "), (" << points[1].x() << ", " << points[1].y() << "), width: " << seg.getWidth() << ", and rectangle pad center at " << pinDbLocation.x() << ", " << pinDbLocation.y() << std::endl; ++numViolations; } } } } else if (pad.getPadShape() == padShape::CIRCLE) { point_double_t center{pinDbLocation.x(), pinDbLocation.y()}; if (!isSegmentTouchAPoint(bgLs, center, seg.getWidth())) { std::cout << __FUNCTION__ << "(): Violation between segment: (" << points[0].x() << ", " << points[0].y() << "), (" << points[1].x() << ", " << points[1].y() << ") and circle pad center at " << pinDbLocation.x() << ", " << pinDbLocation.y() << std::endl; ++numViolations; } } } } } } std::cout << "Total # acute angle violations: " << numViolations << std::endl; std::cout << "End of " << __FUNCTION__ << "()..." << std::endl; return numViolations; } int DesignRuleChecker::checkTJunctionViolation() { std::cout << "Starting " << __FUNCTION__ << "()..." << std::endl; std::cout << std::fixed << std::setprecision((int)round(std::log(mInputPrecision))); int numViolations = 0; std::vector<TJunctionPatch> patches; // Iterate nets for (auto &net : mDb.getNets()) { // if (net.getId() != 27) continue; if (GlobalParam::gVerboseLevel <= VerboseLevel::DEBUG) { std::cout << "\nNet: " << net.getName() << ", netId: " << net.getId() << ", netDegree: " << net.getPins().size() << "..." << std::endl; } for (int segId = 0; segId < net.getSegments().size(); ++segId) { for (int segId2 = segId + 1; segId2 < net.getSegments().size(); ++segId2) { auto &seg1 = net.getSegment(segId); auto &seg2 = net.getSegment(segId2); if (seg1.getLayer() != seg2.getLayer()) { continue; } points_2d &ptsSeg1 = seg1.getPos(); points_2d &ptsSeg2 = seg2.getPos(); if (ptsSeg1.size() < 2 || ptsSeg2.size() < 2) { std::cout << __FUNCTION__ << "(): Invalid # segment's points." << std::endl; continue; } linestring_double_t bgLs1{point_double_t(ptsSeg1[0].x(), ptsSeg1[0].y()), point_double_t(ptsSeg1[1].x(), ptsSeg1[1].y())}; linestring_double_t bgLs2{point_double_t(ptsSeg2[0].x(), ptsSeg2[0].y()), point_double_t(ptsSeg2[1].x(), ptsSeg2[1].y())}; if (areConnectedSegments(bgLs1, bgLs2)) { continue; } // Check if is T-Junction ++numViolations; double patchSize = seg1.getWidth() * 2.0; polygon_double_t patchPoly; if (bg::distance(bgLs1.back(), bgLs2) < mTJunctionEpsilon) { std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg1[1].x() << ", " << ptsSeg1[1].y() << ")" << std::endl; addTJunctionPatch(bgLs1.back(), bgLs1, bgLs2, patchSize, patchPoly); } else if (bg::distance(bgLs1.front(), bgLs2) < mTJunctionEpsilon) { std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg1[0].x() << ", " << ptsSeg1[0].y() << ")" << std::endl; addTJunctionPatch(bgLs1.front(), bgLs1, bgLs2, patchSize, patchPoly); } else if (bg::distance(bgLs2.front(), bgLs1) < mTJunctionEpsilon) { std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg2[0].x() << ", " << ptsSeg2[0].y() << ")" << std::endl; addTJunctionPatch(bgLs2.front(), bgLs2, bgLs1, patchSize, patchPoly); } else if (bg::distance(bgLs2.back(), bgLs1) < mTJunctionEpsilon) { std::cout << __FUNCTION__ << "(): Violation at point: (" << ptsSeg2[1].x() << ", " << ptsSeg2[1].y() << ")" << std::endl; addTJunctionPatch(bgLs2.back(), bgLs2, bgLs1, patchSize, patchPoly); } else { --numViolations; } if (!bg::is_empty(patchPoly)) { patches.emplace_back(TJunctionPatch{patchPoly, seg1.getLayer(), seg1.getNetId()}); } } } } printTJunctionPatchToKiCadZone(patches); std::cout << "Total # T-Junction violations: " << numViolations << std::endl; std::cout << "End of " << __FUNCTION__ << "()..." << std::endl; return numViolations; } void DesignRuleChecker::printTJunctionPatchToKiCadZone(std::vector<TJunctionPatch> &patches) { // Print all the patches in KiCadPcbFormat for (const auto &patch : patches) { std::cout << "( zone ( net 0 )"; std::cout << "( polygon ( pts "; // ( xy 148.9585 131.8135 ) for (auto it = boost::begin(bg::exterior_ring(patch.poly)); it != boost::end(bg::exterior_ring(patch.poly)); ++it) { auto x = bg::get<0>(*it); auto y = bg::get<1>(*it); std::cout << "( xy " << x << " " << y << ") "; } std::cout << ")"; std::cout << ")"; std::cout << ")"; std::cout << std::endl; } } void DesignRuleChecker::addTJunctionPatch(const point_double_t &point, const linestring_double_t &bgLs1, const linestring_double_t &bgLs2, const double size, polygon_double_t &patchPoly) { std::cout << "Add T-Junction Patch at: " << std::endl; std::cout << "Seg1: (" << bg::get<0>(bgLs1.front()) << ", " << bg::get<1>(bgLs1.front()) << "), (" << bg::get<0>(bgLs1.back()) << ", " << bg::get<1>(bgLs1.back()) << ")" << std::endl; std::cout << "Seg2: (" << bg::get<0>(bgLs2.front()) << ", " << bg::get<1>(bgLs2.front()) << "), (" << bg::get<0>(bgLs2.back()) << ", " << bg::get<1>(bgLs2.back()) << ")" << std::endl; std::cout << "bg::distance(bgLs1.back(), bgLs2): " << bg::distance(bgLs1.back(), bgLs2) << std::endl; std::cout << "bg::distance(bgLs1.front(), bgLs2): " << bg::distance(bgLs1.front(), bgLs2) << std::endl; std::cout << "bg::distance(bgLs2.front(), bgLs1): " << bg::distance(bgLs2.front(), bgLs1) << std::endl; std::cout << "bg::distance(bgLs2.back(), bgLs1): " << bg::distance(bgLs2.back(), bgLs1) << std::endl; // First Point point_2d vec{bg::get<0>(bgLs2.front()) - bg::get<0>(point), bg::get<1>(bgLs2.front()) - bg::get<1>(point)}; double vecLen = sqrt(vec.x() * vec.x() + vec.y() * vec.y()); point_2d unitVec{vec.x() / vecLen, vec.y() / vecLen}; double length = (size / 2.0); if (length < vecLen) { bg::append(patchPoly.outer(), point_double_t(bg::get<0>(point) + unitVec.x() * length, bg::get<1>(point) + unitVec.y() * length)); } else { bg::append(patchPoly.outer(), bgLs2.front()); } // Seoncd Point vec = point_2d{bg::get<0>(bgLs2.back()) - bg::get<0>(point), bg::get<1>(bgLs2.back()) - bg::get<1>(point)}; vecLen = sqrt(vec.x() * vec.x() + vec.y() * vec.y()); unitVec = point_2d{vec.x() / vecLen, vec.y() / vecLen}; length = (size / 2.0); if (length < vecLen) { bg::append(patchPoly.outer(), point_double_t(bg::get<0>(point) + unitVec.x() * length, bg::get<1>(point) + unitVec.y() * length)); } else { bg::append(patchPoly.outer(), bgLs2.back()); } // Third Point point_double_t point2 = bg::distance(bgLs1.front(), point) > bg::distance(bgLs1.back(), point) ? bgLs1.front() : bgLs1.back(); vec = point_2d{bg::get<0>(point2) - bg::get<0>(point), bg::get<1>(point2) - bg::get<1>(point)}; vecLen = sqrt(vec.x() * vec.x() + vec.y() * vec.y()); unitVec = point_2d{vec.x() / vecLen, vec.y() / vecLen}; length = ((size / 2.0) * sqrt(3)); if (length < vecLen) { bg::append(patchPoly.outer(), point_double_t(bg::get<0>(point) + unitVec.x() * length, bg::get<1>(point) + unitVec.y() * length)); } else { bg::append(patchPoly.outer(), point2); } bg::correct(patchPoly); } bool DesignRuleChecker::areConnectedSegments(linestring_double_t &ls1, linestring_double_t &ls2) { double minDis = numeric_limits<double>::max(); minDis = min(minDis, bg::distance(ls1.front(), ls2.front())); minDis = min(minDis, bg::distance(ls1.front(), ls2.back())); minDis = min(minDis, bg::distance(ls1.back(), ls2.back())); minDis = min(minDis, bg::distance(ls1.back(), ls2.front())); return minDis < this->mEpsilon; } bool DesignRuleChecker::isSegmentTouchAPoint(linestring_double_t &ls, point_double_t &point, double wireWidth) { double minDis = numeric_limits<double>::max(); minDis = min(minDis, bg::distance(point, ls.front())); minDis = min(minDis, bg::distance(point, ls.back())); return minDis < (wireWidth / 2.0); } bool DesignRuleChecker::isIntersectionPointOnTheBoxCorner(point_double_t &point, polygon_double_t &poly, double wireWidth, double tol) { //See if minimum distance to the corner is within half wire width double minDis = numeric_limits<double>::max(); for (auto it = boost::begin(bg::exterior_ring(poly)); it != boost::end(bg::exterior_ring(poly)); ++it) { minDis = min(minDis, bg::distance(point, *it)); } return minDis < ((wireWidth / 2.0) * GlobalParam::gSqrt2 * (1 + tol)); // return minDis < (wireWidth / 2.0) * GlobalParam::gSqrt2; } bool DesignRuleChecker::isOrthogonalSegment(Point_2D<long long> &pt1, Point_2D<long long> &pt2) { if ((pt1.x() == pt2.x() && pt1.y() != pt2.y()) || (pt1.x() != pt2.x() && pt2.y() == pt1.y())) { return true; } return false; } bool DesignRuleChecker::isOrthogonalSegment(points_2d &points) { Point_2D<long long> pt1{(long long)round(points[0].x() * mInputPrecision), (long long)round(points[0].y() * mInputPrecision)}; Point_2D<long long> pt2{(long long)round(points[1].x() * mInputPrecision), (long long)round(points[1].y() * mInputPrecision)}; return isOrthogonalSegment(pt1, pt2); } bool DesignRuleChecker::isDiagonalSegment(Point_2D<long long> &pt1, Point_2D<long long> &pt2) { if (pt1.x() != pt2.x() && pt1.y() != pt2.y() && abs(pt1.x() - pt2.x()) == abs(pt1.y() - pt2.y())) { return true; } return false; } bool DesignRuleChecker::isDiagonalSegment(points_2d &points) { Point_2D<long long> pt1{(long long)round(points[0].x() * mInputPrecision), (long long)round(points[0].y() * mInputPrecision)}; Point_2D<long long> pt2{(long long)round(points[1].x() * mInputPrecision), (long long)round(points[1].y() * mInputPrecision)}; return isDiagonalSegment(pt1, pt2); } bool DesignRuleChecker::isPadstackAndSegmentHaveSameLayer(instance &inst, padstack &pad, Segment &seg) { auto pinLayers = mDb.getPinLayer(inst.getId(), pad.getId()); for (const auto layerId : pinLayers) { if (layerId == mDb.getLayerId(seg.getLayer())) { return true; } } return false; }
51.374194
188
0.538867
k2973363
ee02f664246c6cfa29fe97715ec872f61385bd8c
380
cpp
C++
tram.cpp
piyushmishra12/codeforces-practice
4ce977a41aa0ac919a08c0b47d95bb7b3ff9468f
[ "MIT" ]
null
null
null
tram.cpp
piyushmishra12/codeforces-practice
4ce977a41aa0ac919a08c0b47d95bb7b3ff9468f
[ "MIT" ]
null
null
null
tram.cpp
piyushmishra12/codeforces-practice
4ce977a41aa0ac919a08c0b47d95bb7b3ff9468f
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> using namespace std; int main() { int n, i; cin>> n; int enter[n], exit[n], net_enter[n]; for(i = 0; i < n; i++) { cin>> exit[i]; cin>> enter[i]; } net_enter[0] = enter[0]; for(i = 1; i < n; i++) { net_enter[i] = net_enter[i - 1] - exit[i] + enter[i]; } sort(net_enter, net_enter + n); cout<< net_enter[n - 1]; return 0; }
17.272727
55
0.563158
piyushmishra12
ee03432db8a1164f29848f8c19220c780aa2ec10
694
hpp
C++
src/option.hpp
vcoutasso/AmiaMond
958a5a935ffd8c702147f1a53dd964dccb566a12
[ "MIT" ]
3
2020-05-13T21:44:25.000Z
2021-09-23T20:21:52.000Z
src/option.hpp
vcoutasso/AmiaMond
958a5a935ffd8c702147f1a53dd964dccb566a12
[ "MIT" ]
1
2019-06-18T02:08:15.000Z
2019-07-01T18:29:15.000Z
src/option.hpp
vcoutasso/AmiaMond
958a5a935ffd8c702147f1a53dd964dccb566a12
[ "MIT" ]
1
2020-06-23T17:59:24.000Z
2020-06-23T17:59:24.000Z
#ifndef _OPTION_HPP #define _OPTION_HPP #define FPS 60.0 #define BUTTON_COLOR sf::Color::White #define HOVER_COLOR sf::Color(150, 150, 150) #define SELECTED_COLOR sf::Color::Black #include <SFML/Graphics.hpp> #include <string> class Option { //Funcionalidade dos Botões private: bool hovering; bool selected; public: Option(float px, float py, unsigned int s, std::string t, std::string pathToFont); sf::Font font; sf::Text text; void setHovering(bool b); bool getHovering() const; bool isHovering(int x, int y) const; void setSelected(bool b); bool getSelected() const; void setFont(std::string pathToFile); sf::RectangleShape printRect() const; }; #endif
19.277778
84
0.720461
vcoutasso
ee04dff316f10678ec524f7a5e6b325524636e41
72,460
cpp
C++
vegastrike/src/vsfilesystem.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/vsfilesystem.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/vsfilesystem.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#include <stdio.h> #include <assert.h> #include <stdarg.h> #if defined (_WIN32) && !defined (__CYGWIN__) #include <direct.h> #include <config.h> #include <string.h> #ifndef NOMINMAX #define NOMINMAX #endif //tells VCC not to generate min/max macros #include <windows.h> #include <stdlib.h> struct dirent { char d_name[1]; }; #else #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <dirent.h> #endif #include <sys/stat.h> #include "config.h" #include "configxml.h" #include "vsfilesystem.h" #include "vs_globals.h" #include "vegastrike.h" #include "common/common.h" #include "galaxy_gen.h" #include "pk3.h" #include "gnuhash.h" using VSFileSystem::VSVolumeType; using VSFileSystem::VSFSNone; using std::cout; using std::cerr; using std::endl; using std::string; int VSFS_DEBUG() { if (vs_config) { static int vs_debug = XMLSupport::parse_int( vs_config->getVariable( "general", "debug_fs", "0" ) ); return vs_debug; } return 0; } char *CONFIGFILE; char pwd[65536]; VSVolumeType isin_bigvolumes = VSFSNone; string curmodpath = ""; ObjSerial serial_seed = 0; //Server/client serials won't intersect. std::map< ObjSerial, bool >usedSerials; void usedSerial( ObjSerial ser, bool used ) { usedSerials[ser] = used; } ObjSerial getUniqueSerial() { int offset = (SERVER ? 2 : 1); size_t maxserial=(1<<(sizeof(ObjSerial)*8)); if (usedSerials.size()>=maxserial/3) { static bool firstBadness=true; if (firstBadness) { fprintf(stderr,"Error recycling used serial since serial map is completely full at size %d\n",(int)usedSerials.size()); firstBadness=false; } return ((rand()%(maxserial/3-1))+1)*3;//OFFSET..set to emergency zero } std::map< ObjSerial, bool >::const_iterator iter; ObjSerial ret; do { serial_seed = (serial_seed+3)%MAXSERIAL; ret = serial_seed+offset; } while ( ( iter = usedSerials.find( ret ) ) != usedSerials.end() && (*iter).second ); usedSerial( ret, true ); return ret; } extern string GetUnitDir( string filename ); string selectcurrentdir; #if defined (__APPLE__) int selectdirs( struct dirent *entry ) #else int selectdirs( const struct dirent * entry ) #endif { if (string( entry->d_name ) == "." && string( entry->d_name ) == "..") return 0; //Have to check if we have the full path or just relative (which would be a problem) std::string tmp = selectcurrentdir+'/'+entry->d_name; //cerr<<"Read directory entry : "<< tmp <<endl; struct stat s; if (stat( tmp.c_str(), &s ) < 0) return 0; if ( (s.st_mode&S_IFDIR) ) return 1; return 0; } #if defined (__FreeBSD__) || defined (__APPLE__) int selectpk3s( struct dirent *entry ) #else int selectpk3s( const struct dirent * entry ) #endif { //If this is a regular file and we have ".pk3" in it if ( ( string( entry->d_name ).find( ".pk3" ) ) != std::string::npos && ( string( entry->d_name ).find( "data" ) ) == std::string::npos ) return 1; return 0; } #if defined (__FreeBSD__) || defined (__APPLE__) int selectbigpk3s( struct dirent *entry ) #else int selectbigpk3s( const struct dirent * entry ) #endif { //If this is a regular file and we have ".pk3" in it if ( ( string( entry->d_name ).find( "data.pk3" ) ) != std::string::npos ) return 1; return 0; } namespace VSFileSystem { std::string vegastrike_cwd; void ChangeToProgramDirectory( char *argv0 ) { { char pwd[8192]; pwd[0] = '\0'; if (NULL != getcwd( pwd, 8191 )) { pwd[8191] = '\0'; vegastrike_cwd = pwd; } else { VSFileSystem::vs_fprintf( stderr, "Cannot change to program directory: path too long"); } } int ret = -1; /* Should it use argv[0] directly? */ char *program = argv0; #ifndef _WIN32 char buf[65536]; { char linkname[128]; /* /proc/<pid>/exe */ linkname[0] = '\0'; pid_t pid; /* Get our PID and build the name of the link in /proc */ pid = getpid(); sprintf( linkname, "/proc/%d/exe", pid ); ret = readlink( linkname, buf, 65535 ); if (ret <= 0) { sprintf( linkname, "/proc/%d/file", pid ); ret = readlink( linkname, buf, 65535 ); } if (ret <= 0) ret = readlink( program, buf, 65535 ); if (ret > 0) { buf[ret] = '\0'; /* Ensure proper NUL termination */ program = buf; } } #endif char *parentdir; int pathlen = strlen( program ); parentdir = new char[pathlen+1]; char *c; strncpy( parentdir, program, pathlen+1 ); c = (char*) parentdir; while (*c != '\0') /* go to end */ c++; while ( (*c != '/') && (*c != '\\') && c > parentdir ) /* back up to parent */ c--; *c = '\0'; /* cut off last part (binary name) */ if (strlen( parentdir ) > 0) { if (chdir( parentdir )) /* chdir to the binary app's parent */ VSFileSystem::vs_fprintf( stderr, "Cannot change to program directory."); } delete[] parentdir; } VSError CachedFileLookup( FileLookupCache &cache, const string &file, VSFileType type ) { string hashName = GetHashName( file ); FileLookupCache::iterator it = cache.find( hashName ); if ( it != cache.end() ) return it->second; else return cache[hashName] = LookForFile( file, type ); } void DisplayType( VSFileSystem::VSFileType type ) { DisplayType( type, std::cerr ); } #define CASE( a ) \ case a: \ ostr<<#a; break; void DisplayType( VSFileSystem::VSFileType type, std::ostream &ostr ) { switch (type) { CASE( VSFileSystem::UniverseFile ) CASE( VSFileSystem::SystemFile ) CASE( VSFileSystem::CockpitFile ) CASE( VSFileSystem::UnitFile ) CASE( VSFileSystem::PythonFile ) CASE( VSFileSystem::TextureFile ) CASE( VSFileSystem::SoundFile ) CASE( VSFileSystem::MeshFile ) CASE( VSFileSystem::CommFile ) CASE( VSFileSystem::AiFile ) CASE( VSFileSystem::SaveFile ) CASE( VSFileSystem::AnimFile ) CASE( VSFileSystem::VideoFile ) CASE( VSFileSystem::VSSpriteFile ) CASE( VSFileSystem::MissionFile ) CASE( VSFileSystem::MusicFile ) CASE( VSFileSystem::AccountFile ) CASE( VSFileSystem::ZoneBuffer ) CASE( VSFileSystem::UnknownFile ) default: ostr<<"VSFileSystem::<undefined VSFileType>"; break; } } #undef CASE int GetReadBytes( char *fmt, va_list ap ) { int ret = 0; cerr<<"STARTING ARGLIST"<<endl; while (*fmt) { switch (*fmt++) { case 'd': break; case 'f': break; case 's': break; case 'g': break; case 'n': //Number of bytes ret = va_arg( ap, int ); cerr<<"\tFound 'n' : "<<ret<<endl; break; default: cerr<<"\tOther arg"<<endl; } } cerr<<"ENDING ARGLIST"<<endl; return ret; } /* *********************************************************************************************** **** VSFileSystem global variables *** *********************************************************************************************** */ bool use_volumes; string volume_format; enum VSVolumeFormat q_volume_format; vector< vector< string > >SubDirectories; //Subdirectories where we should look for VSFileTypes files vector< string > Directories; //Directories where we should look for VSFileTypes files vector< string > Rootdir; //Root directories where we should look for VSFileTypes files string sharedtextures; string sharedunits; string sharedsounds; string sharedmeshes; string sharedsectors; string sharedcockpits; string shareduniverse; string aidir; string sharedanims; string sharedvideos; string sharedsprites; string savedunitpath; string modname; string moddir; string datadir; string homedir; string config_file; string weapon_list; string universe_name; string HOMESUBDIR( ".vegastrike" ); vector< string >current_path; vector< string >current_directory; vector< string >current_subdirectory; vector< VSFileType > current_type; //vs_path only stuff vector< std::string >savedpwd; vector< std::string >curdir; //current dir starting from datadir vector< std::vector< std::string > >savedcurdir; //current dir starting from datadir vector< int >UseVolumes; string failed; //Map of the currently opened PK3 volume/resource files vsUMap< string, CPK3* >pk3_opened_files; /* *********************************************************************************************** **** vs_path functions *** *********************************************************************************************** */ std::string GetHashName( const std::string &name ) { std::string result( "" ); result = current_path.back()+current_directory.back()+current_subdirectory.back()+name; return result; } std::string GetHashName( const std::string &name, const Vector &scale, int faction ) { std::string result( "" ); result = current_path.back()+current_directory.back()+current_subdirectory.back()+name; result += XMLSupport::VectorToString( scale )+"|"+XMLSupport::tostring( faction ); return result; } std::string GetSharedMeshHashName( const std::string &name, const Vector &scale, int faction ) { return string( "#" )+XMLSupport::VectorToString( scale )+string( "#" )+name+string( "#" )+XMLSupport::tostring( faction ); } std::string GetSharedTextureHashName( const std::string &name ) { return string( "#stex#" )+name; } std::string GetSharedSoundHashName( const std::string &name ) { return string( "#ssnd#" )+name; } std::string MakeSharedPathReturnHome( const std::string &newpath ) { CreateDirectoryHome( newpath ); return newpath+string( "/" ); } std::string MakeSharedPath( const std::string &s ) { VSFileSystem::vs_fprintf( stderr, "MakingSharedPath %s", s.c_str() ); return MakeSharedPathReturnHome( s )+s; } std::string MakeSharedStarSysPath( const std::string &s ) { string syspath = sharedsectors+"/"+getStarSystemSector( s ); return MakeSharedPathReturnHome( syspath )+s; } std::string GetCorrectStarSysPath( const std::string &name, bool &autogenerated ) { autogenerated = false; if (name.length() == 0) return string( "" ); string newname( name ); if (Network != NULL) { std::string::size_type dot = name.find( "." ); if (dot != std::string::npos) newname = name.substr( 0, dot ); newname += ".net.system"; } VSFile f; VSError err = f.OpenReadOnly( newname, SystemFile ); autogenerated = false; if (err <= Ok) autogenerated = (err == Shared); return newname; } /* *********************************************************************************************** **** VSFileSystem wrappers to stdio function calls *** *********************************************************************************************** */ FILE * vs_open( const char *filename, const char *mode ) { if (VSFS_DEBUG() > 1) cerr<<"-= VS_OPEN in mode "<<mode<<" =- "; FILE *fp; string fullpath = homedir+"/"+string( filename ); if ( !use_volumes && (string( mode ) == "rb" || string( mode ) == "r") ) { string output( "" ); fp = fopen( fullpath.c_str(), mode ); if (!fp) { fullpath = string( filename ); output += fullpath+"... NOT FOUND\n\tTry loading : "+fullpath; fp = fopen( fullpath.c_str(), mode ); } if (!fp) { fullpath = datadir+"/"+string( filename ); output += "... NOT FOUND\n\tTry loading : "+fullpath; fp = fopen( fullpath.c_str(), mode ); } if ( VSFS_DEBUG() ) { if (fp) { if (VSFS_DEBUG() > 2) cerr<<fullpath<<" SUCCESS !!!"<<endl; } else { cerr<<output<<" NOT FOUND !!!"<<endl; } } } else { fp = fopen( fullpath.c_str(), mode ); if (fp) { if (VSFS_DEBUG() > 2) cerr<<fullpath<<" opened for writing SUCCESS !!!"<<endl; } else if ( VSFS_DEBUG() ) { cerr<<fullpath<<" FAILED !!!"<<endl; } } return fp; return NULL; } size_t vs_read( void *ptr, size_t size, size_t nmemb, FILE *fp ) { if (!use_volumes) { return fread( ptr, size, nmemb, fp ); } else {} return 0; } size_t vs_write( const void *ptr, size_t size, size_t nmemb, FILE *fp ) { if (!use_volumes) { return fwrite( ptr, size, nmemb, fp ); } else {} return 0; } void vs_close( FILE *fp ) { if (!use_volumes) { fclose( fp ); } else {} } int vs_fprintf( FILE *fp, const char *format, ... ) { if (!use_volumes) { va_list ap; va_start( ap, format ); return vfprintf( fp, format, ap ); } else {} return 0; } void vs_dprintf( char level, const char *format, ... ) { if (!use_volumes && level <= g_game.vsdebug) { va_list ap; va_start( ap, format ); vfprintf( stderr, format, ap ); } } #if 0 int vs_fscanf( FILE *fp, const char *format, ... ) { if (!use_volumes) { va_list arglist; va_start( arglist, format ); //return _input(fp,(unsigned char*)format,arglist); return vfscanf( fp, format, arglist ); } else {} return 0; } #endif int vs_fseek( FILE *fp, long offset, int whence ) { return fseek( fp, offset, whence ); } long vs_ftell( FILE *fp ) { return ftell( fp ); } void vs_rewind( FILE *fp ) { rewind( fp ); } bool vs_feof( FILE *fp ) { return feof( fp ); } long vs_getsize( FILE *fp ) { if (!use_volumes) { struct stat st; if (fstat( fileno( fp ), &st ) == 0) return st.st_size; return -1; } return -1; } /* *********************************************************************************************** **** VSFileSystem functions *** *********************************************************************************************** */ void InitHomeDirectory() { //Setup home directory char *chome_path = NULL; #ifndef _WIN32 struct passwd *pwent; pwent = getpwuid( getuid() ); chome_path = pwent->pw_dir; if ( !DirectoryExists( chome_path ) ) { cerr<<"!!! ERROR : home directory not found"<<endl; VSExit( 1 ); } string user_home_path( chome_path ); homedir = user_home_path+"/"+HOMESUBDIR; #else homedir = datadir+"/"+HOMESUBDIR; #endif cerr<<"USING HOMEDIR : "<<homedir<<" As the home directory "<<endl; CreateDirectoryAbs( homedir ); } void InitDataDirectory() { vector< string >data_paths; /* commandline-specified paths come first */ if (!datadir.empty()) data_paths.push_back( datadir ); /* DATA_DIR should no longer be necessary--it will either use the path * to the binary, or the current directory. */ #ifdef DATA_DIR data_paths.push_back( DATA_DIR ); #endif if ( !vegastrike_cwd.empty() ) { data_paths.push_back( vegastrike_cwd ); data_paths.push_back( vegastrike_cwd+"/.." ); data_paths.push_back( vegastrike_cwd+"/../data4.x" ); data_paths.push_back( vegastrike_cwd+"/../../data4.x" ); data_paths.push_back( vegastrike_cwd+"/../../data" ); data_paths.push_back( vegastrike_cwd+"/data4.x" ); data_paths.push_back( vegastrike_cwd+"/data" ); data_paths.push_back( vegastrike_cwd+"/../data" ); data_paths.push_back( vegastrike_cwd+"/../Resources" ); } data_paths.push_back( "." ); data_paths.push_back( ".." ); //data_paths.push_back( "../data4.x" ); DELETE 4.x no longer used since .5 release obsolete, removal required. //data_paths.push_back( "../../data4.x" ); data_paths.push_back( "../data" ); data_paths.push_back( "../../data" ); data_paths.push_back( "../Resources" ); data_paths.push_back( "../Resources/data" ); //data_paths.push_back( "../Resources/data4.x" ); //Win32 data should be "." char tmppath[16384]; for (vector< string >::iterator vsit = data_paths.begin(); vsit != data_paths.end(); vsit++) //Test if the dir exist and contains config_file if (FileExists( (*vsit), config_file ) >= 0) { cerr<<"Found data in "<<(*vsit)<<endl; if (NULL != getcwd( tmppath, 16384 )) { if ( (*vsit).substr( 0, 1 ) == "." ) datadir = string( tmppath )+"/"+(*vsit); else datadir = (*vsit); } else { VSFileSystem::vs_fprintf( stderr, "Cannot get current path: path too long"); } if (chdir( datadir.c_str() ) < 0) { cerr<<"Error changing to datadir"<<endl; exit( 1 ); } if (NULL != getcwd( tmppath, 16384 )) { datadir = string( tmppath ); } else { VSFileSystem::vs_fprintf( stderr, "Cannot get current path: path too long"); } cerr<<"Using "<<datadir<<" as data directory"<<endl; break; } data_paths.clear(); string versionloc = datadir+"/Version.txt"; FILE *version = fopen( versionloc.c_str(), "r" ); if (!version) { versionloc = datadir+"Version.txt"; version = fopen( versionloc.c_str(), "r" ); } if (!version) version = fopen( "Version.txt", "r" ); if (version) { string hsd = ""; int c; while ( ( c = fgetc( version ) ) != EOF ) { if ( isspace( c ) ) break; hsd += (char) c; } fclose( version ); if ( hsd.length() ) { HOMESUBDIR = hsd; printf( "Using %s as the home directory\n", hsd.c_str() ); } } //Get the mods path moddir = datadir+"/"+string( "mods" ); cout<<"Found MODDIR = "<<moddir<<endl; } //Config file has been loaded from data dir but now we look at the specified moddir in order //to see if we should use a mod config file void LoadConfig( string subdir ) { bool found = false; bool foundweapons = false; //First check if we have a config file in homedir+"/"+subdir or in datadir+"/"+subdir weapon_list = "weapon_list.xml"; if (subdir != "") { modname = subdir; if ( DirectoryExists( homedir+"/mods/"+subdir ) ) { if (FileExists( homedir+"/mods/"+subdir, config_file ) >= 0) { cout<<"CONFIGFILE - Found a config file in home mod directory, using : " <<(homedir+"/mods/"+subdir+"/"+config_file)<<endl; if (FileExists( homedir+"/mods/"+subdir, "weapon_list.xml" ) >= 0) { weapon_list = homedir+"/mods/"+subdir+"/weapon_list.xml"; foundweapons = true; } config_file = homedir+"/mods/"+subdir+"/"+config_file; found = true; } } if (!found) cout<<"WARNING : coudn't find a mod named '"<<subdir<<"' in homedir/mods"<<endl; if ( DirectoryExists( moddir+"/"+subdir ) ) { if (FileExists( moddir+"/"+subdir, config_file ) >= 0) { if (!found) cout<<"CONFIGFILE - Found a config file in mods directory, using : " <<(moddir+"/"+subdir+"/"+config_file)<<endl; if ( (!foundweapons) && FileExists( moddir+"/"+subdir, "weapon_list.xml" ) >= 0 ) { weapon_list = moddir+"/"+subdir+"/weapon_list.xml"; foundweapons = true; } if (!found) config_file = moddir+"/"+subdir+"/"+config_file; found = true; } } else { cout<<"ERROR : coudn't find a mod named '"<<subdir<<"' in datadir/mods"<<endl; } //} } if (!found) { //Next check if we have a config file in homedir if we haven't found one for mod if (FileExists( homedir, config_file ) >= 0) { cerr<<"CONFIGFILE - Found a config file in home directory, using : "<<(homedir+"/"+config_file)<<endl; config_file = homedir+"/"+config_file; } else { cerr<<"CONFIGFILE - No config found in home : "<<(homedir+"/"+config_file)<<endl; if (FileExists( datadir, config_file ) >= 0) { cerr<<"CONFIGFILE - No home config file found, using datadir config file : "<<(datadir+"/"+config_file)<<endl; //We didn't find a config file in home_path so we load the data_path one } else { cerr<<"CONFIGFILE - No config found in data dir : "<<(datadir+"/"+config_file)<<endl; cerr<<"CONFIG FILE NOT FOUND !!!"<<endl; VSExit( 1 ); } } } else if (subdir != "") { printf( "Using Mod Directory %s\n", moddir.c_str() ); CreateDirectoryHome( "mods" ); CreateDirectoryHome( "mods/"+subdir ); homedir = homedir+"/mods/"+subdir; } //Delete the default config in order to reallocate it with the right one (if it is a mod) if (vs_config) { fprintf( stderr, "reallocating vs_config \n" ); delete vs_config; } vs_config = createVegaConfig( config_file.c_str() ); //Now check if there is a data directory specified in it //NOTE : THIS IS NOT A GOOD IDEA TO HAVE A DATADIR SPECIFIED IN THE CONFIG FILE static string data_path( vs_config->getVariable( "data", "datadir", "" ) ); if (data_path != "") { //We found a path to data in config file cout<<"DATADIR - Found a datadir in config, using : "<<data_path<<endl; datadir = data_path; } else { cout<<"DATADIR - No datadir specified in config file, using ; "<<datadir<<endl; } } void InitMods() { string curpath; struct dirent **dirlist; //new config program should insert hqtextures variable //with value "hqtextures" in data section. string hq = vs_config->getVariable( "data", "hqtextures", "" ); if (hq != "") { //HQ Texture dir sits alongside data dir. selectcurrentdir = datadir+"/.."; int ret = scandir( selectcurrentdir.c_str(), &dirlist, selectdirs, 0 ); if (ret >= 0) { while (ret--) { string dname( dirlist[ret]->d_name ); if (dname == hq) { curpath = selectcurrentdir+"/"+dname; cout<<"\n\nAdding HQ Textures Pack\n\n"; Rootdir.push_back( curpath ); } } } free( dirlist ); } selectcurrentdir = moddir; int ret = scandir( selectcurrentdir.c_str(), &dirlist, selectdirs, 0 ); if (ret < 0) { return; } else { while (ret--) { string dname( dirlist[ret]->d_name ); if (dname == modname) { curpath = moddir+"/"+dname; cout<<"Adding mod path : "<<curpath<<endl; Rootdir.push_back( curpath ); } } } free( dirlist ); //Scan for mods with standard data subtree curmodpath = homedir+"/mods/"; selectcurrentdir = curmodpath; ret = scandir( selectcurrentdir.c_str(), &dirlist, selectdirs, 0 ); if (ret < 0) { return; } else { while (ret--) { string dname( dirlist[ret]->d_name ); if (dname == modname) { curpath = curmodpath+dname; cout<<"Adding mod path : "<<curpath<<endl; Rootdir.push_back( curpath ); } } } free( dirlist ); } void InitPaths( string conf, string subdir ) { config_file = conf; current_path.push_back( "" ); current_directory.push_back( "" ); current_subdirectory.push_back( "" ); current_type.push_back( UnknownFile ); int i; for (i = 0; i <= UnknownFile; i++) UseVolumes.push_back( 0 ); /************************** Data and home directory settings *************************/ InitDataDirectory(); //Need to be first for win32 InitHomeDirectory(); LoadConfig( subdir ); //Paths relative to datadir or homedir (both should have the same structure) //Units are in sharedunits/unitname/, sharedunits/subunits/unitname/ or sharedunits/weapons/unitname/ or in sharedunits/faction/unitname/ //Meshes are in sharedmeshes/ or in current unit that is being loaded //Textures are in sharedtextures/ or in current unit dir that is being loaded or in the current animation dir that is being loaded or in the current sprite dir that is being loeded //Sounds are in sharedsounds/ //Universes are in universe/ //Systems are in "sectors"/ config variable //Cockpits are in cockpits/ (also a config var) //Animations are in animations/ //VSSprite are in sprites/ or in ./ (when full subpath is provided) or in the current cockpit dir that is being loaded //First allocate an empty directory list for each file type for (i = 0; i < UnknownFile; i++) { vector< string >vec; Directories.push_back( "" ); SubDirectories.push_back( vec ); } sharedsectors = vs_config->getVariable( "data", "sectors", "sectors" ); sharedcockpits = vs_config->getVariable( "data", "cockpits", "cockpits" ); shareduniverse = vs_config->getVariable( "data", "universe_path", "universe" ); sharedanims = vs_config->getVariable( "data", "animations", "animations" ); sharedvideos = vs_config->getVariable( "data", "movies", "movies" ); sharedsprites = vs_config->getVariable( "data", "sprites", "sprites" ); savedunitpath = vs_config->getVariable( "data", "serialized_xml", "serialized_xml" ); sharedtextures = vs_config->getVariable( "data", "sharedtextures", "textures" ); sharedsounds = vs_config->getVariable( "data", "sharedsounds", "sounds" ); sharedmeshes = vs_config->getVariable( "data", "sharedmeshes", "meshes" ); sharedunits = vs_config->getVariable( "data", "sharedunits", "units" ); aidir = vs_config->getVariable( "data", "ai_directory", "ai" ); universe_name = vs_config->getVariable( "general", "galaxy", "milky_way.xml" ); //Setup the directory lists we know about - note these are relative paths to datadir or homedir //----- THE Directories vector contains the resource/volume files name without extension or the main directory to files Directories[UnitFile] = sharedunits; //Have to put it in first place otherwise VS will find default unit file SubDirectories[UnitFile].push_back( "subunits" ); SubDirectories[UnitFile].push_back( "weapons" ); SubDirectories[UnitFile].push_back( "" ); SubDirectories[UnitFile].push_back( "factions/planets" ); SubDirectories[UnitFile].push_back( "factions/upgrades" ); SubDirectories[UnitFile].push_back( "factions/neutral" ); SubDirectories[UnitFile].push_back( "factions/aera" ); SubDirectories[UnitFile].push_back( "factions/confed" ); SubDirectories[UnitFile].push_back( "factions/pirates" ); SubDirectories[UnitFile].push_back( "factions/rlaan" ); Directories[UnitSaveFile] = savedunitpath; Directories[MeshFile] = sharedmeshes; SubDirectories[MeshFile].push_back( "mounts" ); SubDirectories[MeshFile].push_back( "nav/default" ); Directories[TextureFile] = sharedtextures; SubDirectories[TextureFile].push_back( "mounts" ); SubDirectories[TextureFile].push_back( "nav/default" ); //We will also look in subdirectories with universe name Directories[SystemFile] = sharedsectors; SubDirectories[SystemFile].push_back( universe_name ); Directories[UniverseFile] = shareduniverse; Directories[SoundFile] = sharedsounds; Directories[CockpitFile] = sharedcockpits; Directories[AnimFile] = sharedanims; Directories[VideoFile] = sharedvideos; Directories[VSSpriteFile] = sharedsprites; Directories[AiFile] = aidir; SubDirectories[AiFile].push_back( "events" ); SubDirectories[AiFile].push_back( "script" ); Directories[MissionFile] = "mission"; Directories[CommFile] = "communications"; Directories[SaveFile] = "save"; Directories[MusicFile] = "music"; Directories[PythonFile] = "bases"; Directories[AccountFile] = "accounts"; simulation_atom_var = atof( vs_config->getVariable( "general", "simulation_atom", "0.1" ).c_str() ); cout<<"SIMULATION_ATOM: "<<SIMULATION_ATOM<<endl; /************************* Home directory subdirectories creation ************************/ CreateDirectoryHome( savedunitpath ); CreateDirectoryHome( sharedtextures ); CreateDirectoryHome( sharedtextures+"/backgrounds" ); CreateDirectoryHome( sharedsectors ); CreateDirectoryHome( sharedsectors+"/"+universe_name ); CreateDirectoryHome( sharedsounds ); CreateDirectoryHome( "save" ); //We will be able to automatically add mods files (set of resources or even directory structure similar to the data tree) //by just adding a subdirectory named with the mod name in the subdirectory "mods"... //I just have to implement that and then add all mods/ subdirs in Rootdir vector Rootdir.push_back( homedir ); InitMods(); Rootdir.push_back( datadir ); //NOTE : UniverseFiles cannot use volumes since some are needed by python //Also : Have to try with systems, not sure it would work well //Setup the use of volumes for certain VSFileType volume_format = vs_config->getVariable( "data", "volume_format", "pk3" ); if (volume_format == "vsr") q_volume_format = vfmtVSR; else if (volume_format == "pk3") q_volume_format = vfmtPK3; else q_volume_format = vfmtUNK; if (FileExists( datadir, "/data."+volume_format ) >= 0) { //Every kind of file will use the big volume except Unknown files and python files that needs to remain standard files for (i = 0; i < UnknownFile; i++) UseVolumes[i] = 2; UseVolumes[PythonFile] = 0; UseVolumes[AccountFile] = 0; } else { if (FileExists( datadir, "/"+sharedunits+"."+volume_format ) >= 0) { UseVolumes[UnitFile] = 1; cout<<"Using volume file "<<(datadir+"/"+sharedunits)<<".pk3"<<endl; } if (FileExists( datadir, "/"+sharedmeshes+"."+volume_format ) >= 0) { UseVolumes[MeshFile] = 1; cout<<"Using volume file "<<(datadir+"/"+sharedmeshes)<<".pk3"<<endl; } if (FileExists( datadir, "/"+sharedtextures+"."+volume_format ) >= 0) { UseVolumes[TextureFile] = 1; cout<<"Using volume file "<<(datadir+"/"+sharedtextures)<<".pk3"<<endl; } if (FileExists( datadir, "/"+sharedsounds+"."+volume_format ) >= 0) { UseVolumes[SoundFile] = 1; cout<<"Using volume file "<<(datadir+"/"+sharedsounds)<<".pk3"<<endl; } if (FileExists( datadir, "/"+sharedcockpits+"."+volume_format ) >= 0) { UseVolumes[CockpitFile] = 1; cout<<"Using volume file "<<(datadir+"/"+sharedcockpits)<<".pk3"<<endl; } if (FileExists( datadir, "/"+sharedsprites+"."+volume_format ) >= 0) { UseVolumes[VSSpriteFile] = 1; cout<<"Using volume file "<<(datadir+"/"+sharedsprites)<<".pk3"<<endl; } if (FileExists( datadir, "/animations."+volume_format ) >= 0) { UseVolumes[AnimFile] = 1; cout<<"Using volume file "<<(datadir+"/animations")<<".pk3"<<endl; } if (FileExists( datadir, "/movies."+volume_format ) >= 0) { UseVolumes[VideoFile] = 1; cout<<"Using volume file "<<(datadir+"/movies")<<".pk3"<<endl; } if (FileExists( datadir, "/communications."+volume_format ) >= 0) { UseVolumes[CommFile] = 1; cout<<"Using volume file "<<(datadir+"/communications")<<".pk3"<<endl; } if (FileExists( datadir, "/mission."+volume_format ) >= 0) { UseVolumes[MissionFile] = 1; cout<<"Using volume file "<<(datadir+"/mission")<<".pk3"<<endl; } if (FileExists( datadir, "/ai."+volume_format ) >= 0) { UseVolumes[AiFile] = 1; cout<<"Using volume file "<<(datadir+"/ai")<<".pk3"<<endl; } UseVolumes[ZoneBuffer] = 0; } } void CreateDirectoryAbs( const char *filename ) { int err; if ( !DirectoryExists( filename ) ) { err = mkdir( filename #if !defined (_WIN32) || defined (__CYGWIN__) , 0xFFFFFFFF #endif ); if (err < 0 && errno != EEXIST) { cerr<<"Errno="<<errno<<" - FAILED TO CREATE : "<<filename<<endl; GetError( "CreateDirectory" ); VSExit( 1 ); } } } void CreateDirectoryAbs( const string &filename ) { CreateDirectoryAbs( filename.c_str() ); } void CreateDirectoryHome( const char *filename ) { CreateDirectoryAbs( homedir+"/"+string( filename ) ); } void CreateDirectoryHome( const string &filename ) { CreateDirectoryHome( filename.c_str() ); } void CreateDirectoryData( const char *filename ) { CreateDirectoryAbs( datadir+"/"+string( filename ) ); } void CreateDirectoryData( const string &filename ) { CreateDirectoryData( filename.c_str() ); } //Absolute directory -- DO NOT USE FOR TESTS IN VOLUMES !! bool DirectoryExists( const char *filename ) { struct stat s; if (stat( filename, &s ) < 0) return false; if (s.st_mode&S_IFDIR) return true; return false; } bool DirectoryExists( const string &filename ) { return DirectoryExists( filename.c_str() ); } //root is the path to the type directory or the type volume //filename is the subdirectory+"/"+filename int FileExists( const string &root, const char *filename, VSFileType type, bool lookinvolume ) { int found = -1; bool volok = false; string fullpath; const char *file; if (filename[0] == '/') file = filename+1; else file = filename; const char *rootsep = (root == "" || root == "/") ? "" : "/"; if (!UseVolumes[type] || !lookinvolume) { if (type == UnknownFile) fullpath = root+rootsep+file; else fullpath = root+rootsep+Directories[type]+"/"+file; struct stat s; if (stat( fullpath.c_str(), &s ) >= 0) { if (s.st_mode&S_IFDIR) { cerr<<" File is a directory ! "; found = -1; } else { isin_bigvolumes = VSFSNone; found = 1; } } //} } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { CPK3 *vol; string filestr; //TRY TO OPEN A DATA.VOLFORMAT FILE IN THE ROOT DIRECTORY PASSED AS AN ARG filestr = Directories[type]+"/"+file; fullpath = root+rootsep+"data."+volume_format; vsUMap< string, CPK3* >::iterator it; it = pk3_opened_files.find( fullpath ); failed += "Looking for file in VOLUME : "+fullpath+"... "; if ( it == pk3_opened_files.end() ) { //File is not opened so we open it and add it in the pk3 file map vol = new CPK3; if ( ( volok = vol->Open( fullpath.c_str() ) ) ) { failed += " VOLUME OPENED\n"; //We add the resource file to the map only if we could have opened it std::pair< std::string, CPK3* >pk3_pair( fullpath, vol ); pk3_opened_files.insert( pk3_pair ); } else { failed += " COULD NOT OPEN VOLUME\n"; } } else { failed += " VOLUME FOUND\n"; vol = it->second; volok = true; } //Try to get the file index in the archive if (volok) { found = vol->FileExists( filestr.c_str() ); if (found >= 0) isin_bigvolumes = VSFSBig; } else { found = -1; } if (found < 0) { //AND THEN A VOLUME FILE BASED ON DIRECTORIES[TYPE] filestr = string( file ); fullpath = root+rootsep+Directories[type]+"."+volume_format; it = pk3_opened_files.find( fullpath ); failed += "Looking for file in VOLUME : "+fullpath+"... "; if ( it == pk3_opened_files.end() ) { //File is not opened so we open it and add it in the pk3 file map vol = new CPK3; if ( ( volok = vol->Open( fullpath.c_str() ) ) ) { failed += " VOLUME OPENED\n"; //We add the resource file to the map only if we could have opened it std::pair< std::string, CPK3* >pk3_pair( fullpath, vol ); pk3_opened_files.insert( pk3_pair ); } else { failed += " COULD NOT OPEN VOLUME\n"; } } else { failed += " VOLUME FOUND\n"; vol = it->second; volok = true; } //Try to get the file index in the archive if (volok) { found = vol->FileExists( filestr.c_str() ); if (found >= 0) isin_bigvolumes = VSFSSplit; } else { found = -1; } } } } if (found < 0) { if (!UseVolumes[type]) failed += "\tTRY LOADING : "+nameof( type )+" "+fullpath+"... NOT FOUND\n"; else if (VSFS_DEBUG() > 1) failed += "\tTRY LOADING in "+nameof( type )+" "+fullpath+" : "+file+"... NOT FOUND\n"; } else { if (!UseVolumes[type]) failed = "\tTRY LOADING : "+nameof( type )+" "+fullpath+"... SUCCESS"; else if (VSFS_DEBUG() > 1) failed = "\tTRY LOADING in "+nameof( type )+" "+fullpath+" : "+file+"... SUCCESS"; else failed.erase(); } return found; } int FileExists( const string &root, const string &filename, VSFileType type, bool lookinvolume ) { return FileExists( root, filename.c_str(), type, lookinvolume ); } int FileExistsData( const char *filename, VSFileType type ) { return FileExists( datadir, filename, type ); } int FileExistsData( const string &filename, VSFileType type ) { return FileExists( datadir, filename, type ); } int FileExistsHome( const char *filename, VSFileType type ) { return FileExists( homedir, filename, type ); } int FileExistsHome( const string &filename, VSFileType type ) { return FileExists( homedir, filename, type ); } VSError GetError( const char *str ) { cerr<<"!!! ERROR/WARNING VSFile : "; if (str) cerr<<"on "<<str<<" : "; if (errno == ENOENT) { cerr<<"File not found"<<endl; return FileNotFound; } else if (errno == EPERM) { cerr<<"Permission denied"<<endl; return LocalPermissionDenied; } else if (errno == EACCES) { cerr<<"Access denied"<<endl; return LocalPermissionDenied; } else { cerr<<"Unspecified error (maybe to document in VSFile ?)"<<endl; return Unspecified; } } VSError LookForFile( const string &file, VSFileType type, VSFileMode mode ) { VSFile vsfile; vsfile.SetFilename( file ); VSError err = LookForFile( vsfile, type, mode ); return err; } VSError LookForFile( VSFile &f, VSFileType type, VSFileMode mode ) { int found = -1, shared = false; string filepath, curpath, dir, extra( "" ), subdir; failed.erase(); VSFileType curtype = type; //First try in the current path switch (type) { case UnitFile: extra = "/"+GetUnitDir( f.GetFilename() ); break; case CockpitFile: //For cockpits we look in subdirectories that have the same name as the cockpit itself extra = "/"+string( f.GetFilename() ); break; case AnimFile: //Animations are always in subdir named like the anim itself extra += "/"+f.GetFilename(); break; case UniverseFile: case SystemFile: case UnitSaveFile: case TextureFile: case SoundFile: case PythonFile: case MeshFile: case CommFile: case AiFile: case SaveFile: case VideoFile: case VSSpriteFile: case MissionFile: case MusicFile: case AccountFile: case ZoneBuffer: case JPEGBuffer: case UnknownFile: break; } //This test lists all the VSFileType that should be looked for in the current directory unsigned int i = 0, j = 0; for (int LC = 0; LC < 2 && found < 0; ( LC += (extra == "" ? 2 : 1) ), extra = "") { if ( current_path.back() != "" && (type == TextureFile || type == MeshFile || type == VSSpriteFile || type == AnimFile || type == VideoFile) ) { for (i = 0; found < 0 && i < Rootdir.size(); i++) { curpath = Rootdir[i]; subdir = current_subdirectory.back(); if (extra != "") subdir += extra; curtype = current_type.back(); found = FileExists( curpath, ( subdir+"/"+f.GetFilename() ).c_str(), curtype ); if (found >= 0) { shared = false; f.SetAltType( curtype ); } else { //Set curtype back to original type if we didn't find the file in the current dir curtype = type; shared = true; } } } //FIRST LOOK IN HOMEDIR FOR A STANDARD FILE, SO WHEN USING VOLUME WE DO NOT LOOK FIRST IN VOLUMES if (found < 0 && UseVolumes[curtype]) { curpath = homedir; subdir = ""; if (extra != "") subdir += extra; found = FileExists( curpath, ( subdir+"/"+f.GetFilename() ).c_str(), type, false ); for (j = 0; found < 0 && j < SubDirectories[curtype].size(); j++) { subdir = SubDirectories[curtype][j]; if (extra != "") subdir += extra; found = FileExists( curpath, ( subdir+"/"+f.GetFilename() ).c_str(), curtype, false ); f.SetVolume( VSFSNone ); } } //THEN LOOK IN ALL THE REGISTERED ROOT DIRS for (i = 0; found < 0 && i < Rootdir.size(); i++) { curpath = Rootdir[i]; subdir = f.GetSubDirectory(); if (extra != "") subdir += extra; found = FileExists( curpath, ( subdir+"/"+f.GetFilename() ).c_str(), curtype ); for (j = 0; found < 0 && j < SubDirectories[curtype].size(); j++) { curpath = Rootdir[i]; subdir = SubDirectories[curtype][j]; if ( f.GetSubDirectory().length() ) { if ( subdir.length() ) subdir += "/"; subdir += f.GetSubDirectory(); } if (extra != "") subdir += extra; found = FileExists( curpath, ( subdir+"/"+f.GetFilename() ).c_str(), curtype ); } } if (curtype == CockpitFile) { for (i = 0; found < 0 && i < Rootdir.size(); i++) { curpath = Rootdir[i]; subdir = ""; found = FileExists( curpath, ( subdir+"/"+f.GetFilename() ).c_str(), type ); for (j = 0; found < 0 && j < SubDirectories[curtype].size(); j++) { curpath = Rootdir[i]; subdir = SubDirectories[curtype][j]; if (extra != "") subdir += extra; found = FileExists( curpath, ( subdir+"/"+f.GetFilename() ).c_str(), curtype ); } } } } if (VSFS_DEBUG() > 1) { if (isin_bigvolumes > VSFSNone) cerr<<failed<<" - INDEX="<<found<<endl<<endl; else cerr<<failed<<endl; } if (found >= 0) { if ( (type == SystemFile && i == 0) || (type == SoundFile /*right now only allow shared ones?!*/) /* Rootdir[i]==homedir*/ ) shared = true; f.SetDirectory( Directories[curtype] ); f.SetSubDirectory( subdir ); f.SetRoot( curpath ); f.SetVolume( isin_bigvolumes ); //If we found a file in a volume we store its index in the concerned archive if (UseVolumes[curtype] && isin_bigvolumes > VSFSNone) f.SetIndex( found ); isin_bigvolumes = VSFSNone; if (shared) return Shared; else return Ok; } return FileNotFound; } /* *********************************************************************************************** **** VSFileSystem::VSFile class member functions *** *********************************************************************************************** */ //IMPORTANT NOTE : IN MOST FILE OPERATION FUNCTIONS WE USE THE "alt_type" MEMBER BECAUSE A FILE WHOSE NATIVE TYPE //SHOULD BE HANDLED IN VOLUMES MIGHT BE FOUND IN THE CURRENT DIRECTORY OF A TYPE THAT IS NOT HANDLED IN //VOLUMES -> SO WE HAVE TO USE THE ALT_TYPE IN MOST OF THE TEST TO USE THE CORRECT FILE OPERATIONS void VSFile::private_init() { fp = NULL; size = 0; pk3_file = NULL; pk3_extracted_file = NULL; offset = 0; valid = false; file_type = alt_type = UnknownFile; file_index = -1; volume_type = VSFSNone; } VSFile::VSFile() { private_init(); } VSFile::VSFile( const char *buffer, long bufsize, VSFileType type, VSFileMode mode ) { private_init(); this->size = bufsize; this->pk3_extracted_file = new char[bufsize+1]; memcpy( this->pk3_extracted_file, buffer, bufsize ); pk3_extracted_file[bufsize] = 0; this->file_type = this->alt_type = ZoneBuffer; this->file_mode = mode; //To say we want to read in volume even if it is not the case then it will read in pk3_extracted_file this->volume_type = VSFSBig; } VSFile::VSFile( const char *filename, VSFileType type, VSFileMode mode ) { private_init(); if (mode == ReadOnly) this->OpenReadOnly( filename, type ); else if (mode == ReadWrite) this->OpenReadWrite( filename, type ); else if (mode == CreateWrite) this->OpenCreateWrite( filename, type ); } VSFile::~VSFile() { if (fp) { fclose( fp ); this->fp = NULL; } if (pk3_extracted_file) delete[] pk3_extracted_file; } void VSFile::checkExtracted() { if (q_volume_format == vfmtPK3) { if (!pk3_extracted_file) { string full_vol_path; if (this->volume_type == VSFSBig) full_vol_path = this->rootname+"/data."+volume_format; else full_vol_path = this->rootname+"/"+Directories[this->alt_type]+"."+volume_format; vsUMap< string, CPK3* >::iterator it; it = pk3_opened_files.find( full_vol_path ); if ( it == pk3_opened_files.end() ) { //File is not opened so we open it and add it in the pk3 file map CPK3 *pk3newfile = new CPK3; if ( !pk3newfile->Open( full_vol_path.c_str() ) ) { cerr<<"!!! ERROR : opening volume : "<<full_vol_path<<endl; VSExit( 1 ); } std::pair< std::string, CPK3* >pk3_pair( full_vol_path, pk3newfile ); pk3_opened_files.insert( pk3_pair ); this->pk3_file = pk3newfile; } else { this->pk3_file = it->second; } int pk3size = 0; if (this->file_index != -1) pk3_extracted_file = (char*) pk3_file->ExtractFile( this->file_index, &pk3size ); else pk3_extracted_file = (char*) pk3_file->ExtractFile( (this->subdirectoryname+"/"+this->filename).c_str(), &pk3size ); this->size = pk3size; cerr<<"EXTRACTING " <<(this->subdirectoryname+"/"+this->filename)<<" WITH INDEX="<<this->file_index<<" SIZE="<<pk3size<<endl; } } } //Open a read only file VSError VSFile::OpenReadOnly( const char *file, VSFileType type ) { string filestr; int found = -1; this->file_type = this->alt_type = type; this->file_mode = ReadOnly; this->filename = string( file ); failed = ""; VSError err = Ok; if ( VSFS_DEBUG() ) cerr<<"Loading a "<<type<<" : "<<file<<endl; if (type < ZoneBuffer || type == UnknownFile) { //It is a "classic file" if (!UseVolumes[type]) { if (type == UnknownFile) { //We look in the current_path or for a full relative path to either homedir or datadir if (current_path.back() != "") { string filestr1 = current_directory.back() +"/"+current_subdirectory.back()+"/"+string( file ); filestr = current_path.back()+"/"+filestr1; if ( ( found = FileExists( current_path.back(), filestr1 ) ) < 0 ) failed += "\t"+filestr+" NOT FOUND !\n"; } if (found < 0) { for (unsigned int ij = 0; ij < Rootdir.size() && found < 0; ij++) { filestr = Rootdir[ij]+"/"+file; found = FileExists( Rootdir[ij], file ); if (found < 0) failed += "\tRootdir : "+filestr+" NOT FOUND !\n"; } //Look for relative (to datadir) or absolute named file if (found < 0) { filestr = file; if ( ( found = FileExists( "", filestr ) ) < 0 ) failed += "\tAbs or rel : "+filestr+" NOT FOUND !\n"; } } if (found < 0) { if ( VSFS_DEBUG() ) cerr<<failed<<endl; this->valid = false; err = FileNotFound; } else { if ( ( this->fp = fopen( filestr.c_str(), "rb" ) ) == NULL ) { cerr<<"!!! SERIOUS ERROR : failed to open Unknown file "<<filestr<<" - this should not happen"<<endl; VSExit( 1 ); } this->valid = true; if (VSFS_DEBUG() > 1) cerr<<filestr<<" SUCCESS !!!"<<endl; } } else { err = VSFileSystem::LookForFile( *this, type, file_mode ); if (err > Ok) { this->valid = false; return FileNotFound; } filestr = this->GetFullPath(); this->fp = fopen( filestr.c_str(), "rb" ); if (!this->fp) { cerr<<"!!! SERIOUS ERROR : failed to open "<<filestr<<" - this should not happen"<<endl; this->valid = false; return FileNotFound; //fault! } this->valid = true; } } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { //Here we look for the file but we don't really open it, we just check if it exists err = VSFileSystem::LookForFile( *this, type, file_mode ); if (err > Ok) { this->valid = false; return FileNotFound; } //Test if we have found a file in another FileType's dir and if it doesn't use volumes //If so we open the file as a normal one if ( this->volume_type == VSFSNone || (this->alt_type != this->file_type && !UseVolumes[this->alt_type]) ) { filestr = this->GetFullPath(); this->fp = fopen( filestr.c_str(), "rb" ); if (!this->fp) { cerr<<"!!! SERIOUS ERROR : failed to open "<<filestr<<" - this should not happen"<<endl; this->valid = false; return FileNotFound; //fault } } this->valid = true; } } if (err <= Ok) { //We save the current path only when loading a unit, an animation, a sprite or a cockpit if ( (type == UnitFile || type == AnimFile || type == VSSpriteFile || type == CockpitFile) ) { current_path.push_back( this->rootname ); current_subdirectory.push_back( this->subdirectoryname ); current_type.push_back( this->alt_type ); if (VSFS_DEBUG() > 1) { cerr<<endl<<"BEGINNING OF "; DisplayType( type ); cerr<<endl; } } } } else { //This is a "buffer file" if (!this->pk3_extracted_file) err = FileNotFound; else err = Ok; } return err; } //We will always write in homedir+Directories[FileType][0] //Open a standard file read/write VSError VSFile::OpenReadWrite( const char *filename, VSFileType type ) { if (type >= ZoneBuffer && type != UnknownFile) return FileNotFound; this->file_type = this->alt_type = type; this->file_mode = ReadWrite; return Ok; } //We will always write in homedir+Directories[FileType][0] //Open (truncate) or create a standard file read/write VSError VSFile::OpenCreateWrite( const char *filenam, VSFileType type ) { if (type >= ZoneBuffer && type != UnknownFile) return FileNotFound; this->file_type = this->alt_type = type; this->filename = string( filenam ); this->file_mode = CreateWrite; if (type == SystemFile) { string dirpath( sharedsectors+"/"+universe_name ); CreateDirectoryHome( dirpath ); CreateDirectoryHome( dirpath+"/"+getStarSystemSector( this->filename ) ); string fpath( homedir+"/"+dirpath+"/"+this->filename ); this->fp = fopen( fpath.c_str(), "wb" ); if (!fp) return LocalPermissionDenied; } else if (type == TextureFile) { string fpath( homedir+"/"+sharedtextures+"/"+this->filename ); this->fp = fopen( fpath.c_str(), "wb" ); if (!fp) return LocalPermissionDenied; } else if (type == UnitFile) { string fpath( homedir+"/"+savedunitpath+"/"+this->filename ); this->rootname = homedir; this->directoryname = savedunitpath; this->fp = fopen( fpath.c_str(), "wb" ); if (!fp) return LocalPermissionDenied; } else if (type == SaveFile) { string fpath( homedir+"/save/"+this->filename ); this->fp = fopen( fpath.c_str(), "wb" ); if (!fp) return LocalPermissionDenied; } else if (type == AccountFile) { string fpath( datadir+"/accounts/"+this->filename ); this->fp = fopen( fpath.c_str(), "wb" ); if (!fp) return LocalPermissionDenied; } else if (type == UnknownFile) { string fpath( homedir+"/"+this->filename ); this->rootname = homedir; this->directoryname = ""; this->fp = fopen( fpath.c_str(), "wb" ); if (!fp) return LocalPermissionDenied; } return Ok; } size_t VSFile::Read( void *ptr, size_t length ) { size_t nbread = 0; if (!UseVolumes[this->alt_type] || this->volume_type == VSFSNone) { assert( fp != NULL ); nbread = fread( ptr, 1, length, this->fp ); } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { checkExtracted(); if (length > this->size-this->offset) length = this->size-this->offset; memcpy( ptr, (pk3_extracted_file+offset), length ); offset += length; nbread = length; } } return nbread; } VSError VSFile::ReadLine( void *ptr, size_t length ) { char *ret; if (!UseVolumes[alt_type] || this->volume_type == VSFSNone) { ret = fgets( (char*) ptr, length, this->fp ); if (!ret) return Unspecified; } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { checkExtracted(); ret = (char*) ptr; bool nl_found = false; unsigned int i = 0; if (VSFS_DEBUG() > 1) cerr<<"READLINE STARTING OFFSET="<<offset; for (i = 0; !nl_found && i < length && offset < size; offset++, i++) { if (pk3_extracted_file[offset] == '\n' || pk3_extracted_file[offset] == '\r') { nl_found = true; if (VSFS_DEBUG() > 1) { if (pk3_extracted_file[offset] == '\n') cerr<<"\\n "; if (pk3_extracted_file[offset] == '\r') cerr<<"\\r "; } } else { ret[i] = pk3_extracted_file[offset]; if (VSFS_DEBUG() > 1) cerr<<std::hex<<ret[i]<<" "; } } this->GoAfterEOL( length ); ret[i] = 0; if (VSFS_DEBUG() > 1) cerr<<std::dec<<" - read "<<i<<" char - "<<ret<<endl; if (!nl_found) return Unspecified; } } return Ok; } string VSFile::ReadFull() { if (this->Size() < 0) { cerr<<"Attempt to call ReadFull on a bad file "<<this->filename<<" "<<this->Size()<<" "<<this->GetFullPath().c_str()<<endl; return string(); } if (!UseVolumes[alt_type] || this->volume_type == VSFSNone) { char *content = new char[this->Size()+1]; content[this->Size()] = 0; int readsize = fread( content, 1, this->Size(), this->fp ); if (this->Size() != readsize) { cerr<<"Only read "<<readsize<<" out of "<<this->Size()<<" bytes of "<<this->filename<<endl; GetError( "ReadFull" ); if (readsize <= 0) return string(); else content[readsize] = '\0'; } string res( content ); delete[] content; return res; } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { checkExtracted(); offset = this->Size(); return string( pk3_extracted_file ); } } return string( "" ); } size_t VSFile::Write( const void *ptr, size_t length ) { if (!UseVolumes[this->alt_type] || this->volume_type == VSFSNone) { size_t nbwritten = fwrite( ptr, 1, length, this->fp ); return nbwritten; } else { cerr<<"!!! ERROR : Writing is not supported within resource/volume files"<<endl; VSExit( 1 ); } return Ok; } size_t VSFile::Write( const string &content ) { std::string::size_type length = content.length(); return this->Write( content.c_str(), length ); } VSError VSFile::WriteLine( const void *ptr ) { if (!UseVolumes[alt_type] || this->volume_type == VSFSNone) { fputs( (const char*) ptr, this->fp ); } else { cerr<<"!!! ERROR : Writing is not supported within resource/volume files"<<endl; VSExit( 1 ); } return Ok; } void VSFile::WriteFull( void *ptr ) {} int VSFile::Fprintf( const char *format, ... ) { if (!UseVolumes[alt_type] || this->volume_type == VSFSNone) { va_list ap; va_start( ap, format ); return vfprintf( this->fp, format, ap ); } else { cerr<<"!!! ERROR : Writing is not supported within resource/volume files"<<endl; VSExit( 1 ); } return 0; } #if 0 #ifdef HAVE_VFSCANF int VSFile::Fscanf( const char *format, ... ) { int ret = -1; int readbytes = 0; //We add the parameter %n to the format string in order to get the number of bytes read int format_length = strlen( format ); char *newformat = new char[format_length+3]; memset( newformat, 0, format_length+3 ); memcpy( newformat, format, format_length ); strcat( newformat, "%n" ); va_list arglist; va_start( arglist, format ); if (!UseVolumes[alt_type] || this->volume_type == VSFSNone) { //return _input(fp,(unsigned char*)format,arglist); ret = vfscanf( this->fp, newformat, arglist ); va_end( arglist ); } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { //If the file has not been extracted yet we do now checkExtracted(); ret = vsscanf( pk3_extracted_file+offset, newformat, arglist ); readbytes = GetReadBytes( newformat, arglist ); va_end( arglist ); cerr<<" SSCANF : Read "<<readbytes<<" bytes"<<endl; this->offset += readbytes; } } delete[] newformat; return ret; } #endif #endif void VSFile::Begin() { if (!UseVolumes[alt_type] || this->volume_type == VSFSNone || this->file_mode != ReadOnly) { fseek( this->fp, 0, SEEK_SET ); } else { if (q_volume_format == vfmtVSR) offset = 0; else if (q_volume_format == vfmtPK3) offset = 0; } } void VSFile::End() { if (!UseVolumes[alt_type] || this->volume_type == VSFSNone || this->file_mode != ReadOnly) { fseek( this->fp, 0, SEEK_END ); } else { if (q_volume_format == vfmtVSR) offset = size; else if (q_volume_format == vfmtPK3) offset = size; } } void VSFile::GoTo( long foffset ) //Does a VSFileSystem::Fseek( fp, offset, SEEK_SET); { if (!UseVolumes[alt_type] || this->volume_type == VSFSNone || this->file_mode != ReadOnly) { fseek( this->fp, foffset, SEEK_SET ); } else { if (q_volume_format == vfmtVSR) offset = foffset; else if (q_volume_format == vfmtPK3) offset = foffset; } } long VSFile::Size() { if (size == 0) { if (!UseVolumes[alt_type] || this->volume_type == VSFSNone || file_mode != ReadOnly) { struct stat st; if ( (fp != NULL) && fstat( fileno( fp ), &st ) == 0 ) return this->size = st.st_size; return -1; } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { checkExtracted(); return this->size; } } return -1; } return this->size; } void VSFile::Clear() { if (!UseVolumes[alt_type] || this->volume_type == VSFSNone || file_mode != ReadOnly) { fclose( fp ); this->fp = fopen( this->GetFullPath().c_str(), "w+b" ); //This should not happen if (!fp) { GetError( "Clear" ); VSExit( 1 ); } } else { cerr<<"!!! ERROR : Writing is not supported within resource/volume files"<<endl; VSExit( 1 ); } } long VSFile::GetPosition() { long ret = 0; if (!UseVolumes[alt_type] || this->volume_type == VSFSNone || file_mode != ReadOnly) { ret = ftell( this->fp ); } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { ret = offset; } } return ret; } bool VSFile::Eof() { bool eof = false; if (!UseVolumes[alt_type] || this->volume_type == VSFSNone || file_mode != ReadOnly) { eof = vs_feof( this->fp ); } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { eof = (this->Size() < 0) || ( offset == (unsigned long)this->Size() ); } } return eof; } bool VSFile::Valid() { return valid; } void VSFile::Close() { if (this->file_type >= ZoneBuffer && this->file_type != UnknownFile && this->pk3_extracted_file) { delete this->pk3_extracted_file; this->pk3_extracted_file = NULL; return; } if ( this->valid && this->file_mode == ReadOnly && (file_type == UnitFile || file_type == AnimFile || file_type == VSSpriteFile || file_type == CockpitFile) ) { assert( current_path.size() > 1 ); current_path.pop_back(); current_subdirectory.pop_back(); current_type.pop_back(); if (VSFS_DEBUG() > 2) { cerr<<"END OF "; DisplayType( this->file_type ); cerr<<endl<<endl; } } if (!UseVolumes[file_type] || this->volume_type == VSFSNone || file_mode != ReadOnly) { fclose( this->fp ); this->fp = NULL; } else { if (q_volume_format == vfmtVSR) {} else if (q_volume_format == vfmtPK3) { if (pk3_extracted_file) delete[] pk3_extracted_file; pk3_extracted_file = NULL; } } this->size = -1; this->valid = false; this->filename = ""; this->directoryname = ""; this->subdirectoryname = ""; this->rootname = ""; this->offset = 0; this->file_index = -1; } static void pathAppend( string &dest, string &suffix ) { if ( suffix.empty() ) return; if (suffix[0] != '/' && !dest.empty() && dest[dest.length()-1] != '/') dest += "/"; dest += suffix; } string VSFile::GetFullPath() { string tmp = this->rootname; pathAppend( tmp, this->directoryname ); pathAppend( tmp, this->subdirectoryname ); pathAppend( tmp, this->filename ); return tmp; } string VSFile::GetAbsPath() { string tmp = this->directoryname; pathAppend( tmp, this->subdirectoryname ); pathAppend( tmp, this->filename ); return tmp; } void VSFile::SetType( VSFileType type ) { this->file_type = type; } void VSFile::SetAltType( VSFileType type ) { this->alt_type = type; } void VSFile::SetIndex( int index ) { this->file_index = index; } void VSFile::SetVolume( VSVolumeType big ) { this->volume_type = big; } bool VSFile::UseVolume() { return UseVolumes[alt_type] && volume_type != VSFSNone; } void VSFile::GoAfterEOL( unsigned int length ) { while ( this->offset < length && this->offset < this->size && (this->pk3_extracted_file[offset] == '\r' || this->pk3_extracted_file[offset] == '\n') ) this->offset++; } void VSFile::GoAfterEOL() { while ( this->offset < this->size && (this->pk3_extracted_file[offset] == '\r' || this->pk3_extracted_file[offset] == '\n') ) this->offset++; } } #define CASE( a ) \ case a: \ ostr<<#a; break; std::ostream&operator<<( std::ostream &ostr, VSFileSystem::VSError err ) { switch (err) { CASE( VSFileSystem::Shared ) CASE( VSFileSystem::Ok ) CASE( VSFileSystem::SocketError ) CASE( VSFileSystem::FileNotFound ) CASE( VSFileSystem::LocalPermissionDenied ) CASE( VSFileSystem::RemotePermissionDenied ) CASE( VSFileSystem::DownloadInterrupted ) CASE( VSFileSystem::IncompleteWrite ) CASE( VSFileSystem::IncompleteRead ) CASE( VSFileSystem::EndOfFile ) CASE( VSFileSystem::IsDirectory ) CASE( VSFileSystem::BadFormat ) CASE( VSFileSystem::Unspecified ) default: ostr<<"VSFileSystem::<undefined VSError>"; break; } return ostr; } #undef CASE std::ostream&operator<<( std::ostream &ostr, VSFileSystem::VSFileType type ) { VSFileSystem::DisplayType( type, ostr ); return ostr; } std::string nameof( VSFileSystem::VSFileType type ) { #define CASE( a ) \ case a: \ return #a; break; switch (type) { CASE( VSFileSystem::UniverseFile ) CASE( VSFileSystem::SystemFile ) CASE( VSFileSystem::CockpitFile ) CASE( VSFileSystem::UnitFile ) CASE( VSFileSystem::PythonFile ) CASE( VSFileSystem::TextureFile ) CASE( VSFileSystem::SoundFile ) CASE( VSFileSystem::MeshFile ) CASE( VSFileSystem::CommFile ) CASE( VSFileSystem::AiFile ) CASE( VSFileSystem::SaveFile ) CASE( VSFileSystem::AnimFile ) CASE( VSFileSystem::VSSpriteFile ) CASE( VSFileSystem::MissionFile ) CASE( VSFileSystem::MusicFile ) CASE( VSFileSystem::AccountFile ) CASE( VSFileSystem::ZoneBuffer ) CASE( VSFileSystem::UnknownFile ) default: return "VSFileSystem::<undefined VSFileType>"; break; } #undef CASE } #if defined (_WIN32) && !defined (__CYGWIN__) int scandir( const char *dirname, struct dirent ***namelist, int (*select)( const struct dirent* ), int (*compar)( const struct dirent**, const struct dirent** ) ) { int len; char *findIn, *d; WIN32_FIND_DATA find; HANDLE h; int nDir = 0, NDir = 0; struct dirent **dir = 0, *selectDir; unsigned long ret; len = strlen( dirname ); findIn = (char*) malloc( len+5 ); strcpy( findIn, dirname ); for (d = findIn; *d; d++) if (*d == '/') *d = '\\'; if ( (len == 0) ) strcpy( findIn, ".\\*" ); if ( (len == 1) && (d[-1] == '.') ) strcpy( findIn, ".\\*" ); if ( (len > 0) && (d[-1] == '\\') ) { *d++ = '*'; *d = 0; } if ( (len > 1) && (d[-1] == '.') && (d[-2] == '\\') ) d[-1] = '*'; if ( ( h = FindFirstFile( findIn, &find ) ) == INVALID_HANDLE_VALUE ) { ret = GetLastError(); if (ret != ERROR_NO_MORE_FILES) { //TODO: return some error code } *namelist = dir; return nDir; } do { selectDir = (struct dirent*) malloc( sizeof (struct dirent)+strlen( find.cFileName ) ); strcpy( selectDir->d_name, find.cFileName ); if ( !select || (*select)(selectDir) ) { if (nDir == NDir) { struct dirent **tempDir = (dirent**) calloc( sizeof (struct dirent*), NDir+33 ); if (NDir) memcpy( tempDir, dir, sizeof (struct dirent*) *NDir ); if (dir) free( dir ); dir = tempDir; NDir += 32; } dir[nDir] = selectDir; nDir++; dir[nDir] = 0; } else { free( selectDir ); } } while ( FindNextFile( h, &find ) ); ret = GetLastError(); if (ret != ERROR_NO_MORE_FILES) { //TODO: return some error code } FindClose( h ); free( findIn ); if (compar) qsort( dir, nDir, sizeof (*dir), ( int (*)( const void*, const void* ) )compar ); *namelist = dir; return nDir; } int alphasort( struct dirent **a, struct dirent **b ) { return strcmp( (*a)->d_name, (*b)->d_name ); } #endif
34.422803
184
0.541899
Ezeer
ee093f7c722eee7467fd46465a2a21fd56584c3b
334
hpp
C++
include/Node.hpp
Algorithms-and-Data-Structures-2021/semester-work-suffix-tree
a91dcaa869cd2c144869901247d16199e027e141
[ "MIT" ]
null
null
null
include/Node.hpp
Algorithms-and-Data-Structures-2021/semester-work-suffix-tree
a91dcaa869cd2c144869901247d16199e027e141
[ "MIT" ]
null
null
null
include/Node.hpp
Algorithms-and-Data-Structures-2021/semester-work-suffix-tree
a91dcaa869cd2c144869901247d16199e027e141
[ "MIT" ]
1
2021-05-22T19:20:20.000Z
2021-05-22T19:20:20.000Z
#pragma once #include "SuffixTree.hpp" #include "Constants.hpp" #include <algorithm> namespace itis { struct Node { int start, end, slink; int next[ALPHABET_SIZE]; // if there is an edge from node starting with certain ASCII letter int edge_length(int pos) { return std::min(end, pos + 1) - start; } }; }
19.647059
96
0.661677
Algorithms-and-Data-Structures-2021
ee09e18578220f71af6f0dfc3c9ec8d6e352ad46
468
cpp
C++
src/6/ScopeOperatorUnary.cpp
jhxie/CPlusPlusHowToProgram
a622902a9e5e9766d9ddb83a38070d57dba786c3
[ "BSD-2-Clause" ]
1
2018-01-10T03:32:46.000Z
2018-01-10T03:32:46.000Z
src/6/ScopeOperatorUnary.cpp
jhxie/CPlusPlusHowToProgram
a622902a9e5e9766d9ddb83a38070d57dba786c3
[ "BSD-2-Clause" ]
null
null
null
src/6/ScopeOperatorUnary.cpp
jhxie/CPlusPlusHowToProgram
a622902a9e5e9766d9ddb83a38070d57dba786c3
[ "BSD-2-Clause" ]
null
null
null
/** * 6.15 * Unary scope resolution operator; used to access global namespace. */ #include <iostream> using namespace std; static int number {7}; // global variable int main(void) { double number {10.5}; // local variable shadows the global variable // Display values of local and global variables. cout \ << "Local double value of 'number' = " << number << "\nGlobal int value of 'number' = " << ::number << endl; return 0; }
20.347826
71
0.630342
jhxie
ee0ce34ba34e86595c7861d9bacbddab83798457
1,494
cpp
C++
LongestPalindromicSubstring.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
LongestPalindromicSubstring.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
LongestPalindromicSubstring.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <cstdlib> #include <string> #include <vector> using namespace std; class Solution { private: const char sep_char = '\1'; public: string longestPalindrome(string s) { int max_len = 0; int len = s.length(); if (len <= 1) return s; string str; str.push_back(sep_char); for (int i=0; i<len; i++) { str.push_back(s[i]); str.push_back(sep_char); } cout<<str<<endl; int nlen = 2 * len + 1; vector<int> P(nlen, 0); int last_i = 0; int last_r = 0; int maxv = -1; int maxi = -1; for (int i=0; i<nlen; i++) { int p = i, q = i; if (i < last_r) { int j = 2 * last_i - i; // (i + j) / 2 = last_i int slen = min(P[j], last_r - i); p-= slen; q+= slen; } while(p >= 0 && q < nlen && str[p] == str[q]) p--, q++; if (q > last_r) { last_r = q; last_i = i; } P[i] = q - i; if (P[i] > maxv) { maxv = P[i]; maxi = i; } } return s.substr((maxi + 1 - P[maxi]) / 2, P[maxi] - 1); } }; int main() { string str("missing"); Solution s; cout<<s.longestPalindrome(str)<<endl; system("pause"); return 0; }
21.652174
67
0.394913
hgfeaon
ee0d1fc6705ab1343fd8846b3e0a89896f6e86e8
1,675
hpp
C++
graph/edmonds_karp.hpp
fumiphys/programming_contest
b9466e646045e1c64571af2a1e64813908e70841
[ "MIT" ]
7
2019-04-30T14:25:40.000Z
2020-12-19T17:38:11.000Z
graph/edmonds_karp.hpp
fumiphys/programming_contest
b9466e646045e1c64571af2a1e64813908e70841
[ "MIT" ]
46
2018-09-19T16:42:09.000Z
2020-05-07T09:05:08.000Z
graph/edmonds_karp.hpp
fumiphys/programming_contest
b9466e646045e1c64571af2a1e64813908e70841
[ "MIT" ]
null
null
null
/* * Library for Edmonds Karp */ #ifndef _EDMONDS_KARP_H_ #define _EDMONDS_KARP_H_ #include <climits> #include <vector> #include <queue> #include <utility> #include <algorithm> #include <limits> using namespace std; template <typename T> struct edge {int to; T cap; int rev;}; template <typename T> struct Graph{ int n; vector<vector<edge<T>>> vec; Graph(int n): n(n){ vec.resize(n); } void adde(int at, int to, T cap){ vec[at].push_back((edge<T>){to, cap, (int)vec[to].size()}); vec[to].push_back((edge<T>){at, 0, (int)vec[at].size() - 1}); } T max_flow(int s, int t){ T f = 0; while(true){ queue<int> q; q.push(s); vector<pair<int, int>> prev(n, make_pair(-1, -1)); prev[s] = make_pair(s, -1); while(!q.empty() && prev[t].first < 0){ auto p = q.front(); q.pop(); for(int i = 0; i < vec[p].size(); i++){ auto e = vec[p][i]; if(prev[e.to].first < 0 && e.cap > 0){ prev[e.to] = make_pair(p, i); q.push(e.to); } } } if(prev[t].first < 0)return f; T mini = numeric_limits<T>::max(); for(int i = t; prev[i].first != i; i = prev[i].first){ int p = prev[i].first; auto e = vec[p][prev[i].second]; mini = min(mini, e.cap); } for(int i = t; prev[i].first != i; i = prev[i].first){ int p = prev[i].first; auto& e = vec[p][prev[i].second]; e.cap -= mini; vec[i][e.rev].cap += mini; } f += mini; } } T min_cut(int s, int t){ return max_flow(s, t); } }; using GraphI = Graph<int>; using GraphL = Graph<long long>; #endif
23.928571
65
0.518806
fumiphys
ee0e95c13a708e09aa3b0df85bc3e3bc0c3a3349
6,194
cc
C++
src/xzero/http/hpack/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
24
2016-07-10T08:05:11.000Z
2021-11-16T10:53:48.000Z
src/xzero/http/hpack/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
14
2015-04-12T10:45:26.000Z
2016-06-28T22:27:50.000Z
src/xzero/http/hpack/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
4
2016-10-05T17:51:38.000Z
2020-04-20T07:45:23.000Z
// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2018 Christian Parpart <christian@parpart.family> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/http/hpack/Parser.h> #include <xzero/http/HeaderFieldList.h> #include <xzero/testing.h> #include <optional> using namespace xzero; using namespace xzero::http; using namespace xzero::http::hpack; TEST(hpack_Parser, decodeInt) { DynamicTable dt(4096); Parser parser(&dt, 4096, nullptr); uint8_t helloInt[4] = {0}; uint8_t* helloIntEnd = helloInt + 4; uint64_t decodedInt = 0; /* (C.1.1) Example 1: Encoding 10 Using a 5-Bit Prefix * * 0 1 2 3 4 5 6 7 * +---+---+---+---+---+---+---+---+ * | X | X | X | 0 | 1 | 0 | 1 | 0 | 10 stored on 5 bits * +---+---+---+---+---+---+---+---+ */ helloInt[0] = 0b00001010; size_t nparsed = Parser::decodeInt(5, &decodedInt, helloInt, helloIntEnd); ASSERT_EQ(1, nparsed); ASSERT_EQ(10, decodedInt); /* (C.1.2) Example 2: Encoding 1337 Using a 5-Bit Prefix * * 0 1 2 3 4 5 6 7 * +---+---+---+---+---+---+---+---+ * | X | X | X | 1 | 1 | 1 | 1 | 1 | Prefix = 31, I = 1306 * | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1306>=128, encode(154), I=1306/128 * | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 10<128, encode(10), done * +---+---+---+---+---+---+---+---+ */ helloInt[0] = 0b00011111; helloInt[1] = 0b10011010; helloInt[2] = 0b00001010; nparsed = Parser::decodeInt(5, &decodedInt, helloInt, helloIntEnd); ASSERT_EQ(3, nparsed); ASSERT_EQ(1337, decodedInt); /* (C.1.3) Example 3: Encoding 42 Starting at an Octet Boundary * * 0 1 2 3 4 5 6 7 * +---+---+---+---+---+---+---+---+ * | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 42 stored on 8 bits * +---+---+---+---+---+---+---+---+ */ helloInt[0] = 0b00101010; nparsed = Parser::decodeInt(8, &decodedInt, helloInt, helloIntEnd); ASSERT_EQ(1, nparsed); ASSERT_EQ(42, decodedInt); } TEST(hpack_Parser, decodeString) { std::string decoded; size_t nparsed; const uint8_t empty[] = {0x00}; nparsed = Parser::decodeString(&decoded, empty, std::end(empty)); ASSERT_EQ(1, nparsed); ASSERT_EQ("", decoded); const uint8_t hello[] = { 0x05, 'H', 'e', 'l', 'l', 'o' }; nparsed = Parser::decodeString(&decoded, hello, std::end(hello)); ASSERT_EQ(6, nparsed); ASSERT_EQ("Hello", decoded); } TEST(hpack_Parser, literalHeaderFieldWithIndex) { /* C.2.1 Literal Header Field with Indexing * * custom-key: custom-header * * 400a 6375 7374 6f6d 2d6b 6579 0d63 7573 | @.custom-key.cus * 746f 6d2d 6865 6164 6572 | tom-header */ uint8_t block[] = { 0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72 }; std::string name; std::string value; std::optional<bool> sensitive; auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) { name = _name; value = _value; sensitive = s; }; DynamicTable dt(4096); Parser parser(&dt, 4096, gotcha); size_t nparsed = parser.parse(block, std::end(block)); ASSERT_EQ(26, nparsed); ASSERT_EQ("custom-key", name); ASSERT_EQ("custom-header", value); ASSERT_TRUE(sensitive.has_value()); ASSERT_FALSE(sensitive.value()); } TEST(hpack_Parser, literalHeaderWithoutIndexing) { /* C.2.2 Literal Header Field without Indexing * * :path: /sample/path * * 040c 2f73 616d 706c 652f 7061 7468 | ../sample/path */ uint8_t block[] = { 0x04, 0x0c, 0x2f, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2f, 0x70, 0x61, 0x74, 0x68 }; std::string name; std::string value; std::optional<bool> sensitive; auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) { name = _name; value = _value; sensitive = s; }; DynamicTable dt(4096); Parser parser(&dt, 4096, gotcha); size_t nparsed = parser.parse(block, std::end(block)); ASSERT_EQ(14, nparsed); ASSERT_EQ(":path", name); ASSERT_EQ("/sample/path", value); ASSERT_TRUE(sensitive.has_value()); ASSERT_FALSE(sensitive.value()); } TEST(hpack_Parser, literalHeaderNeverIndex) { /* C.2.3 Literal Header Field Never Indexed * * password: secret */ uint8_t block[] = { 0x10, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74 }; std::string name; std::string value; std::optional<bool> sensitive; auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) { name = _name; value = _value; sensitive = s; }; DynamicTable dt(4096); Parser parser(&dt, 4096, gotcha); size_t nparsed = parser.parse(block, std::end(block)); ASSERT_EQ(17, nparsed); ASSERT_EQ("password", name); ASSERT_EQ("secret", value); ASSERT_TRUE(sensitive.has_value()); ASSERT_TRUE(sensitive.value()); } TEST(hpack_Parser, literalHeaderFieldFromIndex) { /* C.2.4 Indexed Header Field * * :method: GET * * 82 */ uint8_t block[] = { 0x82 }; std::string name; std::string value; std::optional<bool> sensitive; auto gotcha = [&](const std::string& _name, const std::string& _value, bool s) { name = _name; value = _value; sensitive = s; }; DynamicTable dt(4096); Parser parser(&dt, 4096, gotcha); size_t nparsed = parser.parse(block, std::end(block)); ASSERT_EQ(1, nparsed); ASSERT_EQ(":method", name); ASSERT_EQ("GET", value); ASSERT_TRUE(sensitive.has_value()); ASSERT_FALSE(sensitive.value()); } TEST(hpack_Parser, updateTableSize) { uint8_t block[] = { 0x25 }; DynamicTable dt(4096); Parser parser(&dt, 4096, nullptr); size_t nparsed = parser.parse(block, std::end(block)); ASSERT_EQ(1, nparsed); ASSERT_EQ(5, parser.internalMaxSize()); } // TODO: C.3.x three requests without huffman coding // TODO: C.4.x three requests with huffman coding
27.775785
82
0.611075
pjsaksa
ee0f7fb2e784d6e9a83d94ee47573f361c163331
1,157
cpp
C++
Dataset/Leetcode/train/2/927.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/2/927.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/2/927.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: ListNode* XXX(ListNode* l1, ListNode* l2) { ListNode* l3=new ListNode; ListNode* h=l3; int c=0; while(l1&&l2){ int val=l1->val+l2->val+c; c=val/10; val%=10; ListNode* tmp=new ListNode(val); tmp->next=nullptr; l3->next=tmp; l3=l3->next; l1=l1->next; l2=l2->next; } while(l1){ int val=l1->val+c; c=val/10; val%=10; ListNode* tmp=new ListNode(val); tmp->next=nullptr; l3->next=tmp; l3=l3->next; l1=l1->next; } while(l2){ int val=l2->val+c; c=val/10; val%=10; ListNode* tmp=new ListNode(val); tmp->next=nullptr; l3->next=tmp; l3=l3->next; l2=l2->next; } if(c){ ListNode* tmp=new ListNode(c); tmp->next=nullptr; l3->next=tmp; l3=l3->next; } h=h->next; return h; } };
23.14
47
0.392394
kkcookies99
ee17950bcdf71de7b006e8586be7abefaf3b17ff
2,343
cc
C++
src/tools/binary_errors.cc
walkingeyerobot/wasp
882f051f61af14308829686fa2b79f864ea1009d
[ "Apache-2.0" ]
47
2020-10-24T18:29:12.000Z
2022-03-31T02:08:17.000Z
src/tools/binary_errors.cc
walkingeyerobot/wasp
882f051f61af14308829686fa2b79f864ea1009d
[ "Apache-2.0" ]
27
2020-10-23T17:12:48.000Z
2021-09-09T18:02:24.000Z
src/tools/binary_errors.cc
walkingeyerobot/wasp
882f051f61af14308829686fa2b79f864ea1009d
[ "Apache-2.0" ]
13
2020-10-23T06:28:12.000Z
2022-03-14T10:08:01.000Z
// // Copyright 2020 WebAssembly Community Group participants // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "src/tools/binary_errors.h" #include <iostream> #include <utility> #include "absl/strings/str_format.h" namespace wasp::tools { BinaryErrors::BinaryErrors(SpanU8 data) : BinaryErrors{"<unknown>", data} {} BinaryErrors::BinaryErrors(string_view filename, SpanU8 data) : filename{filename}, data{data} {} void BinaryErrors::PrintTo(std::ostream& os) { for (const auto& error : errors) { os << ErrorToString(error); } } void BinaryErrors::HandlePushContext(Location loc, string_view desc) {} void BinaryErrors::HandlePopContext() {} void BinaryErrors::HandleOnError(Location loc, string_view message) { errors.push_back(Error{loc, std::string(message)}); } auto BinaryErrors::ErrorToString(const Error& error) const -> std::string { auto& loc = error.loc; const ptrdiff_t before = 4, after = 8, max_size = 32; size_t start = std::max(before, loc.begin() - data.begin()) - before; size_t end = data.size() - std::max(after, data.end() - loc.end()) + after; end = std::min(end, start + max_size); Location context = MakeSpan(data.begin() + start, data.begin() + end); std::string line1 = " "; std::string line2 = " "; bool space = false; for (auto iter = context.begin(); iter < context.end(); ++iter) { u8 x = *iter; line1 += absl::StrFormat("%02x", x); if (iter >= loc.begin() && iter < loc.end()) { line2 += "^^"; } else { line2 += " "; } if (space) { line1 += ' '; line2 += ' '; } space = !space; } return absl::StrFormat("%s:%08x: %s\n%s\n%s\n", filename, loc.begin() - data.begin(), error.message, line1, line2); } } // namespace wasp::tools
29.658228
77
0.647887
walkingeyerobot
ee1ea1d4d631eccf7690ba030ace94510499911a
5,456
cpp
C++
src/util/sll/regexp.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/util/sll/regexp.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/util/sll/regexp.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "regexp.h" #include <QDataStream> #include <QtDebug> #ifdef USE_PCRE #include <pcre.h> #else #include <QRegExp> #endif namespace LeechCraft { namespace Util { #ifdef USE_PCRE #ifndef PCRE_STUDY_JIT_COMPILE #define PCRE_STUDY_JIT_COMPILE 0 #endif class PCREWrapper { pcre *RE_; pcre_extra *Extra_; QString Pattern_; Qt::CaseSensitivity CS_; public: PCREWrapper () : RE_ (0) , Extra_ (0) { } PCREWrapper (const QString& str, Qt::CaseSensitivity cs) : RE_ (Compile (str, cs)) , Extra_ (0) , Pattern_ (str) , CS_ (cs) { if (RE_) { pcre_refcount (RE_, 1); const char *error = 0; const int opts = PCRE_STUDY_JIT_COMPILE; Extra_ = pcre_study (RE_, opts, &error); } } PCREWrapper (const PCREWrapper& other) : RE_ (0) , Extra_ (0) { *this = other; } PCREWrapper& operator= (const PCREWrapper& other) { if (RE_ && !pcre_refcount (RE_, -1)) { FreeStudy (); pcre_free (RE_); } RE_ = other.RE_; Extra_ = other.Extra_; if (RE_) pcre_refcount (RE_, 1); return *this; } ~PCREWrapper () { if (!RE_) return; if (!pcre_refcount (RE_, -1)) { FreeStudy (); pcre_free (RE_); } } const QString& GetPattern () const { return Pattern_; } Qt::CaseSensitivity GetCS () const { return CS_; } int Exec (const QByteArray& utf8) const { return RE_ ? pcre_exec (RE_, Extra_, utf8.constData (), utf8.size (), 0, 0, NULL, 0) : -1; } private: pcre* Compile (const QString& str, Qt::CaseSensitivity cs) { const char *error = 0; int errOffset = 0; int options = PCRE_UTF8; if (cs == Qt::CaseInsensitive) options |= PCRE_CASELESS; auto re = pcre_compile (str.toUtf8 ().constData (), options, &error, &errOffset, NULL); if (!re) qWarning () << Q_FUNC_INFO << "failed compiling" << str << error; return re; } void FreeStudy () { if (Extra_) #ifdef PCRE_CONFIG_JIT pcre_free_study (Extra_); #else pcre_free (Extra_); #endif } }; #endif namespace { struct RegExpRegisterGuard { RegExpRegisterGuard () { qRegisterMetaType<RegExp> ("Util::RegExp"); qRegisterMetaTypeStreamOperators<RegExp> (); } } Guard; } struct RegExpImpl { #if USE_PCRE PCREWrapper PRx_; #else QRegExp Rx_; #endif }; bool RegExp::IsFast () { #ifdef USE_PCRE return true; #else return false; #endif } RegExp::RegExp (const QString& str, Qt::CaseSensitivity cs) #ifdef USE_PCRE : Impl_ { new RegExpImpl { { str, cs } } } #else : Impl_ { new RegExpImpl { QRegExp { str, cs, QRegExp::RegExp } } } #endif { } bool RegExp::Matches (const QString& str) const { if (!Impl_) return {}; #ifdef USE_PCRE return Impl_->PRx_.Exec (str.toUtf8 ()) >= 0; #else return Impl_->Rx_.exactMatch (str); #endif } QString RegExp::GetPattern () const { if (!Impl_) return {}; #ifdef USE_PCRE return Impl_->PRx_.GetPattern (); #else return Impl_->Rx_.pattern (); #endif } Qt::CaseSensitivity RegExp::GetCaseSensitivity () const { if (!Impl_) return {}; #ifdef USE_PCRE return Impl_->PRx_.GetCS (); #else return Impl_->Rx_.caseSensitivity (); #endif } } } QDataStream& operator<< (QDataStream& out, const LeechCraft::Util::RegExp& rx) { out << static_cast<quint8> (1); out << rx.GetPattern () << static_cast<quint8> (rx.GetCaseSensitivity ()); return out; } QDataStream& operator>> (QDataStream& in, LeechCraft::Util::RegExp& rx) { quint8 version = 0; in >> version; if (version != 1) { qWarning () << Q_FUNC_INFO << "unknown version" << version; return in; } QString pattern; quint8 cs; in >> pattern >> cs; rx = LeechCraft::Util::RegExp { pattern, static_cast<Qt::CaseSensitivity> (cs) }; return in; }
20.745247
93
0.649194
MellonQ